instcombine shouldn't delete all null checks for mallocs.
[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/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #include "llvm/ADT/STLExtras.h"
65 #include <algorithm>
66 #include <climits>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   /// InstCombineWorklist - This is the worklist management logic for
78   /// InstCombine.
79   class InstCombineWorklist {
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     
83     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
84     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85   public:
86     InstCombineWorklist() {}
87     
88     bool isEmpty() const { return Worklist.empty(); }
89     
90     /// Add - Add the specified instruction to the worklist if it isn't already
91     /// in it.
92     void Add(Instruction *I) {
93       DEBUG(errs() << "IC: ADD: " << *I << '\n');
94       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95         Worklist.push_back(I);
96     }
97     
98     void AddValue(Value *V) {
99       if (Instruction *I = dyn_cast<Instruction>(V))
100         Add(I);
101     }
102     
103     // Remove - remove I from the worklist if it exists.
104     void Remove(Instruction *I) {
105       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
106       if (It == WorklistMap.end()) return; // Not in worklist.
107       
108       // Don't bother moving everything down, just null out the slot.
109       Worklist[It->second] = 0;
110       
111       WorklistMap.erase(It);
112     }
113     
114     Instruction *RemoveOne() {
115       Instruction *I = Worklist.back();
116       Worklist.pop_back();
117       WorklistMap.erase(I);
118       return I;
119     }
120
121     /// AddUsersToWorkList - When an instruction is simplified, add all users of
122     /// the instruction to the work lists because they might get more simplified
123     /// now.
124     ///
125     void AddUsersToWorkList(Instruction &I) {
126       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
127            UI != UE; ++UI)
128         Add(cast<Instruction>(*UI));
129     }
130     
131     
132     /// Zap - check that the worklist is empty and nuke the backing store for
133     /// the map if it is large.
134     void Zap() {
135       assert(WorklistMap.empty() && "Worklist empty, but map not?");
136       
137       // Do an explicit clear, this shrinks the map if needed.
138       WorklistMap.clear();
139     }
140   };
141 } // end anonymous namespace.
142
143
144 namespace {
145   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
146   /// just like the normal insertion helper, but also adds any new instructions
147   /// to the instcombine worklist.
148   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
149     InstCombineWorklist &Worklist;
150   public:
151     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
152     
153     void InsertHelper(Instruction *I, const Twine &Name,
154                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
155       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
156       Worklist.Add(I);
157     }
158   };
159 } // end anonymous namespace
160
161
162 namespace {
163   class InstCombiner : public FunctionPass,
164                        public InstVisitor<InstCombiner, Instruction*> {
165     TargetData *TD;
166     bool MustPreserveLCSSA;
167     bool MadeIRChange;
168   public:
169     /// Worklist - All of the instructions that need to be simplified.
170     InstCombineWorklist Worklist;
171
172     /// Builder - This is an IRBuilder that automatically inserts new
173     /// instructions into the worklist when they are created.
174     typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
175     BuilderTy *Builder;
176         
177     static char ID; // Pass identification, replacement for typeid
178     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
179
180     LLVMContext *Context;
181     LLVMContext *getContext() const { return Context; }
182
183   public:
184     virtual bool runOnFunction(Function &F);
185     
186     bool DoOneIteration(Function &F, unsigned ItNum);
187
188     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
189       AU.addPreservedID(LCSSAID);
190       AU.setPreservesCFG();
191     }
192
193     TargetData *getTargetData() const { return TD; }
194
195     // Visitation implementation - Implement instruction combining for different
196     // instruction types.  The semantics are as follows:
197     // Return Value:
198     //    null        - No change was made
199     //     I          - Change was made, I is still valid, I may be dead though
200     //   otherwise    - Change was made, replace I with returned instruction
201     //
202     Instruction *visitAdd(BinaryOperator &I);
203     Instruction *visitFAdd(BinaryOperator &I);
204     Instruction *visitSub(BinaryOperator &I);
205     Instruction *visitFSub(BinaryOperator &I);
206     Instruction *visitMul(BinaryOperator &I);
207     Instruction *visitFMul(BinaryOperator &I);
208     Instruction *visitURem(BinaryOperator &I);
209     Instruction *visitSRem(BinaryOperator &I);
210     Instruction *visitFRem(BinaryOperator &I);
211     bool SimplifyDivRemOfSelect(BinaryOperator &I);
212     Instruction *commonRemTransforms(BinaryOperator &I);
213     Instruction *commonIRemTransforms(BinaryOperator &I);
214     Instruction *commonDivTransforms(BinaryOperator &I);
215     Instruction *commonIDivTransforms(BinaryOperator &I);
216     Instruction *visitUDiv(BinaryOperator &I);
217     Instruction *visitSDiv(BinaryOperator &I);
218     Instruction *visitFDiv(BinaryOperator &I);
219     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
220     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
221     Instruction *visitAnd(BinaryOperator &I);
222     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
223     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
224     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
225                                      Value *A, Value *B, Value *C);
226     Instruction *visitOr (BinaryOperator &I);
227     Instruction *visitXor(BinaryOperator &I);
228     Instruction *visitShl(BinaryOperator &I);
229     Instruction *visitAShr(BinaryOperator &I);
230     Instruction *visitLShr(BinaryOperator &I);
231     Instruction *commonShiftTransforms(BinaryOperator &I);
232     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
233                                       Constant *RHSC);
234     Instruction *visitFCmpInst(FCmpInst &I);
235     Instruction *visitICmpInst(ICmpInst &I);
236     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
237     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
238                                                 Instruction *LHS,
239                                                 ConstantInt *RHS);
240     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
241                                 ConstantInt *DivRHS);
242
243     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
244                              ICmpInst::Predicate Cond, Instruction &I);
245     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
246                                      BinaryOperator &I);
247     Instruction *commonCastTransforms(CastInst &CI);
248     Instruction *commonIntCastTransforms(CastInst &CI);
249     Instruction *commonPointerCastTransforms(CastInst &CI);
250     Instruction *visitTrunc(TruncInst &CI);
251     Instruction *visitZExt(ZExtInst &CI);
252     Instruction *visitSExt(SExtInst &CI);
253     Instruction *visitFPTrunc(FPTruncInst &CI);
254     Instruction *visitFPExt(CastInst &CI);
255     Instruction *visitFPToUI(FPToUIInst &FI);
256     Instruction *visitFPToSI(FPToSIInst &FI);
257     Instruction *visitUIToFP(CastInst &CI);
258     Instruction *visitSIToFP(CastInst &CI);
259     Instruction *visitPtrToInt(PtrToIntInst &CI);
260     Instruction *visitIntToPtr(IntToPtrInst &CI);
261     Instruction *visitBitCast(BitCastInst &CI);
262     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
263                                 Instruction *FI);
264     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
265     Instruction *visitSelectInst(SelectInst &SI);
266     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
267     Instruction *visitCallInst(CallInst &CI);
268     Instruction *visitInvokeInst(InvokeInst &II);
269     Instruction *visitPHINode(PHINode &PN);
270     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
271     Instruction *visitAllocationInst(AllocationInst &AI);
272     Instruction *visitFreeInst(FreeInst &FI);
273     Instruction *visitLoadInst(LoadInst &LI);
274     Instruction *visitStoreInst(StoreInst &SI);
275     Instruction *visitBranchInst(BranchInst &BI);
276     Instruction *visitSwitchInst(SwitchInst &SI);
277     Instruction *visitInsertElementInst(InsertElementInst &IE);
278     Instruction *visitExtractElementInst(ExtractElementInst &EI);
279     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
280     Instruction *visitExtractValueInst(ExtractValueInst &EV);
281
282     // visitInstruction - Specify what to return for unhandled instructions...
283     Instruction *visitInstruction(Instruction &I) { return 0; }
284
285   private:
286     Instruction *visitCallSite(CallSite CS);
287     bool transformConstExprCastCall(CallSite CS);
288     Instruction *transformCallThroughTrampoline(CallSite CS);
289     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290                                    bool DoXform = true);
291     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
292     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
293
294
295   public:
296     // InsertNewInstBefore - insert an instruction New before instruction Old
297     // in the program.  Add the new instruction to the worklist.
298     //
299     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
300       assert(New && New->getParent() == 0 &&
301              "New instruction already inserted into a basic block!");
302       BasicBlock *BB = Old.getParent();
303       BB->getInstList().insert(&Old, New);  // Insert inst
304       Worklist.Add(New);
305       return New;
306     }
307         
308     // ReplaceInstUsesWith - This method is to be used when an instruction is
309     // found to be dead, replacable with another preexisting expression.  Here
310     // we add all uses of I to the worklist, replace all uses of I with the new
311     // value, then return I, so that the inst combiner will know that I was
312     // modified.
313     //
314     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
315       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
316       
317       // If we are replacing the instruction with itself, this must be in a
318       // segment of unreachable code, so just clobber the instruction.
319       if (&I == V) 
320         V = UndefValue::get(I.getType());
321         
322       I.replaceAllUsesWith(V);
323       return &I;
324     }
325
326     // EraseInstFromFunction - When dealing with an instruction that has side
327     // effects or produces a void value, we can't rely on DCE to delete the
328     // instruction.  Instead, visit methods should return the value returned by
329     // this function.
330     Instruction *EraseInstFromFunction(Instruction &I) {
331       DEBUG(errs() << "IC: ERASE " << I << '\n');
332
333       assert(I.use_empty() && "Cannot erase instruction that is used!");
334       // Make sure that we reprocess all operands now that we reduced their
335       // use counts.
336       if (I.getNumOperands() < 8) {
337         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
338           if (Instruction *Op = dyn_cast<Instruction>(*i))
339             Worklist.Add(Op);
340       }
341       Worklist.Remove(&I);
342       I.eraseFromParent();
343       MadeIRChange = true;
344       return 0;  // Don't do anything with FI
345     }
346         
347     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
348                            APInt &KnownOne, unsigned Depth = 0) const {
349       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
350     }
351     
352     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
353                            unsigned Depth = 0) const {
354       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
355     }
356     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
357       return llvm::ComputeNumSignBits(Op, TD, Depth);
358     }
359
360   private:
361
362     /// SimplifyCommutative - This performs a few simplifications for 
363     /// commutative operators.
364     bool SimplifyCommutative(BinaryOperator &I);
365
366     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
367     /// most-complex to least-complex order.
368     bool SimplifyCompare(CmpInst &I);
369
370     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
371     /// based on the demanded bits.
372     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
373                                    APInt& KnownZero, APInt& KnownOne,
374                                    unsigned Depth);
375     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
376                               APInt& KnownZero, APInt& KnownOne,
377                               unsigned Depth=0);
378         
379     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
380     /// SimplifyDemandedBits knows about.  See if the instruction has any
381     /// properties that allow us to simplify its operands.
382     bool SimplifyDemandedInstructionBits(Instruction &Inst);
383         
384     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
385                                       APInt& UndefElts, unsigned Depth = 0);
386       
387     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
388     // which has a PHI node as operand #0, see if we can fold the instruction
389     // into the PHI (which is only possible if all operands to the PHI are
390     // constants).
391     //
392     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
393     // that would normally be unprofitable because they strongly encourage jump
394     // threading.
395     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
396
397     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
398     // operator and they all are only used by the PHI, PHI together their
399     // inputs, and do the operation once, to the result of the PHI.
400     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
401     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
402     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
403
404     
405     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
406                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
407     
408     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
409                               bool isSub, Instruction &I);
410     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
411                                  bool isSigned, bool Inside, Instruction &IB);
412     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
413     Instruction *MatchBSwap(BinaryOperator &I);
414     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
415     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
416     Instruction *SimplifyMemSet(MemSetInst *MI);
417
418
419     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
420
421     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
422                                     unsigned CastOpc, int &NumCastsRemoved);
423     unsigned GetOrEnforceKnownAlignment(Value *V,
424                                         unsigned PrefAlign = 0);
425
426   };
427 } // end anonymous namespace
428
429 char InstCombiner::ID = 0;
430 static RegisterPass<InstCombiner>
431 X("instcombine", "Combine redundant instructions");
432
433 // getComplexity:  Assign a complexity or rank value to LLVM Values...
434 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
435 static unsigned getComplexity(Value *V) {
436   if (isa<Instruction>(V)) {
437     if (BinaryOperator::isNeg(V) ||
438         BinaryOperator::isFNeg(V) ||
439         BinaryOperator::isNot(V))
440       return 3;
441     return 4;
442   }
443   if (isa<Argument>(V)) return 3;
444   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
445 }
446
447 // isOnlyUse - Return true if this instruction will be deleted if we stop using
448 // it.
449 static bool isOnlyUse(Value *V) {
450   return V->hasOneUse() || isa<Constant>(V);
451 }
452
453 // getPromotedType - Return the specified type promoted as it would be to pass
454 // though a va_arg area...
455 static const Type *getPromotedType(const Type *Ty) {
456   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
457     if (ITy->getBitWidth() < 32)
458       return Type::getInt32Ty(Ty->getContext());
459   }
460   return Ty;
461 }
462
463 /// getBitCastOperand - If the specified operand is a CastInst, a constant
464 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
465 /// operand value, otherwise return null.
466 static Value *getBitCastOperand(Value *V) {
467   if (Operator *O = dyn_cast<Operator>(V)) {
468     if (O->getOpcode() == Instruction::BitCast)
469       return O->getOperand(0);
470     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
471       if (GEP->hasAllZeroIndices())
472         return GEP->getPointerOperand();
473   }
474   return 0;
475 }
476
477 /// This function is a wrapper around CastInst::isEliminableCastPair. It
478 /// simply extracts arguments and returns what that function returns.
479 static Instruction::CastOps 
480 isEliminableCastPair(
481   const CastInst *CI, ///< The first cast instruction
482   unsigned opcode,       ///< The opcode of the second cast instruction
483   const Type *DstTy,     ///< The target type for the second cast instruction
484   TargetData *TD         ///< The target data for pointer size
485 ) {
486
487   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
488   const Type *MidTy = CI->getType();                  // B from above
489
490   // Get the opcodes of the two Cast instructions
491   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
492   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
493
494   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
495                                                 DstTy,
496                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
497   
498   // We don't want to form an inttoptr or ptrtoint that converts to an integer
499   // type that differs from the pointer size.
500   if ((Res == Instruction::IntToPtr &&
501           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
502       (Res == Instruction::PtrToInt &&
503           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
504     Res = 0;
505   
506   return Instruction::CastOps(Res);
507 }
508
509 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
510 /// in any code being generated.  It does not require codegen if V is simple
511 /// enough or if the cast can be folded into other casts.
512 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
513                               const Type *Ty, TargetData *TD) {
514   if (V->getType() == Ty || isa<Constant>(V)) return false;
515   
516   // If this is another cast that can be eliminated, it isn't codegen either.
517   if (const CastInst *CI = dyn_cast<CastInst>(V))
518     if (isEliminableCastPair(CI, opcode, Ty, TD))
519       return false;
520   return true;
521 }
522
523 // SimplifyCommutative - This performs a few simplifications for commutative
524 // operators:
525 //
526 //  1. Order operands such that they are listed from right (least complex) to
527 //     left (most complex).  This puts constants before unary operators before
528 //     binary operators.
529 //
530 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
531 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532 //
533 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
534   bool Changed = false;
535   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
536     Changed = !I.swapOperands();
537
538   if (!I.isAssociative()) return Changed;
539   Instruction::BinaryOps Opcode = I.getOpcode();
540   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
541     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
542       if (isa<Constant>(I.getOperand(1))) {
543         Constant *Folded = ConstantExpr::get(I.getOpcode(),
544                                              cast<Constant>(I.getOperand(1)),
545                                              cast<Constant>(Op->getOperand(1)));
546         I.setOperand(0, Op->getOperand(0));
547         I.setOperand(1, Folded);
548         return true;
549       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
550         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
551             isOnlyUse(Op) && isOnlyUse(Op1)) {
552           Constant *C1 = cast<Constant>(Op->getOperand(1));
553           Constant *C2 = cast<Constant>(Op1->getOperand(1));
554
555           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
556           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
557           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
558                                                     Op1->getOperand(0),
559                                                     Op1->getName(), &I);
560           Worklist.Add(New);
561           I.setOperand(0, New);
562           I.setOperand(1, Folded);
563           return true;
564         }
565     }
566   return Changed;
567 }
568
569 /// SimplifyCompare - For a CmpInst this function just orders the operands
570 /// so that theyare listed from right (least complex) to left (most complex).
571 /// This puts constants before unary operators before binary operators.
572 bool InstCombiner::SimplifyCompare(CmpInst &I) {
573   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
574     return false;
575   I.swapOperands();
576   // Compare instructions are not associative so there's nothing else we can do.
577   return true;
578 }
579
580 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
581 // if the LHS is a constant zero (which is the 'negate' form).
582 //
583 static inline Value *dyn_castNegVal(Value *V) {
584   if (BinaryOperator::isNeg(V))
585     return BinaryOperator::getNegArgument(V);
586
587   // Constants can be considered to be negated values if they can be folded.
588   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
589     return ConstantExpr::getNeg(C);
590
591   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
592     if (C->getType()->getElementType()->isInteger())
593       return ConstantExpr::getNeg(C);
594
595   return 0;
596 }
597
598 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
599 // instruction if the LHS is a constant negative zero (which is the 'negate'
600 // form).
601 //
602 static inline Value *dyn_castFNegVal(Value *V) {
603   if (BinaryOperator::isFNeg(V))
604     return BinaryOperator::getFNegArgument(V);
605
606   // Constants can be considered to be negated values if they can be folded.
607   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
608     return ConstantExpr::getFNeg(C);
609
610   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
611     if (C->getType()->getElementType()->isFloatingPoint())
612       return ConstantExpr::getFNeg(C);
613
614   return 0;
615 }
616
617 static inline Value *dyn_castNotVal(Value *V) {
618   if (BinaryOperator::isNot(V))
619     return BinaryOperator::getNotArgument(V);
620
621   // Constants can be considered to be not'ed values...
622   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
623     return ConstantInt::get(C->getType(), ~C->getValue());
624   return 0;
625 }
626
627 // dyn_castFoldableMul - If this value is a multiply that can be folded into
628 // other computations (because it has a constant operand), return the
629 // non-constant operand of the multiply, and set CST to point to the multiplier.
630 // Otherwise, return null.
631 //
632 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
633   if (V->hasOneUse() && V->getType()->isInteger())
634     if (Instruction *I = dyn_cast<Instruction>(V)) {
635       if (I->getOpcode() == Instruction::Mul)
636         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
637           return I->getOperand(0);
638       if (I->getOpcode() == Instruction::Shl)
639         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
640           // The multiplier is really 1 << CST.
641           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
642           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
643           CST = ConstantInt::get(V->getType()->getContext(),
644                                  APInt(BitWidth, 1).shl(CSTVal));
645           return I->getOperand(0);
646         }
647     }
648   return 0;
649 }
650
651 /// AddOne - Add one to a ConstantInt
652 static Constant *AddOne(Constant *C) {
653   return ConstantExpr::getAdd(C, 
654     ConstantInt::get(C->getType(), 1));
655 }
656 /// SubOne - Subtract one from a ConstantInt
657 static Constant *SubOne(ConstantInt *C) {
658   return ConstantExpr::getSub(C, 
659     ConstantInt::get(C->getType(), 1));
660 }
661 /// MultiplyOverflows - True if the multiply can not be expressed in an int
662 /// this size.
663 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
664   uint32_t W = C1->getBitWidth();
665   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
666   if (sign) {
667     LHSExt.sext(W * 2);
668     RHSExt.sext(W * 2);
669   } else {
670     LHSExt.zext(W * 2);
671     RHSExt.zext(W * 2);
672   }
673
674   APInt MulExt = LHSExt * RHSExt;
675
676   if (sign) {
677     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
678     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
679     return MulExt.slt(Min) || MulExt.sgt(Max);
680   } else 
681     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
682 }
683
684
685 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
686 /// specified instruction is a constant integer.  If so, check to see if there
687 /// are any bits set in the constant that are not demanded.  If so, shrink the
688 /// constant and return true.
689 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
690                                    APInt Demanded) {
691   assert(I && "No instruction?");
692   assert(OpNo < I->getNumOperands() && "Operand index too large");
693
694   // If the operand is not a constant integer, nothing to do.
695   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
696   if (!OpC) return false;
697
698   // If there are no bits set that aren't demanded, nothing to do.
699   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
700   if ((~Demanded & OpC->getValue()) == 0)
701     return false;
702
703   // This instruction is producing bits that are not demanded. Shrink the RHS.
704   Demanded &= OpC->getValue();
705   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
706   return true;
707 }
708
709 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
710 // set of known zero and one bits, compute the maximum and minimum values that
711 // could have the specified known zero and known one bits, returning them in
712 // min/max.
713 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
714                                                    const APInt& KnownOne,
715                                                    APInt& Min, APInt& Max) {
716   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
717          KnownZero.getBitWidth() == Min.getBitWidth() &&
718          KnownZero.getBitWidth() == Max.getBitWidth() &&
719          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
720   APInt UnknownBits = ~(KnownZero|KnownOne);
721
722   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723   // bit if it is unknown.
724   Min = KnownOne;
725   Max = KnownOne|UnknownBits;
726   
727   if (UnknownBits.isNegative()) { // Sign bit is unknown
728     Min.set(Min.getBitWidth()-1);
729     Max.clear(Max.getBitWidth()-1);
730   }
731 }
732
733 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734 // a set of known zero and one bits, compute the maximum and minimum values that
735 // could have the specified known zero and known one bits, returning them in
736 // min/max.
737 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
738                                                      const APInt &KnownOne,
739                                                      APInt &Min, APInt &Max) {
740   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
741          KnownZero.getBitWidth() == Min.getBitWidth() &&
742          KnownZero.getBitWidth() == Max.getBitWidth() &&
743          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
744   APInt UnknownBits = ~(KnownZero|KnownOne);
745   
746   // The minimum value is when the unknown bits are all zeros.
747   Min = KnownOne;
748   // The maximum value is when the unknown bits are all ones.
749   Max = KnownOne|UnknownBits;
750 }
751
752 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
753 /// SimplifyDemandedBits knows about.  See if the instruction has any
754 /// properties that allow us to simplify its operands.
755 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
756   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
757   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
758   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
759   
760   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
761                                      KnownZero, KnownOne, 0);
762   if (V == 0) return false;
763   if (V == &Inst) return true;
764   ReplaceInstUsesWith(Inst, V);
765   return true;
766 }
767
768 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
769 /// specified instruction operand if possible, updating it in place.  It returns
770 /// true if it made any change and false otherwise.
771 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
772                                         APInt &KnownZero, APInt &KnownOne,
773                                         unsigned Depth) {
774   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
775                                           KnownZero, KnownOne, Depth);
776   if (NewVal == 0) return false;
777   U.set(NewVal);
778   return true;
779 }
780
781
782 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
783 /// value based on the demanded bits.  When this function is called, it is known
784 /// that only the bits set in DemandedMask of the result of V are ever used
785 /// downstream. Consequently, depending on the mask and V, it may be possible
786 /// to replace V with a constant or one of its operands. In such cases, this
787 /// function does the replacement and returns true. In all other cases, it
788 /// returns false after analyzing the expression and setting KnownOne and known
789 /// to be one in the expression.  KnownZero contains all the bits that are known
790 /// to be zero in the expression. These are provided to potentially allow the
791 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
792 /// the expression. KnownOne and KnownZero always follow the invariant that 
793 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
794 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
795 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
796 /// and KnownOne must all be the same.
797 ///
798 /// This returns null if it did not change anything and it permits no
799 /// simplification.  This returns V itself if it did some simplification of V's
800 /// operands based on the information about what bits are demanded. This returns
801 /// some other non-null value if it found out that V is equal to another value
802 /// in the context where the specified bits are demanded, but not for all users.
803 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
804                                              APInt &KnownZero, APInt &KnownOne,
805                                              unsigned Depth) {
806   assert(V != 0 && "Null pointer of Value???");
807   assert(Depth <= 6 && "Limit Search Depth");
808   uint32_t BitWidth = DemandedMask.getBitWidth();
809   const Type *VTy = V->getType();
810   assert((TD || !isa<PointerType>(VTy)) &&
811          "SimplifyDemandedBits needs to know bit widths!");
812   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
813          (!VTy->isIntOrIntVector() ||
814           VTy->getScalarSizeInBits() == BitWidth) &&
815          KnownZero.getBitWidth() == BitWidth &&
816          KnownOne.getBitWidth() == BitWidth &&
817          "Value *V, DemandedMask, KnownZero and KnownOne "
818          "must have same BitWidth");
819   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
820     // We know all of the bits for a constant!
821     KnownOne = CI->getValue() & DemandedMask;
822     KnownZero = ~KnownOne & DemandedMask;
823     return 0;
824   }
825   if (isa<ConstantPointerNull>(V)) {
826     // We know all of the bits for a constant!
827     KnownOne.clear();
828     KnownZero = DemandedMask;
829     return 0;
830   }
831
832   KnownZero.clear();
833   KnownOne.clear();
834   if (DemandedMask == 0) {   // Not demanding any bits from V.
835     if (isa<UndefValue>(V))
836       return 0;
837     return UndefValue::get(VTy);
838   }
839   
840   if (Depth == 6)        // Limit search depth.
841     return 0;
842   
843   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
844   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
845
846   Instruction *I = dyn_cast<Instruction>(V);
847   if (!I) {
848     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
849     return 0;        // Only analyze instructions.
850   }
851
852   // If there are multiple uses of this value and we aren't at the root, then
853   // we can't do any simplifications of the operands, because DemandedMask
854   // only reflects the bits demanded by *one* of the users.
855   if (Depth != 0 && !I->hasOneUse()) {
856     // Despite the fact that we can't simplify this instruction in all User's
857     // context, we can at least compute the knownzero/knownone bits, and we can
858     // do simplifications that apply to *just* the one user if we know that
859     // this instruction has a simpler value in that context.
860     if (I->getOpcode() == Instruction::And) {
861       // If either the LHS or the RHS are Zero, the result is zero.
862       ComputeMaskedBits(I->getOperand(1), DemandedMask,
863                         RHSKnownZero, RHSKnownOne, Depth+1);
864       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
865                         LHSKnownZero, LHSKnownOne, Depth+1);
866       
867       // If all of the demanded bits are known 1 on one side, return the other.
868       // These bits cannot contribute to the result of the 'and' in this
869       // context.
870       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
871           (DemandedMask & ~LHSKnownZero))
872         return I->getOperand(0);
873       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
874           (DemandedMask & ~RHSKnownZero))
875         return I->getOperand(1);
876       
877       // If all of the demanded bits in the inputs are known zeros, return zero.
878       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
879         return Constant::getNullValue(VTy);
880       
881     } else if (I->getOpcode() == Instruction::Or) {
882       // We can simplify (X|Y) -> X or Y in the user's context if we know that
883       // only bits from X or Y are demanded.
884       
885       // If either the LHS or the RHS are One, the result is One.
886       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
887                         RHSKnownZero, RHSKnownOne, Depth+1);
888       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
889                         LHSKnownZero, LHSKnownOne, Depth+1);
890       
891       // If all of the demanded bits are known zero on one side, return the
892       // other.  These bits cannot contribute to the result of the 'or' in this
893       // context.
894       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
895           (DemandedMask & ~LHSKnownOne))
896         return I->getOperand(0);
897       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
898           (DemandedMask & ~RHSKnownOne))
899         return I->getOperand(1);
900       
901       // If all of the potentially set bits on one side are known to be set on
902       // the other side, just use the 'other' side.
903       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
904           (DemandedMask & (~RHSKnownZero)))
905         return I->getOperand(0);
906       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
907           (DemandedMask & (~LHSKnownZero)))
908         return I->getOperand(1);
909     }
910     
911     // Compute the KnownZero/KnownOne bits to simplify things downstream.
912     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
913     return 0;
914   }
915   
916   // If this is the root being simplified, allow it to have multiple uses,
917   // just set the DemandedMask to all bits so that we can try to simplify the
918   // operands.  This allows visitTruncInst (for example) to simplify the
919   // operand of a trunc without duplicating all the logic below.
920   if (Depth == 0 && !V->hasOneUse())
921     DemandedMask = APInt::getAllOnesValue(BitWidth);
922   
923   switch (I->getOpcode()) {
924   default:
925     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
926     break;
927   case Instruction::And:
928     // If either the LHS or the RHS are Zero, the result is zero.
929     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
930                              RHSKnownZero, RHSKnownOne, Depth+1) ||
931         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
932                              LHSKnownZero, LHSKnownOne, Depth+1))
933       return I;
934     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
935     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
936
937     // If all of the demanded bits are known 1 on one side, return the other.
938     // These bits cannot contribute to the result of the 'and'.
939     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
940         (DemandedMask & ~LHSKnownZero))
941       return I->getOperand(0);
942     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
943         (DemandedMask & ~RHSKnownZero))
944       return I->getOperand(1);
945     
946     // If all of the demanded bits in the inputs are known zeros, return zero.
947     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
948       return Constant::getNullValue(VTy);
949       
950     // If the RHS is a constant, see if we can simplify it.
951     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
952       return I;
953       
954     // Output known-1 bits are only known if set in both the LHS & RHS.
955     RHSKnownOne &= LHSKnownOne;
956     // Output known-0 are known to be clear if zero in either the LHS | RHS.
957     RHSKnownZero |= LHSKnownZero;
958     break;
959   case Instruction::Or:
960     // If either the LHS or the RHS are One, the result is One.
961     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
962                              RHSKnownZero, RHSKnownOne, Depth+1) ||
963         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
964                              LHSKnownZero, LHSKnownOne, Depth+1))
965       return I;
966     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
967     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
968     
969     // If all of the demanded bits are known zero on one side, return the other.
970     // These bits cannot contribute to the result of the 'or'.
971     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
972         (DemandedMask & ~LHSKnownOne))
973       return I->getOperand(0);
974     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
975         (DemandedMask & ~RHSKnownOne))
976       return I->getOperand(1);
977
978     // If all of the potentially set bits on one side are known to be set on
979     // the other side, just use the 'other' side.
980     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
981         (DemandedMask & (~RHSKnownZero)))
982       return I->getOperand(0);
983     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
984         (DemandedMask & (~LHSKnownZero)))
985       return I->getOperand(1);
986         
987     // If the RHS is a constant, see if we can simplify it.
988     if (ShrinkDemandedConstant(I, 1, DemandedMask))
989       return I;
990           
991     // Output known-0 bits are only known if clear in both the LHS & RHS.
992     RHSKnownZero &= LHSKnownZero;
993     // Output known-1 are known to be set if set in either the LHS | RHS.
994     RHSKnownOne |= LHSKnownOne;
995     break;
996   case Instruction::Xor: {
997     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
998                              RHSKnownZero, RHSKnownOne, Depth+1) ||
999         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1000                              LHSKnownZero, LHSKnownOne, Depth+1))
1001       return I;
1002     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1003     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1004     
1005     // If all of the demanded bits are known zero on one side, return the other.
1006     // These bits cannot contribute to the result of the 'xor'.
1007     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1008       return I->getOperand(0);
1009     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1010       return I->getOperand(1);
1011     
1012     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1013     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1014                          (RHSKnownOne & LHSKnownOne);
1015     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1016     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1017                         (RHSKnownOne & LHSKnownZero);
1018     
1019     // If all of the demanded bits are known to be zero on one side or the
1020     // other, turn this into an *inclusive* or.
1021     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1022     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1023       Instruction *Or = 
1024         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1025                                  I->getName());
1026       return InsertNewInstBefore(Or, *I);
1027     }
1028     
1029     // If all of the demanded bits on one side are known, and all of the set
1030     // bits on that side are also known to be set on the other side, turn this
1031     // into an AND, as we know the bits will be cleared.
1032     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1033     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1034       // all known
1035       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1036         Constant *AndC = Constant::getIntegerValue(VTy,
1037                                                    ~RHSKnownOne & DemandedMask);
1038         Instruction *And = 
1039           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1040         return InsertNewInstBefore(And, *I);
1041       }
1042     }
1043     
1044     // If the RHS is a constant, see if we can simplify it.
1045     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1046     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1047       return I;
1048     
1049     RHSKnownZero = KnownZeroOut;
1050     RHSKnownOne  = KnownOneOut;
1051     break;
1052   }
1053   case Instruction::Select:
1054     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1055                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1056         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1057                              LHSKnownZero, LHSKnownOne, Depth+1))
1058       return I;
1059     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1060     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1061     
1062     // If the operands are constants, see if we can simplify them.
1063     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1064         ShrinkDemandedConstant(I, 2, DemandedMask))
1065       return I;
1066     
1067     // Only known if known in both the LHS and RHS.
1068     RHSKnownOne &= LHSKnownOne;
1069     RHSKnownZero &= LHSKnownZero;
1070     break;
1071   case Instruction::Trunc: {
1072     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1073     DemandedMask.zext(truncBf);
1074     RHSKnownZero.zext(truncBf);
1075     RHSKnownOne.zext(truncBf);
1076     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1077                              RHSKnownZero, RHSKnownOne, Depth+1))
1078       return I;
1079     DemandedMask.trunc(BitWidth);
1080     RHSKnownZero.trunc(BitWidth);
1081     RHSKnownOne.trunc(BitWidth);
1082     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1083     break;
1084   }
1085   case Instruction::BitCast:
1086     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1087       return false;  // vector->int or fp->int?
1088
1089     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1090       if (const VectorType *SrcVTy =
1091             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1092         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1093           // Don't touch a bitcast between vectors of different element counts.
1094           return false;
1095       } else
1096         // Don't touch a scalar-to-vector bitcast.
1097         return false;
1098     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1099       // Don't touch a vector-to-scalar bitcast.
1100       return false;
1101
1102     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103                              RHSKnownZero, RHSKnownOne, Depth+1))
1104       return I;
1105     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1106     break;
1107   case Instruction::ZExt: {
1108     // Compute the bits in the result that are not present in the input.
1109     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1110     
1111     DemandedMask.trunc(SrcBitWidth);
1112     RHSKnownZero.trunc(SrcBitWidth);
1113     RHSKnownOne.trunc(SrcBitWidth);
1114     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1115                              RHSKnownZero, RHSKnownOne, Depth+1))
1116       return I;
1117     DemandedMask.zext(BitWidth);
1118     RHSKnownZero.zext(BitWidth);
1119     RHSKnownOne.zext(BitWidth);
1120     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1121     // The top bits are known to be zero.
1122     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1123     break;
1124   }
1125   case Instruction::SExt: {
1126     // Compute the bits in the result that are not present in the input.
1127     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1128     
1129     APInt InputDemandedBits = DemandedMask & 
1130                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1131
1132     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1133     // If any of the sign extended bits are demanded, we know that the sign
1134     // bit is demanded.
1135     if ((NewBits & DemandedMask) != 0)
1136       InputDemandedBits.set(SrcBitWidth-1);
1137       
1138     InputDemandedBits.trunc(SrcBitWidth);
1139     RHSKnownZero.trunc(SrcBitWidth);
1140     RHSKnownOne.trunc(SrcBitWidth);
1141     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1142                              RHSKnownZero, RHSKnownOne, Depth+1))
1143       return I;
1144     InputDemandedBits.zext(BitWidth);
1145     RHSKnownZero.zext(BitWidth);
1146     RHSKnownOne.zext(BitWidth);
1147     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1148       
1149     // If the sign bit of the input is known set or clear, then we know the
1150     // top bits of the result.
1151
1152     // If the input sign bit is known zero, or if the NewBits are not demanded
1153     // convert this into a zero extension.
1154     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1155       // Convert to ZExt cast
1156       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1157       return InsertNewInstBefore(NewCast, *I);
1158     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1159       RHSKnownOne |= NewBits;
1160     }
1161     break;
1162   }
1163   case Instruction::Add: {
1164     // Figure out what the input bits are.  If the top bits of the and result
1165     // are not demanded, then the add doesn't demand them from its input
1166     // either.
1167     unsigned NLZ = DemandedMask.countLeadingZeros();
1168       
1169     // If there is a constant on the RHS, there are a variety of xformations
1170     // we can do.
1171     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172       // If null, this should be simplified elsewhere.  Some of the xforms here
1173       // won't work if the RHS is zero.
1174       if (RHS->isZero())
1175         break;
1176       
1177       // If the top bit of the output is demanded, demand everything from the
1178       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1179       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1180
1181       // Find information about known zero/one bits in the input.
1182       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1183                                LHSKnownZero, LHSKnownOne, Depth+1))
1184         return I;
1185
1186       // If the RHS of the add has bits set that can't affect the input, reduce
1187       // the constant.
1188       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1189         return I;
1190       
1191       // Avoid excess work.
1192       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1193         break;
1194       
1195       // Turn it into OR if input bits are zero.
1196       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1197         Instruction *Or =
1198           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1199                                    I->getName());
1200         return InsertNewInstBefore(Or, *I);
1201       }
1202       
1203       // We can say something about the output known-zero and known-one bits,
1204       // depending on potential carries from the input constant and the
1205       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1206       // bits set and the RHS constant is 0x01001, then we know we have a known
1207       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1208       
1209       // To compute this, we first compute the potential carry bits.  These are
1210       // the bits which may be modified.  I'm not aware of a better way to do
1211       // this scan.
1212       const APInt &RHSVal = RHS->getValue();
1213       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1214       
1215       // Now that we know which bits have carries, compute the known-1/0 sets.
1216       
1217       // Bits are known one if they are known zero in one operand and one in the
1218       // other, and there is no input carry.
1219       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1220                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1221       
1222       // Bits are known zero if they are known zero in both operands and there
1223       // is no input carry.
1224       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1225     } else {
1226       // If the high-bits of this ADD are not demanded, then it does not demand
1227       // the high bits of its LHS or RHS.
1228       if (DemandedMask[BitWidth-1] == 0) {
1229         // Right fill the mask of bits for this ADD to demand the most
1230         // significant bit and all those below it.
1231         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1232         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1234             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1235                                  LHSKnownZero, LHSKnownOne, Depth+1))
1236           return I;
1237       }
1238     }
1239     break;
1240   }
1241   case Instruction::Sub:
1242     // If the high-bits of this SUB are not demanded, then it does not demand
1243     // the high bits of its LHS or RHS.
1244     if (DemandedMask[BitWidth-1] == 0) {
1245       // Right fill the mask of bits for this SUB to demand the most
1246       // significant bit and all those below it.
1247       uint32_t NLZ = DemandedMask.countLeadingZeros();
1248       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1249       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1250                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1251           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1252                                LHSKnownZero, LHSKnownOne, Depth+1))
1253         return I;
1254     }
1255     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1256     // the known zeros and ones.
1257     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1258     break;
1259   case Instruction::Shl:
1260     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1261       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1262       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1263       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1264                                RHSKnownZero, RHSKnownOne, Depth+1))
1265         return I;
1266       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1267       RHSKnownZero <<= ShiftAmt;
1268       RHSKnownOne  <<= ShiftAmt;
1269       // low bits known zero.
1270       if (ShiftAmt)
1271         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1272     }
1273     break;
1274   case Instruction::LShr:
1275     // For a logical shift right
1276     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1278       
1279       // Unsigned shift right.
1280       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1281       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1282                                RHSKnownZero, RHSKnownOne, Depth+1))
1283         return I;
1284       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1285       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1286       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1287       if (ShiftAmt) {
1288         // Compute the new bits that are at the top now.
1289         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1290         RHSKnownZero |= HighBits;  // high bits known zero.
1291       }
1292     }
1293     break;
1294   case Instruction::AShr:
1295     // If this is an arithmetic shift right and only the low-bit is set, we can
1296     // always convert this into a logical shr, even if the shift amount is
1297     // variable.  The low bit of the shift cannot be an input sign bit unless
1298     // the shift amount is >= the size of the datatype, which is undefined.
1299     if (DemandedMask == 1) {
1300       // Perform the logical shift right.
1301       Instruction *NewVal = BinaryOperator::CreateLShr(
1302                         I->getOperand(0), I->getOperand(1), I->getName());
1303       return InsertNewInstBefore(NewVal, *I);
1304     }    
1305
1306     // If the sign bit is the only bit demanded by this ashr, then there is no
1307     // need to do it, the shift doesn't change the high bit.
1308     if (DemandedMask.isSignBit())
1309       return I->getOperand(0);
1310     
1311     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1312       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1313       
1314       // Signed shift right.
1315       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1316       // If any of the "high bits" are demanded, we should set the sign bit as
1317       // demanded.
1318       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1319         DemandedMaskIn.set(BitWidth-1);
1320       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1321                                RHSKnownZero, RHSKnownOne, Depth+1))
1322         return I;
1323       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1324       // Compute the new bits that are at the top now.
1325       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1326       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1327       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1328         
1329       // Handle the sign bits.
1330       APInt SignBit(APInt::getSignBit(BitWidth));
1331       // Adjust to where it is now in the mask.
1332       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1333         
1334       // If the input sign bit is known to be zero, or if none of the top bits
1335       // are demanded, turn this into an unsigned shift right.
1336       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1337           (HighBits & ~DemandedMask) == HighBits) {
1338         // Perform the logical shift right.
1339         Instruction *NewVal = BinaryOperator::CreateLShr(
1340                           I->getOperand(0), SA, I->getName());
1341         return InsertNewInstBefore(NewVal, *I);
1342       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1343         RHSKnownOne |= HighBits;
1344       }
1345     }
1346     break;
1347   case Instruction::SRem:
1348     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1349       APInt RA = Rem->getValue().abs();
1350       if (RA.isPowerOf2()) {
1351         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1352           return I->getOperand(0);
1353
1354         APInt LowBits = RA - 1;
1355         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1356         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1357                                  LHSKnownZero, LHSKnownOne, Depth+1))
1358           return I;
1359
1360         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1361           LHSKnownZero |= ~LowBits;
1362
1363         KnownZero |= LHSKnownZero & DemandedMask;
1364
1365         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1366       }
1367     }
1368     break;
1369   case Instruction::URem: {
1370     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1371     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1372     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1373                              KnownZero2, KnownOne2, Depth+1) ||
1374         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1375                              KnownZero2, KnownOne2, Depth+1))
1376       return I;
1377
1378     unsigned Leaders = KnownZero2.countLeadingOnes();
1379     Leaders = std::max(Leaders,
1380                        KnownZero2.countLeadingOnes());
1381     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1382     break;
1383   }
1384   case Instruction::Call:
1385     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1386       switch (II->getIntrinsicID()) {
1387       default: break;
1388       case Intrinsic::bswap: {
1389         // If the only bits demanded come from one byte of the bswap result,
1390         // just shift the input byte into position to eliminate the bswap.
1391         unsigned NLZ = DemandedMask.countLeadingZeros();
1392         unsigned NTZ = DemandedMask.countTrailingZeros();
1393           
1394         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1395         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1396         // have 14 leading zeros, round to 8.
1397         NLZ &= ~7;
1398         NTZ &= ~7;
1399         // If we need exactly one byte, we can do this transformation.
1400         if (BitWidth-NLZ-NTZ == 8) {
1401           unsigned ResultBit = NTZ;
1402           unsigned InputBit = BitWidth-NTZ-8;
1403           
1404           // Replace this with either a left or right shift to get the byte into
1405           // the right place.
1406           Instruction *NewVal;
1407           if (InputBit > ResultBit)
1408             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1409                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1410           else
1411             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1412                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1413           NewVal->takeName(I);
1414           return InsertNewInstBefore(NewVal, *I);
1415         }
1416           
1417         // TODO: Could compute known zero/one bits based on the input.
1418         break;
1419       }
1420       }
1421     }
1422     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1423     break;
1424   }
1425   
1426   // If the client is only demanding bits that we know, return the known
1427   // constant.
1428   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1429     return Constant::getIntegerValue(VTy, RHSKnownOne);
1430   return false;
1431 }
1432
1433
1434 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1435 /// any number of elements. DemandedElts contains the set of elements that are
1436 /// actually used by the caller.  This method analyzes which elements of the
1437 /// operand are undef and returns that information in UndefElts.
1438 ///
1439 /// If the information about demanded elements can be used to simplify the
1440 /// operation, the operation is simplified, then the resultant value is
1441 /// returned.  This returns null if no change was made.
1442 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1443                                                 APInt& UndefElts,
1444                                                 unsigned Depth) {
1445   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1446   APInt EltMask(APInt::getAllOnesValue(VWidth));
1447   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1448
1449   if (isa<UndefValue>(V)) {
1450     // If the entire vector is undefined, just return this info.
1451     UndefElts = EltMask;
1452     return 0;
1453   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1454     UndefElts = EltMask;
1455     return UndefValue::get(V->getType());
1456   }
1457
1458   UndefElts = 0;
1459   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1460     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1461     Constant *Undef = UndefValue::get(EltTy);
1462
1463     std::vector<Constant*> Elts;
1464     for (unsigned i = 0; i != VWidth; ++i)
1465       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1466         Elts.push_back(Undef);
1467         UndefElts.set(i);
1468       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1469         Elts.push_back(Undef);
1470         UndefElts.set(i);
1471       } else {                               // Otherwise, defined.
1472         Elts.push_back(CP->getOperand(i));
1473       }
1474
1475     // If we changed the constant, return it.
1476     Constant *NewCP = ConstantVector::get(Elts);
1477     return NewCP != CP ? NewCP : 0;
1478   } else if (isa<ConstantAggregateZero>(V)) {
1479     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1480     // set to undef.
1481     
1482     // Check if this is identity. If so, return 0 since we are not simplifying
1483     // anything.
1484     if (DemandedElts == ((1ULL << VWidth) -1))
1485       return 0;
1486     
1487     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1488     Constant *Zero = Constant::getNullValue(EltTy);
1489     Constant *Undef = UndefValue::get(EltTy);
1490     std::vector<Constant*> Elts;
1491     for (unsigned i = 0; i != VWidth; ++i) {
1492       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1493       Elts.push_back(Elt);
1494     }
1495     UndefElts = DemandedElts ^ EltMask;
1496     return ConstantVector::get(Elts);
1497   }
1498   
1499   // Limit search depth.
1500   if (Depth == 10)
1501     return 0;
1502
1503   // If multiple users are using the root value, procede with
1504   // simplification conservatively assuming that all elements
1505   // are needed.
1506   if (!V->hasOneUse()) {
1507     // Quit if we find multiple users of a non-root value though.
1508     // They'll be handled when it's their turn to be visited by
1509     // the main instcombine process.
1510     if (Depth != 0)
1511       // TODO: Just compute the UndefElts information recursively.
1512       return 0;
1513
1514     // Conservatively assume that all elements are needed.
1515     DemandedElts = EltMask;
1516   }
1517   
1518   Instruction *I = dyn_cast<Instruction>(V);
1519   if (!I) return 0;        // Only analyze instructions.
1520   
1521   bool MadeChange = false;
1522   APInt UndefElts2(VWidth, 0);
1523   Value *TmpV;
1524   switch (I->getOpcode()) {
1525   default: break;
1526     
1527   case Instruction::InsertElement: {
1528     // If this is a variable index, we don't know which element it overwrites.
1529     // demand exactly the same input as we produce.
1530     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1531     if (Idx == 0) {
1532       // Note that we can't propagate undef elt info, because we don't know
1533       // which elt is getting updated.
1534       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1535                                         UndefElts2, Depth+1);
1536       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1537       break;
1538     }
1539     
1540     // If this is inserting an element that isn't demanded, remove this
1541     // insertelement.
1542     unsigned IdxNo = Idx->getZExtValue();
1543     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1544       Worklist.Add(I);
1545       return I->getOperand(0);
1546     }
1547     
1548     // Otherwise, the element inserted overwrites whatever was there, so the
1549     // input demanded set is simpler than the output set.
1550     APInt DemandedElts2 = DemandedElts;
1551     DemandedElts2.clear(IdxNo);
1552     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1553                                       UndefElts, Depth+1);
1554     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1555
1556     // The inserted element is defined.
1557     UndefElts.clear(IdxNo);
1558     break;
1559   }
1560   case Instruction::ShuffleVector: {
1561     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1562     uint64_t LHSVWidth =
1563       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1564     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1565     for (unsigned i = 0; i < VWidth; i++) {
1566       if (DemandedElts[i]) {
1567         unsigned MaskVal = Shuffle->getMaskValue(i);
1568         if (MaskVal != -1u) {
1569           assert(MaskVal < LHSVWidth * 2 &&
1570                  "shufflevector mask index out of range!");
1571           if (MaskVal < LHSVWidth)
1572             LeftDemanded.set(MaskVal);
1573           else
1574             RightDemanded.set(MaskVal - LHSVWidth);
1575         }
1576       }
1577     }
1578
1579     APInt UndefElts4(LHSVWidth, 0);
1580     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1581                                       UndefElts4, Depth+1);
1582     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1583
1584     APInt UndefElts3(LHSVWidth, 0);
1585     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1586                                       UndefElts3, Depth+1);
1587     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1588
1589     bool NewUndefElts = false;
1590     for (unsigned i = 0; i < VWidth; i++) {
1591       unsigned MaskVal = Shuffle->getMaskValue(i);
1592       if (MaskVal == -1u) {
1593         UndefElts.set(i);
1594       } else if (MaskVal < LHSVWidth) {
1595         if (UndefElts4[MaskVal]) {
1596           NewUndefElts = true;
1597           UndefElts.set(i);
1598         }
1599       } else {
1600         if (UndefElts3[MaskVal - LHSVWidth]) {
1601           NewUndefElts = true;
1602           UndefElts.set(i);
1603         }
1604       }
1605     }
1606
1607     if (NewUndefElts) {
1608       // Add additional discovered undefs.
1609       std::vector<Constant*> Elts;
1610       for (unsigned i = 0; i < VWidth; ++i) {
1611         if (UndefElts[i])
1612           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1613         else
1614           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1615                                           Shuffle->getMaskValue(i)));
1616       }
1617       I->setOperand(2, ConstantVector::get(Elts));
1618       MadeChange = true;
1619     }
1620     break;
1621   }
1622   case Instruction::BitCast: {
1623     // Vector->vector casts only.
1624     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1625     if (!VTy) break;
1626     unsigned InVWidth = VTy->getNumElements();
1627     APInt InputDemandedElts(InVWidth, 0);
1628     unsigned Ratio;
1629
1630     if (VWidth == InVWidth) {
1631       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1632       // elements as are demanded of us.
1633       Ratio = 1;
1634       InputDemandedElts = DemandedElts;
1635     } else if (VWidth > InVWidth) {
1636       // Untested so far.
1637       break;
1638       
1639       // If there are more elements in the result than there are in the source,
1640       // then an input element is live if any of the corresponding output
1641       // elements are live.
1642       Ratio = VWidth/InVWidth;
1643       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1644         if (DemandedElts[OutIdx])
1645           InputDemandedElts.set(OutIdx/Ratio);
1646       }
1647     } else {
1648       // Untested so far.
1649       break;
1650       
1651       // If there are more elements in the source than there are in the result,
1652       // then an input element is live if the corresponding output element is
1653       // live.
1654       Ratio = InVWidth/VWidth;
1655       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1656         if (DemandedElts[InIdx/Ratio])
1657           InputDemandedElts.set(InIdx);
1658     }
1659     
1660     // div/rem demand all inputs, because they don't want divide by zero.
1661     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1662                                       UndefElts2, Depth+1);
1663     if (TmpV) {
1664       I->setOperand(0, TmpV);
1665       MadeChange = true;
1666     }
1667     
1668     UndefElts = UndefElts2;
1669     if (VWidth > InVWidth) {
1670       llvm_unreachable("Unimp");
1671       // If there are more elements in the result than there are in the source,
1672       // then an output element is undef if the corresponding input element is
1673       // undef.
1674       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1675         if (UndefElts2[OutIdx/Ratio])
1676           UndefElts.set(OutIdx);
1677     } else if (VWidth < InVWidth) {
1678       llvm_unreachable("Unimp");
1679       // If there are more elements in the source than there are in the result,
1680       // then a result element is undef if all of the corresponding input
1681       // elements are undef.
1682       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1683       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1684         if (!UndefElts2[InIdx])            // Not undef?
1685           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1686     }
1687     break;
1688   }
1689   case Instruction::And:
1690   case Instruction::Or:
1691   case Instruction::Xor:
1692   case Instruction::Add:
1693   case Instruction::Sub:
1694   case Instruction::Mul:
1695     // div/rem demand all inputs, because they don't want divide by zero.
1696     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1697                                       UndefElts, Depth+1);
1698     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1699     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1700                                       UndefElts2, Depth+1);
1701     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1702       
1703     // Output elements are undefined if both are undefined.  Consider things
1704     // like undef&0.  The result is known zero, not undef.
1705     UndefElts &= UndefElts2;
1706     break;
1707     
1708   case Instruction::Call: {
1709     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1710     if (!II) break;
1711     switch (II->getIntrinsicID()) {
1712     default: break;
1713       
1714     // Binary vector operations that work column-wise.  A dest element is a
1715     // function of the corresponding input elements from the two inputs.
1716     case Intrinsic::x86_sse_sub_ss:
1717     case Intrinsic::x86_sse_mul_ss:
1718     case Intrinsic::x86_sse_min_ss:
1719     case Intrinsic::x86_sse_max_ss:
1720     case Intrinsic::x86_sse2_sub_sd:
1721     case Intrinsic::x86_sse2_mul_sd:
1722     case Intrinsic::x86_sse2_min_sd:
1723     case Intrinsic::x86_sse2_max_sd:
1724       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1725                                         UndefElts, Depth+1);
1726       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1727       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1728                                         UndefElts2, Depth+1);
1729       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1730
1731       // If only the low elt is demanded and this is a scalarizable intrinsic,
1732       // scalarize it now.
1733       if (DemandedElts == 1) {
1734         switch (II->getIntrinsicID()) {
1735         default: break;
1736         case Intrinsic::x86_sse_sub_ss:
1737         case Intrinsic::x86_sse_mul_ss:
1738         case Intrinsic::x86_sse2_sub_sd:
1739         case Intrinsic::x86_sse2_mul_sd:
1740           // TODO: Lower MIN/MAX/ABS/etc
1741           Value *LHS = II->getOperand(1);
1742           Value *RHS = II->getOperand(2);
1743           // Extract the element as scalars.
1744           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1745             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1746           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1747             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1748           
1749           switch (II->getIntrinsicID()) {
1750           default: llvm_unreachable("Case stmts out of sync!");
1751           case Intrinsic::x86_sse_sub_ss:
1752           case Intrinsic::x86_sse2_sub_sd:
1753             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1754                                                         II->getName()), *II);
1755             break;
1756           case Intrinsic::x86_sse_mul_ss:
1757           case Intrinsic::x86_sse2_mul_sd:
1758             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1759                                                          II->getName()), *II);
1760             break;
1761           }
1762           
1763           Instruction *New =
1764             InsertElementInst::Create(
1765               UndefValue::get(II->getType()), TmpV,
1766               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1767           InsertNewInstBefore(New, *II);
1768           return New;
1769         }            
1770       }
1771         
1772       // Output elements are undefined if both are undefined.  Consider things
1773       // like undef&0.  The result is known zero, not undef.
1774       UndefElts &= UndefElts2;
1775       break;
1776     }
1777     break;
1778   }
1779   }
1780   return MadeChange ? I : 0;
1781 }
1782
1783
1784 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1785 /// function is designed to check a chain of associative operators for a
1786 /// potential to apply a certain optimization.  Since the optimization may be
1787 /// applicable if the expression was reassociated, this checks the chain, then
1788 /// reassociates the expression as necessary to expose the optimization
1789 /// opportunity.  This makes use of a special Functor, which must define
1790 /// 'shouldApply' and 'apply' methods.
1791 ///
1792 template<typename Functor>
1793 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1794   unsigned Opcode = Root.getOpcode();
1795   Value *LHS = Root.getOperand(0);
1796
1797   // Quick check, see if the immediate LHS matches...
1798   if (F.shouldApply(LHS))
1799     return F.apply(Root);
1800
1801   // Otherwise, if the LHS is not of the same opcode as the root, return.
1802   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1803   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1804     // Should we apply this transform to the RHS?
1805     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1806
1807     // If not to the RHS, check to see if we should apply to the LHS...
1808     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1809       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1810       ShouldApply = true;
1811     }
1812
1813     // If the functor wants to apply the optimization to the RHS of LHSI,
1814     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1815     if (ShouldApply) {
1816       // Now all of the instructions are in the current basic block, go ahead
1817       // and perform the reassociation.
1818       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1819
1820       // First move the selected RHS to the LHS of the root...
1821       Root.setOperand(0, LHSI->getOperand(1));
1822
1823       // Make what used to be the LHS of the root be the user of the root...
1824       Value *ExtraOperand = TmpLHSI->getOperand(1);
1825       if (&Root == TmpLHSI) {
1826         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1827         return 0;
1828       }
1829       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1830       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1831       BasicBlock::iterator ARI = &Root; ++ARI;
1832       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1833       ARI = Root;
1834
1835       // Now propagate the ExtraOperand down the chain of instructions until we
1836       // get to LHSI.
1837       while (TmpLHSI != LHSI) {
1838         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1839         // Move the instruction to immediately before the chain we are
1840         // constructing to avoid breaking dominance properties.
1841         NextLHSI->moveBefore(ARI);
1842         ARI = NextLHSI;
1843
1844         Value *NextOp = NextLHSI->getOperand(1);
1845         NextLHSI->setOperand(1, ExtraOperand);
1846         TmpLHSI = NextLHSI;
1847         ExtraOperand = NextOp;
1848       }
1849
1850       // Now that the instructions are reassociated, have the functor perform
1851       // the transformation...
1852       return F.apply(Root);
1853     }
1854
1855     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1856   }
1857   return 0;
1858 }
1859
1860 namespace {
1861
1862 // AddRHS - Implements: X + X --> X << 1
1863 struct AddRHS {
1864   Value *RHS;
1865   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1866   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1867   Instruction *apply(BinaryOperator &Add) const {
1868     return BinaryOperator::CreateShl(Add.getOperand(0),
1869                                      ConstantInt::get(Add.getType(), 1));
1870   }
1871 };
1872
1873 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1874 //                 iff C1&C2 == 0
1875 struct AddMaskingAnd {
1876   Constant *C2;
1877   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1878   bool shouldApply(Value *LHS) const {
1879     ConstantInt *C1;
1880     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1881            ConstantExpr::getAnd(C1, C2)->isNullValue();
1882   }
1883   Instruction *apply(BinaryOperator &Add) const {
1884     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1885   }
1886 };
1887
1888 }
1889
1890 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1891                                              InstCombiner *IC) {
1892   if (CastInst *CI = dyn_cast<CastInst>(&I))
1893     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1894
1895   // Figure out if the constant is the left or the right argument.
1896   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1897   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1898
1899   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1900     if (ConstIsRHS)
1901       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1902     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1903   }
1904
1905   Value *Op0 = SO, *Op1 = ConstOperand;
1906   if (!ConstIsRHS)
1907     std::swap(Op0, Op1);
1908   
1909   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1910     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1911                                     SO->getName()+".op");
1912   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1913     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1914                                    SO->getName()+".cmp");
1915   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1916     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1917                                    SO->getName()+".cmp");
1918   llvm_unreachable("Unknown binary instruction type!");
1919 }
1920
1921 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1922 // constant as the other operand, try to fold the binary operator into the
1923 // select arguments.  This also works for Cast instructions, which obviously do
1924 // not have a second operand.
1925 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1926                                      InstCombiner *IC) {
1927   // Don't modify shared select instructions
1928   if (!SI->hasOneUse()) return 0;
1929   Value *TV = SI->getOperand(1);
1930   Value *FV = SI->getOperand(2);
1931
1932   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1933     // Bool selects with constant operands can be folded to logical ops.
1934     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1935
1936     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1937     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1938
1939     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1940                               SelectFalseVal);
1941   }
1942   return 0;
1943 }
1944
1945
1946 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1947 /// has a PHI node as operand #0, see if we can fold the instruction into the
1948 /// PHI (which is only possible if all operands to the PHI are constants).
1949 ///
1950 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1951 /// that would normally be unprofitable because they strongly encourage jump
1952 /// threading.
1953 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1954                                          bool AllowAggressive) {
1955   AllowAggressive = false;
1956   PHINode *PN = cast<PHINode>(I.getOperand(0));
1957   unsigned NumPHIValues = PN->getNumIncomingValues();
1958   if (NumPHIValues == 0 ||
1959       // We normally only transform phis with a single use, unless we're trying
1960       // hard to make jump threading happen.
1961       (!PN->hasOneUse() && !AllowAggressive))
1962     return 0;
1963   
1964   
1965   // Check to see if all of the operands of the PHI are simple constants
1966   // (constantint/constantfp/undef).  If there is one non-constant value,
1967   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
1968   // bail out.  We don't do arbitrary constant expressions here because moving
1969   // their computation can be expensive without a cost model.
1970   BasicBlock *NonConstBB = 0;
1971   for (unsigned i = 0; i != NumPHIValues; ++i)
1972     if (!isa<Constant>(PN->getIncomingValue(i)) ||
1973         isa<ConstantExpr>(PN->getIncomingValue(i))) {
1974       if (NonConstBB) return 0;  // More than one non-const value.
1975       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1976       NonConstBB = PN->getIncomingBlock(i);
1977       
1978       // If the incoming non-constant value is in I's block, we have an infinite
1979       // loop.
1980       if (NonConstBB == I.getParent())
1981         return 0;
1982     }
1983   
1984   // If there is exactly one non-constant value, we can insert a copy of the
1985   // operation in that block.  However, if this is a critical edge, we would be
1986   // inserting the computation one some other paths (e.g. inside a loop).  Only
1987   // do this if the pred block is unconditionally branching into the phi block.
1988   if (NonConstBB != 0 && !AllowAggressive) {
1989     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1990     if (!BI || !BI->isUnconditional()) return 0;
1991   }
1992
1993   // Okay, we can do the transformation: create the new PHI node.
1994   PHINode *NewPN = PHINode::Create(I.getType(), "");
1995   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1996   InsertNewInstBefore(NewPN, *PN);
1997   NewPN->takeName(PN);
1998
1999   // Next, add all of the operands to the PHI.
2000   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2001     // We only currently try to fold the condition of a select when it is a phi,
2002     // not the true/false values.
2003     Value *TrueV = SI->getTrueValue();
2004     Value *FalseV = SI->getFalseValue();
2005     BasicBlock *PhiTransBB = PN->getParent();
2006     for (unsigned i = 0; i != NumPHIValues; ++i) {
2007       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2008       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2009       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2010       Value *InV = 0;
2011       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2012         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2013       } else {
2014         assert(PN->getIncomingBlock(i) == NonConstBB);
2015         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2016                                  FalseVInPred,
2017                                  "phitmp", NonConstBB->getTerminator());
2018         Worklist.Add(cast<Instruction>(InV));
2019       }
2020       NewPN->addIncoming(InV, ThisBB);
2021     }
2022   } else if (I.getNumOperands() == 2) {
2023     Constant *C = cast<Constant>(I.getOperand(1));
2024     for (unsigned i = 0; i != NumPHIValues; ++i) {
2025       Value *InV = 0;
2026       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2027         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2028           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2029         else
2030           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2031       } else {
2032         assert(PN->getIncomingBlock(i) == NonConstBB);
2033         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2034           InV = BinaryOperator::Create(BO->getOpcode(),
2035                                        PN->getIncomingValue(i), C, "phitmp",
2036                                        NonConstBB->getTerminator());
2037         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2038           InV = CmpInst::Create(CI->getOpcode(),
2039                                 CI->getPredicate(),
2040                                 PN->getIncomingValue(i), C, "phitmp",
2041                                 NonConstBB->getTerminator());
2042         else
2043           llvm_unreachable("Unknown binop!");
2044         
2045         Worklist.Add(cast<Instruction>(InV));
2046       }
2047       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2048     }
2049   } else { 
2050     CastInst *CI = cast<CastInst>(&I);
2051     const Type *RetTy = CI->getType();
2052     for (unsigned i = 0; i != NumPHIValues; ++i) {
2053       Value *InV;
2054       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2055         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2056       } else {
2057         assert(PN->getIncomingBlock(i) == NonConstBB);
2058         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2059                                I.getType(), "phitmp", 
2060                                NonConstBB->getTerminator());
2061         Worklist.Add(cast<Instruction>(InV));
2062       }
2063       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2064     }
2065   }
2066   return ReplaceInstUsesWith(I, NewPN);
2067 }
2068
2069
2070 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2071 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2072 /// This basically requires proving that the add in the original type would not
2073 /// overflow to change the sign bit or have a carry out.
2074 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2075   // There are different heuristics we can use for this.  Here are some simple
2076   // ones.
2077   
2078   // Add has the property that adding any two 2's complement numbers can only 
2079   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2080   // have at least two sign bits, we know that the addition of the two values will
2081   // sign extend fine.
2082   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2083     return true;
2084   
2085   
2086   // If one of the operands only has one non-zero bit, and if the other operand
2087   // has a known-zero bit in a more significant place than it (not including the
2088   // sign bit) the ripple may go up to and fill the zero, but won't change the
2089   // sign.  For example, (X & ~4) + 1.
2090   
2091   // TODO: Implement.
2092   
2093   return false;
2094 }
2095
2096
2097 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2098   bool Changed = SimplifyCommutative(I);
2099   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2100
2101   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2102     // X + undef -> undef
2103     if (isa<UndefValue>(RHS))
2104       return ReplaceInstUsesWith(I, RHS);
2105
2106     // X + 0 --> X
2107     if (RHSC->isNullValue())
2108       return ReplaceInstUsesWith(I, LHS);
2109
2110     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2111       // X + (signbit) --> X ^ signbit
2112       const APInt& Val = CI->getValue();
2113       uint32_t BitWidth = Val.getBitWidth();
2114       if (Val == APInt::getSignBit(BitWidth))
2115         return BinaryOperator::CreateXor(LHS, RHS);
2116       
2117       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2118       // (X & 254)+1 -> (X&254)|1
2119       if (SimplifyDemandedInstructionBits(I))
2120         return &I;
2121
2122       // zext(bool) + C -> bool ? C + 1 : C
2123       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2124         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2125           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2126     }
2127
2128     if (isa<PHINode>(LHS))
2129       if (Instruction *NV = FoldOpIntoPhi(I))
2130         return NV;
2131     
2132     ConstantInt *XorRHS = 0;
2133     Value *XorLHS = 0;
2134     if (isa<ConstantInt>(RHSC) &&
2135         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2136       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2137       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2138       
2139       uint32_t Size = TySizeBits / 2;
2140       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2141       APInt CFF80Val(-C0080Val);
2142       do {
2143         if (TySizeBits > Size) {
2144           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2145           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2146           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2147               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2148             // This is a sign extend if the top bits are known zero.
2149             if (!MaskedValueIsZero(XorLHS, 
2150                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2151               Size = 0;  // Not a sign ext, but can't be any others either.
2152             break;
2153           }
2154         }
2155         Size >>= 1;
2156         C0080Val = APIntOps::lshr(C0080Val, Size);
2157         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2158       } while (Size >= 1);
2159       
2160       // FIXME: This shouldn't be necessary. When the backends can handle types
2161       // with funny bit widths then this switch statement should be removed. It
2162       // is just here to get the size of the "middle" type back up to something
2163       // that the back ends can handle.
2164       const Type *MiddleType = 0;
2165       switch (Size) {
2166         default: break;
2167         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2168         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2169         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2170       }
2171       if (MiddleType) {
2172         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2173         return new SExtInst(NewTrunc, I.getType(), I.getName());
2174       }
2175     }
2176   }
2177
2178   if (I.getType() == Type::getInt1Ty(*Context))
2179     return BinaryOperator::CreateXor(LHS, RHS);
2180
2181   // X + X --> X << 1
2182   if (I.getType()->isInteger()) {
2183     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2184       return Result;
2185
2186     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2187       if (RHSI->getOpcode() == Instruction::Sub)
2188         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2189           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2190     }
2191     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2192       if (LHSI->getOpcode() == Instruction::Sub)
2193         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2194           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2195     }
2196   }
2197
2198   // -A + B  -->  B - A
2199   // -A + -B  -->  -(A + B)
2200   if (Value *LHSV = dyn_castNegVal(LHS)) {
2201     if (LHS->getType()->isIntOrIntVector()) {
2202       if (Value *RHSV = dyn_castNegVal(RHS)) {
2203         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2204         return BinaryOperator::CreateNeg(NewAdd);
2205       }
2206     }
2207     
2208     return BinaryOperator::CreateSub(RHS, LHSV);
2209   }
2210
2211   // A + -B  -->  A - B
2212   if (!isa<Constant>(RHS))
2213     if (Value *V = dyn_castNegVal(RHS))
2214       return BinaryOperator::CreateSub(LHS, V);
2215
2216
2217   ConstantInt *C2;
2218   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2219     if (X == RHS)   // X*C + X --> X * (C+1)
2220       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2221
2222     // X*C1 + X*C2 --> X * (C1+C2)
2223     ConstantInt *C1;
2224     if (X == dyn_castFoldableMul(RHS, C1))
2225       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2226   }
2227
2228   // X + X*C --> X * (C+1)
2229   if (dyn_castFoldableMul(RHS, C2) == LHS)
2230     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2231
2232   // X + ~X --> -1   since   ~X = -X-1
2233   if (dyn_castNotVal(LHS) == RHS ||
2234       dyn_castNotVal(RHS) == LHS)
2235     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2236   
2237
2238   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2239   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2240     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2241       return R;
2242   
2243   // A+B --> A|B iff A and B have no bits set in common.
2244   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2245     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2246     APInt LHSKnownOne(IT->getBitWidth(), 0);
2247     APInt LHSKnownZero(IT->getBitWidth(), 0);
2248     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2249     if (LHSKnownZero != 0) {
2250       APInt RHSKnownOne(IT->getBitWidth(), 0);
2251       APInt RHSKnownZero(IT->getBitWidth(), 0);
2252       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2253       
2254       // No bits in common -> bitwise or.
2255       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2256         return BinaryOperator::CreateOr(LHS, RHS);
2257     }
2258   }
2259
2260   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2261   if (I.getType()->isIntOrIntVector()) {
2262     Value *W, *X, *Y, *Z;
2263     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2264         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2265       if (W != Y) {
2266         if (W == Z) {
2267           std::swap(Y, Z);
2268         } else if (Y == X) {
2269           std::swap(W, X);
2270         } else if (X == Z) {
2271           std::swap(Y, Z);
2272           std::swap(W, X);
2273         }
2274       }
2275
2276       if (W == Y) {
2277         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2278         return BinaryOperator::CreateMul(W, NewAdd);
2279       }
2280     }
2281   }
2282
2283   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2284     Value *X = 0;
2285     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2286       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2287
2288     // (X & FF00) + xx00  -> (X+xx00) & FF00
2289     if (LHS->hasOneUse() &&
2290         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2291       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2292       if (Anded == CRHS) {
2293         // See if all bits from the first bit set in the Add RHS up are included
2294         // in the mask.  First, get the rightmost bit.
2295         const APInt& AddRHSV = CRHS->getValue();
2296
2297         // Form a mask of all bits from the lowest bit added through the top.
2298         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2299
2300         // See if the and mask includes all of these bits.
2301         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2302
2303         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2304           // Okay, the xform is safe.  Insert the new add pronto.
2305           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2306           return BinaryOperator::CreateAnd(NewAdd, C2);
2307         }
2308       }
2309     }
2310
2311     // Try to fold constant add into select arguments.
2312     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2313       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2314         return R;
2315   }
2316
2317   // add (select X 0 (sub n A)) A  -->  select X A n
2318   {
2319     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2320     Value *A = RHS;
2321     if (!SI) {
2322       SI = dyn_cast<SelectInst>(RHS);
2323       A = LHS;
2324     }
2325     if (SI && SI->hasOneUse()) {
2326       Value *TV = SI->getTrueValue();
2327       Value *FV = SI->getFalseValue();
2328       Value *N;
2329
2330       // Can we fold the add into the argument of the select?
2331       // We check both true and false select arguments for a matching subtract.
2332       if (match(FV, m_Zero()) &&
2333           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2334         // Fold the add into the true select value.
2335         return SelectInst::Create(SI->getCondition(), N, A);
2336       if (match(TV, m_Zero()) &&
2337           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2338         // Fold the add into the false select value.
2339         return SelectInst::Create(SI->getCondition(), A, N);
2340     }
2341   }
2342
2343   // Check for (add (sext x), y), see if we can merge this into an
2344   // integer add followed by a sext.
2345   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2346     // (add (sext x), cst) --> (sext (add x, cst'))
2347     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2348       Constant *CI = 
2349         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2350       if (LHSConv->hasOneUse() &&
2351           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2352           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2353         // Insert the new, smaller add.
2354         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2355                                            CI, "addconv");
2356         return new SExtInst(NewAdd, I.getType());
2357       }
2358     }
2359     
2360     // (add (sext x), (sext y)) --> (sext (add int x, y))
2361     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2362       // Only do this if x/y have the same type, if at last one of them has a
2363       // single use (so we don't increase the number of sexts), and if the
2364       // integer add will not overflow.
2365       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2366           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2367           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2368                                    RHSConv->getOperand(0))) {
2369         // Insert the new integer add.
2370         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2371                                            RHSConv->getOperand(0), "addconv");
2372         return new SExtInst(NewAdd, I.getType());
2373       }
2374     }
2375   }
2376
2377   return Changed ? &I : 0;
2378 }
2379
2380 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2381   bool Changed = SimplifyCommutative(I);
2382   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2383
2384   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2385     // X + 0 --> X
2386     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2387       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2388                               (I.getType())->getValueAPF()))
2389         return ReplaceInstUsesWith(I, LHS);
2390     }
2391
2392     if (isa<PHINode>(LHS))
2393       if (Instruction *NV = FoldOpIntoPhi(I))
2394         return NV;
2395   }
2396
2397   // -A + B  -->  B - A
2398   // -A + -B  -->  -(A + B)
2399   if (Value *LHSV = dyn_castFNegVal(LHS))
2400     return BinaryOperator::CreateFSub(RHS, LHSV);
2401
2402   // A + -B  -->  A - B
2403   if (!isa<Constant>(RHS))
2404     if (Value *V = dyn_castFNegVal(RHS))
2405       return BinaryOperator::CreateFSub(LHS, V);
2406
2407   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2408   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2409     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2410       return ReplaceInstUsesWith(I, LHS);
2411
2412   // Check for (add double (sitofp x), y), see if we can merge this into an
2413   // integer add followed by a promotion.
2414   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2415     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2416     // ... if the constant fits in the integer value.  This is useful for things
2417     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2418     // requires a constant pool load, and generally allows the add to be better
2419     // instcombined.
2420     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2421       Constant *CI = 
2422       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2423       if (LHSConv->hasOneUse() &&
2424           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2425           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2426         // Insert the new integer add.
2427         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2428                                            CI, "addconv");
2429         return new SIToFPInst(NewAdd, I.getType());
2430       }
2431     }
2432     
2433     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2434     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2435       // Only do this if x/y have the same type, if at last one of them has a
2436       // single use (so we don't increase the number of int->fp conversions),
2437       // and if the integer add will not overflow.
2438       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2439           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2440           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2441                                    RHSConv->getOperand(0))) {
2442         // Insert the new integer add.
2443         Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0), 
2444                                            RHSConv->getOperand(0), "addconv");
2445         return new SIToFPInst(NewAdd, I.getType());
2446       }
2447     }
2448   }
2449   
2450   return Changed ? &I : 0;
2451 }
2452
2453 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2454   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2455
2456   if (Op0 == Op1)                        // sub X, X  -> 0
2457     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2458
2459   // If this is a 'B = x-(-A)', change to B = x+A...
2460   if (Value *V = dyn_castNegVal(Op1))
2461     return BinaryOperator::CreateAdd(Op0, V);
2462
2463   if (isa<UndefValue>(Op0))
2464     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2465   if (isa<UndefValue>(Op1))
2466     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2467
2468   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2469     // Replace (-1 - A) with (~A)...
2470     if (C->isAllOnesValue())
2471       return BinaryOperator::CreateNot(Op1);
2472
2473     // C - ~X == X + (1+C)
2474     Value *X = 0;
2475     if (match(Op1, m_Not(m_Value(X))))
2476       return BinaryOperator::CreateAdd(X, AddOne(C));
2477
2478     // -(X >>u 31) -> (X >>s 31)
2479     // -(X >>s 31) -> (X >>u 31)
2480     if (C->isZero()) {
2481       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2482         if (SI->getOpcode() == Instruction::LShr) {
2483           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2484             // Check to see if we are shifting out everything but the sign bit.
2485             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2486                 SI->getType()->getPrimitiveSizeInBits()-1) {
2487               // Ok, the transformation is safe.  Insert AShr.
2488               return BinaryOperator::Create(Instruction::AShr, 
2489                                           SI->getOperand(0), CU, SI->getName());
2490             }
2491           }
2492         }
2493         else if (SI->getOpcode() == Instruction::AShr) {
2494           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2495             // Check to see if we are shifting out everything but the sign bit.
2496             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2497                 SI->getType()->getPrimitiveSizeInBits()-1) {
2498               // Ok, the transformation is safe.  Insert LShr. 
2499               return BinaryOperator::CreateLShr(
2500                                           SI->getOperand(0), CU, SI->getName());
2501             }
2502           }
2503         }
2504       }
2505     }
2506
2507     // Try to fold constant sub into select arguments.
2508     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2509       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2510         return R;
2511
2512     // C - zext(bool) -> bool ? C - 1 : C
2513     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2514       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2515         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2516   }
2517
2518   if (I.getType() == Type::getInt1Ty(*Context))
2519     return BinaryOperator::CreateXor(Op0, Op1);
2520
2521   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2522     if (Op1I->getOpcode() == Instruction::Add) {
2523       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2524         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2525                                          I.getName());
2526       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2527         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2528                                          I.getName());
2529       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2530         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2531           // C1-(X+C2) --> (C1-C2)-X
2532           return BinaryOperator::CreateSub(
2533             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2534       }
2535     }
2536
2537     if (Op1I->hasOneUse()) {
2538       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2539       // is not used by anyone else...
2540       //
2541       if (Op1I->getOpcode() == Instruction::Sub) {
2542         // Swap the two operands of the subexpr...
2543         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2544         Op1I->setOperand(0, IIOp1);
2545         Op1I->setOperand(1, IIOp0);
2546
2547         // Create the new top level add instruction...
2548         return BinaryOperator::CreateAdd(Op0, Op1);
2549       }
2550
2551       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2552       //
2553       if (Op1I->getOpcode() == Instruction::And &&
2554           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2555         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2556
2557         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2558         return BinaryOperator::CreateAnd(Op0, NewNot);
2559       }
2560
2561       // 0 - (X sdiv C)  -> (X sdiv -C)
2562       if (Op1I->getOpcode() == Instruction::SDiv)
2563         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2564           if (CSI->isZero())
2565             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2566               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2567                                           ConstantExpr::getNeg(DivRHS));
2568
2569       // X - X*C --> X * (1-C)
2570       ConstantInt *C2 = 0;
2571       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2572         Constant *CP1 = 
2573           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2574                                              C2);
2575         return BinaryOperator::CreateMul(Op0, CP1);
2576       }
2577     }
2578   }
2579
2580   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2581     if (Op0I->getOpcode() == Instruction::Add) {
2582       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2583         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2584       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2585         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2586     } else if (Op0I->getOpcode() == Instruction::Sub) {
2587       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2588         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2589                                          I.getName());
2590     }
2591   }
2592
2593   ConstantInt *C1;
2594   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2595     if (X == Op1)  // X*C - X --> X * (C-1)
2596       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2597
2598     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2599     if (X == dyn_castFoldableMul(Op1, C2))
2600       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2601   }
2602   return 0;
2603 }
2604
2605 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2606   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2607
2608   // If this is a 'B = x-(-A)', change to B = x+A...
2609   if (Value *V = dyn_castFNegVal(Op1))
2610     return BinaryOperator::CreateFAdd(Op0, V);
2611
2612   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2613     if (Op1I->getOpcode() == Instruction::FAdd) {
2614       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2615         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2616                                           I.getName());
2617       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2618         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2619                                           I.getName());
2620     }
2621   }
2622
2623   return 0;
2624 }
2625
2626 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2627 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2628 /// TrueIfSigned if the result of the comparison is true when the input value is
2629 /// signed.
2630 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2631                            bool &TrueIfSigned) {
2632   switch (pred) {
2633   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2634     TrueIfSigned = true;
2635     return RHS->isZero();
2636   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2637     TrueIfSigned = true;
2638     return RHS->isAllOnesValue();
2639   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2640     TrueIfSigned = false;
2641     return RHS->isAllOnesValue();
2642   case ICmpInst::ICMP_UGT:
2643     // True if LHS u> RHS and RHS == high-bit-mask - 1
2644     TrueIfSigned = true;
2645     return RHS->getValue() ==
2646       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2647   case ICmpInst::ICMP_UGE: 
2648     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2649     TrueIfSigned = true;
2650     return RHS->getValue().isSignBit();
2651   default:
2652     return false;
2653   }
2654 }
2655
2656 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2657   bool Changed = SimplifyCommutative(I);
2658   Value *Op0 = I.getOperand(0);
2659
2660   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2661     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2662
2663   // Simplify mul instructions with a constant RHS...
2664   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2665     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2666
2667       // ((X << C1)*C2) == (X * (C2 << C1))
2668       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2669         if (SI->getOpcode() == Instruction::Shl)
2670           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2671             return BinaryOperator::CreateMul(SI->getOperand(0),
2672                                         ConstantExpr::getShl(CI, ShOp));
2673
2674       if (CI->isZero())
2675         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2676       if (CI->equalsInt(1))                  // X * 1  == X
2677         return ReplaceInstUsesWith(I, Op0);
2678       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2679         return BinaryOperator::CreateNeg(Op0, I.getName());
2680
2681       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2682       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2683         return BinaryOperator::CreateShl(Op0,
2684                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2685       }
2686     } else if (isa<VectorType>(Op1->getType())) {
2687       if (Op1->isNullValue())
2688         return ReplaceInstUsesWith(I, Op1);
2689
2690       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2691         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2692           return BinaryOperator::CreateNeg(Op0, I.getName());
2693
2694         // As above, vector X*splat(1.0) -> X in all defined cases.
2695         if (Constant *Splat = Op1V->getSplatValue()) {
2696           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2697             if (CI->equalsInt(1))
2698               return ReplaceInstUsesWith(I, Op0);
2699         }
2700       }
2701     }
2702     
2703     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2704       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2705           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2706         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2707         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2708         Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2709         return BinaryOperator::CreateAdd(Add, C1C2);
2710         
2711       }
2712
2713     // Try to fold constant mul into select arguments.
2714     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2715       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2716         return R;
2717
2718     if (isa<PHINode>(Op0))
2719       if (Instruction *NV = FoldOpIntoPhi(I))
2720         return NV;
2721   }
2722
2723   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2724     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2725       return BinaryOperator::CreateMul(Op0v, Op1v);
2726
2727   // (X / Y) *  Y = X - (X % Y)
2728   // (X / Y) * -Y = (X % Y) - X
2729   {
2730     Value *Op1 = I.getOperand(1);
2731     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2732     if (!BO ||
2733         (BO->getOpcode() != Instruction::UDiv && 
2734          BO->getOpcode() != Instruction::SDiv)) {
2735       Op1 = Op0;
2736       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2737     }
2738     Value *Neg = dyn_castNegVal(Op1);
2739     if (BO && BO->hasOneUse() &&
2740         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2741         (BO->getOpcode() == Instruction::UDiv ||
2742          BO->getOpcode() == Instruction::SDiv)) {
2743       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2744
2745       // If the division is exact, X % Y is zero.
2746       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2747         if (SDiv->isExact()) {
2748           if (Op1BO == Op1)
2749             return ReplaceInstUsesWith(I, Op0BO);
2750           else
2751             return BinaryOperator::CreateNeg(Op0BO);
2752         }
2753
2754       Value *Rem;
2755       if (BO->getOpcode() == Instruction::UDiv)
2756         Rem = Builder->CreateURem(Op0BO, Op1BO);
2757       else
2758         Rem = Builder->CreateSRem(Op0BO, Op1BO);
2759       Rem->takeName(BO);
2760
2761       if (Op1BO == Op1)
2762         return BinaryOperator::CreateSub(Op0BO, Rem);
2763       return BinaryOperator::CreateSub(Rem, Op0BO);
2764     }
2765   }
2766
2767   if (I.getType() == Type::getInt1Ty(*Context))
2768     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2769
2770   // If one of the operands of the multiply is a cast from a boolean value, then
2771   // we know the bool is either zero or one, so this is a 'masking' multiply.
2772   // See if we can simplify things based on how the boolean was originally
2773   // formed.
2774   CastInst *BoolCast = 0;
2775   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2776     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2777       BoolCast = CI;
2778   if (!BoolCast)
2779     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2780       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2781         BoolCast = CI;
2782   if (BoolCast) {
2783     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2784       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2785       const Type *SCOpTy = SCIOp0->getType();
2786       bool TIS = false;
2787       
2788       // If the icmp is true iff the sign bit of X is set, then convert this
2789       // multiply into a shift/and combination.
2790       if (isa<ConstantInt>(SCIOp1) &&
2791           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2792           TIS) {
2793         // Shift the X value right to turn it into "all signbits".
2794         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2795                                           SCOpTy->getPrimitiveSizeInBits()-1);
2796         Value *V = Builder->CreateAShr(SCIOp0, Amt,
2797                                     BoolCast->getOperand(0)->getName()+".mask");
2798
2799         // If the multiply type is not the same as the source type, sign extend
2800         // or truncate to the multiply type.
2801         if (I.getType() != V->getType())
2802           V = Builder->CreateIntCast(V, I.getType(), true);
2803
2804         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2805         return BinaryOperator::CreateAnd(V, OtherOp);
2806       }
2807     }
2808   }
2809
2810   return Changed ? &I : 0;
2811 }
2812
2813 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2814   bool Changed = SimplifyCommutative(I);
2815   Value *Op0 = I.getOperand(0);
2816
2817   // Simplify mul instructions with a constant RHS...
2818   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2819     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2820       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2821       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2822       if (Op1F->isExactlyValue(1.0))
2823         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2824     } else if (isa<VectorType>(Op1->getType())) {
2825       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2826         // As above, vector X*splat(1.0) -> X in all defined cases.
2827         if (Constant *Splat = Op1V->getSplatValue()) {
2828           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2829             if (F->isExactlyValue(1.0))
2830               return ReplaceInstUsesWith(I, Op0);
2831         }
2832       }
2833     }
2834
2835     // Try to fold constant mul into select arguments.
2836     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2837       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2838         return R;
2839
2840     if (isa<PHINode>(Op0))
2841       if (Instruction *NV = FoldOpIntoPhi(I))
2842         return NV;
2843   }
2844
2845   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2846     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2847       return BinaryOperator::CreateFMul(Op0v, Op1v);
2848
2849   return Changed ? &I : 0;
2850 }
2851
2852 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2853 /// instruction.
2854 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2855   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2856   
2857   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2858   int NonNullOperand = -1;
2859   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2860     if (ST->isNullValue())
2861       NonNullOperand = 2;
2862   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2863   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2864     if (ST->isNullValue())
2865       NonNullOperand = 1;
2866   
2867   if (NonNullOperand == -1)
2868     return false;
2869   
2870   Value *SelectCond = SI->getOperand(0);
2871   
2872   // Change the div/rem to use 'Y' instead of the select.
2873   I.setOperand(1, SI->getOperand(NonNullOperand));
2874   
2875   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2876   // problem.  However, the select, or the condition of the select may have
2877   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2878   // propagate the known value for the select into other uses of it, and
2879   // propagate a known value of the condition into its other users.
2880   
2881   // If the select and condition only have a single use, don't bother with this,
2882   // early exit.
2883   if (SI->use_empty() && SelectCond->hasOneUse())
2884     return true;
2885   
2886   // Scan the current block backward, looking for other uses of SI.
2887   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2888   
2889   while (BBI != BBFront) {
2890     --BBI;
2891     // If we found a call to a function, we can't assume it will return, so
2892     // information from below it cannot be propagated above it.
2893     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2894       break;
2895     
2896     // Replace uses of the select or its condition with the known values.
2897     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2898          I != E; ++I) {
2899       if (*I == SI) {
2900         *I = SI->getOperand(NonNullOperand);
2901         Worklist.Add(BBI);
2902       } else if (*I == SelectCond) {
2903         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2904                                    ConstantInt::getFalse(*Context);
2905         Worklist.Add(BBI);
2906       }
2907     }
2908     
2909     // If we past the instruction, quit looking for it.
2910     if (&*BBI == SI)
2911       SI = 0;
2912     if (&*BBI == SelectCond)
2913       SelectCond = 0;
2914     
2915     // If we ran out of things to eliminate, break out of the loop.
2916     if (SelectCond == 0 && SI == 0)
2917       break;
2918     
2919   }
2920   return true;
2921 }
2922
2923
2924 /// This function implements the transforms on div instructions that work
2925 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2926 /// used by the visitors to those instructions.
2927 /// @brief Transforms common to all three div instructions
2928 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2929   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2930
2931   // undef / X -> 0        for integer.
2932   // undef / X -> undef    for FP (the undef could be a snan).
2933   if (isa<UndefValue>(Op0)) {
2934     if (Op0->getType()->isFPOrFPVector())
2935       return ReplaceInstUsesWith(I, Op0);
2936     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2937   }
2938
2939   // X / undef -> undef
2940   if (isa<UndefValue>(Op1))
2941     return ReplaceInstUsesWith(I, Op1);
2942
2943   return 0;
2944 }
2945
2946 /// This function implements the transforms common to both integer division
2947 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2948 /// division instructions.
2949 /// @brief Common integer divide transforms
2950 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2951   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2952
2953   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2954   if (Op0 == Op1) {
2955     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2956       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2957       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2958       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2959     }
2960
2961     Constant *CI = ConstantInt::get(I.getType(), 1);
2962     return ReplaceInstUsesWith(I, CI);
2963   }
2964   
2965   if (Instruction *Common = commonDivTransforms(I))
2966     return Common;
2967   
2968   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2969   // This does not apply for fdiv.
2970   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2971     return &I;
2972
2973   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2974     // div X, 1 == X
2975     if (RHS->equalsInt(1))
2976       return ReplaceInstUsesWith(I, Op0);
2977
2978     // (X / C1) / C2  -> X / (C1*C2)
2979     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2980       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2981         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2982           if (MultiplyOverflows(RHS, LHSRHS,
2983                                 I.getOpcode()==Instruction::SDiv))
2984             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2985           else 
2986             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2987                                       ConstantExpr::getMul(RHS, LHSRHS));
2988         }
2989
2990     if (!RHS->isZero()) { // avoid X udiv 0
2991       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2992         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2993           return R;
2994       if (isa<PHINode>(Op0))
2995         if (Instruction *NV = FoldOpIntoPhi(I))
2996           return NV;
2997     }
2998   }
2999
3000   // 0 / X == 0, we don't need to preserve faults!
3001   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3002     if (LHS->equalsInt(0))
3003       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3004
3005   // It can't be division by zero, hence it must be division by one.
3006   if (I.getType() == Type::getInt1Ty(*Context))
3007     return ReplaceInstUsesWith(I, Op0);
3008
3009   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3010     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3011       // div X, 1 == X
3012       if (X->isOne())
3013         return ReplaceInstUsesWith(I, Op0);
3014   }
3015
3016   return 0;
3017 }
3018
3019 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3020   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3021
3022   // Handle the integer div common cases
3023   if (Instruction *Common = commonIDivTransforms(I))
3024     return Common;
3025
3026   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3027     // X udiv C^2 -> X >> C
3028     // Check to see if this is an unsigned division with an exact power of 2,
3029     // if so, convert to a right shift.
3030     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3031       return BinaryOperator::CreateLShr(Op0, 
3032             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3033
3034     // X udiv C, where C >= signbit
3035     if (C->getValue().isNegative()) {
3036       Value *IC = Builder->CreateICmpULT( Op0, C);
3037       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3038                                 ConstantInt::get(I.getType(), 1));
3039     }
3040   }
3041
3042   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3043   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3044     if (RHSI->getOpcode() == Instruction::Shl &&
3045         isa<ConstantInt>(RHSI->getOperand(0))) {
3046       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3047       if (C1.isPowerOf2()) {
3048         Value *N = RHSI->getOperand(1);
3049         const Type *NTy = N->getType();
3050         if (uint32_t C2 = C1.logBase2())
3051           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3052         return BinaryOperator::CreateLShr(Op0, N);
3053       }
3054     }
3055   }
3056   
3057   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3058   // where C1&C2 are powers of two.
3059   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3060     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3061       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3062         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3063         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3064           // Compute the shift amounts
3065           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3066           // Construct the "on true" case of the select
3067           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3068           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3069   
3070           // Construct the "on false" case of the select
3071           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3072           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3073
3074           // construct the select instruction and return it.
3075           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3076         }
3077       }
3078   return 0;
3079 }
3080
3081 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3082   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3083
3084   // Handle the integer div common cases
3085   if (Instruction *Common = commonIDivTransforms(I))
3086     return Common;
3087
3088   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3089     // sdiv X, -1 == -X
3090     if (RHS->isAllOnesValue())
3091       return BinaryOperator::CreateNeg(Op0);
3092
3093     // sdiv X, C  -->  ashr X, log2(C)
3094     if (cast<SDivOperator>(&I)->isExact() &&
3095         RHS->getValue().isNonNegative() &&
3096         RHS->getValue().isPowerOf2()) {
3097       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3098                                             RHS->getValue().exactLogBase2());
3099       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3100     }
3101
3102     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3103     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3104       if (isa<Constant>(Sub->getOperand(0)) &&
3105           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3106           Sub->hasNoSignedWrap())
3107         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3108                                           ConstantExpr::getNeg(RHS));
3109   }
3110
3111   // If the sign bits of both operands are zero (i.e. we can prove they are
3112   // unsigned inputs), turn this into a udiv.
3113   if (I.getType()->isInteger()) {
3114     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3115     if (MaskedValueIsZero(Op0, Mask)) {
3116       if (MaskedValueIsZero(Op1, Mask)) {
3117         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3118         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3119       }
3120       ConstantInt *ShiftedInt;
3121       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3122           ShiftedInt->getValue().isPowerOf2()) {
3123         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3124         // Safe because the only negative value (1 << Y) can take on is
3125         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3126         // the sign bit set.
3127         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3128       }
3129     }
3130   }
3131   
3132   return 0;
3133 }
3134
3135 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3136   return commonDivTransforms(I);
3137 }
3138
3139 /// This function implements the transforms on rem instructions that work
3140 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3141 /// is used by the visitors to those instructions.
3142 /// @brief Transforms common to all three rem instructions
3143 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3144   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3145
3146   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3147     if (I.getType()->isFPOrFPVector())
3148       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3149     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3150   }
3151   if (isa<UndefValue>(Op1))
3152     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3153
3154   // Handle cases involving: rem X, (select Cond, Y, Z)
3155   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3156     return &I;
3157
3158   return 0;
3159 }
3160
3161 /// This function implements the transforms common to both integer remainder
3162 /// instructions (urem and srem). It is called by the visitors to those integer
3163 /// remainder instructions.
3164 /// @brief Common integer remainder transforms
3165 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3166   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3167
3168   if (Instruction *common = commonRemTransforms(I))
3169     return common;
3170
3171   // 0 % X == 0 for integer, we don't need to preserve faults!
3172   if (Constant *LHS = dyn_cast<Constant>(Op0))
3173     if (LHS->isNullValue())
3174       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3175
3176   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3177     // X % 0 == undef, we don't need to preserve faults!
3178     if (RHS->equalsInt(0))
3179       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3180     
3181     if (RHS->equalsInt(1))  // X % 1 == 0
3182       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3183
3184     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3185       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3186         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3187           return R;
3188       } else if (isa<PHINode>(Op0I)) {
3189         if (Instruction *NV = FoldOpIntoPhi(I))
3190           return NV;
3191       }
3192
3193       // See if we can fold away this rem instruction.
3194       if (SimplifyDemandedInstructionBits(I))
3195         return &I;
3196     }
3197   }
3198
3199   return 0;
3200 }
3201
3202 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3203   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205   if (Instruction *common = commonIRemTransforms(I))
3206     return common;
3207   
3208   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209     // X urem C^2 -> X and C
3210     // Check to see if this is an unsigned remainder with an exact power of 2,
3211     // if so, convert to a bitwise and.
3212     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3213       if (C->getValue().isPowerOf2())
3214         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3215   }
3216
3217   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3218     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3219     if (RHSI->getOpcode() == Instruction::Shl &&
3220         isa<ConstantInt>(RHSI->getOperand(0))) {
3221       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3222         Constant *N1 = Constant::getAllOnesValue(I.getType());
3223         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3224         return BinaryOperator::CreateAnd(Op0, Add);
3225       }
3226     }
3227   }
3228
3229   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3230   // where C1&C2 are powers of two.
3231   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3232     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3233       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3234         // STO == 0 and SFO == 0 handled above.
3235         if ((STO->getValue().isPowerOf2()) && 
3236             (SFO->getValue().isPowerOf2())) {
3237           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3238                                               SI->getName()+".t");
3239           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3240                                                SI->getName()+".f");
3241           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3242         }
3243       }
3244   }
3245   
3246   return 0;
3247 }
3248
3249 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3250   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3251
3252   // Handle the integer rem common cases
3253   if (Instruction *Common = commonIRemTransforms(I))
3254     return Common;
3255   
3256   if (Value *RHSNeg = dyn_castNegVal(Op1))
3257     if (!isa<Constant>(RHSNeg) ||
3258         (isa<ConstantInt>(RHSNeg) &&
3259          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3260       // X % -Y -> X % Y
3261       Worklist.AddValue(I.getOperand(1));
3262       I.setOperand(1, RHSNeg);
3263       return &I;
3264     }
3265
3266   // If the sign bits of both operands are zero (i.e. we can prove they are
3267   // unsigned inputs), turn this into a urem.
3268   if (I.getType()->isInteger()) {
3269     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3270     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3271       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3272       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3273     }
3274   }
3275
3276   // If it's a constant vector, flip any negative values positive.
3277   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3278     unsigned VWidth = RHSV->getNumOperands();
3279
3280     bool hasNegative = false;
3281     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3282       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3283         if (RHS->getValue().isNegative())
3284           hasNegative = true;
3285
3286     if (hasNegative) {
3287       std::vector<Constant *> Elts(VWidth);
3288       for (unsigned i = 0; i != VWidth; ++i) {
3289         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3290           if (RHS->getValue().isNegative())
3291             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3292           else
3293             Elts[i] = RHS;
3294         }
3295       }
3296
3297       Constant *NewRHSV = ConstantVector::get(Elts);
3298       if (NewRHSV != RHSV) {
3299         Worklist.AddValue(I.getOperand(1));
3300         I.setOperand(1, NewRHSV);
3301         return &I;
3302       }
3303     }
3304   }
3305
3306   return 0;
3307 }
3308
3309 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3310   return commonRemTransforms(I);
3311 }
3312
3313 // isOneBitSet - Return true if there is exactly one bit set in the specified
3314 // constant.
3315 static bool isOneBitSet(const ConstantInt *CI) {
3316   return CI->getValue().isPowerOf2();
3317 }
3318
3319 // isHighOnes - Return true if the constant is of the form 1+0+.
3320 // This is the same as lowones(~X).
3321 static bool isHighOnes(const ConstantInt *CI) {
3322   return (~CI->getValue() + 1).isPowerOf2();
3323 }
3324
3325 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3326 /// are carefully arranged to allow folding of expressions such as:
3327 ///
3328 ///      (A < B) | (A > B) --> (A != B)
3329 ///
3330 /// Note that this is only valid if the first and second predicates have the
3331 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3332 ///
3333 /// Three bits are used to represent the condition, as follows:
3334 ///   0  A > B
3335 ///   1  A == B
3336 ///   2  A < B
3337 ///
3338 /// <=>  Value  Definition
3339 /// 000     0   Always false
3340 /// 001     1   A >  B
3341 /// 010     2   A == B
3342 /// 011     3   A >= B
3343 /// 100     4   A <  B
3344 /// 101     5   A != B
3345 /// 110     6   A <= B
3346 /// 111     7   Always true
3347 ///  
3348 static unsigned getICmpCode(const ICmpInst *ICI) {
3349   switch (ICI->getPredicate()) {
3350     // False -> 0
3351   case ICmpInst::ICMP_UGT: return 1;  // 001
3352   case ICmpInst::ICMP_SGT: return 1;  // 001
3353   case ICmpInst::ICMP_EQ:  return 2;  // 010
3354   case ICmpInst::ICMP_UGE: return 3;  // 011
3355   case ICmpInst::ICMP_SGE: return 3;  // 011
3356   case ICmpInst::ICMP_ULT: return 4;  // 100
3357   case ICmpInst::ICMP_SLT: return 4;  // 100
3358   case ICmpInst::ICMP_NE:  return 5;  // 101
3359   case ICmpInst::ICMP_ULE: return 6;  // 110
3360   case ICmpInst::ICMP_SLE: return 6;  // 110
3361     // True -> 7
3362   default:
3363     llvm_unreachable("Invalid ICmp predicate!");
3364     return 0;
3365   }
3366 }
3367
3368 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3369 /// predicate into a three bit mask. It also returns whether it is an ordered
3370 /// predicate by reference.
3371 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3372   isOrdered = false;
3373   switch (CC) {
3374   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3375   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3376   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3377   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3378   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3379   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3380   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3381   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3382   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3383   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3384   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3385   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3386   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3387   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3388     // True -> 7
3389   default:
3390     // Not expecting FCMP_FALSE and FCMP_TRUE;
3391     llvm_unreachable("Unexpected FCmp predicate!");
3392     return 0;
3393   }
3394 }
3395
3396 /// getICmpValue - This is the complement of getICmpCode, which turns an
3397 /// opcode and two operands into either a constant true or false, or a brand 
3398 /// new ICmp instruction. The sign is passed in to determine which kind
3399 /// of predicate to use in the new icmp instruction.
3400 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3401                            LLVMContext *Context) {
3402   switch (code) {
3403   default: llvm_unreachable("Illegal ICmp code!");
3404   case  0: return ConstantInt::getFalse(*Context);
3405   case  1: 
3406     if (sign)
3407       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3408     else
3409       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3410   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3411   case  3: 
3412     if (sign)
3413       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3414     else
3415       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3416   case  4: 
3417     if (sign)
3418       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3419     else
3420       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3421   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3422   case  6: 
3423     if (sign)
3424       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3425     else
3426       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3427   case  7: return ConstantInt::getTrue(*Context);
3428   }
3429 }
3430
3431 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3432 /// opcode and two operands into either a FCmp instruction. isordered is passed
3433 /// in to determine which kind of predicate to use in the new fcmp instruction.
3434 static Value *getFCmpValue(bool isordered, unsigned code,
3435                            Value *LHS, Value *RHS, LLVMContext *Context) {
3436   switch (code) {
3437   default: llvm_unreachable("Illegal FCmp code!");
3438   case  0:
3439     if (isordered)
3440       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3441     else
3442       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3443   case  1: 
3444     if (isordered)
3445       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3446     else
3447       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3448   case  2: 
3449     if (isordered)
3450       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3451     else
3452       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3453   case  3: 
3454     if (isordered)
3455       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3456     else
3457       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3458   case  4: 
3459     if (isordered)
3460       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3461     else
3462       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3463   case  5: 
3464     if (isordered)
3465       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3466     else
3467       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3468   case  6: 
3469     if (isordered)
3470       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3471     else
3472       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3473   case  7: return ConstantInt::getTrue(*Context);
3474   }
3475 }
3476
3477 /// PredicatesFoldable - Return true if both predicates match sign or if at
3478 /// least one of them is an equality comparison (which is signless).
3479 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3480   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3481          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3482          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3483 }
3484
3485 namespace { 
3486 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3487 struct FoldICmpLogical {
3488   InstCombiner &IC;
3489   Value *LHS, *RHS;
3490   ICmpInst::Predicate pred;
3491   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3492     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3493       pred(ICI->getPredicate()) {}
3494   bool shouldApply(Value *V) const {
3495     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3496       if (PredicatesFoldable(pred, ICI->getPredicate()))
3497         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3498                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3499     return false;
3500   }
3501   Instruction *apply(Instruction &Log) const {
3502     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3503     if (ICI->getOperand(0) != LHS) {
3504       assert(ICI->getOperand(1) == LHS);
3505       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3506     }
3507
3508     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3509     unsigned LHSCode = getICmpCode(ICI);
3510     unsigned RHSCode = getICmpCode(RHSICI);
3511     unsigned Code;
3512     switch (Log.getOpcode()) {
3513     case Instruction::And: Code = LHSCode & RHSCode; break;
3514     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3515     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3516     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3517     }
3518
3519     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3520                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3521       
3522     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3523     if (Instruction *I = dyn_cast<Instruction>(RV))
3524       return I;
3525     // Otherwise, it's a constant boolean value...
3526     return IC.ReplaceInstUsesWith(Log, RV);
3527   }
3528 };
3529 } // end anonymous namespace
3530
3531 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3532 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3533 // guaranteed to be a binary operator.
3534 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3535                                     ConstantInt *OpRHS,
3536                                     ConstantInt *AndRHS,
3537                                     BinaryOperator &TheAnd) {
3538   Value *X = Op->getOperand(0);
3539   Constant *Together = 0;
3540   if (!Op->isShift())
3541     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3542
3543   switch (Op->getOpcode()) {
3544   case Instruction::Xor:
3545     if (Op->hasOneUse()) {
3546       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3547       Value *And = Builder->CreateAnd(X, AndRHS);
3548       And->takeName(Op);
3549       return BinaryOperator::CreateXor(And, Together);
3550     }
3551     break;
3552   case Instruction::Or:
3553     if (Together == AndRHS) // (X | C) & C --> C
3554       return ReplaceInstUsesWith(TheAnd, AndRHS);
3555
3556     if (Op->hasOneUse() && Together != OpRHS) {
3557       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3558       Value *Or = Builder->CreateOr(X, Together);
3559       Or->takeName(Op);
3560       return BinaryOperator::CreateAnd(Or, AndRHS);
3561     }
3562     break;
3563   case Instruction::Add:
3564     if (Op->hasOneUse()) {
3565       // Adding a one to a single bit bit-field should be turned into an XOR
3566       // of the bit.  First thing to check is to see if this AND is with a
3567       // single bit constant.
3568       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3569
3570       // If there is only one bit set...
3571       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3572         // Ok, at this point, we know that we are masking the result of the
3573         // ADD down to exactly one bit.  If the constant we are adding has
3574         // no bits set below this bit, then we can eliminate the ADD.
3575         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3576
3577         // Check to see if any bits below the one bit set in AndRHSV are set.
3578         if ((AddRHS & (AndRHSV-1)) == 0) {
3579           // If not, the only thing that can effect the output of the AND is
3580           // the bit specified by AndRHSV.  If that bit is set, the effect of
3581           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3582           // no effect.
3583           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3584             TheAnd.setOperand(0, X);
3585             return &TheAnd;
3586           } else {
3587             // Pull the XOR out of the AND.
3588             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3589             NewAnd->takeName(Op);
3590             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3591           }
3592         }
3593       }
3594     }
3595     break;
3596
3597   case Instruction::Shl: {
3598     // We know that the AND will not produce any of the bits shifted in, so if
3599     // the anded constant includes them, clear them now!
3600     //
3601     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3602     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3603     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3604     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3605
3606     if (CI->getValue() == ShlMask) { 
3607     // Masking out bits that the shift already masks
3608       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3609     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3610       TheAnd.setOperand(1, CI);
3611       return &TheAnd;
3612     }
3613     break;
3614   }
3615   case Instruction::LShr:
3616   {
3617     // We know that the AND will not produce any of the bits shifted in, so if
3618     // the anded constant includes them, clear them now!  This only applies to
3619     // unsigned shifts, because a signed shr may bring in set bits!
3620     //
3621     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3622     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3623     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3624     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3625
3626     if (CI->getValue() == ShrMask) {   
3627     // Masking out bits that the shift already masks.
3628       return ReplaceInstUsesWith(TheAnd, Op);
3629     } else if (CI != AndRHS) {
3630       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3631       return &TheAnd;
3632     }
3633     break;
3634   }
3635   case Instruction::AShr:
3636     // Signed shr.
3637     // See if this is shifting in some sign extension, then masking it out
3638     // with an and.
3639     if (Op->hasOneUse()) {
3640       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3641       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3642       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3643       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3644       if (C == AndRHS) {          // Masking out bits shifted in.
3645         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3646         // Make the argument unsigned.
3647         Value *ShVal = Op->getOperand(0);
3648         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3649         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3650       }
3651     }
3652     break;
3653   }
3654   return 0;
3655 }
3656
3657
3658 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3659 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3660 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3661 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3662 /// insert new instructions.
3663 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3664                                            bool isSigned, bool Inside, 
3665                                            Instruction &IB) {
3666   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3667             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3668          "Lo is not <= Hi in range emission code!");
3669     
3670   if (Inside) {
3671     if (Lo == Hi)  // Trivially false.
3672       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3673
3674     // V >= Min && V < Hi --> V < Hi
3675     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3676       ICmpInst::Predicate pred = (isSigned ? 
3677         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3678       return new ICmpInst(pred, V, Hi);
3679     }
3680
3681     // Emit V-Lo <u Hi-Lo
3682     Constant *NegLo = ConstantExpr::getNeg(Lo);
3683     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3684     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3685     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3686   }
3687
3688   if (Lo == Hi)  // Trivially true.
3689     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3690
3691   // V < Min || V >= Hi -> V > Hi-1
3692   Hi = SubOne(cast<ConstantInt>(Hi));
3693   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3694     ICmpInst::Predicate pred = (isSigned ? 
3695         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3696     return new ICmpInst(pred, V, Hi);
3697   }
3698
3699   // Emit V-Lo >u Hi-1-Lo
3700   // Note that Hi has already had one subtracted from it, above.
3701   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3702   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3703   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3704   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3705 }
3706
3707 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3708 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3709 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3710 // not, since all 1s are not contiguous.
3711 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3712   const APInt& V = Val->getValue();
3713   uint32_t BitWidth = Val->getType()->getBitWidth();
3714   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3715
3716   // look for the first zero bit after the run of ones
3717   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3718   // look for the first non-zero bit
3719   ME = V.getActiveBits(); 
3720   return true;
3721 }
3722
3723 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3724 /// where isSub determines whether the operator is a sub.  If we can fold one of
3725 /// the following xforms:
3726 /// 
3727 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3728 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3729 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3730 ///
3731 /// return (A +/- B).
3732 ///
3733 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3734                                         ConstantInt *Mask, bool isSub,
3735                                         Instruction &I) {
3736   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3737   if (!LHSI || LHSI->getNumOperands() != 2 ||
3738       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3739
3740   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3741
3742   switch (LHSI->getOpcode()) {
3743   default: return 0;
3744   case Instruction::And:
3745     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3746       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3747       if ((Mask->getValue().countLeadingZeros() + 
3748            Mask->getValue().countPopulation()) == 
3749           Mask->getValue().getBitWidth())
3750         break;
3751
3752       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3753       // part, we don't need any explicit masks to take them out of A.  If that
3754       // is all N is, ignore it.
3755       uint32_t MB = 0, ME = 0;
3756       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3757         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3758         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3759         if (MaskedValueIsZero(RHS, Mask))
3760           break;
3761       }
3762     }
3763     return 0;
3764   case Instruction::Or:
3765   case Instruction::Xor:
3766     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3767     if ((Mask->getValue().countLeadingZeros() + 
3768          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3769         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3770       break;
3771     return 0;
3772   }
3773   
3774   if (isSub)
3775     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3776   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3777 }
3778
3779 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3780 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3781                                           ICmpInst *LHS, ICmpInst *RHS) {
3782   Value *Val, *Val2;
3783   ConstantInt *LHSCst, *RHSCst;
3784   ICmpInst::Predicate LHSCC, RHSCC;
3785   
3786   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3787   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3788                          m_ConstantInt(LHSCst))) ||
3789       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3790                          m_ConstantInt(RHSCst))))
3791     return 0;
3792   
3793   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3794   // where C is a power of 2
3795   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3796       LHSCst->getValue().isPowerOf2()) {
3797     Value *NewOr = Builder->CreateOr(Val, Val2);
3798     return new ICmpInst(LHSCC, NewOr, LHSCst);
3799   }
3800   
3801   // From here on, we only handle:
3802   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3803   if (Val != Val2) return 0;
3804   
3805   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3806   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3807       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3808       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3809       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3810     return 0;
3811   
3812   // We can't fold (ugt x, C) & (sgt x, C2).
3813   if (!PredicatesFoldable(LHSCC, RHSCC))
3814     return 0;
3815     
3816   // Ensure that the larger constant is on the RHS.
3817   bool ShouldSwap;
3818   if (ICmpInst::isSignedPredicate(LHSCC) ||
3819       (ICmpInst::isEquality(LHSCC) && 
3820        ICmpInst::isSignedPredicate(RHSCC)))
3821     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3822   else
3823     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3824     
3825   if (ShouldSwap) {
3826     std::swap(LHS, RHS);
3827     std::swap(LHSCst, RHSCst);
3828     std::swap(LHSCC, RHSCC);
3829   }
3830
3831   // At this point, we know we have have two icmp instructions
3832   // comparing a value against two constants and and'ing the result
3833   // together.  Because of the above check, we know that we only have
3834   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3835   // (from the FoldICmpLogical check above), that the two constants 
3836   // are not equal and that the larger constant is on the RHS
3837   assert(LHSCst != RHSCst && "Compares not folded above?");
3838
3839   switch (LHSCC) {
3840   default: llvm_unreachable("Unknown integer condition code!");
3841   case ICmpInst::ICMP_EQ:
3842     switch (RHSCC) {
3843     default: llvm_unreachable("Unknown integer condition code!");
3844     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3845     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3846     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3847       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3848     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3849     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3850     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3851       return ReplaceInstUsesWith(I, LHS);
3852     }
3853   case ICmpInst::ICMP_NE:
3854     switch (RHSCC) {
3855     default: llvm_unreachable("Unknown integer condition code!");
3856     case ICmpInst::ICMP_ULT:
3857       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3858         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3859       break;                        // (X != 13 & X u< 15) -> no change
3860     case ICmpInst::ICMP_SLT:
3861       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3862         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3863       break;                        // (X != 13 & X s< 15) -> no change
3864     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3865     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3866     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3867       return ReplaceInstUsesWith(I, RHS);
3868     case ICmpInst::ICMP_NE:
3869       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3870         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3871         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3872         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3873                             ConstantInt::get(Add->getType(), 1));
3874       }
3875       break;                        // (X != 13 & X != 15) -> no change
3876     }
3877     break;
3878   case ICmpInst::ICMP_ULT:
3879     switch (RHSCC) {
3880     default: llvm_unreachable("Unknown integer condition code!");
3881     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3882     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3883       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3884     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3885       break;
3886     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3887     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3888       return ReplaceInstUsesWith(I, LHS);
3889     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3890       break;
3891     }
3892     break;
3893   case ICmpInst::ICMP_SLT:
3894     switch (RHSCC) {
3895     default: llvm_unreachable("Unknown integer condition code!");
3896     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3897     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3898       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3899     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3900       break;
3901     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3902     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3903       return ReplaceInstUsesWith(I, LHS);
3904     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3905       break;
3906     }
3907     break;
3908   case ICmpInst::ICMP_UGT:
3909     switch (RHSCC) {
3910     default: llvm_unreachable("Unknown integer condition code!");
3911     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3912     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3913       return ReplaceInstUsesWith(I, RHS);
3914     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3915       break;
3916     case ICmpInst::ICMP_NE:
3917       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3918         return new ICmpInst(LHSCC, Val, RHSCst);
3919       break;                        // (X u> 13 & X != 15) -> no change
3920     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3921       return InsertRangeTest(Val, AddOne(LHSCst),
3922                              RHSCst, false, true, I);
3923     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3924       break;
3925     }
3926     break;
3927   case ICmpInst::ICMP_SGT:
3928     switch (RHSCC) {
3929     default: llvm_unreachable("Unknown integer condition code!");
3930     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3931     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3932       return ReplaceInstUsesWith(I, RHS);
3933     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3934       break;
3935     case ICmpInst::ICMP_NE:
3936       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3937         return new ICmpInst(LHSCC, Val, RHSCst);
3938       break;                        // (X s> 13 & X != 15) -> no change
3939     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3940       return InsertRangeTest(Val, AddOne(LHSCst),
3941                              RHSCst, true, true, I);
3942     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3943       break;
3944     }
3945     break;
3946   }
3947  
3948   return 0;
3949 }
3950
3951 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3952                                           FCmpInst *RHS) {
3953   
3954   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3955       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3956     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3957     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3958       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3959         // If either of the constants are nans, then the whole thing returns
3960         // false.
3961         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3962           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3963         return new FCmpInst(FCmpInst::FCMP_ORD,
3964                             LHS->getOperand(0), RHS->getOperand(0));
3965       }
3966     
3967     // Handle vector zeros.  This occurs because the canonical form of
3968     // "fcmp ord x,x" is "fcmp ord x, 0".
3969     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3970         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3971       return new FCmpInst(FCmpInst::FCMP_ORD,
3972                           LHS->getOperand(0), RHS->getOperand(0));
3973     return 0;
3974   }
3975   
3976   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3977   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3978   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3979   
3980   
3981   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3982     // Swap RHS operands to match LHS.
3983     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3984     std::swap(Op1LHS, Op1RHS);
3985   }
3986   
3987   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3988     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3989     if (Op0CC == Op1CC)
3990       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3991     
3992     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3993       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3994     if (Op0CC == FCmpInst::FCMP_TRUE)
3995       return ReplaceInstUsesWith(I, RHS);
3996     if (Op1CC == FCmpInst::FCMP_TRUE)
3997       return ReplaceInstUsesWith(I, LHS);
3998     
3999     bool Op0Ordered;
4000     bool Op1Ordered;
4001     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4002     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4003     if (Op1Pred == 0) {
4004       std::swap(LHS, RHS);
4005       std::swap(Op0Pred, Op1Pred);
4006       std::swap(Op0Ordered, Op1Ordered);
4007     }
4008     if (Op0Pred == 0) {
4009       // uno && ueq -> uno && (uno || eq) -> ueq
4010       // ord && olt -> ord && (ord && lt) -> olt
4011       if (Op0Ordered == Op1Ordered)
4012         return ReplaceInstUsesWith(I, RHS);
4013       
4014       // uno && oeq -> uno && (ord && eq) -> false
4015       // uno && ord -> false
4016       if (!Op0Ordered)
4017         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4018       // ord && ueq -> ord && (uno || eq) -> oeq
4019       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4020                                             Op0LHS, Op0RHS, Context));
4021     }
4022   }
4023
4024   return 0;
4025 }
4026
4027
4028 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4029   bool Changed = SimplifyCommutative(I);
4030   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4031
4032   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4033     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4034
4035   // and X, X = X
4036   if (Op0 == Op1)
4037     return ReplaceInstUsesWith(I, Op1);
4038
4039   // See if we can simplify any instructions used by the instruction whose sole 
4040   // purpose is to compute bits we don't care about.
4041   if (SimplifyDemandedInstructionBits(I))
4042     return &I;
4043   if (isa<VectorType>(I.getType())) {
4044     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4045       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4046         return ReplaceInstUsesWith(I, I.getOperand(0));
4047     } else if (isa<ConstantAggregateZero>(Op1)) {
4048       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4049     }
4050   }
4051
4052   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4053     const APInt& AndRHSMask = AndRHS->getValue();
4054     APInt NotAndRHS(~AndRHSMask);
4055
4056     // Optimize a variety of ((val OP C1) & C2) combinations...
4057     if (isa<BinaryOperator>(Op0)) {
4058       Instruction *Op0I = cast<Instruction>(Op0);
4059       Value *Op0LHS = Op0I->getOperand(0);
4060       Value *Op0RHS = Op0I->getOperand(1);
4061       switch (Op0I->getOpcode()) {
4062       case Instruction::Xor:
4063       case Instruction::Or:
4064         // If the mask is only needed on one incoming arm, push it up.
4065         if (Op0I->hasOneUse()) {
4066           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4067             // Not masking anything out for the LHS, move to RHS.
4068             Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4069                                                Op0RHS->getName()+".masked");
4070             return BinaryOperator::Create(
4071                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4072           }
4073           if (!isa<Constant>(Op0RHS) &&
4074               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4075             // Not masking anything out for the RHS, move to LHS.
4076             Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4077                                                Op0LHS->getName()+".masked");
4078             return BinaryOperator::Create(
4079                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4080           }
4081         }
4082
4083         break;
4084       case Instruction::Add:
4085         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4086         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4089           return BinaryOperator::CreateAnd(V, AndRHS);
4090         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4091           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4092         break;
4093
4094       case Instruction::Sub:
4095         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4096         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4099           return BinaryOperator::CreateAnd(V, AndRHS);
4100
4101         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4102         // has 1's for all bits that the subtraction with A might affect.
4103         if (Op0I->hasOneUse()) {
4104           uint32_t BitWidth = AndRHSMask.getBitWidth();
4105           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4106           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4107
4108           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4109           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4110               MaskedValueIsZero(Op0LHS, Mask)) {
4111             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4112             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4113           }
4114         }
4115         break;
4116
4117       case Instruction::Shl:
4118       case Instruction::LShr:
4119         // (1 << x) & 1 --> zext(x == 0)
4120         // (1 >> x) & 1 --> zext(x == 0)
4121         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4122           Value *NewICmp =
4123             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4124           return new ZExtInst(NewICmp, I.getType());
4125         }
4126         break;
4127       }
4128
4129       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4130         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4131           return Res;
4132     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4133       // If this is an integer truncation or change from signed-to-unsigned, and
4134       // if the source is an and/or with immediate, transform it.  This
4135       // frequently occurs for bitfield accesses.
4136       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4137         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4138             CastOp->getNumOperands() == 2)
4139           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4140             if (CastOp->getOpcode() == Instruction::And) {
4141               // Change: and (cast (and X, C1) to T), C2
4142               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4143               // This will fold the two constants together, which may allow 
4144               // other simplifications.
4145               Value *NewCast = Builder->CreateTruncOrBitCast(
4146                 CastOp->getOperand(0), I.getType(), 
4147                 CastOp->getName()+".shrunk");
4148               // trunc_or_bitcast(C1)&C2
4149               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4150               C3 = ConstantExpr::getAnd(C3, AndRHS);
4151               return BinaryOperator::CreateAnd(NewCast, C3);
4152             } else if (CastOp->getOpcode() == Instruction::Or) {
4153               // Change: and (cast (or X, C1) to T), C2
4154               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4155               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4156               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4157                 // trunc(C1)&C2
4158                 return ReplaceInstUsesWith(I, AndRHS);
4159             }
4160           }
4161       }
4162     }
4163
4164     // Try to fold constant and into select arguments.
4165     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4166       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4167         return R;
4168     if (isa<PHINode>(Op0))
4169       if (Instruction *NV = FoldOpIntoPhi(I))
4170         return NV;
4171   }
4172
4173   Value *Op0NotVal = dyn_castNotVal(Op0);
4174   Value *Op1NotVal = dyn_castNotVal(Op1);
4175
4176   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4177     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4178
4179   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4180   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4181     Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4182                                   I.getName()+".demorgan");
4183     return BinaryOperator::CreateNot(Or);
4184   }
4185   
4186   {
4187     Value *A = 0, *B = 0, *C = 0, *D = 0;
4188     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4189       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4190         return ReplaceInstUsesWith(I, Op1);
4191     
4192       // (A|B) & ~(A&B) -> A^B
4193       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4194         if ((A == C && B == D) || (A == D && B == C))
4195           return BinaryOperator::CreateXor(A, B);
4196       }
4197     }
4198     
4199     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4200       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4201         return ReplaceInstUsesWith(I, Op0);
4202
4203       // ~(A&B) & (A|B) -> A^B
4204       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4205         if ((A == C && B == D) || (A == D && B == C))
4206           return BinaryOperator::CreateXor(A, B);
4207       }
4208     }
4209     
4210     if (Op0->hasOneUse() &&
4211         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4212       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4213         I.swapOperands();     // Simplify below
4214         std::swap(Op0, Op1);
4215       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4216         cast<BinaryOperator>(Op0)->swapOperands();
4217         I.swapOperands();     // Simplify below
4218         std::swap(Op0, Op1);
4219       }
4220     }
4221
4222     if (Op1->hasOneUse() &&
4223         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4224       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4225         cast<BinaryOperator>(Op1)->swapOperands();
4226         std::swap(A, B);
4227       }
4228       if (A == Op0)                                // A&(A^B) -> A & ~B
4229         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4230     }
4231
4232     // (A&((~A)|B)) -> A&B
4233     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4234         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4235       return BinaryOperator::CreateAnd(A, Op1);
4236     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4237         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4238       return BinaryOperator::CreateAnd(A, Op0);
4239   }
4240   
4241   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4242     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4243     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4244       return R;
4245
4246     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4247       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4248         return Res;
4249   }
4250
4251   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4252   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4253     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4254       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4255         const Type *SrcTy = Op0C->getOperand(0)->getType();
4256         if (SrcTy == Op1C->getOperand(0)->getType() &&
4257             SrcTy->isIntOrIntVector() &&
4258             // Only do this if the casts both really cause code to be generated.
4259             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4260                               I.getType(), TD) &&
4261             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4262                               I.getType(), TD)) {
4263           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4264                                             Op1C->getOperand(0), I.getName());
4265           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4266         }
4267       }
4268     
4269   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4270   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4271     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4272       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4273           SI0->getOperand(1) == SI1->getOperand(1) &&
4274           (SI0->hasOneUse() || SI1->hasOneUse())) {
4275         Value *NewOp =
4276           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4277                              SI0->getName());
4278         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4279                                       SI1->getOperand(1));
4280       }
4281   }
4282
4283   // If and'ing two fcmp, try combine them into one.
4284   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4285     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4286       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4287         return Res;
4288   }
4289
4290   return Changed ? &I : 0;
4291 }
4292
4293 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4294 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4295 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4296 /// the expression came from the corresponding "byte swapped" byte in some other
4297 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4298 /// we know that the expression deposits the low byte of %X into the high byte
4299 /// of the bswap result and that all other bytes are zero.  This expression is
4300 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4301 /// match.
4302 ///
4303 /// This function returns true if the match was unsuccessful and false if so.
4304 /// On entry to the function the "OverallLeftShift" is a signed integer value
4305 /// indicating the number of bytes that the subexpression is later shifted.  For
4306 /// example, if the expression is later right shifted by 16 bits, the
4307 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4308 /// byte of ByteValues is actually being set.
4309 ///
4310 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4311 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4312 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4313 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4314 /// always in the local (OverallLeftShift) coordinate space.
4315 ///
4316 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4317                               SmallVector<Value*, 8> &ByteValues) {
4318   if (Instruction *I = dyn_cast<Instruction>(V)) {
4319     // If this is an or instruction, it may be an inner node of the bswap.
4320     if (I->getOpcode() == Instruction::Or) {
4321       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4322                                ByteValues) ||
4323              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4324                                ByteValues);
4325     }
4326   
4327     // If this is a logical shift by a constant multiple of 8, recurse with
4328     // OverallLeftShift and ByteMask adjusted.
4329     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4330       unsigned ShAmt = 
4331         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4332       // Ensure the shift amount is defined and of a byte value.
4333       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4334         return true;
4335
4336       unsigned ByteShift = ShAmt >> 3;
4337       if (I->getOpcode() == Instruction::Shl) {
4338         // X << 2 -> collect(X, +2)
4339         OverallLeftShift += ByteShift;
4340         ByteMask >>= ByteShift;
4341       } else {
4342         // X >>u 2 -> collect(X, -2)
4343         OverallLeftShift -= ByteShift;
4344         ByteMask <<= ByteShift;
4345         ByteMask &= (~0U >> (32-ByteValues.size()));
4346       }
4347
4348       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4349       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4350
4351       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4352                                ByteValues);
4353     }
4354
4355     // If this is a logical 'and' with a mask that clears bytes, clear the
4356     // corresponding bytes in ByteMask.
4357     if (I->getOpcode() == Instruction::And &&
4358         isa<ConstantInt>(I->getOperand(1))) {
4359       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4360       unsigned NumBytes = ByteValues.size();
4361       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4362       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4363       
4364       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4365         // If this byte is masked out by a later operation, we don't care what
4366         // the and mask is.
4367         if ((ByteMask & (1 << i)) == 0)
4368           continue;
4369         
4370         // If the AndMask is all zeros for this byte, clear the bit.
4371         APInt MaskB = AndMask & Byte;
4372         if (MaskB == 0) {
4373           ByteMask &= ~(1U << i);
4374           continue;
4375         }
4376         
4377         // If the AndMask is not all ones for this byte, it's not a bytezap.
4378         if (MaskB != Byte)
4379           return true;
4380
4381         // Otherwise, this byte is kept.
4382       }
4383
4384       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4385                                ByteValues);
4386     }
4387   }
4388   
4389   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4390   // the input value to the bswap.  Some observations: 1) if more than one byte
4391   // is demanded from this input, then it could not be successfully assembled
4392   // into a byteswap.  At least one of the two bytes would not be aligned with
4393   // their ultimate destination.
4394   if (!isPowerOf2_32(ByteMask)) return true;
4395   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4396   
4397   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4398   // is demanded, it needs to go into byte 0 of the result.  This means that the
4399   // byte needs to be shifted until it lands in the right byte bucket.  The
4400   // shift amount depends on the position: if the byte is coming from the high
4401   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4402   // low part, it must be shifted left.
4403   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4404   if (InputByteNo < ByteValues.size()/2) {
4405     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4406       return true;
4407   } else {
4408     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4409       return true;
4410   }
4411   
4412   // If the destination byte value is already defined, the values are or'd
4413   // together, which isn't a bswap (unless it's an or of the same bits).
4414   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4415     return true;
4416   ByteValues[DestByteNo] = V;
4417   return false;
4418 }
4419
4420 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4421 /// If so, insert the new bswap intrinsic and return it.
4422 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4423   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4424   if (!ITy || ITy->getBitWidth() % 16 || 
4425       // ByteMask only allows up to 32-byte values.
4426       ITy->getBitWidth() > 32*8) 
4427     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4428   
4429   /// ByteValues - For each byte of the result, we keep track of which value
4430   /// defines each byte.
4431   SmallVector<Value*, 8> ByteValues;
4432   ByteValues.resize(ITy->getBitWidth()/8);
4433     
4434   // Try to find all the pieces corresponding to the bswap.
4435   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4436   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4437     return 0;
4438   
4439   // Check to see if all of the bytes come from the same value.
4440   Value *V = ByteValues[0];
4441   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4442   
4443   // Check to make sure that all of the bytes come from the same value.
4444   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4445     if (ByteValues[i] != V)
4446       return 0;
4447   const Type *Tys[] = { ITy };
4448   Module *M = I.getParent()->getParent()->getParent();
4449   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4450   return CallInst::Create(F, V);
4451 }
4452
4453 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4454 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4455 /// we can simplify this expression to "cond ? C : D or B".
4456 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4457                                          Value *C, Value *D,
4458                                          LLVMContext *Context) {
4459   // If A is not a select of -1/0, this cannot match.
4460   Value *Cond = 0;
4461   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4462     return 0;
4463
4464   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4465   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4466     return SelectInst::Create(Cond, C, B);
4467   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4468     return SelectInst::Create(Cond, C, B);
4469   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4470   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4471     return SelectInst::Create(Cond, C, D);
4472   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4473     return SelectInst::Create(Cond, C, D);
4474   return 0;
4475 }
4476
4477 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4478 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4479                                          ICmpInst *LHS, ICmpInst *RHS) {
4480   Value *Val, *Val2;
4481   ConstantInt *LHSCst, *RHSCst;
4482   ICmpInst::Predicate LHSCC, RHSCC;
4483   
4484   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4485   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4486              m_ConstantInt(LHSCst))) ||
4487       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4488              m_ConstantInt(RHSCst))))
4489     return 0;
4490   
4491   // From here on, we only handle:
4492   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4493   if (Val != Val2) return 0;
4494   
4495   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4496   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4497       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4498       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4499       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4500     return 0;
4501   
4502   // We can't fold (ugt x, C) | (sgt x, C2).
4503   if (!PredicatesFoldable(LHSCC, RHSCC))
4504     return 0;
4505   
4506   // Ensure that the larger constant is on the RHS.
4507   bool ShouldSwap;
4508   if (ICmpInst::isSignedPredicate(LHSCC) ||
4509       (ICmpInst::isEquality(LHSCC) && 
4510        ICmpInst::isSignedPredicate(RHSCC)))
4511     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4512   else
4513     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4514   
4515   if (ShouldSwap) {
4516     std::swap(LHS, RHS);
4517     std::swap(LHSCst, RHSCst);
4518     std::swap(LHSCC, RHSCC);
4519   }
4520   
4521   // At this point, we know we have have two icmp instructions
4522   // comparing a value against two constants and or'ing the result
4523   // together.  Because of the above check, we know that we only have
4524   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4525   // FoldICmpLogical check above), that the two constants are not
4526   // equal.
4527   assert(LHSCst != RHSCst && "Compares not folded above?");
4528
4529   switch (LHSCC) {
4530   default: llvm_unreachable("Unknown integer condition code!");
4531   case ICmpInst::ICMP_EQ:
4532     switch (RHSCC) {
4533     default: llvm_unreachable("Unknown integer condition code!");
4534     case ICmpInst::ICMP_EQ:
4535       if (LHSCst == SubOne(RHSCst)) {
4536         // (X == 13 | X == 14) -> X-13 <u 2
4537         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4538         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4539         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4540         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4541       }
4542       break;                         // (X == 13 | X == 15) -> no change
4543     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4544     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4545       break;
4546     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4547     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4548     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4549       return ReplaceInstUsesWith(I, RHS);
4550     }
4551     break;
4552   case ICmpInst::ICMP_NE:
4553     switch (RHSCC) {
4554     default: llvm_unreachable("Unknown integer condition code!");
4555     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4556     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4557     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4558       return ReplaceInstUsesWith(I, LHS);
4559     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4560     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4561     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4562       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4563     }
4564     break;
4565   case ICmpInst::ICMP_ULT:
4566     switch (RHSCC) {
4567     default: llvm_unreachable("Unknown integer condition code!");
4568     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4569       break;
4570     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4571       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4572       // this can cause overflow.
4573       if (RHSCst->isMaxValue(false))
4574         return ReplaceInstUsesWith(I, LHS);
4575       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4576                              false, false, I);
4577     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4578       break;
4579     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4580     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4581       return ReplaceInstUsesWith(I, RHS);
4582     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4583       break;
4584     }
4585     break;
4586   case ICmpInst::ICMP_SLT:
4587     switch (RHSCC) {
4588     default: llvm_unreachable("Unknown integer condition code!");
4589     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4590       break;
4591     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4592       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4593       // this can cause overflow.
4594       if (RHSCst->isMaxValue(true))
4595         return ReplaceInstUsesWith(I, LHS);
4596       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4597                              true, false, I);
4598     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4599       break;
4600     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4601     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4602       return ReplaceInstUsesWith(I, RHS);
4603     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4604       break;
4605     }
4606     break;
4607   case ICmpInst::ICMP_UGT:
4608     switch (RHSCC) {
4609     default: llvm_unreachable("Unknown integer condition code!");
4610     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4611     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4612       return ReplaceInstUsesWith(I, LHS);
4613     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4614       break;
4615     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4616     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4617       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4618     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4619       break;
4620     }
4621     break;
4622   case ICmpInst::ICMP_SGT:
4623     switch (RHSCC) {
4624     default: llvm_unreachable("Unknown integer condition code!");
4625     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4626     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4627       return ReplaceInstUsesWith(I, LHS);
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) -> true
4631     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4632       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4633     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4634       break;
4635     }
4636     break;
4637   }
4638   return 0;
4639 }
4640
4641 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4642                                          FCmpInst *RHS) {
4643   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4644       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4645       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4646     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4647       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4648         // If either of the constants are nans, then the whole thing returns
4649         // true.
4650         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4651           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4652         
4653         // Otherwise, no need to compare the two constants, compare the
4654         // rest.
4655         return new FCmpInst(FCmpInst::FCMP_UNO,
4656                             LHS->getOperand(0), RHS->getOperand(0));
4657       }
4658     
4659     // Handle vector zeros.  This occurs because the canonical form of
4660     // "fcmp uno x,x" is "fcmp uno x, 0".
4661     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4662         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4663       return new FCmpInst(FCmpInst::FCMP_UNO,
4664                           LHS->getOperand(0), RHS->getOperand(0));
4665     
4666     return 0;
4667   }
4668   
4669   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4670   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4671   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4672   
4673   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4674     // Swap RHS operands to match LHS.
4675     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4676     std::swap(Op1LHS, Op1RHS);
4677   }
4678   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4679     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4680     if (Op0CC == Op1CC)
4681       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4682                           Op0LHS, Op0RHS);
4683     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4684       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4685     if (Op0CC == FCmpInst::FCMP_FALSE)
4686       return ReplaceInstUsesWith(I, RHS);
4687     if (Op1CC == FCmpInst::FCMP_FALSE)
4688       return ReplaceInstUsesWith(I, LHS);
4689     bool Op0Ordered;
4690     bool Op1Ordered;
4691     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4692     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4693     if (Op0Ordered == Op1Ordered) {
4694       // If both are ordered or unordered, return a new fcmp with
4695       // or'ed predicates.
4696       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4697                                Op0LHS, Op0RHS, Context);
4698       if (Instruction *I = dyn_cast<Instruction>(RV))
4699         return I;
4700       // Otherwise, it's a constant boolean value...
4701       return ReplaceInstUsesWith(I, RV);
4702     }
4703   }
4704   return 0;
4705 }
4706
4707 /// FoldOrWithConstants - This helper function folds:
4708 ///
4709 ///     ((A | B) & C1) | (B & C2)
4710 ///
4711 /// into:
4712 /// 
4713 ///     (A & C1) | B
4714 ///
4715 /// when the XOR of the two constants is "all ones" (-1).
4716 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4717                                                Value *A, Value *B, Value *C) {
4718   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4719   if (!CI1) return 0;
4720
4721   Value *V1 = 0;
4722   ConstantInt *CI2 = 0;
4723   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4724
4725   APInt Xor = CI1->getValue() ^ CI2->getValue();
4726   if (!Xor.isAllOnesValue()) return 0;
4727
4728   if (V1 == A || V1 == B) {
4729     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4730     return BinaryOperator::CreateOr(NewOp, V1);
4731   }
4732
4733   return 0;
4734 }
4735
4736 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4737   bool Changed = SimplifyCommutative(I);
4738   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4739
4740   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4741     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4742
4743   // or X, X = X
4744   if (Op0 == Op1)
4745     return ReplaceInstUsesWith(I, Op0);
4746
4747   // See if we can simplify any instructions used by the instruction whose sole 
4748   // purpose is to compute bits we don't care about.
4749   if (SimplifyDemandedInstructionBits(I))
4750     return &I;
4751   if (isa<VectorType>(I.getType())) {
4752     if (isa<ConstantAggregateZero>(Op1)) {
4753       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4754     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4755       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4756         return ReplaceInstUsesWith(I, I.getOperand(1));
4757     }
4758   }
4759
4760   // or X, -1 == -1
4761   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4762     ConstantInt *C1 = 0; Value *X = 0;
4763     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4764     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4765         isOnlyUse(Op0)) {
4766       Value *Or = Builder->CreateOr(X, RHS);
4767       Or->takeName(Op0);
4768       return BinaryOperator::CreateAnd(Or, 
4769                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4770     }
4771
4772     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4773     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4774         isOnlyUse(Op0)) {
4775       Value *Or = Builder->CreateOr(X, RHS);
4776       Or->takeName(Op0);
4777       return BinaryOperator::CreateXor(Or,
4778                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4779     }
4780
4781     // Try to fold constant and into select arguments.
4782     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4783       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4784         return R;
4785     if (isa<PHINode>(Op0))
4786       if (Instruction *NV = FoldOpIntoPhi(I))
4787         return NV;
4788   }
4789
4790   Value *A = 0, *B = 0;
4791   ConstantInt *C1 = 0, *C2 = 0;
4792
4793   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4794     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4795       return ReplaceInstUsesWith(I, Op1);
4796   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4797     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4798       return ReplaceInstUsesWith(I, Op0);
4799
4800   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4801   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4802   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4803       match(Op1, m_Or(m_Value(), m_Value())) ||
4804       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4805        match(Op1, m_Shift(m_Value(), m_Value())))) {
4806     if (Instruction *BSwap = MatchBSwap(I))
4807       return BSwap;
4808   }
4809   
4810   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4811   if (Op0->hasOneUse() &&
4812       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4813       MaskedValueIsZero(Op1, C1->getValue())) {
4814     Value *NOr = Builder->CreateOr(A, Op1);
4815     NOr->takeName(Op0);
4816     return BinaryOperator::CreateXor(NOr, C1);
4817   }
4818
4819   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4820   if (Op1->hasOneUse() &&
4821       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4822       MaskedValueIsZero(Op0, C1->getValue())) {
4823     Value *NOr = Builder->CreateOr(A, Op0);
4824     NOr->takeName(Op0);
4825     return BinaryOperator::CreateXor(NOr, C1);
4826   }
4827
4828   // (A & C)|(B & D)
4829   Value *C = 0, *D = 0;
4830   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4831       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4832     Value *V1 = 0, *V2 = 0, *V3 = 0;
4833     C1 = dyn_cast<ConstantInt>(C);
4834     C2 = dyn_cast<ConstantInt>(D);
4835     if (C1 && C2) {  // (A & C1)|(B & C2)
4836       // If we have: ((V + N) & C1) | (V & C2)
4837       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4838       // replace with V+N.
4839       if (C1->getValue() == ~C2->getValue()) {
4840         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4841             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4842           // Add commutes, try both ways.
4843           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4844             return ReplaceInstUsesWith(I, A);
4845           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4846             return ReplaceInstUsesWith(I, A);
4847         }
4848         // Or commutes, try both ways.
4849         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4850             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4851           // Add commutes, try both ways.
4852           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4853             return ReplaceInstUsesWith(I, B);
4854           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4855             return ReplaceInstUsesWith(I, B);
4856         }
4857       }
4858       V1 = 0; V2 = 0; V3 = 0;
4859     }
4860     
4861     // Check to see if we have any common things being and'ed.  If so, find the
4862     // terms for V1 & (V2|V3).
4863     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4864       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4865         V1 = A, V2 = C, V3 = D;
4866       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4867         V1 = A, V2 = B, V3 = C;
4868       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4869         V1 = C, V2 = A, V3 = D;
4870       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4871         V1 = C, V2 = A, V3 = B;
4872       
4873       if (V1) {
4874         Value *Or = Builder->CreateOr(V2, V3, "tmp");
4875         return BinaryOperator::CreateAnd(V1, Or);
4876       }
4877     }
4878
4879     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4880     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4881       return Match;
4882     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4883       return Match;
4884     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4885       return Match;
4886     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4887       return Match;
4888
4889     // ((A&~B)|(~A&B)) -> A^B
4890     if ((match(C, m_Not(m_Specific(D))) &&
4891          match(B, m_Not(m_Specific(A)))))
4892       return BinaryOperator::CreateXor(A, D);
4893     // ((~B&A)|(~A&B)) -> A^B
4894     if ((match(A, m_Not(m_Specific(D))) &&
4895          match(B, m_Not(m_Specific(C)))))
4896       return BinaryOperator::CreateXor(C, D);
4897     // ((A&~B)|(B&~A)) -> A^B
4898     if ((match(C, m_Not(m_Specific(B))) &&
4899          match(D, m_Not(m_Specific(A)))))
4900       return BinaryOperator::CreateXor(A, B);
4901     // ((~B&A)|(B&~A)) -> A^B
4902     if ((match(A, m_Not(m_Specific(B))) &&
4903          match(D, m_Not(m_Specific(C)))))
4904       return BinaryOperator::CreateXor(C, B);
4905   }
4906   
4907   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4908   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4909     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4910       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4911           SI0->getOperand(1) == SI1->getOperand(1) &&
4912           (SI0->hasOneUse() || SI1->hasOneUse())) {
4913         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4914                                          SI0->getName());
4915         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4916                                       SI1->getOperand(1));
4917       }
4918   }
4919
4920   // ((A|B)&1)|(B&-2) -> (A&1) | B
4921   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4922       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4923     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4924     if (Ret) return Ret;
4925   }
4926   // (B&-2)|((A|B)&1) -> (A&1) | B
4927   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4928       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4929     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4930     if (Ret) return Ret;
4931   }
4932
4933   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4934     if (A == Op1)   // ~A | A == -1
4935       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4936   } else {
4937     A = 0;
4938   }
4939   // Note, A is still live here!
4940   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4941     if (Op0 == B)
4942       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4943
4944     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4945     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4946       Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4947       return BinaryOperator::CreateNot(And);
4948     }
4949   }
4950
4951   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4952   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4953     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4954       return R;
4955
4956     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4957       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4958         return Res;
4959   }
4960     
4961   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4962   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4963     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4964       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4965         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4966             !isa<ICmpInst>(Op1C->getOperand(0))) {
4967           const Type *SrcTy = Op0C->getOperand(0)->getType();
4968           if (SrcTy == Op1C->getOperand(0)->getType() &&
4969               SrcTy->isIntOrIntVector() &&
4970               // Only do this if the casts both really cause code to be
4971               // generated.
4972               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4973                                 I.getType(), TD) &&
4974               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4975                                 I.getType(), TD)) {
4976             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4977                                              Op1C->getOperand(0), I.getName());
4978             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4979           }
4980         }
4981       }
4982   }
4983   
4984     
4985   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4986   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4987     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4988       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4989         return Res;
4990   }
4991
4992   return Changed ? &I : 0;
4993 }
4994
4995 namespace {
4996
4997 // XorSelf - Implements: X ^ X --> 0
4998 struct XorSelf {
4999   Value *RHS;
5000   XorSelf(Value *rhs) : RHS(rhs) {}
5001   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5002   Instruction *apply(BinaryOperator &Xor) const {
5003     return &Xor;
5004   }
5005 };
5006
5007 }
5008
5009 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5010   bool Changed = SimplifyCommutative(I);
5011   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5012
5013   if (isa<UndefValue>(Op1)) {
5014     if (isa<UndefValue>(Op0))
5015       // Handle undef ^ undef -> 0 special case. This is a common
5016       // idiom (misuse).
5017       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5018     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5019   }
5020
5021   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5022   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5023     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5024     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5025   }
5026   
5027   // See if we can simplify any instructions used by the instruction whose sole 
5028   // purpose is to compute bits we don't care about.
5029   if (SimplifyDemandedInstructionBits(I))
5030     return &I;
5031   if (isa<VectorType>(I.getType()))
5032     if (isa<ConstantAggregateZero>(Op1))
5033       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5034
5035   // Is this a ~ operation?
5036   if (Value *NotOp = dyn_castNotVal(&I)) {
5037     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5038     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5039     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5040       if (Op0I->getOpcode() == Instruction::And || 
5041           Op0I->getOpcode() == Instruction::Or) {
5042         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5043         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5044           Value *NotY =
5045             Builder->CreateNot(Op0I->getOperand(1),
5046                                Op0I->getOperand(1)->getName()+".not");
5047           if (Op0I->getOpcode() == Instruction::And)
5048             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5049           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5050         }
5051       }
5052     }
5053   }
5054   
5055   
5056   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5057     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5058       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5059       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5060         return new ICmpInst(ICI->getInversePredicate(),
5061                             ICI->getOperand(0), ICI->getOperand(1));
5062
5063       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5064         return new FCmpInst(FCI->getInversePredicate(),
5065                             FCI->getOperand(0), FCI->getOperand(1));
5066     }
5067
5068     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5069     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5070       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5071         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5072           Instruction::CastOps Opcode = Op0C->getOpcode();
5073           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5074               (RHS == ConstantExpr::getCast(Opcode, 
5075                                             ConstantInt::getTrue(*Context),
5076                                             Op0C->getDestTy()))) {
5077             CI->setPredicate(CI->getInversePredicate());
5078             return CastInst::Create(Opcode, CI, Op0C->getType());
5079           }
5080         }
5081       }
5082     }
5083
5084     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5085       // ~(c-X) == X-c-1 == X+(-c-1)
5086       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5087         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5088           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5089           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5090                                       ConstantInt::get(I.getType(), 1));
5091           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5092         }
5093           
5094       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5095         if (Op0I->getOpcode() == Instruction::Add) {
5096           // ~(X-c) --> (-c-1)-X
5097           if (RHS->isAllOnesValue()) {
5098             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5099             return BinaryOperator::CreateSub(
5100                            ConstantExpr::getSub(NegOp0CI,
5101                                       ConstantInt::get(I.getType(), 1)),
5102                                       Op0I->getOperand(0));
5103           } else if (RHS->getValue().isSignBit()) {
5104             // (X + C) ^ signbit -> (X + C + signbit)
5105             Constant *C = ConstantInt::get(*Context,
5106                                            RHS->getValue() + Op0CI->getValue());
5107             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5108
5109           }
5110         } else if (Op0I->getOpcode() == Instruction::Or) {
5111           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5112           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5113             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5114             // Anything in both C1 and C2 is known to be zero, remove it from
5115             // NewRHS.
5116             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5117             NewRHS = ConstantExpr::getAnd(NewRHS, 
5118                                        ConstantExpr::getNot(CommonBits));
5119             Worklist.Add(Op0I);
5120             I.setOperand(0, Op0I->getOperand(0));
5121             I.setOperand(1, NewRHS);
5122             return &I;
5123           }
5124         }
5125       }
5126     }
5127
5128     // Try to fold constant and into select arguments.
5129     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5130       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5131         return R;
5132     if (isa<PHINode>(Op0))
5133       if (Instruction *NV = FoldOpIntoPhi(I))
5134         return NV;
5135   }
5136
5137   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5138     if (X == Op1)
5139       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5140
5141   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5142     if (X == Op0)
5143       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5144
5145   
5146   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5147   if (Op1I) {
5148     Value *A, *B;
5149     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5150       if (A == Op0) {              // B^(B|A) == (A|B)^B
5151         Op1I->swapOperands();
5152         I.swapOperands();
5153         std::swap(Op0, Op1);
5154       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5155         I.swapOperands();     // Simplified below.
5156         std::swap(Op0, Op1);
5157       }
5158     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5159       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5160     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5161       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5162     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5163                Op1I->hasOneUse()){
5164       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5165         Op1I->swapOperands();
5166         std::swap(A, B);
5167       }
5168       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5169         I.swapOperands();     // Simplified below.
5170         std::swap(Op0, Op1);
5171       }
5172     }
5173   }
5174   
5175   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5176   if (Op0I) {
5177     Value *A, *B;
5178     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5179         Op0I->hasOneUse()) {
5180       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5181         std::swap(A, B);
5182       if (B == Op1)                                  // (A|B)^B == A & ~B
5183         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5184     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5185       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5186     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5187       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5188     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5189                Op0I->hasOneUse()){
5190       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5191         std::swap(A, B);
5192       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5193           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5194         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5195       }
5196     }
5197   }
5198   
5199   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5200   if (Op0I && Op1I && Op0I->isShift() && 
5201       Op0I->getOpcode() == Op1I->getOpcode() && 
5202       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5203       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5204     Value *NewOp =
5205       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5206                          Op0I->getName());
5207     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5208                                   Op1I->getOperand(1));
5209   }
5210     
5211   if (Op0I && Op1I) {
5212     Value *A, *B, *C, *D;
5213     // (A & B)^(A | B) -> A ^ B
5214     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5215         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5216       if ((A == C && B == D) || (A == D && B == C)) 
5217         return BinaryOperator::CreateXor(A, B);
5218     }
5219     // (A | B)^(A & B) -> A ^ B
5220     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5221         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5222       if ((A == C && B == D) || (A == D && B == C)) 
5223         return BinaryOperator::CreateXor(A, B);
5224     }
5225     
5226     // (A & B)^(C & D)
5227     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5228         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5229         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5230       // (X & Y)^(X & Y) -> (Y^Z) & X
5231       Value *X = 0, *Y = 0, *Z = 0;
5232       if (A == C)
5233         X = A, Y = B, Z = D;
5234       else if (A == D)
5235         X = A, Y = B, Z = C;
5236       else if (B == C)
5237         X = B, Y = A, Z = D;
5238       else if (B == D)
5239         X = B, Y = A, Z = C;
5240       
5241       if (X) {
5242         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5243         return BinaryOperator::CreateAnd(NewOp, X);
5244       }
5245     }
5246   }
5247     
5248   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5249   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5250     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5251       return R;
5252
5253   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5254   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5255     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5256       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5257         const Type *SrcTy = Op0C->getOperand(0)->getType();
5258         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5259             // Only do this if the casts both really cause code to be generated.
5260             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5261                               I.getType(), TD) &&
5262             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5263                               I.getType(), TD)) {
5264           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5265                                             Op1C->getOperand(0), I.getName());
5266           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5267         }
5268       }
5269   }
5270
5271   return Changed ? &I : 0;
5272 }
5273
5274 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5275                                    LLVMContext *Context) {
5276   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5277 }
5278
5279 static bool HasAddOverflow(ConstantInt *Result,
5280                            ConstantInt *In1, ConstantInt *In2,
5281                            bool IsSigned) {
5282   if (IsSigned)
5283     if (In2->getValue().isNegative())
5284       return Result->getValue().sgt(In1->getValue());
5285     else
5286       return Result->getValue().slt(In1->getValue());
5287   else
5288     return Result->getValue().ult(In1->getValue());
5289 }
5290
5291 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5292 /// overflowed for this type.
5293 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5294                             Constant *In2, LLVMContext *Context,
5295                             bool IsSigned = false) {
5296   Result = ConstantExpr::getAdd(In1, In2);
5297
5298   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5299     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5300       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5301       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5302                          ExtractElement(In1, Idx, Context),
5303                          ExtractElement(In2, Idx, Context),
5304                          IsSigned))
5305         return true;
5306     }
5307     return false;
5308   }
5309
5310   return HasAddOverflow(cast<ConstantInt>(Result),
5311                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5312                         IsSigned);
5313 }
5314
5315 static bool HasSubOverflow(ConstantInt *Result,
5316                            ConstantInt *In1, ConstantInt *In2,
5317                            bool IsSigned) {
5318   if (IsSigned)
5319     if (In2->getValue().isNegative())
5320       return Result->getValue().slt(In1->getValue());
5321     else
5322       return Result->getValue().sgt(In1->getValue());
5323   else
5324     return Result->getValue().ugt(In1->getValue());
5325 }
5326
5327 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5328 /// overflowed for this type.
5329 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5330                             Constant *In2, LLVMContext *Context,
5331                             bool IsSigned = false) {
5332   Result = ConstantExpr::getSub(In1, In2);
5333
5334   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5335     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5336       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5337       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5338                          ExtractElement(In1, Idx, Context),
5339                          ExtractElement(In2, Idx, Context),
5340                          IsSigned))
5341         return true;
5342     }
5343     return false;
5344   }
5345
5346   return HasSubOverflow(cast<ConstantInt>(Result),
5347                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5348                         IsSigned);
5349 }
5350
5351 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5352 /// code necessary to compute the offset from the base pointer (without adding
5353 /// in the base pointer).  Return the result as a signed integer of intptr size.
5354 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5355   TargetData &TD = *IC.getTargetData();
5356   gep_type_iterator GTI = gep_type_begin(GEP);
5357   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5358   Value *Result = Constant::getNullValue(IntPtrTy);
5359
5360   // Build a mask for high order bits.
5361   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5362   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5363
5364   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5365        ++i, ++GTI) {
5366     Value *Op = *i;
5367     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5368     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5369       if (OpC->isZero()) continue;
5370       
5371       // Handle a struct index, which adds its field offset to the pointer.
5372       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5373         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5374         
5375         Result = IC.Builder->CreateAdd(Result,
5376                                        ConstantInt::get(IntPtrTy, Size),
5377                                        GEP->getName()+".offs");
5378         continue;
5379       }
5380       
5381       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5382       Constant *OC =
5383               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5384       Scale = ConstantExpr::getMul(OC, Scale);
5385       // Emit an add instruction.
5386       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5387       continue;
5388     }
5389     // Convert to correct type.
5390     if (Op->getType() != IntPtrTy)
5391       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5392     if (Size != 1) {
5393       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5394       // We'll let instcombine(mul) convert this to a shl if possible.
5395       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5396     }
5397
5398     // Emit an add instruction.
5399     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5400   }
5401   return Result;
5402 }
5403
5404
5405 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5406 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5407 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5408 /// be complex, and scales are involved.  The above expression would also be
5409 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5410 /// This later form is less amenable to optimization though, and we are allowed
5411 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5412 ///
5413 /// If we can't emit an optimized form for this expression, this returns null.
5414 /// 
5415 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5416                                           InstCombiner &IC) {
5417   TargetData &TD = *IC.getTargetData();
5418   gep_type_iterator GTI = gep_type_begin(GEP);
5419
5420   // Check to see if this gep only has a single variable index.  If so, and if
5421   // any constant indices are a multiple of its scale, then we can compute this
5422   // in terms of the scale of the variable index.  For example, if the GEP
5423   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5424   // because the expression will cross zero at the same point.
5425   unsigned i, e = GEP->getNumOperands();
5426   int64_t Offset = 0;
5427   for (i = 1; i != e; ++i, ++GTI) {
5428     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5429       // Compute the aggregate offset of constant indices.
5430       if (CI->isZero()) continue;
5431
5432       // Handle a struct index, which adds its field offset to the pointer.
5433       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5434         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5435       } else {
5436         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5437         Offset += Size*CI->getSExtValue();
5438       }
5439     } else {
5440       // Found our variable index.
5441       break;
5442     }
5443   }
5444   
5445   // If there are no variable indices, we must have a constant offset, just
5446   // evaluate it the general way.
5447   if (i == e) return 0;
5448   
5449   Value *VariableIdx = GEP->getOperand(i);
5450   // Determine the scale factor of the variable element.  For example, this is
5451   // 4 if the variable index is into an array of i32.
5452   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5453   
5454   // Verify that there are no other variable indices.  If so, emit the hard way.
5455   for (++i, ++GTI; i != e; ++i, ++GTI) {
5456     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5457     if (!CI) return 0;
5458    
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   }
5470   
5471   // Okay, we know we have a single variable index, which must be a
5472   // pointer/array/vector index.  If there is no offset, life is simple, return
5473   // the index.
5474   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5475   if (Offset == 0) {
5476     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5477     // we don't need to bother extending: the extension won't affect where the
5478     // computation crosses zero.
5479     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5480       VariableIdx = new TruncInst(VariableIdx, 
5481                                   TD.getIntPtrType(VariableIdx->getContext()),
5482                                   VariableIdx->getName(), &I);
5483     return VariableIdx;
5484   }
5485   
5486   // Otherwise, there is an index.  The computation we will do will be modulo
5487   // the pointer size, so get it.
5488   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5489   
5490   Offset &= PtrSizeMask;
5491   VariableScale &= PtrSizeMask;
5492
5493   // To do this transformation, any constant index must be a multiple of the
5494   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5495   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5496   // multiple of the variable scale.
5497   int64_t NewOffs = Offset / (int64_t)VariableScale;
5498   if (Offset != NewOffs*(int64_t)VariableScale)
5499     return 0;
5500
5501   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5502   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5503   if (VariableIdx->getType() != IntPtrTy)
5504     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5505                                               true /*SExt*/, 
5506                                               VariableIdx->getName(), &I);
5507   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5508   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5509 }
5510
5511
5512 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5513 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5514 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5515                                        ICmpInst::Predicate Cond,
5516                                        Instruction &I) {
5517   // Look through bitcasts.
5518   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5519     RHS = BCI->getOperand(0);
5520
5521   Value *PtrBase = GEPLHS->getOperand(0);
5522   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5523     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5524     // This transformation (ignoring the base and scales) is valid because we
5525     // know pointers can't overflow since the gep is inbounds.  See if we can
5526     // output an optimized form.
5527     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5528     
5529     // If not, synthesize the offset the hard way.
5530     if (Offset == 0)
5531       Offset = EmitGEPOffset(GEPLHS, I, *this);
5532     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5533                         Constant::getNullValue(Offset->getType()));
5534   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5535     // If the base pointers are different, but the indices are the same, just
5536     // compare the base pointer.
5537     if (PtrBase != GEPRHS->getOperand(0)) {
5538       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5539       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5540                         GEPRHS->getOperand(0)->getType();
5541       if (IndicesTheSame)
5542         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5543           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5544             IndicesTheSame = false;
5545             break;
5546           }
5547
5548       // If all indices are the same, just compare the base pointers.
5549       if (IndicesTheSame)
5550         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5551                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5552
5553       // Otherwise, the base pointers are different and the indices are
5554       // different, bail out.
5555       return 0;
5556     }
5557
5558     // If one of the GEPs has all zero indices, recurse.
5559     bool AllZeros = true;
5560     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5561       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5562           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5563         AllZeros = false;
5564         break;
5565       }
5566     if (AllZeros)
5567       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5568                           ICmpInst::getSwappedPredicate(Cond), I);
5569
5570     // If the other GEP has all zero indices, recurse.
5571     AllZeros = true;
5572     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5573       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5574           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5575         AllZeros = false;
5576         break;
5577       }
5578     if (AllZeros)
5579       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5580
5581     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5582       // If the GEPs only differ by one index, compare it.
5583       unsigned NumDifferences = 0;  // Keep track of # differences.
5584       unsigned DiffOperand = 0;     // The operand that differs.
5585       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5586         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5587           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5588                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5589             // Irreconcilable differences.
5590             NumDifferences = 2;
5591             break;
5592           } else {
5593             if (NumDifferences++) break;
5594             DiffOperand = i;
5595           }
5596         }
5597
5598       if (NumDifferences == 0)   // SAME GEP?
5599         return ReplaceInstUsesWith(I, // No comparison is needed here.
5600                                    ConstantInt::get(Type::getInt1Ty(*Context),
5601                                              ICmpInst::isTrueWhenEqual(Cond)));
5602
5603       else if (NumDifferences == 1) {
5604         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5605         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5606         // Make sure we do a signed comparison here.
5607         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5608       }
5609     }
5610
5611     // Only lower this if the icmp is the only user of the GEP or if we expect
5612     // the result to fold to a constant!
5613     if (TD &&
5614         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5615         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5616       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5617       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5618       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5619       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5620     }
5621   }
5622   return 0;
5623 }
5624
5625 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5626 ///
5627 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5628                                                 Instruction *LHSI,
5629                                                 Constant *RHSC) {
5630   if (!isa<ConstantFP>(RHSC)) return 0;
5631   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5632   
5633   // Get the width of the mantissa.  We don't want to hack on conversions that
5634   // might lose information from the integer, e.g. "i64 -> float"
5635   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5636   if (MantissaWidth == -1) return 0;  // Unknown.
5637   
5638   // Check to see that the input is converted from an integer type that is small
5639   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5640   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5641   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5642   
5643   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5644   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5645   if (LHSUnsigned)
5646     ++InputSize;
5647   
5648   // If the conversion would lose info, don't hack on this.
5649   if ((int)InputSize > MantissaWidth)
5650     return 0;
5651   
5652   // Otherwise, we can potentially simplify the comparison.  We know that it
5653   // will always come through as an integer value and we know the constant is
5654   // not a NAN (it would have been previously simplified).
5655   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5656   
5657   ICmpInst::Predicate Pred;
5658   switch (I.getPredicate()) {
5659   default: llvm_unreachable("Unexpected predicate!");
5660   case FCmpInst::FCMP_UEQ:
5661   case FCmpInst::FCMP_OEQ:
5662     Pred = ICmpInst::ICMP_EQ;
5663     break;
5664   case FCmpInst::FCMP_UGT:
5665   case FCmpInst::FCMP_OGT:
5666     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5667     break;
5668   case FCmpInst::FCMP_UGE:
5669   case FCmpInst::FCMP_OGE:
5670     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5671     break;
5672   case FCmpInst::FCMP_ULT:
5673   case FCmpInst::FCMP_OLT:
5674     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5675     break;
5676   case FCmpInst::FCMP_ULE:
5677   case FCmpInst::FCMP_OLE:
5678     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5679     break;
5680   case FCmpInst::FCMP_UNE:
5681   case FCmpInst::FCMP_ONE:
5682     Pred = ICmpInst::ICMP_NE;
5683     break;
5684   case FCmpInst::FCMP_ORD:
5685     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5686   case FCmpInst::FCMP_UNO:
5687     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5688   }
5689   
5690   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5691   
5692   // Now we know that the APFloat is a normal number, zero or inf.
5693   
5694   // See if the FP constant is too large for the integer.  For example,
5695   // comparing an i8 to 300.0.
5696   unsigned IntWidth = IntTy->getScalarSizeInBits();
5697   
5698   if (!LHSUnsigned) {
5699     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5700     // and large values.
5701     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5702     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5703                           APFloat::rmNearestTiesToEven);
5704     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5705       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5706           Pred == ICmpInst::ICMP_SLE)
5707         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5708       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5709     }
5710   } else {
5711     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5712     // +INF and large values.
5713     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5714     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5715                           APFloat::rmNearestTiesToEven);
5716     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5717       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5718           Pred == ICmpInst::ICMP_ULE)
5719         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5720       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5721     }
5722   }
5723   
5724   if (!LHSUnsigned) {
5725     // See if the RHS value is < SignedMin.
5726     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5727     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5728                           APFloat::rmNearestTiesToEven);
5729     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5730       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5731           Pred == ICmpInst::ICMP_SGE)
5732         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5733       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5734     }
5735   }
5736
5737   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5738   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5739   // casting the FP value to the integer value and back, checking for equality.
5740   // Don't do this for zero, because -0.0 is not fractional.
5741   Constant *RHSInt = LHSUnsigned
5742     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5743     : ConstantExpr::getFPToSI(RHSC, IntTy);
5744   if (!RHS.isZero()) {
5745     bool Equal = LHSUnsigned
5746       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5747       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5748     if (!Equal) {
5749       // If we had a comparison against a fractional value, we have to adjust
5750       // the compare predicate and sometimes the value.  RHSC is rounded towards
5751       // zero at this point.
5752       switch (Pred) {
5753       default: llvm_unreachable("Unexpected integer comparison!");
5754       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5755         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5756       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5757         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5758       case ICmpInst::ICMP_ULE:
5759         // (float)int <= 4.4   --> int <= 4
5760         // (float)int <= -4.4  --> false
5761         if (RHS.isNegative())
5762           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5763         break;
5764       case ICmpInst::ICMP_SLE:
5765         // (float)int <= 4.4   --> int <= 4
5766         // (float)int <= -4.4  --> int < -4
5767         if (RHS.isNegative())
5768           Pred = ICmpInst::ICMP_SLT;
5769         break;
5770       case ICmpInst::ICMP_ULT:
5771         // (float)int < -4.4   --> false
5772         // (float)int < 4.4    --> int <= 4
5773         if (RHS.isNegative())
5774           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5775         Pred = ICmpInst::ICMP_ULE;
5776         break;
5777       case ICmpInst::ICMP_SLT:
5778         // (float)int < -4.4   --> int < -4
5779         // (float)int < 4.4    --> int <= 4
5780         if (!RHS.isNegative())
5781           Pred = ICmpInst::ICMP_SLE;
5782         break;
5783       case ICmpInst::ICMP_UGT:
5784         // (float)int > 4.4    --> int > 4
5785         // (float)int > -4.4   --> true
5786         if (RHS.isNegative())
5787           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5788         break;
5789       case ICmpInst::ICMP_SGT:
5790         // (float)int > 4.4    --> int > 4
5791         // (float)int > -4.4   --> int >= -4
5792         if (RHS.isNegative())
5793           Pred = ICmpInst::ICMP_SGE;
5794         break;
5795       case ICmpInst::ICMP_UGE:
5796         // (float)int >= -4.4   --> true
5797         // (float)int >= 4.4    --> int > 4
5798         if (!RHS.isNegative())
5799           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5800         Pred = ICmpInst::ICMP_UGT;
5801         break;
5802       case ICmpInst::ICMP_SGE:
5803         // (float)int >= -4.4   --> int >= -4
5804         // (float)int >= 4.4    --> int > 4
5805         if (!RHS.isNegative())
5806           Pred = ICmpInst::ICMP_SGT;
5807         break;
5808       }
5809     }
5810   }
5811
5812   // Lower this FP comparison into an appropriate integer version of the
5813   // comparison.
5814   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5815 }
5816
5817 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5818   bool Changed = SimplifyCompare(I);
5819   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5820
5821   // Fold trivial predicates.
5822   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5823     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5824   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5825     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5826   
5827   // Simplify 'fcmp pred X, X'
5828   if (Op0 == Op1) {
5829     switch (I.getPredicate()) {
5830     default: llvm_unreachable("Unknown predicate!");
5831     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5832     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5833     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5834       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5835     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5836     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5837     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5838       return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5839       
5840     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5841     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5842     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5843     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5844       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5845       I.setPredicate(FCmpInst::FCMP_UNO);
5846       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5847       return &I;
5848       
5849     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5850     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5851     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5852     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5853       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5854       I.setPredicate(FCmpInst::FCMP_ORD);
5855       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5856       return &I;
5857     }
5858   }
5859     
5860   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5861     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5862
5863   // Handle fcmp with constant RHS
5864   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5865     // If the constant is a nan, see if we can fold the comparison based on it.
5866     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5867       if (CFP->getValueAPF().isNaN()) {
5868         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5869           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5870         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5871                "Comparison must be either ordered or unordered!");
5872         // True if unordered.
5873         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5874       }
5875     }
5876     
5877     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5878       switch (LHSI->getOpcode()) {
5879       case Instruction::PHI:
5880         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5881         // block.  If in the same block, we're encouraging jump threading.  If
5882         // not, we are just pessimizing the code by making an i1 phi.
5883         if (LHSI->getParent() == I.getParent())
5884           if (Instruction *NV = FoldOpIntoPhi(I, true))
5885             return NV;
5886         break;
5887       case Instruction::SIToFP:
5888       case Instruction::UIToFP:
5889         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5890           return NV;
5891         break;
5892       case Instruction::Select:
5893         // If either operand of the select is a constant, we can fold the
5894         // comparison into the select arms, which will cause one to be
5895         // constant folded and the select turned into a bitwise or.
5896         Value *Op1 = 0, *Op2 = 0;
5897         if (LHSI->hasOneUse()) {
5898           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5899             // Fold the known value into the constant operand.
5900             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5901             // Insert a new FCmp of the other select operand.
5902             Op2 = Builder->CreateFCmp(I.getPredicate(),
5903                                       LHSI->getOperand(2), RHSC, I.getName());
5904           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5905             // Fold the known value into the constant operand.
5906             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5907             // Insert a new FCmp of the other select operand.
5908             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5909                                       RHSC, I.getName());
5910           }
5911         }
5912
5913         if (Op1)
5914           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5915         break;
5916       }
5917   }
5918
5919   return Changed ? &I : 0;
5920 }
5921
5922 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5923   bool Changed = SimplifyCompare(I);
5924   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5925   const Type *Ty = Op0->getType();
5926
5927   // icmp X, X
5928   if (Op0 == Op1)
5929     return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5930                                                    I.isTrueWhenEqual()));
5931
5932   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5933     return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5934   
5935   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5936   // addresses never equal each other!  We already know that Op0 != Op1.
5937   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || 
5938        isa<ConstantPointerNull>(Op0)) &&
5939       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || 
5940        isa<ConstantPointerNull>(Op1)))
5941     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
5942                                                    !I.isTrueWhenEqual()));
5943
5944   // icmp's with boolean values can always be turned into bitwise operations
5945   if (Ty == Type::getInt1Ty(*Context)) {
5946     switch (I.getPredicate()) {
5947     default: llvm_unreachable("Invalid icmp instruction!");
5948     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5949       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5950       return BinaryOperator::CreateNot(Xor);
5951     }
5952     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5953       return BinaryOperator::CreateXor(Op0, Op1);
5954
5955     case ICmpInst::ICMP_UGT:
5956       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5957       // FALL THROUGH
5958     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5959       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5960       return BinaryOperator::CreateAnd(Not, Op1);
5961     }
5962     case ICmpInst::ICMP_SGT:
5963       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5964       // FALL THROUGH
5965     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5966       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5967       return BinaryOperator::CreateAnd(Not, Op0);
5968     }
5969     case ICmpInst::ICMP_UGE:
5970       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5971       // FALL THROUGH
5972     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5973       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5974       return BinaryOperator::CreateOr(Not, Op1);
5975     }
5976     case ICmpInst::ICMP_SGE:
5977       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5978       // FALL THROUGH
5979     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5980       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5981       return BinaryOperator::CreateOr(Not, Op0);
5982     }
5983     }
5984   }
5985
5986   unsigned BitWidth = 0;
5987   if (TD)
5988     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5989   else if (Ty->isIntOrIntVector())
5990     BitWidth = Ty->getScalarSizeInBits();
5991
5992   bool isSignBit = false;
5993
5994   // See if we are doing a comparison with a constant.
5995   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5996     Value *A = 0, *B = 0;
5997     
5998     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5999     if (I.isEquality() && CI->isNullValue() &&
6000         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6001       // (icmp cond A B) if cond is equality
6002       return new ICmpInst(I.getPredicate(), A, B);
6003     }
6004     
6005     // If we have an icmp le or icmp ge instruction, turn it into the
6006     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6007     // them being folded in the code below.
6008     switch (I.getPredicate()) {
6009     default: break;
6010     case ICmpInst::ICMP_ULE:
6011       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6012         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6013       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6014                           AddOne(CI));
6015     case ICmpInst::ICMP_SLE:
6016       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6017         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6018       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6019                           AddOne(CI));
6020     case ICmpInst::ICMP_UGE:
6021       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6022         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6023       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6024                           SubOne(CI));
6025     case ICmpInst::ICMP_SGE:
6026       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6027         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6028       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6029                           SubOne(CI));
6030     }
6031     
6032     // If this comparison is a normal comparison, it demands all
6033     // bits, if it is a sign bit comparison, it only demands the sign bit.
6034     bool UnusedBit;
6035     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6036   }
6037
6038   // See if we can fold the comparison based on range information we can get
6039   // by checking whether bits are known to be zero or one in the input.
6040   if (BitWidth != 0) {
6041     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6042     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6043
6044     if (SimplifyDemandedBits(I.getOperandUse(0),
6045                              isSignBit ? APInt::getSignBit(BitWidth)
6046                                        : APInt::getAllOnesValue(BitWidth),
6047                              Op0KnownZero, Op0KnownOne, 0))
6048       return &I;
6049     if (SimplifyDemandedBits(I.getOperandUse(1),
6050                              APInt::getAllOnesValue(BitWidth),
6051                              Op1KnownZero, Op1KnownOne, 0))
6052       return &I;
6053
6054     // Given the known and unknown bits, compute a range that the LHS could be
6055     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6056     // EQ and NE we use unsigned values.
6057     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6058     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6059     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6060       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6061                                              Op0Min, Op0Max);
6062       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6063                                              Op1Min, Op1Max);
6064     } else {
6065       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6066                                                Op0Min, Op0Max);
6067       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6068                                                Op1Min, Op1Max);
6069     }
6070
6071     // If Min and Max are known to be the same, then SimplifyDemandedBits
6072     // figured out that the LHS is a constant.  Just constant fold this now so
6073     // that code below can assume that Min != Max.
6074     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6075       return new ICmpInst(I.getPredicate(),
6076                           ConstantInt::get(*Context, Op0Min), Op1);
6077     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6078       return new ICmpInst(I.getPredicate(), Op0,
6079                           ConstantInt::get(*Context, Op1Min));
6080
6081     // Based on the range information we know about the LHS, see if we can
6082     // simplify this comparison.  For example, (x&4) < 8  is always true.
6083     switch (I.getPredicate()) {
6084     default: llvm_unreachable("Unknown icmp opcode!");
6085     case ICmpInst::ICMP_EQ:
6086       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6087         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6088       break;
6089     case ICmpInst::ICMP_NE:
6090       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6091         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6092       break;
6093     case ICmpInst::ICMP_ULT:
6094       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6095         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6096       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6097         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6098       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6099         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6100       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6101         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6102           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6103                               SubOne(CI));
6104
6105         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6106         if (CI->isMinValue(true))
6107           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6108                            Constant::getAllOnesValue(Op0->getType()));
6109       }
6110       break;
6111     case ICmpInst::ICMP_UGT:
6112       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6113         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6114       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6115         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6116
6117       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6118         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6119       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6120         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6121           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6122                               AddOne(CI));
6123
6124         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6125         if (CI->isMaxValue(true))
6126           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6127                               Constant::getNullValue(Op0->getType()));
6128       }
6129       break;
6130     case ICmpInst::ICMP_SLT:
6131       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6132         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6133       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6134         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6135       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6136         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6137       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6138         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6139           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6140                               SubOne(CI));
6141       }
6142       break;
6143     case ICmpInst::ICMP_SGT:
6144       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6145         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6146       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6147         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6148
6149       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6150         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6151       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6152         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6153           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6154                               AddOne(CI));
6155       }
6156       break;
6157     case ICmpInst::ICMP_SGE:
6158       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6159       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6160         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6161       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6162         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6163       break;
6164     case ICmpInst::ICMP_SLE:
6165       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6166       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6167         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6168       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6169         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6170       break;
6171     case ICmpInst::ICMP_UGE:
6172       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6173       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6174         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6175       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6176         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6177       break;
6178     case ICmpInst::ICMP_ULE:
6179       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6180       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6181         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6182       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6183         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6184       break;
6185     }
6186
6187     // Turn a signed comparison into an unsigned one if both operands
6188     // are known to have the same sign.
6189     if (I.isSignedPredicate() &&
6190         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6191          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6192       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6193   }
6194
6195   // Test if the ICmpInst instruction is used exclusively by a select as
6196   // part of a minimum or maximum operation. If so, refrain from doing
6197   // any other folding. This helps out other analyses which understand
6198   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6199   // and CodeGen. And in this case, at least one of the comparison
6200   // operands has at least one user besides the compare (the select),
6201   // which would often largely negate the benefit of folding anyway.
6202   if (I.hasOneUse())
6203     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6204       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6205           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6206         return 0;
6207
6208   // See if we are doing a comparison between a constant and an instruction that
6209   // can be folded into the comparison.
6210   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6211     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6212     // instruction, see if that instruction also has constants so that the 
6213     // instruction can be folded into the icmp 
6214     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6215       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6216         return Res;
6217   }
6218
6219   // Handle icmp with constant (but not simple integer constant) RHS
6220   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6221     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6222       switch (LHSI->getOpcode()) {
6223       case Instruction::GetElementPtr:
6224         if (RHSC->isNullValue()) {
6225           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6226           bool isAllZeros = true;
6227           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6228             if (!isa<Constant>(LHSI->getOperand(i)) ||
6229                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6230               isAllZeros = false;
6231               break;
6232             }
6233           if (isAllZeros)
6234             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6235                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6236         }
6237         break;
6238
6239       case Instruction::PHI:
6240         // Only fold icmp into the PHI if the phi and icmp are in the same
6241         // block.  If in the same block, we're encouraging jump threading.  If
6242         // not, we are just pessimizing the code by making an i1 phi.
6243         if (LHSI->getParent() == I.getParent())
6244           if (Instruction *NV = FoldOpIntoPhi(I, true))
6245             return NV;
6246         break;
6247       case Instruction::Select: {
6248         // If either operand of the select is a constant, we can fold the
6249         // comparison into the select arms, which will cause one to be
6250         // constant folded and the select turned into a bitwise or.
6251         Value *Op1 = 0, *Op2 = 0;
6252         if (LHSI->hasOneUse()) {
6253           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6254             // Fold the known value into the constant operand.
6255             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6256             // Insert a new ICmp of the other select operand.
6257             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6258                                       RHSC, I.getName());
6259           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6260             // Fold the known value into the constant operand.
6261             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6262             // Insert a new ICmp of the other select operand.
6263             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6264                                       RHSC, I.getName());
6265           }
6266         }
6267
6268         if (Op1)
6269           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6270         break;
6271       }
6272       case Instruction::Malloc:
6273         // If we have (malloc != null), and if the malloc has a single use, we
6274         // can assume it is successful and remove the malloc.
6275         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6276           Worklist.Add(LHSI);
6277           return ReplaceInstUsesWith(I,
6278                                      ConstantInt::get(Type::getInt1Ty(*Context),
6279                                                       !I.isTrueWhenEqual()));
6280         }
6281         break;
6282       case Instruction::Call:
6283         // If we have (malloc != null), and if the malloc has a single use, we
6284         // can assume it is successful and remove the malloc.
6285         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6286             isa<ConstantPointerNull>(RHSC)) {
6287           Worklist.Add(LHSI);
6288           return ReplaceInstUsesWith(I,
6289                                      ConstantInt::get(Type::getInt1Ty(*Context),
6290                                                       !I.isTrueWhenEqual()));
6291         }
6292         break;
6293       }
6294   }
6295
6296   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6297   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6298     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6299       return NI;
6300   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6301     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6302                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6303       return NI;
6304
6305   // Test to see if the operands of the icmp are casted versions of other
6306   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6307   // now.
6308   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6309     if (isa<PointerType>(Op0->getType()) && 
6310         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6311       // We keep moving the cast from the left operand over to the right
6312       // operand, where it can often be eliminated completely.
6313       Op0 = CI->getOperand(0);
6314
6315       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6316       // so eliminate it as well.
6317       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6318         Op1 = CI2->getOperand(0);
6319
6320       // If Op1 is a constant, we can fold the cast into the constant.
6321       if (Op0->getType() != Op1->getType()) {
6322         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6323           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6324         } else {
6325           // Otherwise, cast the RHS right before the icmp
6326           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6327         }
6328       }
6329       return new ICmpInst(I.getPredicate(), Op0, Op1);
6330     }
6331   }
6332   
6333   if (isa<CastInst>(Op0)) {
6334     // Handle the special case of: icmp (cast bool to X), <cst>
6335     // This comes up when you have code like
6336     //   int X = A < B;
6337     //   if (X) ...
6338     // For generality, we handle any zero-extension of any operand comparison
6339     // with a constant or another cast from the same type.
6340     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6341       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6342         return R;
6343   }
6344   
6345   // See if it's the same type of instruction on the left and right.
6346   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6347     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6348       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6349           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6350         switch (Op0I->getOpcode()) {
6351         default: break;
6352         case Instruction::Add:
6353         case Instruction::Sub:
6354         case Instruction::Xor:
6355           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6356             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6357                                 Op1I->getOperand(0));
6358           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6359           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6360             if (CI->getValue().isSignBit()) {
6361               ICmpInst::Predicate Pred = I.isSignedPredicate()
6362                                              ? I.getUnsignedPredicate()
6363                                              : I.getSignedPredicate();
6364               return new ICmpInst(Pred, Op0I->getOperand(0),
6365                                   Op1I->getOperand(0));
6366             }
6367             
6368             if (CI->getValue().isMaxSignedValue()) {
6369               ICmpInst::Predicate Pred = I.isSignedPredicate()
6370                                              ? I.getUnsignedPredicate()
6371                                              : I.getSignedPredicate();
6372               Pred = I.getSwappedPredicate(Pred);
6373               return new ICmpInst(Pred, Op0I->getOperand(0),
6374                                   Op1I->getOperand(0));
6375             }
6376           }
6377           break;
6378         case Instruction::Mul:
6379           if (!I.isEquality())
6380             break;
6381
6382           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6383             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6384             // Mask = -1 >> count-trailing-zeros(Cst).
6385             if (!CI->isZero() && !CI->isOne()) {
6386               const APInt &AP = CI->getValue();
6387               ConstantInt *Mask = ConstantInt::get(*Context, 
6388                                       APInt::getLowBitsSet(AP.getBitWidth(),
6389                                                            AP.getBitWidth() -
6390                                                       AP.countTrailingZeros()));
6391               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6392               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6393               return new ICmpInst(I.getPredicate(), And1, And2);
6394             }
6395           }
6396           break;
6397         }
6398       }
6399     }
6400   }
6401   
6402   // ~x < ~y --> y < x
6403   { Value *A, *B;
6404     if (match(Op0, m_Not(m_Value(A))) &&
6405         match(Op1, m_Not(m_Value(B))))
6406       return new ICmpInst(I.getPredicate(), B, A);
6407   }
6408   
6409   if (I.isEquality()) {
6410     Value *A, *B, *C, *D;
6411     
6412     // -x == -y --> x == y
6413     if (match(Op0, m_Neg(m_Value(A))) &&
6414         match(Op1, m_Neg(m_Value(B))))
6415       return new ICmpInst(I.getPredicate(), A, B);
6416     
6417     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6418       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6419         Value *OtherVal = A == Op1 ? B : A;
6420         return new ICmpInst(I.getPredicate(), OtherVal,
6421                             Constant::getNullValue(A->getType()));
6422       }
6423
6424       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6425         // A^c1 == C^c2 --> A == C^(c1^c2)
6426         ConstantInt *C1, *C2;
6427         if (match(B, m_ConstantInt(C1)) &&
6428             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6429           Constant *NC = 
6430                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6431           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6432           return new ICmpInst(I.getPredicate(), A, Xor);
6433         }
6434         
6435         // A^B == A^D -> B == D
6436         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6437         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6438         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6439         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6440       }
6441     }
6442     
6443     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6444         (A == Op0 || B == Op0)) {
6445       // A == (A^B)  ->  B == 0
6446       Value *OtherVal = A == Op0 ? B : A;
6447       return new ICmpInst(I.getPredicate(), OtherVal,
6448                           Constant::getNullValue(A->getType()));
6449     }
6450
6451     // (A-B) == A  ->  B == 0
6452     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6453       return new ICmpInst(I.getPredicate(), B, 
6454                           Constant::getNullValue(B->getType()));
6455
6456     // A == (A-B)  ->  B == 0
6457     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6458       return new ICmpInst(I.getPredicate(), B,
6459                           Constant::getNullValue(B->getType()));
6460     
6461     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6462     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6463         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6464         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6465       Value *X = 0, *Y = 0, *Z = 0;
6466       
6467       if (A == C) {
6468         X = B; Y = D; Z = A;
6469       } else if (A == D) {
6470         X = B; Y = C; Z = A;
6471       } else if (B == C) {
6472         X = A; Y = D; Z = B;
6473       } else if (B == D) {
6474         X = A; Y = C; Z = B;
6475       }
6476       
6477       if (X) {   // Build (X^Y) & Z
6478         Op1 = Builder->CreateXor(X, Y, "tmp");
6479         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6480         I.setOperand(0, Op1);
6481         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6482         return &I;
6483       }
6484     }
6485   }
6486   return Changed ? &I : 0;
6487 }
6488
6489
6490 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6491 /// and CmpRHS are both known to be integer constants.
6492 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6493                                           ConstantInt *DivRHS) {
6494   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6495   const APInt &CmpRHSV = CmpRHS->getValue();
6496   
6497   // FIXME: If the operand types don't match the type of the divide 
6498   // then don't attempt this transform. The code below doesn't have the
6499   // logic to deal with a signed divide and an unsigned compare (and
6500   // vice versa). This is because (x /s C1) <s C2  produces different 
6501   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6502   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6503   // work. :(  The if statement below tests that condition and bails 
6504   // if it finds it. 
6505   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6506   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6507     return 0;
6508   if (DivRHS->isZero())
6509     return 0; // The ProdOV computation fails on divide by zero.
6510   if (DivIsSigned && DivRHS->isAllOnesValue())
6511     return 0; // The overflow computation also screws up here
6512   if (DivRHS->isOne())
6513     return 0; // Not worth bothering, and eliminates some funny cases
6514               // with INT_MIN.
6515
6516   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6517   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6518   // C2 (CI). By solving for X we can turn this into a range check 
6519   // instead of computing a divide. 
6520   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6521
6522   // Determine if the product overflows by seeing if the product is
6523   // not equal to the divide. Make sure we do the same kind of divide
6524   // as in the LHS instruction that we're folding. 
6525   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6526                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6527
6528   // Get the ICmp opcode
6529   ICmpInst::Predicate Pred = ICI.getPredicate();
6530
6531   // Figure out the interval that is being checked.  For example, a comparison
6532   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6533   // Compute this interval based on the constants involved and the signedness of
6534   // the compare/divide.  This computes a half-open interval, keeping track of
6535   // whether either value in the interval overflows.  After analysis each
6536   // overflow variable is set to 0 if it's corresponding bound variable is valid
6537   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6538   int LoOverflow = 0, HiOverflow = 0;
6539   Constant *LoBound = 0, *HiBound = 0;
6540   
6541   if (!DivIsSigned) {  // udiv
6542     // e.g. X/5 op 3  --> [15, 20)
6543     LoBound = Prod;
6544     HiOverflow = LoOverflow = ProdOV;
6545     if (!HiOverflow)
6546       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6547   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6548     if (CmpRHSV == 0) {       // (X / pos) op 0
6549       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6550       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6551       HiBound = DivRHS;
6552     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6553       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6554       HiOverflow = LoOverflow = ProdOV;
6555       if (!HiOverflow)
6556         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6557     } else {                       // (X / pos) op neg
6558       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6559       HiBound = AddOne(Prod);
6560       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6561       if (!LoOverflow) {
6562         ConstantInt* DivNeg =
6563                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6564         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6565                                      true) ? -1 : 0;
6566        }
6567     }
6568   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6569     if (CmpRHSV == 0) {       // (X / neg) op 0
6570       // e.g. X/-5 op 0  --> [-4, 5)
6571       LoBound = AddOne(DivRHS);
6572       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6573       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6574         HiOverflow = 1;            // [INTMIN+1, overflow)
6575         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6576       }
6577     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6578       // e.g. X/-5 op 3  --> [-19, -14)
6579       HiBound = AddOne(Prod);
6580       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6581       if (!LoOverflow)
6582         LoOverflow = AddWithOverflow(LoBound, HiBound,
6583                                      DivRHS, Context, true) ? -1 : 0;
6584     } else {                       // (X / neg) op neg
6585       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6586       LoOverflow = HiOverflow = ProdOV;
6587       if (!HiOverflow)
6588         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6589     }
6590     
6591     // Dividing by a negative swaps the condition.  LT <-> GT
6592     Pred = ICmpInst::getSwappedPredicate(Pred);
6593   }
6594
6595   Value *X = DivI->getOperand(0);
6596   switch (Pred) {
6597   default: llvm_unreachable("Unhandled icmp opcode!");
6598   case ICmpInst::ICMP_EQ:
6599     if (LoOverflow && HiOverflow)
6600       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6601     else if (HiOverflow)
6602       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6603                           ICmpInst::ICMP_UGE, X, LoBound);
6604     else if (LoOverflow)
6605       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6606                           ICmpInst::ICMP_ULT, X, HiBound);
6607     else
6608       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6609   case ICmpInst::ICMP_NE:
6610     if (LoOverflow && HiOverflow)
6611       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6612     else if (HiOverflow)
6613       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6614                           ICmpInst::ICMP_ULT, X, LoBound);
6615     else if (LoOverflow)
6616       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6617                           ICmpInst::ICMP_UGE, X, HiBound);
6618     else
6619       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6620   case ICmpInst::ICMP_ULT:
6621   case ICmpInst::ICMP_SLT:
6622     if (LoOverflow == +1)   // Low bound is greater than input range.
6623       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6624     if (LoOverflow == -1)   // Low bound is less than input range.
6625       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6626     return new ICmpInst(Pred, X, LoBound);
6627   case ICmpInst::ICMP_UGT:
6628   case ICmpInst::ICMP_SGT:
6629     if (HiOverflow == +1)       // High bound greater than input range.
6630       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6631     else if (HiOverflow == -1)  // High bound less than input range.
6632       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6633     if (Pred == ICmpInst::ICMP_UGT)
6634       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6635     else
6636       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6637   }
6638 }
6639
6640
6641 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6642 ///
6643 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6644                                                           Instruction *LHSI,
6645                                                           ConstantInt *RHS) {
6646   const APInt &RHSV = RHS->getValue();
6647   
6648   switch (LHSI->getOpcode()) {
6649   case Instruction::Trunc:
6650     if (ICI.isEquality() && LHSI->hasOneUse()) {
6651       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6652       // of the high bits truncated out of x are known.
6653       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6654              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6655       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6656       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6657       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6658       
6659       // If all the high bits are known, we can do this xform.
6660       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6661         // Pull in the high bits from known-ones set.
6662         APInt NewRHS(RHS->getValue());
6663         NewRHS.zext(SrcBits);
6664         NewRHS |= KnownOne;
6665         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6666                             ConstantInt::get(*Context, NewRHS));
6667       }
6668     }
6669     break;
6670       
6671   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6672     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6673       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6674       // fold the xor.
6675       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6676           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6677         Value *CompareVal = LHSI->getOperand(0);
6678         
6679         // If the sign bit of the XorCST is not set, there is no change to
6680         // the operation, just stop using the Xor.
6681         if (!XorCST->getValue().isNegative()) {
6682           ICI.setOperand(0, CompareVal);
6683           Worklist.Add(LHSI);
6684           return &ICI;
6685         }
6686         
6687         // Was the old condition true if the operand is positive?
6688         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6689         
6690         // If so, the new one isn't.
6691         isTrueIfPositive ^= true;
6692         
6693         if (isTrueIfPositive)
6694           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6695                               SubOne(RHS));
6696         else
6697           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6698                               AddOne(RHS));
6699       }
6700
6701       if (LHSI->hasOneUse()) {
6702         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6703         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6704           const APInt &SignBit = XorCST->getValue();
6705           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6706                                          ? ICI.getUnsignedPredicate()
6707                                          : ICI.getSignedPredicate();
6708           return new ICmpInst(Pred, LHSI->getOperand(0),
6709                               ConstantInt::get(*Context, RHSV ^ SignBit));
6710         }
6711
6712         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6713         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6714           const APInt &NotSignBit = XorCST->getValue();
6715           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6716                                          ? ICI.getUnsignedPredicate()
6717                                          : ICI.getSignedPredicate();
6718           Pred = ICI.getSwappedPredicate(Pred);
6719           return new ICmpInst(Pred, LHSI->getOperand(0),
6720                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6721         }
6722       }
6723     }
6724     break;
6725   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6726     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6727         LHSI->getOperand(0)->hasOneUse()) {
6728       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6729       
6730       // If the LHS is an AND of a truncating cast, we can widen the
6731       // and/compare to be the input width without changing the value
6732       // produced, eliminating a cast.
6733       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6734         // We can do this transformation if either the AND constant does not
6735         // have its sign bit set or if it is an equality comparison. 
6736         // Extending a relational comparison when we're checking the sign
6737         // bit would not work.
6738         if (Cast->hasOneUse() &&
6739             (ICI.isEquality() ||
6740              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6741           uint32_t BitWidth = 
6742             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6743           APInt NewCST = AndCST->getValue();
6744           NewCST.zext(BitWidth);
6745           APInt NewCI = RHSV;
6746           NewCI.zext(BitWidth);
6747           Value *NewAnd = 
6748             Builder->CreateAnd(Cast->getOperand(0),
6749                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6750           return new ICmpInst(ICI.getPredicate(), NewAnd,
6751                               ConstantInt::get(*Context, NewCI));
6752         }
6753       }
6754       
6755       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6756       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6757       // happens a LOT in code produced by the C front-end, for bitfield
6758       // access.
6759       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6760       if (Shift && !Shift->isShift())
6761         Shift = 0;
6762       
6763       ConstantInt *ShAmt;
6764       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6765       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6766       const Type *AndTy = AndCST->getType();          // Type of the and.
6767       
6768       // We can fold this as long as we can't shift unknown bits
6769       // into the mask.  This can only happen with signed shift
6770       // rights, as they sign-extend.
6771       if (ShAmt) {
6772         bool CanFold = Shift->isLogicalShift();
6773         if (!CanFold) {
6774           // To test for the bad case of the signed shr, see if any
6775           // of the bits shifted in could be tested after the mask.
6776           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6777           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6778           
6779           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6780           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6781                AndCST->getValue()) == 0)
6782             CanFold = true;
6783         }
6784         
6785         if (CanFold) {
6786           Constant *NewCst;
6787           if (Shift->getOpcode() == Instruction::Shl)
6788             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6789           else
6790             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6791           
6792           // Check to see if we are shifting out any of the bits being
6793           // compared.
6794           if (ConstantExpr::get(Shift->getOpcode(),
6795                                        NewCst, ShAmt) != RHS) {
6796             // If we shifted bits out, the fold is not going to work out.
6797             // As a special case, check to see if this means that the
6798             // result is always true or false now.
6799             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6800               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6801             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6802               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6803           } else {
6804             ICI.setOperand(1, NewCst);
6805             Constant *NewAndCST;
6806             if (Shift->getOpcode() == Instruction::Shl)
6807               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6808             else
6809               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6810             LHSI->setOperand(1, NewAndCST);
6811             LHSI->setOperand(0, Shift->getOperand(0));
6812             Worklist.Add(Shift); // Shift is dead.
6813             return &ICI;
6814           }
6815         }
6816       }
6817       
6818       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6819       // preferable because it allows the C<<Y expression to be hoisted out
6820       // of a loop if Y is invariant and X is not.
6821       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6822           ICI.isEquality() && !Shift->isArithmeticShift() &&
6823           !isa<Constant>(Shift->getOperand(0))) {
6824         // Compute C << Y.
6825         Value *NS;
6826         if (Shift->getOpcode() == Instruction::LShr) {
6827           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6828         } else {
6829           // Insert a logical shift.
6830           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6831         }
6832         
6833         // Compute X & (C << Y).
6834         Value *NewAnd = 
6835           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6836         
6837         ICI.setOperand(0, NewAnd);
6838         return &ICI;
6839       }
6840     }
6841     break;
6842     
6843   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6844     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6845     if (!ShAmt) break;
6846     
6847     uint32_t TypeBits = RHSV.getBitWidth();
6848     
6849     // Check that the shift amount is in range.  If not, don't perform
6850     // undefined shifts.  When the shift is visited it will be
6851     // simplified.
6852     if (ShAmt->uge(TypeBits))
6853       break;
6854     
6855     if (ICI.isEquality()) {
6856       // If we are comparing against bits always shifted out, the
6857       // comparison cannot succeed.
6858       Constant *Comp =
6859         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6860                                                                  ShAmt);
6861       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6862         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6863         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6864         return ReplaceInstUsesWith(ICI, Cst);
6865       }
6866       
6867       if (LHSI->hasOneUse()) {
6868         // Otherwise strength reduce the shift into an and.
6869         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6870         Constant *Mask =
6871           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6872                                                        TypeBits-ShAmtVal));
6873         
6874         Value *And =
6875           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6876         return new ICmpInst(ICI.getPredicate(), And,
6877                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6878       }
6879     }
6880     
6881     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6882     bool TrueIfSigned = false;
6883     if (LHSI->hasOneUse() &&
6884         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6885       // (X << 31) <s 0  --> (X&1) != 0
6886       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6887                                            (TypeBits-ShAmt->getZExtValue()-1));
6888       Value *And =
6889         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6890       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6891                           And, Constant::getNullValue(And->getType()));
6892     }
6893     break;
6894   }
6895     
6896   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6897   case Instruction::AShr: {
6898     // Only handle equality comparisons of shift-by-constant.
6899     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6900     if (!ShAmt || !ICI.isEquality()) break;
6901
6902     // Check that the shift amount is in range.  If not, don't perform
6903     // undefined shifts.  When the shift is visited it will be
6904     // simplified.
6905     uint32_t TypeBits = RHSV.getBitWidth();
6906     if (ShAmt->uge(TypeBits))
6907       break;
6908     
6909     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6910       
6911     // If we are comparing against bits always shifted out, the
6912     // comparison cannot succeed.
6913     APInt Comp = RHSV << ShAmtVal;
6914     if (LHSI->getOpcode() == Instruction::LShr)
6915       Comp = Comp.lshr(ShAmtVal);
6916     else
6917       Comp = Comp.ashr(ShAmtVal);
6918     
6919     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6920       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6921       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6922       return ReplaceInstUsesWith(ICI, Cst);
6923     }
6924     
6925     // Otherwise, check to see if the bits shifted out are known to be zero.
6926     // If so, we can compare against the unshifted value:
6927     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6928     if (LHSI->hasOneUse() &&
6929         MaskedValueIsZero(LHSI->getOperand(0), 
6930                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6931       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6932                           ConstantExpr::getShl(RHS, ShAmt));
6933     }
6934       
6935     if (LHSI->hasOneUse()) {
6936       // Otherwise strength reduce the shift into an and.
6937       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6938       Constant *Mask = ConstantInt::get(*Context, Val);
6939       
6940       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6941                                       Mask, LHSI->getName()+".mask");
6942       return new ICmpInst(ICI.getPredicate(), And,
6943                           ConstantExpr::getShl(RHS, ShAmt));
6944     }
6945     break;
6946   }
6947     
6948   case Instruction::SDiv:
6949   case Instruction::UDiv:
6950     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6951     // Fold this div into the comparison, producing a range check. 
6952     // Determine, based on the divide type, what the range is being 
6953     // checked.  If there is an overflow on the low or high side, remember 
6954     // it, otherwise compute the range [low, hi) bounding the new value.
6955     // See: InsertRangeTest above for the kinds of replacements possible.
6956     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6957       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6958                                           DivRHS))
6959         return R;
6960     break;
6961
6962   case Instruction::Add:
6963     // Fold: icmp pred (add, X, C1), C2
6964
6965     if (!ICI.isEquality()) {
6966       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6967       if (!LHSC) break;
6968       const APInt &LHSV = LHSC->getValue();
6969
6970       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6971                             .subtract(LHSV);
6972
6973       if (ICI.isSignedPredicate()) {
6974         if (CR.getLower().isSignBit()) {
6975           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6976                               ConstantInt::get(*Context, CR.getUpper()));
6977         } else if (CR.getUpper().isSignBit()) {
6978           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6979                               ConstantInt::get(*Context, CR.getLower()));
6980         }
6981       } else {
6982         if (CR.getLower().isMinValue()) {
6983           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6984                               ConstantInt::get(*Context, CR.getUpper()));
6985         } else if (CR.getUpper().isMinValue()) {
6986           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6987                               ConstantInt::get(*Context, CR.getLower()));
6988         }
6989       }
6990     }
6991     break;
6992   }
6993   
6994   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6995   if (ICI.isEquality()) {
6996     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6997     
6998     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6999     // the second operand is a constant, simplify a bit.
7000     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7001       switch (BO->getOpcode()) {
7002       case Instruction::SRem:
7003         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7004         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7005           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7006           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7007             Value *NewRem =
7008               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7009                                   BO->getName());
7010             return new ICmpInst(ICI.getPredicate(), NewRem,
7011                                 Constant::getNullValue(BO->getType()));
7012           }
7013         }
7014         break;
7015       case Instruction::Add:
7016         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7017         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7018           if (BO->hasOneUse())
7019             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7020                                 ConstantExpr::getSub(RHS, BOp1C));
7021         } else if (RHSV == 0) {
7022           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7023           // efficiently invertible, or if the add has just this one use.
7024           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7025           
7026           if (Value *NegVal = dyn_castNegVal(BOp1))
7027             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7028           else if (Value *NegVal = dyn_castNegVal(BOp0))
7029             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7030           else if (BO->hasOneUse()) {
7031             Value *Neg = Builder->CreateNeg(BOp1);
7032             Neg->takeName(BO);
7033             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7034           }
7035         }
7036         break;
7037       case Instruction::Xor:
7038         // For the xor case, we can xor two constants together, eliminating
7039         // the explicit xor.
7040         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7041           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7042                               ConstantExpr::getXor(RHS, BOC));
7043         
7044         // FALLTHROUGH
7045       case Instruction::Sub:
7046         // Replace (([sub|xor] A, B) != 0) with (A != B)
7047         if (RHSV == 0)
7048           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7049                               BO->getOperand(1));
7050         break;
7051         
7052       case Instruction::Or:
7053         // If bits are being or'd in that are not present in the constant we
7054         // are comparing against, then the comparison could never succeed!
7055         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7056           Constant *NotCI = ConstantExpr::getNot(RHS);
7057           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7058             return ReplaceInstUsesWith(ICI,
7059                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7060                                        isICMP_NE));
7061         }
7062         break;
7063         
7064       case Instruction::And:
7065         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7066           // If bits are being compared against that are and'd out, then the
7067           // comparison can never succeed!
7068           if ((RHSV & ~BOC->getValue()) != 0)
7069             return ReplaceInstUsesWith(ICI,
7070                                        ConstantInt::get(Type::getInt1Ty(*Context),
7071                                        isICMP_NE));
7072           
7073           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7074           if (RHS == BOC && RHSV.isPowerOf2())
7075             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7076                                 ICmpInst::ICMP_NE, LHSI,
7077                                 Constant::getNullValue(RHS->getType()));
7078           
7079           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7080           if (BOC->getValue().isSignBit()) {
7081             Value *X = BO->getOperand(0);
7082             Constant *Zero = Constant::getNullValue(X->getType());
7083             ICmpInst::Predicate pred = isICMP_NE ? 
7084               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7085             return new ICmpInst(pred, X, Zero);
7086           }
7087           
7088           // ((X & ~7) == 0) --> X < 8
7089           if (RHSV == 0 && isHighOnes(BOC)) {
7090             Value *X = BO->getOperand(0);
7091             Constant *NegX = ConstantExpr::getNeg(BOC);
7092             ICmpInst::Predicate pred = isICMP_NE ? 
7093               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7094             return new ICmpInst(pred, X, NegX);
7095           }
7096         }
7097       default: break;
7098       }
7099     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7100       // Handle icmp {eq|ne} <intrinsic>, intcst.
7101       if (II->getIntrinsicID() == Intrinsic::bswap) {
7102         Worklist.Add(II);
7103         ICI.setOperand(0, II->getOperand(1));
7104         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7105         return &ICI;
7106       }
7107     }
7108   }
7109   return 0;
7110 }
7111
7112 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7113 /// We only handle extending casts so far.
7114 ///
7115 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7116   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7117   Value *LHSCIOp        = LHSCI->getOperand(0);
7118   const Type *SrcTy     = LHSCIOp->getType();
7119   const Type *DestTy    = LHSCI->getType();
7120   Value *RHSCIOp;
7121
7122   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7123   // integer type is the same size as the pointer type.
7124   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7125       TD->getPointerSizeInBits() ==
7126          cast<IntegerType>(DestTy)->getBitWidth()) {
7127     Value *RHSOp = 0;
7128     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7129       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7130     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7131       RHSOp = RHSC->getOperand(0);
7132       // If the pointer types don't match, insert a bitcast.
7133       if (LHSCIOp->getType() != RHSOp->getType())
7134         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7135     }
7136
7137     if (RHSOp)
7138       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7139   }
7140   
7141   // The code below only handles extension cast instructions, so far.
7142   // Enforce this.
7143   if (LHSCI->getOpcode() != Instruction::ZExt &&
7144       LHSCI->getOpcode() != Instruction::SExt)
7145     return 0;
7146
7147   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7148   bool isSignedCmp = ICI.isSignedPredicate();
7149
7150   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7151     // Not an extension from the same type?
7152     RHSCIOp = CI->getOperand(0);
7153     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7154       return 0;
7155     
7156     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7157     // and the other is a zext), then we can't handle this.
7158     if (CI->getOpcode() != LHSCI->getOpcode())
7159       return 0;
7160
7161     // Deal with equality cases early.
7162     if (ICI.isEquality())
7163       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7164
7165     // A signed comparison of sign extended values simplifies into a
7166     // signed comparison.
7167     if (isSignedCmp && isSignedExt)
7168       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7169
7170     // The other three cases all fold into an unsigned comparison.
7171     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7172   }
7173
7174   // If we aren't dealing with a constant on the RHS, exit early
7175   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7176   if (!CI)
7177     return 0;
7178
7179   // Compute the constant that would happen if we truncated to SrcTy then
7180   // reextended to DestTy.
7181   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7182   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7183                                                 Res1, DestTy);
7184
7185   // If the re-extended constant didn't change...
7186   if (Res2 == CI) {
7187     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7188     // For example, we might have:
7189     //    %A = sext i16 %X to i32
7190     //    %B = icmp ugt i32 %A, 1330
7191     // It is incorrect to transform this into 
7192     //    %B = icmp ugt i16 %X, 1330
7193     // because %A may have negative value. 
7194     //
7195     // However, we allow this when the compare is EQ/NE, because they are
7196     // signless.
7197     if (isSignedExt == isSignedCmp || ICI.isEquality())
7198       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7199     return 0;
7200   }
7201
7202   // The re-extended constant changed so the constant cannot be represented 
7203   // in the shorter type. Consequently, we cannot emit a simple comparison.
7204
7205   // First, handle some easy cases. We know the result cannot be equal at this
7206   // point so handle the ICI.isEquality() cases
7207   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7208     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7209   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7210     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7211
7212   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7213   // should have been folded away previously and not enter in here.
7214   Value *Result;
7215   if (isSignedCmp) {
7216     // We're performing a signed comparison.
7217     if (cast<ConstantInt>(CI)->getValue().isNegative())
7218       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7219     else
7220       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7221   } else {
7222     // We're performing an unsigned comparison.
7223     if (isSignedExt) {
7224       // We're performing an unsigned comp with a sign extended value.
7225       // This is true if the input is >= 0. [aka >s -1]
7226       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7227       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7228     } else {
7229       // Unsigned extend & unsigned compare -> always true.
7230       Result = ConstantInt::getTrue(*Context);
7231     }
7232   }
7233
7234   // Finally, return the value computed.
7235   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7236       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7237     return ReplaceInstUsesWith(ICI, Result);
7238
7239   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7240           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7241          "ICmp should be folded!");
7242   if (Constant *CI = dyn_cast<Constant>(Result))
7243     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7244   return BinaryOperator::CreateNot(Result);
7245 }
7246
7247 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7248   return commonShiftTransforms(I);
7249 }
7250
7251 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7252   return commonShiftTransforms(I);
7253 }
7254
7255 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7256   if (Instruction *R = commonShiftTransforms(I))
7257     return R;
7258   
7259   Value *Op0 = I.getOperand(0);
7260   
7261   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7262   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7263     if (CSI->isAllOnesValue())
7264       return ReplaceInstUsesWith(I, CSI);
7265
7266   // See if we can turn a signed shr into an unsigned shr.
7267   if (MaskedValueIsZero(Op0,
7268                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7269     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7270
7271   // Arithmetic shifting an all-sign-bit value is a no-op.
7272   unsigned NumSignBits = ComputeNumSignBits(Op0);
7273   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7274     return ReplaceInstUsesWith(I, Op0);
7275
7276   return 0;
7277 }
7278
7279 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7280   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7281   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7282
7283   // shl X, 0 == X and shr X, 0 == X
7284   // shl 0, X == 0 and shr 0, X == 0
7285   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7286       Op0 == Constant::getNullValue(Op0->getType()))
7287     return ReplaceInstUsesWith(I, Op0);
7288   
7289   if (isa<UndefValue>(Op0)) {            
7290     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7291       return ReplaceInstUsesWith(I, Op0);
7292     else                                    // undef << X -> 0, undef >>u X -> 0
7293       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7294   }
7295   if (isa<UndefValue>(Op1)) {
7296     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7297       return ReplaceInstUsesWith(I, Op0);          
7298     else                                     // X << undef, X >>u undef -> 0
7299       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7300   }
7301
7302   // See if we can fold away this shift.
7303   if (SimplifyDemandedInstructionBits(I))
7304     return &I;
7305
7306   // Try to fold constant and into select arguments.
7307   if (isa<Constant>(Op0))
7308     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7309       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7310         return R;
7311
7312   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7313     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7314       return Res;
7315   return 0;
7316 }
7317
7318 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7319                                                BinaryOperator &I) {
7320   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7321
7322   // See if we can simplify any instructions used by the instruction whose sole 
7323   // purpose is to compute bits we don't care about.
7324   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7325   
7326   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7327   // a signed shift.
7328   //
7329   if (Op1->uge(TypeBits)) {
7330     if (I.getOpcode() != Instruction::AShr)
7331       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7332     else {
7333       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7334       return &I;
7335     }
7336   }
7337   
7338   // ((X*C1) << C2) == (X * (C1 << C2))
7339   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7340     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7341       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7342         return BinaryOperator::CreateMul(BO->getOperand(0),
7343                                         ConstantExpr::getShl(BOOp, Op1));
7344   
7345   // Try to fold constant and into select arguments.
7346   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7347     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7348       return R;
7349   if (isa<PHINode>(Op0))
7350     if (Instruction *NV = FoldOpIntoPhi(I))
7351       return NV;
7352   
7353   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7354   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7355     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7356     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7357     // place.  Don't try to do this transformation in this case.  Also, we
7358     // require that the input operand is a shift-by-constant so that we have
7359     // confidence that the shifts will get folded together.  We could do this
7360     // xform in more cases, but it is unlikely to be profitable.
7361     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7362         isa<ConstantInt>(TrOp->getOperand(1))) {
7363       // Okay, we'll do this xform.  Make the shift of shift.
7364       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7365       // (shift2 (shift1 & 0x00FF), c2)
7366       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7367
7368       // For logical shifts, the truncation has the effect of making the high
7369       // part of the register be zeros.  Emulate this by inserting an AND to
7370       // clear the top bits as needed.  This 'and' will usually be zapped by
7371       // other xforms later if dead.
7372       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7373       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7374       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7375       
7376       // The mask we constructed says what the trunc would do if occurring
7377       // between the shifts.  We want to know the effect *after* the second
7378       // shift.  We know that it is a logical shift by a constant, so adjust the
7379       // mask as appropriate.
7380       if (I.getOpcode() == Instruction::Shl)
7381         MaskV <<= Op1->getZExtValue();
7382       else {
7383         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7384         MaskV = MaskV.lshr(Op1->getZExtValue());
7385       }
7386
7387       // shift1 & 0x00FF
7388       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7389                                       TI->getName());
7390
7391       // Return the value truncated to the interesting size.
7392       return new TruncInst(And, I.getType());
7393     }
7394   }
7395   
7396   if (Op0->hasOneUse()) {
7397     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7398       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7399       Value *V1, *V2;
7400       ConstantInt *CC;
7401       switch (Op0BO->getOpcode()) {
7402         default: break;
7403         case Instruction::Add:
7404         case Instruction::And:
7405         case Instruction::Or:
7406         case Instruction::Xor: {
7407           // These operators commute.
7408           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7409           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7410               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7411                     m_Specific(Op1)))) {
7412             Value *YS =         // (Y << C)
7413               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7414             // (X + (Y << C))
7415             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7416                                             Op0BO->getOperand(1)->getName());
7417             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7418             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7419                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7420           }
7421           
7422           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7423           Value *Op0BOOp1 = Op0BO->getOperand(1);
7424           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7425               match(Op0BOOp1, 
7426                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7427                           m_ConstantInt(CC))) &&
7428               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7429             Value *YS =   // (Y << C)
7430               Builder->CreateShl(Op0BO->getOperand(0), Op1,
7431                                            Op0BO->getName());
7432             // X & (CC << C)
7433             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7434                                            V1->getName()+".mask");
7435             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7436           }
7437         }
7438           
7439         // FALL THROUGH.
7440         case Instruction::Sub: {
7441           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7442           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7443               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7444                     m_Specific(Op1)))) {
7445             Value *YS =  // (Y << C)
7446               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7447             // (X + (Y << C))
7448             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7449                                             Op0BO->getOperand(0)->getName());
7450             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7451             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7452                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7453           }
7454           
7455           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7456           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7457               match(Op0BO->getOperand(0),
7458                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7459                           m_ConstantInt(CC))) && V2 == Op1 &&
7460               cast<BinaryOperator>(Op0BO->getOperand(0))
7461                   ->getOperand(0)->hasOneUse()) {
7462             Value *YS = // (Y << C)
7463               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7464             // X & (CC << C)
7465             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7466                                            V1->getName()+".mask");
7467             
7468             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7469           }
7470           
7471           break;
7472         }
7473       }
7474       
7475       
7476       // If the operand is an bitwise operator with a constant RHS, and the
7477       // shift is the only use, we can pull it out of the shift.
7478       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7479         bool isValid = true;     // Valid only for And, Or, Xor
7480         bool highBitSet = false; // Transform if high bit of constant set?
7481         
7482         switch (Op0BO->getOpcode()) {
7483           default: isValid = false; break;   // Do not perform transform!
7484           case Instruction::Add:
7485             isValid = isLeftShift;
7486             break;
7487           case Instruction::Or:
7488           case Instruction::Xor:
7489             highBitSet = false;
7490             break;
7491           case Instruction::And:
7492             highBitSet = true;
7493             break;
7494         }
7495         
7496         // If this is a signed shift right, and the high bit is modified
7497         // by the logical operation, do not perform the transformation.
7498         // The highBitSet boolean indicates the value of the high bit of
7499         // the constant which would cause it to be modified for this
7500         // operation.
7501         //
7502         if (isValid && I.getOpcode() == Instruction::AShr)
7503           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7504         
7505         if (isValid) {
7506           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7507           
7508           Value *NewShift =
7509             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7510           NewShift->takeName(Op0BO);
7511           
7512           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7513                                         NewRHS);
7514         }
7515       }
7516     }
7517   }
7518   
7519   // Find out if this is a shift of a shift by a constant.
7520   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7521   if (ShiftOp && !ShiftOp->isShift())
7522     ShiftOp = 0;
7523   
7524   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7525     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7526     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7527     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7528     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7529     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7530     Value *X = ShiftOp->getOperand(0);
7531     
7532     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7533     
7534     const IntegerType *Ty = cast<IntegerType>(I.getType());
7535     
7536     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7537     if (I.getOpcode() == ShiftOp->getOpcode()) {
7538       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7539       // saturates.
7540       if (AmtSum >= TypeBits) {
7541         if (I.getOpcode() != Instruction::AShr)
7542           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7543         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7544       }
7545       
7546       return BinaryOperator::Create(I.getOpcode(), X,
7547                                     ConstantInt::get(Ty, AmtSum));
7548     }
7549     
7550     if (ShiftOp->getOpcode() == Instruction::LShr &&
7551         I.getOpcode() == Instruction::AShr) {
7552       if (AmtSum >= TypeBits)
7553         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7554       
7555       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7556       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7557     }
7558     
7559     if (ShiftOp->getOpcode() == Instruction::AShr &&
7560         I.getOpcode() == Instruction::LShr) {
7561       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7562       if (AmtSum >= TypeBits)
7563         AmtSum = TypeBits-1;
7564       
7565       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7566
7567       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7568       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7569     }
7570     
7571     // Okay, if we get here, one shift must be left, and the other shift must be
7572     // right.  See if the amounts are equal.
7573     if (ShiftAmt1 == ShiftAmt2) {
7574       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7575       if (I.getOpcode() == Instruction::Shl) {
7576         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7577         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7578       }
7579       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7580       if (I.getOpcode() == Instruction::LShr) {
7581         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7582         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7583       }
7584       // We can simplify ((X << C) >>s C) into a trunc + sext.
7585       // NOTE: we could do this for any C, but that would make 'unusual' integer
7586       // types.  For now, just stick to ones well-supported by the code
7587       // generators.
7588       const Type *SExtType = 0;
7589       switch (Ty->getBitWidth() - ShiftAmt1) {
7590       case 1  :
7591       case 8  :
7592       case 16 :
7593       case 32 :
7594       case 64 :
7595       case 128:
7596         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7597         break;
7598       default: break;
7599       }
7600       if (SExtType)
7601         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7602       // Otherwise, we can't handle it yet.
7603     } else if (ShiftAmt1 < ShiftAmt2) {
7604       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7605       
7606       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7607       if (I.getOpcode() == Instruction::Shl) {
7608         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7609                ShiftOp->getOpcode() == Instruction::AShr);
7610         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7611         
7612         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7613         return BinaryOperator::CreateAnd(Shift,
7614                                          ConstantInt::get(*Context, Mask));
7615       }
7616       
7617       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7618       if (I.getOpcode() == Instruction::LShr) {
7619         assert(ShiftOp->getOpcode() == Instruction::Shl);
7620         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7621         
7622         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7623         return BinaryOperator::CreateAnd(Shift,
7624                                          ConstantInt::get(*Context, Mask));
7625       }
7626       
7627       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7628     } else {
7629       assert(ShiftAmt2 < ShiftAmt1);
7630       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7631
7632       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7633       if (I.getOpcode() == Instruction::Shl) {
7634         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7635                ShiftOp->getOpcode() == Instruction::AShr);
7636         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7637                                             ConstantInt::get(Ty, ShiftDiff));
7638         
7639         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7640         return BinaryOperator::CreateAnd(Shift,
7641                                          ConstantInt::get(*Context, Mask));
7642       }
7643       
7644       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7645       if (I.getOpcode() == Instruction::LShr) {
7646         assert(ShiftOp->getOpcode() == Instruction::Shl);
7647         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7648         
7649         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7650         return BinaryOperator::CreateAnd(Shift,
7651                                          ConstantInt::get(*Context, Mask));
7652       }
7653       
7654       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7655     }
7656   }
7657   return 0;
7658 }
7659
7660
7661 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7662 /// expression.  If so, decompose it, returning some value X, such that Val is
7663 /// X*Scale+Offset.
7664 ///
7665 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7666                                         int &Offset, LLVMContext *Context) {
7667   assert(Val->getType() == Type::getInt32Ty(*Context) && 
7668          "Unexpected allocation size type!");
7669   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7670     Offset = CI->getZExtValue();
7671     Scale  = 0;
7672     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7673   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7674     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7675       if (I->getOpcode() == Instruction::Shl) {
7676         // This is a value scaled by '1 << the shift amt'.
7677         Scale = 1U << RHS->getZExtValue();
7678         Offset = 0;
7679         return I->getOperand(0);
7680       } else if (I->getOpcode() == Instruction::Mul) {
7681         // This value is scaled by 'RHS'.
7682         Scale = RHS->getZExtValue();
7683         Offset = 0;
7684         return I->getOperand(0);
7685       } else if (I->getOpcode() == Instruction::Add) {
7686         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7687         // where C1 is divisible by C2.
7688         unsigned SubScale;
7689         Value *SubVal = 
7690           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7691                                     Offset, Context);
7692         Offset += RHS->getZExtValue();
7693         Scale = SubScale;
7694         return SubVal;
7695       }
7696     }
7697   }
7698
7699   // Otherwise, we can't look past this.
7700   Scale = 1;
7701   Offset = 0;
7702   return Val;
7703 }
7704
7705
7706 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7707 /// try to eliminate the cast by moving the type information into the alloc.
7708 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7709                                                    AllocationInst &AI) {
7710   const PointerType *PTy = cast<PointerType>(CI.getType());
7711   
7712   BuilderTy AllocaBuilder(*Builder);
7713   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7714   
7715   // Remove any uses of AI that are dead.
7716   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7717   
7718   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7719     Instruction *User = cast<Instruction>(*UI++);
7720     if (isInstructionTriviallyDead(User)) {
7721       while (UI != E && *UI == User)
7722         ++UI; // If this instruction uses AI more than once, don't break UI.
7723       
7724       ++NumDeadInst;
7725       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7726       EraseInstFromFunction(*User);
7727     }
7728   }
7729
7730   // This requires TargetData to get the alloca alignment and size information.
7731   if (!TD) return 0;
7732
7733   // Get the type really allocated and the type casted to.
7734   const Type *AllocElTy = AI.getAllocatedType();
7735   const Type *CastElTy = PTy->getElementType();
7736   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7737
7738   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7739   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7740   if (CastElTyAlign < AllocElTyAlign) return 0;
7741
7742   // If the allocation has multiple uses, only promote it if we are strictly
7743   // increasing the alignment of the resultant allocation.  If we keep it the
7744   // same, we open the door to infinite loops of various kinds.  (A reference
7745   // from a dbg.declare doesn't count as a use for this purpose.)
7746   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7747       CastElTyAlign == AllocElTyAlign) return 0;
7748
7749   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7750   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7751   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7752
7753   // See if we can satisfy the modulus by pulling a scale out of the array
7754   // size argument.
7755   unsigned ArraySizeScale;
7756   int ArrayOffset;
7757   Value *NumElements = // See if the array size is a decomposable linear expr.
7758     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7759                               ArrayOffset, Context);
7760  
7761   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7762   // do the xform.
7763   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7764       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7765
7766   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7767   Value *Amt = 0;
7768   if (Scale == 1) {
7769     Amt = NumElements;
7770   } else {
7771     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7772     // Insert before the alloca, not before the cast.
7773     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7774   }
7775   
7776   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7777     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7778     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7779   }
7780   
7781   AllocationInst *New;
7782   if (isa<MallocInst>(AI))
7783     New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7784   else
7785     New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7786   New->setAlignment(AI.getAlignment());
7787   New->takeName(&AI);
7788   
7789   // If the allocation has one real use plus a dbg.declare, just remove the
7790   // declare.
7791   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7792     EraseInstFromFunction(*DI);
7793   }
7794   // If the allocation has multiple real uses, insert a cast and change all
7795   // things that used it to use the new cast.  This will also hack on CI, but it
7796   // will die soon.
7797   else if (!AI.hasOneUse()) {
7798     // New is the allocation instruction, pointer typed. AI is the original
7799     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7800     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7801     AI.replaceAllUsesWith(NewCast);
7802   }
7803   return ReplaceInstUsesWith(CI, New);
7804 }
7805
7806 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7807 /// and return it as type Ty without inserting any new casts and without
7808 /// changing the computed value.  This is used by code that tries to decide
7809 /// whether promoting or shrinking integer operations to wider or smaller types
7810 /// will allow us to eliminate a truncate or extend.
7811 ///
7812 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7813 /// extension operation if Ty is larger.
7814 ///
7815 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7816 /// should return true if trunc(V) can be computed by computing V in the smaller
7817 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7818 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7819 /// efficiently truncated.
7820 ///
7821 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7822 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7823 /// the final result.
7824 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7825                                               unsigned CastOpc,
7826                                               int &NumCastsRemoved){
7827   // We can always evaluate constants in another type.
7828   if (isa<Constant>(V))
7829     return true;
7830   
7831   Instruction *I = dyn_cast<Instruction>(V);
7832   if (!I) return false;
7833   
7834   const Type *OrigTy = V->getType();
7835   
7836   // If this is an extension or truncate, we can often eliminate it.
7837   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7838     // If this is a cast from the destination type, we can trivially eliminate
7839     // it, and this will remove a cast overall.
7840     if (I->getOperand(0)->getType() == Ty) {
7841       // If the first operand is itself a cast, and is eliminable, do not count
7842       // this as an eliminable cast.  We would prefer to eliminate those two
7843       // casts first.
7844       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7845         ++NumCastsRemoved;
7846       return true;
7847     }
7848   }
7849
7850   // We can't extend or shrink something that has multiple uses: doing so would
7851   // require duplicating the instruction in general, which isn't profitable.
7852   if (!I->hasOneUse()) return false;
7853
7854   unsigned Opc = I->getOpcode();
7855   switch (Opc) {
7856   case Instruction::Add:
7857   case Instruction::Sub:
7858   case Instruction::Mul:
7859   case Instruction::And:
7860   case Instruction::Or:
7861   case Instruction::Xor:
7862     // These operators can all arbitrarily be extended or truncated.
7863     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7864                                       NumCastsRemoved) &&
7865            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7866                                       NumCastsRemoved);
7867
7868   case Instruction::UDiv:
7869   case Instruction::URem: {
7870     // UDiv and URem can be truncated if all the truncated bits are zero.
7871     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7872     uint32_t BitWidth = Ty->getScalarSizeInBits();
7873     if (BitWidth < OrigBitWidth) {
7874       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7875       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7876           MaskedValueIsZero(I->getOperand(1), Mask)) {
7877         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7878                                           NumCastsRemoved) &&
7879                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7880                                           NumCastsRemoved);
7881       }
7882     }
7883     break;
7884   }
7885   case Instruction::Shl:
7886     // If we are truncating the result of this SHL, and if it's a shift of a
7887     // constant amount, we can always perform a SHL in a smaller type.
7888     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7889       uint32_t BitWidth = Ty->getScalarSizeInBits();
7890       if (BitWidth < OrigTy->getScalarSizeInBits() &&
7891           CI->getLimitedValue(BitWidth) < BitWidth)
7892         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7893                                           NumCastsRemoved);
7894     }
7895     break;
7896   case Instruction::LShr:
7897     // If this is a truncate of a logical shr, we can truncate it to a smaller
7898     // lshr iff we know that the bits we would otherwise be shifting in are
7899     // already zeros.
7900     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7901       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7902       uint32_t BitWidth = Ty->getScalarSizeInBits();
7903       if (BitWidth < OrigBitWidth &&
7904           MaskedValueIsZero(I->getOperand(0),
7905             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7906           CI->getLimitedValue(BitWidth) < BitWidth) {
7907         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7908                                           NumCastsRemoved);
7909       }
7910     }
7911     break;
7912   case Instruction::ZExt:
7913   case Instruction::SExt:
7914   case Instruction::Trunc:
7915     // If this is the same kind of case as our original (e.g. zext+zext), we
7916     // can safely replace it.  Note that replacing it does not reduce the number
7917     // of casts in the input.
7918     if (Opc == CastOpc)
7919       return true;
7920
7921     // sext (zext ty1), ty2 -> zext ty2
7922     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7923       return true;
7924     break;
7925   case Instruction::Select: {
7926     SelectInst *SI = cast<SelectInst>(I);
7927     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7928                                       NumCastsRemoved) &&
7929            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7930                                       NumCastsRemoved);
7931   }
7932   case Instruction::PHI: {
7933     // We can change a phi if we can change all operands.
7934     PHINode *PN = cast<PHINode>(I);
7935     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7936       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7937                                       NumCastsRemoved))
7938         return false;
7939     return true;
7940   }
7941   default:
7942     // TODO: Can handle more cases here.
7943     break;
7944   }
7945   
7946   return false;
7947 }
7948
7949 /// EvaluateInDifferentType - Given an expression that 
7950 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7951 /// evaluate the expression.
7952 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7953                                              bool isSigned) {
7954   if (Constant *C = dyn_cast<Constant>(V))
7955     return ConstantExpr::getIntegerCast(C, Ty,
7956                                                isSigned /*Sext or ZExt*/);
7957
7958   // Otherwise, it must be an instruction.
7959   Instruction *I = cast<Instruction>(V);
7960   Instruction *Res = 0;
7961   unsigned Opc = I->getOpcode();
7962   switch (Opc) {
7963   case Instruction::Add:
7964   case Instruction::Sub:
7965   case Instruction::Mul:
7966   case Instruction::And:
7967   case Instruction::Or:
7968   case Instruction::Xor:
7969   case Instruction::AShr:
7970   case Instruction::LShr:
7971   case Instruction::Shl:
7972   case Instruction::UDiv:
7973   case Instruction::URem: {
7974     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7975     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7976     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7977     break;
7978   }    
7979   case Instruction::Trunc:
7980   case Instruction::ZExt:
7981   case Instruction::SExt:
7982     // If the source type of the cast is the type we're trying for then we can
7983     // just return the source.  There's no need to insert it because it is not
7984     // new.
7985     if (I->getOperand(0)->getType() == Ty)
7986       return I->getOperand(0);
7987     
7988     // Otherwise, must be the same type of cast, so just reinsert a new one.
7989     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7990                            Ty);
7991     break;
7992   case Instruction::Select: {
7993     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7994     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7995     Res = SelectInst::Create(I->getOperand(0), True, False);
7996     break;
7997   }
7998   case Instruction::PHI: {
7999     PHINode *OPN = cast<PHINode>(I);
8000     PHINode *NPN = PHINode::Create(Ty);
8001     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8002       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8003       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8004     }
8005     Res = NPN;
8006     break;
8007   }
8008   default: 
8009     // TODO: Can handle more cases here.
8010     llvm_unreachable("Unreachable!");
8011     break;
8012   }
8013   
8014   Res->takeName(I);
8015   return InsertNewInstBefore(Res, *I);
8016 }
8017
8018 /// @brief Implement the transforms common to all CastInst visitors.
8019 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8020   Value *Src = CI.getOperand(0);
8021
8022   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8023   // eliminate it now.
8024   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8025     if (Instruction::CastOps opc = 
8026         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8027       // The first cast (CSrc) is eliminable so we need to fix up or replace
8028       // the second cast (CI). CSrc will then have a good chance of being dead.
8029       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8030     }
8031   }
8032
8033   // If we are casting a select then fold the cast into the select
8034   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8035     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8036       return NV;
8037
8038   // If we are casting a PHI then fold the cast into the PHI
8039   if (isa<PHINode>(Src))
8040     if (Instruction *NV = FoldOpIntoPhi(CI))
8041       return NV;
8042   
8043   return 0;
8044 }
8045
8046 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8047 /// or not there is a sequence of GEP indices into the type that will land us at
8048 /// the specified offset.  If so, fill them into NewIndices and return the
8049 /// resultant element type, otherwise return null.
8050 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8051                                        SmallVectorImpl<Value*> &NewIndices,
8052                                        const TargetData *TD,
8053                                        LLVMContext *Context) {
8054   if (!TD) return 0;
8055   if (!Ty->isSized()) return 0;
8056   
8057   // Start with the index over the outer type.  Note that the type size
8058   // might be zero (even if the offset isn't zero) if the indexed type
8059   // is something like [0 x {int, int}]
8060   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8061   int64_t FirstIdx = 0;
8062   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8063     FirstIdx = Offset/TySize;
8064     Offset -= FirstIdx*TySize;
8065     
8066     // Handle hosts where % returns negative instead of values [0..TySize).
8067     if (Offset < 0) {
8068       --FirstIdx;
8069       Offset += TySize;
8070       assert(Offset >= 0);
8071     }
8072     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8073   }
8074   
8075   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8076     
8077   // Index into the types.  If we fail, set OrigBase to null.
8078   while (Offset) {
8079     // Indexing into tail padding between struct/array elements.
8080     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8081       return 0;
8082     
8083     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8084       const StructLayout *SL = TD->getStructLayout(STy);
8085       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8086              "Offset must stay within the indexed type");
8087       
8088       unsigned Elt = SL->getElementContainingOffset(Offset);
8089       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8090       
8091       Offset -= SL->getElementOffset(Elt);
8092       Ty = STy->getElementType(Elt);
8093     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8094       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8095       assert(EltSize && "Cannot index into a zero-sized array");
8096       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8097       Offset %= EltSize;
8098       Ty = AT->getElementType();
8099     } else {
8100       // Otherwise, we can't index into the middle of this atomic type, bail.
8101       return 0;
8102     }
8103   }
8104   
8105   return Ty;
8106 }
8107
8108 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8109 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8110   Value *Src = CI.getOperand(0);
8111   
8112   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8113     // If casting the result of a getelementptr instruction with no offset, turn
8114     // this into a cast of the original pointer!
8115     if (GEP->hasAllZeroIndices()) {
8116       // Changing the cast operand is usually not a good idea but it is safe
8117       // here because the pointer operand is being replaced with another 
8118       // pointer operand so the opcode doesn't need to change.
8119       Worklist.Add(GEP);
8120       CI.setOperand(0, GEP->getOperand(0));
8121       return &CI;
8122     }
8123     
8124     // If the GEP has a single use, and the base pointer is a bitcast, and the
8125     // GEP computes a constant offset, see if we can convert these three
8126     // instructions into fewer.  This typically happens with unions and other
8127     // non-type-safe code.
8128     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8129       if (GEP->hasAllConstantIndices()) {
8130         // We are guaranteed to get a constant from EmitGEPOffset.
8131         ConstantInt *OffsetV =
8132                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8133         int64_t Offset = OffsetV->getSExtValue();
8134         
8135         // Get the base pointer input of the bitcast, and the type it points to.
8136         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8137         const Type *GEPIdxTy =
8138           cast<PointerType>(OrigBase->getType())->getElementType();
8139         SmallVector<Value*, 8> NewIndices;
8140         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8141           // If we were able to index down into an element, create the GEP
8142           // and bitcast the result.  This eliminates one bitcast, potentially
8143           // two.
8144           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8145             Builder->CreateInBoundsGEP(OrigBase,
8146                                        NewIndices.begin(), NewIndices.end()) :
8147             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8148           NGEP->takeName(GEP);
8149           
8150           if (isa<BitCastInst>(CI))
8151             return new BitCastInst(NGEP, CI.getType());
8152           assert(isa<PtrToIntInst>(CI));
8153           return new PtrToIntInst(NGEP, CI.getType());
8154         }
8155       }      
8156     }
8157   }
8158     
8159   return commonCastTransforms(CI);
8160 }
8161
8162 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8163 /// type like i42.  We don't want to introduce operations on random non-legal
8164 /// integer types where they don't already exist in the code.  In the future,
8165 /// we should consider making this based off target-data, so that 32-bit targets
8166 /// won't get i64 operations etc.
8167 static bool isSafeIntegerType(const Type *Ty) {
8168   switch (Ty->getPrimitiveSizeInBits()) {
8169   case 8:
8170   case 16:
8171   case 32:
8172   case 64:
8173     return true;
8174   default: 
8175     return false;
8176   }
8177 }
8178
8179 /// commonIntCastTransforms - This function implements the common transforms
8180 /// for trunc, zext, and sext.
8181 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8182   if (Instruction *Result = commonCastTransforms(CI))
8183     return Result;
8184
8185   Value *Src = CI.getOperand(0);
8186   const Type *SrcTy = Src->getType();
8187   const Type *DestTy = CI.getType();
8188   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8189   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8190
8191   // See if we can simplify any instructions used by the LHS whose sole 
8192   // purpose is to compute bits we don't care about.
8193   if (SimplifyDemandedInstructionBits(CI))
8194     return &CI;
8195
8196   // If the source isn't an instruction or has more than one use then we
8197   // can't do anything more. 
8198   Instruction *SrcI = dyn_cast<Instruction>(Src);
8199   if (!SrcI || !Src->hasOneUse())
8200     return 0;
8201
8202   // Attempt to propagate the cast into the instruction for int->int casts.
8203   int NumCastsRemoved = 0;
8204   // Only do this if the dest type is a simple type, don't convert the
8205   // expression tree to something weird like i93 unless the source is also
8206   // strange.
8207   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8208        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8209       CanEvaluateInDifferentType(SrcI, DestTy,
8210                                  CI.getOpcode(), NumCastsRemoved)) {
8211     // If this cast is a truncate, evaluting in a different type always
8212     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8213     // we need to do an AND to maintain the clear top-part of the computation,
8214     // so we require that the input have eliminated at least one cast.  If this
8215     // is a sign extension, we insert two new casts (to do the extension) so we
8216     // require that two casts have been eliminated.
8217     bool DoXForm = false;
8218     bool JustReplace = false;
8219     switch (CI.getOpcode()) {
8220     default:
8221       // All the others use floating point so we shouldn't actually 
8222       // get here because of the check above.
8223       llvm_unreachable("Unknown cast type");
8224     case Instruction::Trunc:
8225       DoXForm = true;
8226       break;
8227     case Instruction::ZExt: {
8228       DoXForm = NumCastsRemoved >= 1;
8229       if (!DoXForm && 0) {
8230         // If it's unnecessary to issue an AND to clear the high bits, it's
8231         // always profitable to do this xform.
8232         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8233         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8234         if (MaskedValueIsZero(TryRes, Mask))
8235           return ReplaceInstUsesWith(CI, TryRes);
8236         
8237         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8238           if (TryI->use_empty())
8239             EraseInstFromFunction(*TryI);
8240       }
8241       break;
8242     }
8243     case Instruction::SExt: {
8244       DoXForm = NumCastsRemoved >= 2;
8245       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8246         // If we do not have to emit the truncate + sext pair, then it's always
8247         // profitable to do this xform.
8248         //
8249         // It's not safe to eliminate the trunc + sext pair if one of the
8250         // eliminated cast is a truncate. e.g.
8251         // t2 = trunc i32 t1 to i16
8252         // t3 = sext i16 t2 to i32
8253         // !=
8254         // i32 t1
8255         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8256         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8257         if (NumSignBits > (DestBitSize - SrcBitSize))
8258           return ReplaceInstUsesWith(CI, TryRes);
8259         
8260         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8261           if (TryI->use_empty())
8262             EraseInstFromFunction(*TryI);
8263       }
8264       break;
8265     }
8266     }
8267     
8268     if (DoXForm) {
8269       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8270             " to avoid cast: " << CI);
8271       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8272                                            CI.getOpcode() == Instruction::SExt);
8273       if (JustReplace)
8274         // Just replace this cast with the result.
8275         return ReplaceInstUsesWith(CI, Res);
8276
8277       assert(Res->getType() == DestTy);
8278       switch (CI.getOpcode()) {
8279       default: llvm_unreachable("Unknown cast type!");
8280       case Instruction::Trunc:
8281         // Just replace this cast with the result.
8282         return ReplaceInstUsesWith(CI, Res);
8283       case Instruction::ZExt: {
8284         assert(SrcBitSize < DestBitSize && "Not a zext?");
8285
8286         // If the high bits are already zero, just replace this cast with the
8287         // result.
8288         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8289         if (MaskedValueIsZero(Res, Mask))
8290           return ReplaceInstUsesWith(CI, Res);
8291
8292         // We need to emit an AND to clear the high bits.
8293         Constant *C = ConstantInt::get(*Context, 
8294                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8295         return BinaryOperator::CreateAnd(Res, C);
8296       }
8297       case Instruction::SExt: {
8298         // If the high bits are already filled with sign bit, just replace this
8299         // cast with the result.
8300         unsigned NumSignBits = ComputeNumSignBits(Res);
8301         if (NumSignBits > (DestBitSize - SrcBitSize))
8302           return ReplaceInstUsesWith(CI, Res);
8303
8304         // We need to emit a cast to truncate, then a cast to sext.
8305         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8306       }
8307       }
8308     }
8309   }
8310   
8311   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8312   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8313
8314   switch (SrcI->getOpcode()) {
8315   case Instruction::Add:
8316   case Instruction::Mul:
8317   case Instruction::And:
8318   case Instruction::Or:
8319   case Instruction::Xor:
8320     // If we are discarding information, rewrite.
8321     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8322       // Don't insert two casts unless at least one can be eliminated.
8323       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8324           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8325         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8326         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8327         return BinaryOperator::Create(
8328             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8329       }
8330     }
8331
8332     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8333     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8334         SrcI->getOpcode() == Instruction::Xor &&
8335         Op1 == ConstantInt::getTrue(*Context) &&
8336         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8337       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8338       return BinaryOperator::CreateXor(New,
8339                                       ConstantInt::get(CI.getType(), 1));
8340     }
8341     break;
8342
8343   case Instruction::Shl: {
8344     // Canonicalize trunc inside shl, if we can.
8345     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8346     if (CI && DestBitSize < SrcBitSize &&
8347         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8348       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8349       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8350       return BinaryOperator::CreateShl(Op0c, Op1c);
8351     }
8352     break;
8353   }
8354   }
8355   return 0;
8356 }
8357
8358 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8359   if (Instruction *Result = commonIntCastTransforms(CI))
8360     return Result;
8361   
8362   Value *Src = CI.getOperand(0);
8363   const Type *Ty = CI.getType();
8364   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8365   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8366
8367   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8368   if (DestBitWidth == 1) {
8369     Constant *One = ConstantInt::get(Src->getType(), 1);
8370     Src = Builder->CreateAnd(Src, One, "tmp");
8371     Value *Zero = Constant::getNullValue(Src->getType());
8372     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8373   }
8374
8375   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8376   ConstantInt *ShAmtV = 0;
8377   Value *ShiftOp = 0;
8378   if (Src->hasOneUse() &&
8379       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8380     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8381     
8382     // Get a mask for the bits shifting in.
8383     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8384     if (MaskedValueIsZero(ShiftOp, Mask)) {
8385       if (ShAmt >= DestBitWidth)        // All zeros.
8386         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8387       
8388       // Okay, we can shrink this.  Truncate the input, then return a new
8389       // shift.
8390       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8391       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8392       return BinaryOperator::CreateLShr(V1, V2);
8393     }
8394   }
8395   
8396   return 0;
8397 }
8398
8399 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8400 /// in order to eliminate the icmp.
8401 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8402                                              bool DoXform) {
8403   // If we are just checking for a icmp eq of a single bit and zext'ing it
8404   // to an integer, then shift the bit to the appropriate place and then
8405   // cast to integer to avoid the comparison.
8406   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8407     const APInt &Op1CV = Op1C->getValue();
8408       
8409     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8410     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8411     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8412         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8413       if (!DoXform) return ICI;
8414
8415       Value *In = ICI->getOperand(0);
8416       Value *Sh = ConstantInt::get(In->getType(),
8417                                    In->getType()->getScalarSizeInBits()-1);
8418       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8419       if (In->getType() != CI.getType())
8420         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8421
8422       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8423         Constant *One = ConstantInt::get(In->getType(), 1);
8424         In = Builder->CreateXor(In, One, In->getName()+".not");
8425       }
8426
8427       return ReplaceInstUsesWith(CI, In);
8428     }
8429       
8430       
8431       
8432     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8433     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8434     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8435     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8436     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8437     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8438     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8439     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8440     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8441         // This only works for EQ and NE
8442         ICI->isEquality()) {
8443       // If Op1C some other power of two, convert:
8444       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8445       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8446       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8447       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8448         
8449       APInt KnownZeroMask(~KnownZero);
8450       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8451         if (!DoXform) return ICI;
8452
8453         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8454         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8455           // (X&4) == 2 --> false
8456           // (X&4) != 2 --> true
8457           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8458           Res = ConstantExpr::getZExt(Res, CI.getType());
8459           return ReplaceInstUsesWith(CI, Res);
8460         }
8461           
8462         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8463         Value *In = ICI->getOperand(0);
8464         if (ShiftAmt) {
8465           // Perform a logical shr by shiftamt.
8466           // Insert the shift to put the result in the low bit.
8467           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8468                                    In->getName()+".lobit");
8469         }
8470           
8471         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8472           Constant *One = ConstantInt::get(In->getType(), 1);
8473           In = Builder->CreateXor(In, One, "tmp");
8474         }
8475           
8476         if (CI.getType() == In->getType())
8477           return ReplaceInstUsesWith(CI, In);
8478         else
8479           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8480       }
8481     }
8482   }
8483
8484   return 0;
8485 }
8486
8487 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8488   // If one of the common conversion will work ..
8489   if (Instruction *Result = commonIntCastTransforms(CI))
8490     return Result;
8491
8492   Value *Src = CI.getOperand(0);
8493
8494   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8495   // types and if the sizes are just right we can convert this into a logical
8496   // 'and' which will be much cheaper than the pair of casts.
8497   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8498     // Get the sizes of the types involved.  We know that the intermediate type
8499     // will be smaller than A or C, but don't know the relation between A and C.
8500     Value *A = CSrc->getOperand(0);
8501     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8502     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8503     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8504     // If we're actually extending zero bits, then if
8505     // SrcSize <  DstSize: zext(a & mask)
8506     // SrcSize == DstSize: a & mask
8507     // SrcSize  > DstSize: trunc(a) & mask
8508     if (SrcSize < DstSize) {
8509       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8510       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8511       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8512       return new ZExtInst(And, CI.getType());
8513     }
8514     
8515     if (SrcSize == DstSize) {
8516       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8517       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8518                                                            AndValue));
8519     }
8520     if (SrcSize > DstSize) {
8521       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8522       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8523       return BinaryOperator::CreateAnd(Trunc, 
8524                                        ConstantInt::get(Trunc->getType(),
8525                                                                AndValue));
8526     }
8527   }
8528
8529   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8530     return transformZExtICmp(ICI, CI);
8531
8532   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8533   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8534     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8535     // of the (zext icmp) will be transformed.
8536     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8537     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8538     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8539         (transformZExtICmp(LHS, CI, false) ||
8540          transformZExtICmp(RHS, CI, false))) {
8541       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8542       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8543       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8544     }
8545   }
8546
8547   // zext(trunc(t) & C) -> (t & zext(C)).
8548   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8549     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8550       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8551         Value *TI0 = TI->getOperand(0);
8552         if (TI0->getType() == CI.getType())
8553           return
8554             BinaryOperator::CreateAnd(TI0,
8555                                 ConstantExpr::getZExt(C, CI.getType()));
8556       }
8557
8558   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8559   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8560     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8561       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8562         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8563             And->getOperand(1) == C)
8564           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8565             Value *TI0 = TI->getOperand(0);
8566             if (TI0->getType() == CI.getType()) {
8567               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8568               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8569               return BinaryOperator::CreateXor(NewAnd, ZC);
8570             }
8571           }
8572
8573   return 0;
8574 }
8575
8576 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8577   if (Instruction *I = commonIntCastTransforms(CI))
8578     return I;
8579   
8580   Value *Src = CI.getOperand(0);
8581   
8582   // Canonicalize sign-extend from i1 to a select.
8583   if (Src->getType() == Type::getInt1Ty(*Context))
8584     return SelectInst::Create(Src,
8585                               Constant::getAllOnesValue(CI.getType()),
8586                               Constant::getNullValue(CI.getType()));
8587
8588   // See if the value being truncated is already sign extended.  If so, just
8589   // eliminate the trunc/sext pair.
8590   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8591     Value *Op = cast<User>(Src)->getOperand(0);
8592     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8593     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8594     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8595     unsigned NumSignBits = ComputeNumSignBits(Op);
8596
8597     if (OpBits == DestBits) {
8598       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8599       // bits, it is already ready.
8600       if (NumSignBits > DestBits-MidBits)
8601         return ReplaceInstUsesWith(CI, Op);
8602     } else if (OpBits < DestBits) {
8603       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8604       // bits, just sext from i32.
8605       if (NumSignBits > OpBits-MidBits)
8606         return new SExtInst(Op, CI.getType(), "tmp");
8607     } else {
8608       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8609       // bits, just truncate to i32.
8610       if (NumSignBits > OpBits-MidBits)
8611         return new TruncInst(Op, CI.getType(), "tmp");
8612     }
8613   }
8614
8615   // If the input is a shl/ashr pair of a same constant, then this is a sign
8616   // extension from a smaller value.  If we could trust arbitrary bitwidth
8617   // integers, we could turn this into a truncate to the smaller bit and then
8618   // use a sext for the whole extension.  Since we don't, look deeper and check
8619   // for a truncate.  If the source and dest are the same type, eliminate the
8620   // trunc and extend and just do shifts.  For example, turn:
8621   //   %a = trunc i32 %i to i8
8622   //   %b = shl i8 %a, 6
8623   //   %c = ashr i8 %b, 6
8624   //   %d = sext i8 %c to i32
8625   // into:
8626   //   %a = shl i32 %i, 30
8627   //   %d = ashr i32 %a, 30
8628   Value *A = 0;
8629   ConstantInt *BA = 0, *CA = 0;
8630   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8631                         m_ConstantInt(CA))) &&
8632       BA == CA && isa<TruncInst>(A)) {
8633     Value *I = cast<TruncInst>(A)->getOperand(0);
8634     if (I->getType() == CI.getType()) {
8635       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8636       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8637       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8638       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8639       I = Builder->CreateShl(I, ShAmtV, CI.getName());
8640       return BinaryOperator::CreateAShr(I, ShAmtV);
8641     }
8642   }
8643   
8644   return 0;
8645 }
8646
8647 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8648 /// in the specified FP type without changing its value.
8649 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8650                               LLVMContext *Context) {
8651   bool losesInfo;
8652   APFloat F = CFP->getValueAPF();
8653   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8654   if (!losesInfo)
8655     return ConstantFP::get(*Context, F);
8656   return 0;
8657 }
8658
8659 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8660 /// through it until we get the source value.
8661 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8662   if (Instruction *I = dyn_cast<Instruction>(V))
8663     if (I->getOpcode() == Instruction::FPExt)
8664       return LookThroughFPExtensions(I->getOperand(0), Context);
8665   
8666   // If this value is a constant, return the constant in the smallest FP type
8667   // that can accurately represent it.  This allows us to turn
8668   // (float)((double)X+2.0) into x+2.0f.
8669   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8670     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8671       return V;  // No constant folding of this.
8672     // See if the value can be truncated to float and then reextended.
8673     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8674       return V;
8675     if (CFP->getType() == Type::getDoubleTy(*Context))
8676       return V;  // Won't shrink.
8677     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8678       return V;
8679     // Don't try to shrink to various long double types.
8680   }
8681   
8682   return V;
8683 }
8684
8685 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8686   if (Instruction *I = commonCastTransforms(CI))
8687     return I;
8688   
8689   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8690   // smaller than the destination type, we can eliminate the truncate by doing
8691   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8692   // many builtins (sqrt, etc).
8693   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8694   if (OpI && OpI->hasOneUse()) {
8695     switch (OpI->getOpcode()) {
8696     default: break;
8697     case Instruction::FAdd:
8698     case Instruction::FSub:
8699     case Instruction::FMul:
8700     case Instruction::FDiv:
8701     case Instruction::FRem:
8702       const Type *SrcTy = OpI->getType();
8703       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8704       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8705       if (LHSTrunc->getType() != SrcTy && 
8706           RHSTrunc->getType() != SrcTy) {
8707         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8708         // If the source types were both smaller than the destination type of
8709         // the cast, do this xform.
8710         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8711             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8712           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8713           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8714           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8715         }
8716       }
8717       break;  
8718     }
8719   }
8720   return 0;
8721 }
8722
8723 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8724   return commonCastTransforms(CI);
8725 }
8726
8727 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8728   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8729   if (OpI == 0)
8730     return commonCastTransforms(FI);
8731
8732   // fptoui(uitofp(X)) --> X
8733   // fptoui(sitofp(X)) --> X
8734   // This is safe if the intermediate type has enough bits in its mantissa to
8735   // accurately represent all values of X.  For example, do not do this with
8736   // i64->float->i64.  This is also safe for sitofp case, because any negative
8737   // 'X' value would cause an undefined result for the fptoui. 
8738   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8739       OpI->getOperand(0)->getType() == FI.getType() &&
8740       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8741                     OpI->getType()->getFPMantissaWidth())
8742     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8743
8744   return commonCastTransforms(FI);
8745 }
8746
8747 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8748   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8749   if (OpI == 0)
8750     return commonCastTransforms(FI);
8751   
8752   // fptosi(sitofp(X)) --> X
8753   // fptosi(uitofp(X)) --> X
8754   // This is safe if the intermediate type has enough bits in its mantissa to
8755   // accurately represent all values of X.  For example, do not do this with
8756   // i64->float->i64.  This is also safe for sitofp case, because any negative
8757   // 'X' value would cause an undefined result for the fptoui. 
8758   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8759       OpI->getOperand(0)->getType() == FI.getType() &&
8760       (int)FI.getType()->getScalarSizeInBits() <=
8761                     OpI->getType()->getFPMantissaWidth())
8762     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8763   
8764   return commonCastTransforms(FI);
8765 }
8766
8767 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8768   return commonCastTransforms(CI);
8769 }
8770
8771 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8772   return commonCastTransforms(CI);
8773 }
8774
8775 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8776   // If the destination integer type is smaller than the intptr_t type for
8777   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8778   // trunc to be exposed to other transforms.  Don't do this for extending
8779   // ptrtoint's, because we don't know if the target sign or zero extends its
8780   // pointers.
8781   if (TD &&
8782       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8783     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8784                                        TD->getIntPtrType(CI.getContext()),
8785                                        "tmp");
8786     return new TruncInst(P, CI.getType());
8787   }
8788   
8789   return commonPointerCastTransforms(CI);
8790 }
8791
8792 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8793   // If the source integer type is larger than the intptr_t type for
8794   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8795   // allows the trunc to be exposed to other transforms.  Don't do this for
8796   // extending inttoptr's, because we don't know if the target sign or zero
8797   // extends to pointers.
8798   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8799       TD->getPointerSizeInBits()) {
8800     Value *P = Builder->CreateTrunc(CI.getOperand(0),
8801                                     TD->getIntPtrType(CI.getContext()), "tmp");
8802     return new IntToPtrInst(P, CI.getType());
8803   }
8804   
8805   if (Instruction *I = commonCastTransforms(CI))
8806     return I;
8807
8808   return 0;
8809 }
8810
8811 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8812   // If the operands are integer typed then apply the integer transforms,
8813   // otherwise just apply the common ones.
8814   Value *Src = CI.getOperand(0);
8815   const Type *SrcTy = Src->getType();
8816   const Type *DestTy = CI.getType();
8817
8818   if (isa<PointerType>(SrcTy)) {
8819     if (Instruction *I = commonPointerCastTransforms(CI))
8820       return I;
8821   } else {
8822     if (Instruction *Result = commonCastTransforms(CI))
8823       return Result;
8824   }
8825
8826
8827   // Get rid of casts from one type to the same type. These are useless and can
8828   // be replaced by the operand.
8829   if (DestTy == Src->getType())
8830     return ReplaceInstUsesWith(CI, Src);
8831
8832   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8833     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8834     const Type *DstElTy = DstPTy->getElementType();
8835     const Type *SrcElTy = SrcPTy->getElementType();
8836     
8837     // If the address spaces don't match, don't eliminate the bitcast, which is
8838     // required for changing types.
8839     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8840       return 0;
8841     
8842     // If we are casting a alloca to a pointer to a type of the same
8843     // size, rewrite the allocation instruction to allocate the "right" type.
8844     // There is no need to modify malloc calls because it is their bitcast that
8845     // needs to be cleaned up.
8846     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8847       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8848         return V;
8849     
8850     // If the source and destination are pointers, and this cast is equivalent
8851     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8852     // This can enhance SROA and other transforms that want type-safe pointers.
8853     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8854     unsigned NumZeros = 0;
8855     while (SrcElTy != DstElTy && 
8856            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8857            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8858       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8859       ++NumZeros;
8860     }
8861
8862     // If we found a path from the src to dest, create the getelementptr now.
8863     if (SrcElTy == DstElTy) {
8864       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8865       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8866                                                ((Instruction*) NULL));
8867     }
8868   }
8869
8870   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8871     if (DestVTy->getNumElements() == 1) {
8872       if (!isa<VectorType>(SrcTy)) {
8873         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8874         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8875                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8876       }
8877       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8878     }
8879   }
8880
8881   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8882     if (SrcVTy->getNumElements() == 1) {
8883       if (!isa<VectorType>(DestTy)) {
8884         Value *Elem = 
8885           Builder->CreateExtractElement(Src,
8886                             Constant::getNullValue(Type::getInt32Ty(*Context)));
8887         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8888       }
8889     }
8890   }
8891
8892   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8893     if (SVI->hasOneUse()) {
8894       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8895       // a bitconvert to a vector with the same # elts.
8896       if (isa<VectorType>(DestTy) && 
8897           cast<VectorType>(DestTy)->getNumElements() ==
8898                 SVI->getType()->getNumElements() &&
8899           SVI->getType()->getNumElements() ==
8900             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8901         CastInst *Tmp;
8902         // If either of the operands is a cast from CI.getType(), then
8903         // evaluating the shuffle in the casted destination's type will allow
8904         // us to eliminate at least one cast.
8905         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8906              Tmp->getOperand(0)->getType() == DestTy) ||
8907             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8908              Tmp->getOperand(0)->getType() == DestTy)) {
8909           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8910           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8911           // Return a new shuffle vector.  Use the same element ID's, as we
8912           // know the vector types match #elts.
8913           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8914         }
8915       }
8916     }
8917   }
8918   return 0;
8919 }
8920
8921 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8922 ///   %C = or %A, %B
8923 ///   %D = select %cond, %C, %A
8924 /// into:
8925 ///   %C = select %cond, %B, 0
8926 ///   %D = or %A, %C
8927 ///
8928 /// Assuming that the specified instruction is an operand to the select, return
8929 /// a bitmask indicating which operands of this instruction are foldable if they
8930 /// equal the other incoming value of the select.
8931 ///
8932 static unsigned GetSelectFoldableOperands(Instruction *I) {
8933   switch (I->getOpcode()) {
8934   case Instruction::Add:
8935   case Instruction::Mul:
8936   case Instruction::And:
8937   case Instruction::Or:
8938   case Instruction::Xor:
8939     return 3;              // Can fold through either operand.
8940   case Instruction::Sub:   // Can only fold on the amount subtracted.
8941   case Instruction::Shl:   // Can only fold on the shift amount.
8942   case Instruction::LShr:
8943   case Instruction::AShr:
8944     return 1;
8945   default:
8946     return 0;              // Cannot fold
8947   }
8948 }
8949
8950 /// GetSelectFoldableConstant - For the same transformation as the previous
8951 /// function, return the identity constant that goes into the select.
8952 static Constant *GetSelectFoldableConstant(Instruction *I,
8953                                            LLVMContext *Context) {
8954   switch (I->getOpcode()) {
8955   default: llvm_unreachable("This cannot happen!");
8956   case Instruction::Add:
8957   case Instruction::Sub:
8958   case Instruction::Or:
8959   case Instruction::Xor:
8960   case Instruction::Shl:
8961   case Instruction::LShr:
8962   case Instruction::AShr:
8963     return Constant::getNullValue(I->getType());
8964   case Instruction::And:
8965     return Constant::getAllOnesValue(I->getType());
8966   case Instruction::Mul:
8967     return ConstantInt::get(I->getType(), 1);
8968   }
8969 }
8970
8971 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8972 /// have the same opcode and only one use each.  Try to simplify this.
8973 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8974                                           Instruction *FI) {
8975   if (TI->getNumOperands() == 1) {
8976     // If this is a non-volatile load or a cast from the same type,
8977     // merge.
8978     if (TI->isCast()) {
8979       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8980         return 0;
8981     } else {
8982       return 0;  // unknown unary op.
8983     }
8984
8985     // Fold this by inserting a select from the input values.
8986     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8987                                           FI->getOperand(0), SI.getName()+".v");
8988     InsertNewInstBefore(NewSI, SI);
8989     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8990                             TI->getType());
8991   }
8992
8993   // Only handle binary operators here.
8994   if (!isa<BinaryOperator>(TI))
8995     return 0;
8996
8997   // Figure out if the operations have any operands in common.
8998   Value *MatchOp, *OtherOpT, *OtherOpF;
8999   bool MatchIsOpZero;
9000   if (TI->getOperand(0) == FI->getOperand(0)) {
9001     MatchOp  = TI->getOperand(0);
9002     OtherOpT = TI->getOperand(1);
9003     OtherOpF = FI->getOperand(1);
9004     MatchIsOpZero = true;
9005   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9006     MatchOp  = TI->getOperand(1);
9007     OtherOpT = TI->getOperand(0);
9008     OtherOpF = FI->getOperand(0);
9009     MatchIsOpZero = false;
9010   } else if (!TI->isCommutative()) {
9011     return 0;
9012   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9013     MatchOp  = TI->getOperand(0);
9014     OtherOpT = TI->getOperand(1);
9015     OtherOpF = FI->getOperand(0);
9016     MatchIsOpZero = true;
9017   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9018     MatchOp  = TI->getOperand(1);
9019     OtherOpT = TI->getOperand(0);
9020     OtherOpF = FI->getOperand(1);
9021     MatchIsOpZero = true;
9022   } else {
9023     return 0;
9024   }
9025
9026   // If we reach here, they do have operations in common.
9027   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9028                                          OtherOpF, SI.getName()+".v");
9029   InsertNewInstBefore(NewSI, SI);
9030
9031   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9032     if (MatchIsOpZero)
9033       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9034     else
9035       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9036   }
9037   llvm_unreachable("Shouldn't get here");
9038   return 0;
9039 }
9040
9041 static bool isSelect01(Constant *C1, Constant *C2) {
9042   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9043   if (!C1I)
9044     return false;
9045   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9046   if (!C2I)
9047     return false;
9048   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9049 }
9050
9051 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9052 /// facilitate further optimization.
9053 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9054                                             Value *FalseVal) {
9055   // See the comment above GetSelectFoldableOperands for a description of the
9056   // transformation we are doing here.
9057   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9058     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9059         !isa<Constant>(FalseVal)) {
9060       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9061         unsigned OpToFold = 0;
9062         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9063           OpToFold = 1;
9064         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9065           OpToFold = 2;
9066         }
9067
9068         if (OpToFold) {
9069           Constant *C = GetSelectFoldableConstant(TVI, Context);
9070           Value *OOp = TVI->getOperand(2-OpToFold);
9071           // Avoid creating select between 2 constants unless it's selecting
9072           // between 0 and 1.
9073           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9074             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9075             InsertNewInstBefore(NewSel, SI);
9076             NewSel->takeName(TVI);
9077             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9078               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9079             llvm_unreachable("Unknown instruction!!");
9080           }
9081         }
9082       }
9083     }
9084   }
9085
9086   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9087     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9088         !isa<Constant>(TrueVal)) {
9089       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9090         unsigned OpToFold = 0;
9091         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9092           OpToFold = 1;
9093         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9094           OpToFold = 2;
9095         }
9096
9097         if (OpToFold) {
9098           Constant *C = GetSelectFoldableConstant(FVI, Context);
9099           Value *OOp = FVI->getOperand(2-OpToFold);
9100           // Avoid creating select between 2 constants unless it's selecting
9101           // between 0 and 1.
9102           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9103             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9104             InsertNewInstBefore(NewSel, SI);
9105             NewSel->takeName(FVI);
9106             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9107               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9108             llvm_unreachable("Unknown instruction!!");
9109           }
9110         }
9111       }
9112     }
9113   }
9114
9115   return 0;
9116 }
9117
9118 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9119 /// ICmpInst as its first operand.
9120 ///
9121 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9122                                                    ICmpInst *ICI) {
9123   bool Changed = false;
9124   ICmpInst::Predicate Pred = ICI->getPredicate();
9125   Value *CmpLHS = ICI->getOperand(0);
9126   Value *CmpRHS = ICI->getOperand(1);
9127   Value *TrueVal = SI.getTrueValue();
9128   Value *FalseVal = SI.getFalseValue();
9129
9130   // Check cases where the comparison is with a constant that
9131   // can be adjusted to fit the min/max idiom. We may edit ICI in
9132   // place here, so make sure the select is the only user.
9133   if (ICI->hasOneUse())
9134     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9135       switch (Pred) {
9136       default: break;
9137       case ICmpInst::ICMP_ULT:
9138       case ICmpInst::ICMP_SLT: {
9139         // X < MIN ? T : F  -->  F
9140         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9141           return ReplaceInstUsesWith(SI, FalseVal);
9142         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9143         Constant *AdjustedRHS = SubOne(CI);
9144         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9145             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9146           Pred = ICmpInst::getSwappedPredicate(Pred);
9147           CmpRHS = AdjustedRHS;
9148           std::swap(FalseVal, TrueVal);
9149           ICI->setPredicate(Pred);
9150           ICI->setOperand(1, CmpRHS);
9151           SI.setOperand(1, TrueVal);
9152           SI.setOperand(2, FalseVal);
9153           Changed = true;
9154         }
9155         break;
9156       }
9157       case ICmpInst::ICMP_UGT:
9158       case ICmpInst::ICMP_SGT: {
9159         // X > MAX ? T : F  -->  F
9160         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9161           return ReplaceInstUsesWith(SI, FalseVal);
9162         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9163         Constant *AdjustedRHS = AddOne(CI);
9164         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9165             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9166           Pred = ICmpInst::getSwappedPredicate(Pred);
9167           CmpRHS = AdjustedRHS;
9168           std::swap(FalseVal, TrueVal);
9169           ICI->setPredicate(Pred);
9170           ICI->setOperand(1, CmpRHS);
9171           SI.setOperand(1, TrueVal);
9172           SI.setOperand(2, FalseVal);
9173           Changed = true;
9174         }
9175         break;
9176       }
9177       }
9178
9179       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9180       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9181       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9182       if (match(TrueVal, m_ConstantInt<-1>()) &&
9183           match(FalseVal, m_ConstantInt<0>()))
9184         Pred = ICI->getPredicate();
9185       else if (match(TrueVal, m_ConstantInt<0>()) &&
9186                match(FalseVal, m_ConstantInt<-1>()))
9187         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9188       
9189       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9190         // If we are just checking for a icmp eq of a single bit and zext'ing it
9191         // to an integer, then shift the bit to the appropriate place and then
9192         // cast to integer to avoid the comparison.
9193         const APInt &Op1CV = CI->getValue();
9194     
9195         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9196         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9197         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9198             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9199           Value *In = ICI->getOperand(0);
9200           Value *Sh = ConstantInt::get(In->getType(),
9201                                        In->getType()->getScalarSizeInBits()-1);
9202           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9203                                                         In->getName()+".lobit"),
9204                                    *ICI);
9205           if (In->getType() != SI.getType())
9206             In = CastInst::CreateIntegerCast(In, SI.getType(),
9207                                              true/*SExt*/, "tmp", ICI);
9208     
9209           if (Pred == ICmpInst::ICMP_SGT)
9210             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9211                                        In->getName()+".not"), *ICI);
9212     
9213           return ReplaceInstUsesWith(SI, In);
9214         }
9215       }
9216     }
9217
9218   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9219     // Transform (X == Y) ? X : Y  -> Y
9220     if (Pred == ICmpInst::ICMP_EQ)
9221       return ReplaceInstUsesWith(SI, FalseVal);
9222     // Transform (X != Y) ? X : Y  -> X
9223     if (Pred == ICmpInst::ICMP_NE)
9224       return ReplaceInstUsesWith(SI, TrueVal);
9225     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9226
9227   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9228     // Transform (X == Y) ? Y : X  -> X
9229     if (Pred == ICmpInst::ICMP_EQ)
9230       return ReplaceInstUsesWith(SI, FalseVal);
9231     // Transform (X != Y) ? Y : X  -> Y
9232     if (Pred == ICmpInst::ICMP_NE)
9233       return ReplaceInstUsesWith(SI, TrueVal);
9234     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9235   }
9236
9237   /// NOTE: if we wanted to, this is where to detect integer ABS
9238
9239   return Changed ? &SI : 0;
9240 }
9241
9242 /// isDefinedInBB - Return true if the value is an instruction defined in the
9243 /// specified basicblock.
9244 static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9245   const Instruction *I = dyn_cast<Instruction>(V);
9246   return I != 0 && I->getParent() == BB;
9247 }
9248
9249
9250 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9251   Value *CondVal = SI.getCondition();
9252   Value *TrueVal = SI.getTrueValue();
9253   Value *FalseVal = SI.getFalseValue();
9254
9255   // select true, X, Y  -> X
9256   // select false, X, Y -> Y
9257   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9258     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9259
9260   // select C, X, X -> X
9261   if (TrueVal == FalseVal)
9262     return ReplaceInstUsesWith(SI, TrueVal);
9263
9264   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9265     return ReplaceInstUsesWith(SI, FalseVal);
9266   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9267     return ReplaceInstUsesWith(SI, TrueVal);
9268   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9269     if (isa<Constant>(TrueVal))
9270       return ReplaceInstUsesWith(SI, TrueVal);
9271     else
9272       return ReplaceInstUsesWith(SI, FalseVal);
9273   }
9274
9275   if (SI.getType() == Type::getInt1Ty(*Context)) {
9276     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9277       if (C->getZExtValue()) {
9278         // Change: A = select B, true, C --> A = or B, C
9279         return BinaryOperator::CreateOr(CondVal, FalseVal);
9280       } else {
9281         // Change: A = select B, false, C --> A = and !B, C
9282         Value *NotCond =
9283           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9284                                              "not."+CondVal->getName()), SI);
9285         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9286       }
9287     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9288       if (C->getZExtValue() == false) {
9289         // Change: A = select B, C, false --> A = and B, C
9290         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9291       } else {
9292         // Change: A = select B, C, true --> A = or !B, C
9293         Value *NotCond =
9294           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9295                                              "not."+CondVal->getName()), SI);
9296         return BinaryOperator::CreateOr(NotCond, TrueVal);
9297       }
9298     }
9299     
9300     // select a, b, a  -> a&b
9301     // select a, a, b  -> a|b
9302     if (CondVal == TrueVal)
9303       return BinaryOperator::CreateOr(CondVal, FalseVal);
9304     else if (CondVal == FalseVal)
9305       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9306   }
9307
9308   // Selecting between two integer constants?
9309   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9310     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9311       // select C, 1, 0 -> zext C to int
9312       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9313         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9314       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9315         // select C, 0, 1 -> zext !C to int
9316         Value *NotCond =
9317           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9318                                                "not."+CondVal->getName()), SI);
9319         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9320       }
9321
9322       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9323         // If one of the constants is zero (we know they can't both be) and we
9324         // have an icmp instruction with zero, and we have an 'and' with the
9325         // non-constant value, eliminate this whole mess.  This corresponds to
9326         // cases like this: ((X & 27) ? 27 : 0)
9327         if (TrueValC->isZero() || FalseValC->isZero())
9328           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9329               cast<Constant>(IC->getOperand(1))->isNullValue())
9330             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9331               if (ICA->getOpcode() == Instruction::And &&
9332                   isa<ConstantInt>(ICA->getOperand(1)) &&
9333                   (ICA->getOperand(1) == TrueValC ||
9334                    ICA->getOperand(1) == FalseValC) &&
9335                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9336                 // Okay, now we know that everything is set up, we just don't
9337                 // know whether we have a icmp_ne or icmp_eq and whether the 
9338                 // true or false val is the zero.
9339                 bool ShouldNotVal = !TrueValC->isZero();
9340                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9341                 Value *V = ICA;
9342                 if (ShouldNotVal)
9343                   V = InsertNewInstBefore(BinaryOperator::Create(
9344                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9345                 return ReplaceInstUsesWith(SI, V);
9346               }
9347       }
9348     }
9349
9350   // See if we are selecting two values based on a comparison of the two values.
9351   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9352     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9353       // Transform (X == Y) ? X : Y  -> Y
9354       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9355         // This is not safe in general for floating point:  
9356         // consider X== -0, Y== +0.
9357         // It becomes safe if either operand is a nonzero constant.
9358         ConstantFP *CFPt, *CFPf;
9359         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9360               !CFPt->getValueAPF().isZero()) ||
9361             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9362              !CFPf->getValueAPF().isZero()))
9363         return ReplaceInstUsesWith(SI, FalseVal);
9364       }
9365       // Transform (X != Y) ? X : Y  -> X
9366       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9367         return ReplaceInstUsesWith(SI, TrueVal);
9368       // NOTE: if we wanted to, this is where to detect MIN/MAX
9369
9370     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9371       // Transform (X == Y) ? Y : X  -> X
9372       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9373         // This is not safe in general for floating point:  
9374         // consider X== -0, Y== +0.
9375         // It becomes safe if either operand is a nonzero constant.
9376         ConstantFP *CFPt, *CFPf;
9377         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9378               !CFPt->getValueAPF().isZero()) ||
9379             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9380              !CFPf->getValueAPF().isZero()))
9381           return ReplaceInstUsesWith(SI, FalseVal);
9382       }
9383       // Transform (X != Y) ? Y : X  -> Y
9384       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9385         return ReplaceInstUsesWith(SI, TrueVal);
9386       // NOTE: if we wanted to, this is where to detect MIN/MAX
9387     }
9388     // NOTE: if we wanted to, this is where to detect ABS
9389   }
9390
9391   // See if we are selecting two values based on a comparison of the two values.
9392   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9393     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9394       return Result;
9395
9396   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9397     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9398       if (TI->hasOneUse() && FI->hasOneUse()) {
9399         Instruction *AddOp = 0, *SubOp = 0;
9400
9401         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9402         if (TI->getOpcode() == FI->getOpcode())
9403           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9404             return IV;
9405
9406         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9407         // even legal for FP.
9408         if ((TI->getOpcode() == Instruction::Sub &&
9409              FI->getOpcode() == Instruction::Add) ||
9410             (TI->getOpcode() == Instruction::FSub &&
9411              FI->getOpcode() == Instruction::FAdd)) {
9412           AddOp = FI; SubOp = TI;
9413         } else if ((FI->getOpcode() == Instruction::Sub &&
9414                     TI->getOpcode() == Instruction::Add) ||
9415                    (FI->getOpcode() == Instruction::FSub &&
9416                     TI->getOpcode() == Instruction::FAdd)) {
9417           AddOp = TI; SubOp = FI;
9418         }
9419
9420         if (AddOp) {
9421           Value *OtherAddOp = 0;
9422           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9423             OtherAddOp = AddOp->getOperand(1);
9424           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9425             OtherAddOp = AddOp->getOperand(0);
9426           }
9427
9428           if (OtherAddOp) {
9429             // So at this point we know we have (Y -> OtherAddOp):
9430             //        select C, (add X, Y), (sub X, Z)
9431             Value *NegVal;  // Compute -Z
9432             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9433               NegVal = ConstantExpr::getNeg(C);
9434             } else {
9435               NegVal = InsertNewInstBefore(
9436                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9437                                               "tmp"), SI);
9438             }
9439
9440             Value *NewTrueOp = OtherAddOp;
9441             Value *NewFalseOp = NegVal;
9442             if (AddOp != TI)
9443               std::swap(NewTrueOp, NewFalseOp);
9444             Instruction *NewSel =
9445               SelectInst::Create(CondVal, NewTrueOp,
9446                                  NewFalseOp, SI.getName() + ".p");
9447
9448             NewSel = InsertNewInstBefore(NewSel, SI);
9449             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9450           }
9451         }
9452       }
9453
9454   // See if we can fold the select into one of our operands.
9455   if (SI.getType()->isInteger()) {
9456     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9457     if (FoldI)
9458       return FoldI;
9459   }
9460
9461   // See if we can fold the select into a phi node.  The true/false values have
9462   // to be live in the predecessor blocks.  If they are instructions in SI's
9463   // block, we can't map to the predecessor.
9464   if (isa<PHINode>(SI.getCondition()) &&
9465       (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9466        isa<PHINode>(SI.getTrueValue())) &&
9467       (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9468        isa<PHINode>(SI.getFalseValue())))
9469     if (Instruction *NV = FoldOpIntoPhi(SI))
9470       return NV;
9471
9472   if (BinaryOperator::isNot(CondVal)) {
9473     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9474     SI.setOperand(1, FalseVal);
9475     SI.setOperand(2, TrueVal);
9476     return &SI;
9477   }
9478
9479   return 0;
9480 }
9481
9482 /// EnforceKnownAlignment - If the specified pointer points to an object that
9483 /// we control, modify the object's alignment to PrefAlign. This isn't
9484 /// often possible though. If alignment is important, a more reliable approach
9485 /// is to simply align all global variables and allocation instructions to
9486 /// their preferred alignment from the beginning.
9487 ///
9488 static unsigned EnforceKnownAlignment(Value *V,
9489                                       unsigned Align, unsigned PrefAlign) {
9490
9491   User *U = dyn_cast<User>(V);
9492   if (!U) return Align;
9493
9494   switch (Operator::getOpcode(U)) {
9495   default: break;
9496   case Instruction::BitCast:
9497     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9498   case Instruction::GetElementPtr: {
9499     // If all indexes are zero, it is just the alignment of the base pointer.
9500     bool AllZeroOperands = true;
9501     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9502       if (!isa<Constant>(*i) ||
9503           !cast<Constant>(*i)->isNullValue()) {
9504         AllZeroOperands = false;
9505         break;
9506       }
9507
9508     if (AllZeroOperands) {
9509       // Treat this like a bitcast.
9510       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9511     }
9512     break;
9513   }
9514   }
9515
9516   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9517     // If there is a large requested alignment and we can, bump up the alignment
9518     // of the global.
9519     if (!GV->isDeclaration()) {
9520       if (GV->getAlignment() >= PrefAlign)
9521         Align = GV->getAlignment();
9522       else {
9523         GV->setAlignment(PrefAlign);
9524         Align = PrefAlign;
9525       }
9526     }
9527   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9528     // If there is a requested alignment and if this is an alloca, round up.
9529     if (AI->getAlignment() >= PrefAlign)
9530       Align = AI->getAlignment();
9531     else {
9532       AI->setAlignment(PrefAlign);
9533       Align = PrefAlign;
9534     }
9535   }
9536
9537   return Align;
9538 }
9539
9540 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9541 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9542 /// and it is more than the alignment of the ultimate object, see if we can
9543 /// increase the alignment of the ultimate object, making this check succeed.
9544 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9545                                                   unsigned PrefAlign) {
9546   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9547                       sizeof(PrefAlign) * CHAR_BIT;
9548   APInt Mask = APInt::getAllOnesValue(BitWidth);
9549   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9550   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9551   unsigned TrailZ = KnownZero.countTrailingOnes();
9552   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9553
9554   if (PrefAlign > Align)
9555     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9556   
9557     // We don't need to make any adjustment.
9558   return Align;
9559 }
9560
9561 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9562   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9563   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9564   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9565   unsigned CopyAlign = MI->getAlignment();
9566
9567   if (CopyAlign < MinAlign) {
9568     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9569                                              MinAlign, false));
9570     return MI;
9571   }
9572   
9573   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9574   // load/store.
9575   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9576   if (MemOpLength == 0) return 0;
9577   
9578   // Source and destination pointer types are always "i8*" for intrinsic.  See
9579   // if the size is something we can handle with a single primitive load/store.
9580   // A single load+store correctly handles overlapping memory in the memmove
9581   // case.
9582   unsigned Size = MemOpLength->getZExtValue();
9583   if (Size == 0) return MI;  // Delete this mem transfer.
9584   
9585   if (Size > 8 || (Size&(Size-1)))
9586     return 0;  // If not 1/2/4/8 bytes, exit.
9587   
9588   // Use an integer load+store unless we can find something better.
9589   Type *NewPtrTy =
9590                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9591   
9592   // Memcpy forces the use of i8* for the source and destination.  That means
9593   // that if you're using memcpy to move one double around, you'll get a cast
9594   // from double* to i8*.  We'd much rather use a double load+store rather than
9595   // an i64 load+store, here because this improves the odds that the source or
9596   // dest address will be promotable.  See if we can find a better type than the
9597   // integer datatype.
9598   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9599     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9600     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9601       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9602       // down through these levels if so.
9603       while (!SrcETy->isSingleValueType()) {
9604         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9605           if (STy->getNumElements() == 1)
9606             SrcETy = STy->getElementType(0);
9607           else
9608             break;
9609         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9610           if (ATy->getNumElements() == 1)
9611             SrcETy = ATy->getElementType();
9612           else
9613             break;
9614         } else
9615           break;
9616       }
9617       
9618       if (SrcETy->isSingleValueType())
9619         NewPtrTy = PointerType::getUnqual(SrcETy);
9620     }
9621   }
9622   
9623   
9624   // If the memcpy/memmove provides better alignment info than we can
9625   // infer, use it.
9626   SrcAlign = std::max(SrcAlign, CopyAlign);
9627   DstAlign = std::max(DstAlign, CopyAlign);
9628   
9629   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9630   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9631   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9632   InsertNewInstBefore(L, *MI);
9633   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9634
9635   // Set the size of the copy to 0, it will be deleted on the next iteration.
9636   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9637   return MI;
9638 }
9639
9640 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9641   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9642   if (MI->getAlignment() < Alignment) {
9643     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9644                                              Alignment, false));
9645     return MI;
9646   }
9647   
9648   // Extract the length and alignment and fill if they are constant.
9649   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9650   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9651   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9652     return 0;
9653   uint64_t Len = LenC->getZExtValue();
9654   Alignment = MI->getAlignment();
9655   
9656   // If the length is zero, this is a no-op
9657   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9658   
9659   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9660   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9661     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9662     
9663     Value *Dest = MI->getDest();
9664     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9665
9666     // Alignment 0 is identity for alignment 1 for memset, but not store.
9667     if (Alignment == 0) Alignment = 1;
9668     
9669     // Extract the fill value and store.
9670     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9671     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9672                                       Dest, false, Alignment), *MI);
9673     
9674     // Set the size of the copy to 0, it will be deleted on the next iteration.
9675     MI->setLength(Constant::getNullValue(LenC->getType()));
9676     return MI;
9677   }
9678
9679   return 0;
9680 }
9681
9682
9683 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9684 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9685 /// the heavy lifting.
9686 ///
9687 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9688   // If the caller function is nounwind, mark the call as nounwind, even if the
9689   // callee isn't.
9690   if (CI.getParent()->getParent()->doesNotThrow() &&
9691       !CI.doesNotThrow()) {
9692     CI.setDoesNotThrow();
9693     return &CI;
9694   }
9695   
9696   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9697   if (!II) return visitCallSite(&CI);
9698   
9699   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9700   // visitCallSite.
9701   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9702     bool Changed = false;
9703
9704     // memmove/cpy/set of zero bytes is a noop.
9705     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9706       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9707
9708       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9709         if (CI->getZExtValue() == 1) {
9710           // Replace the instruction with just byte operations.  We would
9711           // transform other cases to loads/stores, but we don't know if
9712           // alignment is sufficient.
9713         }
9714     }
9715
9716     // If we have a memmove and the source operation is a constant global,
9717     // then the source and dest pointers can't alias, so we can change this
9718     // into a call to memcpy.
9719     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9720       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9721         if (GVSrc->isConstant()) {
9722           Module *M = CI.getParent()->getParent()->getParent();
9723           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9724           const Type *Tys[1];
9725           Tys[0] = CI.getOperand(3)->getType();
9726           CI.setOperand(0, 
9727                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9728           Changed = true;
9729         }
9730
9731       // memmove(x,x,size) -> noop.
9732       if (MMI->getSource() == MMI->getDest())
9733         return EraseInstFromFunction(CI);
9734     }
9735
9736     // If we can determine a pointer alignment that is bigger than currently
9737     // set, update the alignment.
9738     if (isa<MemTransferInst>(MI)) {
9739       if (Instruction *I = SimplifyMemTransfer(MI))
9740         return I;
9741     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9742       if (Instruction *I = SimplifyMemSet(MSI))
9743         return I;
9744     }
9745           
9746     if (Changed) return II;
9747   }
9748   
9749   switch (II->getIntrinsicID()) {
9750   default: break;
9751   case Intrinsic::bswap:
9752     // bswap(bswap(x)) -> x
9753     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9754       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9755         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9756     break;
9757   case Intrinsic::ppc_altivec_lvx:
9758   case Intrinsic::ppc_altivec_lvxl:
9759   case Intrinsic::x86_sse_loadu_ps:
9760   case Intrinsic::x86_sse2_loadu_pd:
9761   case Intrinsic::x86_sse2_loadu_dq:
9762     // Turn PPC lvx     -> load if the pointer is known aligned.
9763     // Turn X86 loadups -> load if the pointer is known aligned.
9764     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9765       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9766                                          PointerType::getUnqual(II->getType()));
9767       return new LoadInst(Ptr);
9768     }
9769     break;
9770   case Intrinsic::ppc_altivec_stvx:
9771   case Intrinsic::ppc_altivec_stvxl:
9772     // Turn stvx -> store if the pointer is known aligned.
9773     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9774       const Type *OpPtrTy = 
9775         PointerType::getUnqual(II->getOperand(1)->getType());
9776       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9777       return new StoreInst(II->getOperand(1), Ptr);
9778     }
9779     break;
9780   case Intrinsic::x86_sse_storeu_ps:
9781   case Intrinsic::x86_sse2_storeu_pd:
9782   case Intrinsic::x86_sse2_storeu_dq:
9783     // Turn X86 storeu -> store if the pointer is known aligned.
9784     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9785       const Type *OpPtrTy = 
9786         PointerType::getUnqual(II->getOperand(2)->getType());
9787       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9788       return new StoreInst(II->getOperand(2), Ptr);
9789     }
9790     break;
9791     
9792   case Intrinsic::x86_sse_cvttss2si: {
9793     // These intrinsics only demands the 0th element of its input vector.  If
9794     // we can simplify the input based on that, do so now.
9795     unsigned VWidth =
9796       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9797     APInt DemandedElts(VWidth, 1);
9798     APInt UndefElts(VWidth, 0);
9799     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9800                                               UndefElts)) {
9801       II->setOperand(1, V);
9802       return II;
9803     }
9804     break;
9805   }
9806     
9807   case Intrinsic::ppc_altivec_vperm:
9808     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9809     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9810       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9811       
9812       // Check that all of the elements are integer constants or undefs.
9813       bool AllEltsOk = true;
9814       for (unsigned i = 0; i != 16; ++i) {
9815         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9816             !isa<UndefValue>(Mask->getOperand(i))) {
9817           AllEltsOk = false;
9818           break;
9819         }
9820       }
9821       
9822       if (AllEltsOk) {
9823         // Cast the input vectors to byte vectors.
9824         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9825         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9826         Value *Result = UndefValue::get(Op0->getType());
9827         
9828         // Only extract each element once.
9829         Value *ExtractedElts[32];
9830         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9831         
9832         for (unsigned i = 0; i != 16; ++i) {
9833           if (isa<UndefValue>(Mask->getOperand(i)))
9834             continue;
9835           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9836           Idx &= 31;  // Match the hardware behavior.
9837           
9838           if (ExtractedElts[Idx] == 0) {
9839             ExtractedElts[Idx] = 
9840               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
9841                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9842                                             "tmp");
9843           }
9844         
9845           // Insert this value into the result vector.
9846           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9847                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9848                                                 "tmp");
9849         }
9850         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9851       }
9852     }
9853     break;
9854
9855   case Intrinsic::stackrestore: {
9856     // If the save is right next to the restore, remove the restore.  This can
9857     // happen when variable allocas are DCE'd.
9858     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9859       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9860         BasicBlock::iterator BI = SS;
9861         if (&*++BI == II)
9862           return EraseInstFromFunction(CI);
9863       }
9864     }
9865     
9866     // Scan down this block to see if there is another stack restore in the
9867     // same block without an intervening call/alloca.
9868     BasicBlock::iterator BI = II;
9869     TerminatorInst *TI = II->getParent()->getTerminator();
9870     bool CannotRemove = false;
9871     for (++BI; &*BI != TI; ++BI) {
9872       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9873         CannotRemove = true;
9874         break;
9875       }
9876       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9877         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9878           // If there is a stackrestore below this one, remove this one.
9879           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9880             return EraseInstFromFunction(CI);
9881           // Otherwise, ignore the intrinsic.
9882         } else {
9883           // If we found a non-intrinsic call, we can't remove the stack
9884           // restore.
9885           CannotRemove = true;
9886           break;
9887         }
9888       }
9889     }
9890     
9891     // If the stack restore is in a return/unwind block and if there are no
9892     // allocas or calls between the restore and the return, nuke the restore.
9893     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9894       return EraseInstFromFunction(CI);
9895     break;
9896   }
9897   }
9898
9899   return visitCallSite(II);
9900 }
9901
9902 // InvokeInst simplification
9903 //
9904 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9905   return visitCallSite(&II);
9906 }
9907
9908 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9909 /// passed through the varargs area, we can eliminate the use of the cast.
9910 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9911                                          const CastInst * const CI,
9912                                          const TargetData * const TD,
9913                                          const int ix) {
9914   if (!CI->isLosslessCast())
9915     return false;
9916
9917   // The size of ByVal arguments is derived from the type, so we
9918   // can't change to a type with a different size.  If the size were
9919   // passed explicitly we could avoid this check.
9920   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9921     return true;
9922
9923   const Type* SrcTy = 
9924             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9925   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9926   if (!SrcTy->isSized() || !DstTy->isSized())
9927     return false;
9928   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9929     return false;
9930   return true;
9931 }
9932
9933 // visitCallSite - Improvements for call and invoke instructions.
9934 //
9935 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9936   bool Changed = false;
9937
9938   // If the callee is a constexpr cast of a function, attempt to move the cast
9939   // to the arguments of the call/invoke.
9940   if (transformConstExprCastCall(CS)) return 0;
9941
9942   Value *Callee = CS.getCalledValue();
9943
9944   if (Function *CalleeF = dyn_cast<Function>(Callee))
9945     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9946       Instruction *OldCall = CS.getInstruction();
9947       // If the call and callee calling conventions don't match, this call must
9948       // be unreachable, as the call is undefined.
9949       new StoreInst(ConstantInt::getTrue(*Context),
9950                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
9951                                   OldCall);
9952       if (!OldCall->use_empty())
9953         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9954       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9955         return EraseInstFromFunction(*OldCall);
9956       return 0;
9957     }
9958
9959   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9960     // This instruction is not reachable, just remove it.  We insert a store to
9961     // undef so that we know that this code is not reachable, despite the fact
9962     // that we can't modify the CFG here.
9963     new StoreInst(ConstantInt::getTrue(*Context),
9964                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9965                   CS.getInstruction());
9966
9967     if (!CS.getInstruction()->use_empty())
9968       CS.getInstruction()->
9969         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9970
9971     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9972       // Don't break the CFG, insert a dummy cond branch.
9973       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9974                          ConstantInt::getTrue(*Context), II);
9975     }
9976     return EraseInstFromFunction(*CS.getInstruction());
9977   }
9978
9979   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9980     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9981       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9982         return transformCallThroughTrampoline(CS);
9983
9984   const PointerType *PTy = cast<PointerType>(Callee->getType());
9985   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9986   if (FTy->isVarArg()) {
9987     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9988     // See if we can optimize any arguments passed through the varargs area of
9989     // the call.
9990     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9991            E = CS.arg_end(); I != E; ++I, ++ix) {
9992       CastInst *CI = dyn_cast<CastInst>(*I);
9993       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9994         *I = CI->getOperand(0);
9995         Changed = true;
9996       }
9997     }
9998   }
9999
10000   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10001     // Inline asm calls cannot throw - mark them 'nounwind'.
10002     CS.setDoesNotThrow();
10003     Changed = true;
10004   }
10005
10006   return Changed ? CS.getInstruction() : 0;
10007 }
10008
10009 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10010 // attempt to move the cast to the arguments of the call/invoke.
10011 //
10012 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10013   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10014   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10015   if (CE->getOpcode() != Instruction::BitCast || 
10016       !isa<Function>(CE->getOperand(0)))
10017     return false;
10018   Function *Callee = cast<Function>(CE->getOperand(0));
10019   Instruction *Caller = CS.getInstruction();
10020   const AttrListPtr &CallerPAL = CS.getAttributes();
10021
10022   // Okay, this is a cast from a function to a different type.  Unless doing so
10023   // would cause a type conversion of one of our arguments, change this call to
10024   // be a direct call with arguments casted to the appropriate types.
10025   //
10026   const FunctionType *FT = Callee->getFunctionType();
10027   const Type *OldRetTy = Caller->getType();
10028   const Type *NewRetTy = FT->getReturnType();
10029
10030   if (isa<StructType>(NewRetTy))
10031     return false; // TODO: Handle multiple return values.
10032
10033   // Check to see if we are changing the return type...
10034   if (OldRetTy != NewRetTy) {
10035     if (Callee->isDeclaration() &&
10036         // Conversion is ok if changing from one pointer type to another or from
10037         // a pointer to an integer of the same size.
10038         !((isa<PointerType>(OldRetTy) || !TD ||
10039            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10040           (isa<PointerType>(NewRetTy) || !TD ||
10041            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10042       return false;   // Cannot transform this return value.
10043
10044     if (!Caller->use_empty() &&
10045         // void -> non-void is handled specially
10046         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10047       return false;   // Cannot transform this return value.
10048
10049     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10050       Attributes RAttrs = CallerPAL.getRetAttributes();
10051       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10052         return false;   // Attribute not compatible with transformed value.
10053     }
10054
10055     // If the callsite is an invoke instruction, and the return value is used by
10056     // a PHI node in a successor, we cannot change the return type of the call
10057     // because there is no place to put the cast instruction (without breaking
10058     // the critical edge).  Bail out in this case.
10059     if (!Caller->use_empty())
10060       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10061         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10062              UI != E; ++UI)
10063           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10064             if (PN->getParent() == II->getNormalDest() ||
10065                 PN->getParent() == II->getUnwindDest())
10066               return false;
10067   }
10068
10069   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10070   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10071
10072   CallSite::arg_iterator AI = CS.arg_begin();
10073   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10074     const Type *ParamTy = FT->getParamType(i);
10075     const Type *ActTy = (*AI)->getType();
10076
10077     if (!CastInst::isCastable(ActTy, ParamTy))
10078       return false;   // Cannot transform this parameter value.
10079
10080     if (CallerPAL.getParamAttributes(i + 1) 
10081         & Attribute::typeIncompatible(ParamTy))
10082       return false;   // Attribute not compatible with transformed value.
10083
10084     // Converting from one pointer type to another or between a pointer and an
10085     // integer of the same size is safe even if we do not have a body.
10086     bool isConvertible = ActTy == ParamTy ||
10087       (TD && ((isa<PointerType>(ParamTy) ||
10088       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10089               (isa<PointerType>(ActTy) ||
10090               ActTy == TD->getIntPtrType(Caller->getContext()))));
10091     if (Callee->isDeclaration() && !isConvertible) return false;
10092   }
10093
10094   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10095       Callee->isDeclaration())
10096     return false;   // Do not delete arguments unless we have a function body.
10097
10098   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10099       !CallerPAL.isEmpty())
10100     // In this case we have more arguments than the new function type, but we
10101     // won't be dropping them.  Check that these extra arguments have attributes
10102     // that are compatible with being a vararg call argument.
10103     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10104       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10105         break;
10106       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10107       if (PAttrs & Attribute::VarArgsIncompatible)
10108         return false;
10109     }
10110
10111   // Okay, we decided that this is a safe thing to do: go ahead and start
10112   // inserting cast instructions as necessary...
10113   std::vector<Value*> Args;
10114   Args.reserve(NumActualArgs);
10115   SmallVector<AttributeWithIndex, 8> attrVec;
10116   attrVec.reserve(NumCommonArgs);
10117
10118   // Get any return attributes.
10119   Attributes RAttrs = CallerPAL.getRetAttributes();
10120
10121   // If the return value is not being used, the type may not be compatible
10122   // with the existing attributes.  Wipe out any problematic attributes.
10123   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10124
10125   // Add the new return attributes.
10126   if (RAttrs)
10127     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10128
10129   AI = CS.arg_begin();
10130   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10131     const Type *ParamTy = FT->getParamType(i);
10132     if ((*AI)->getType() == ParamTy) {
10133       Args.push_back(*AI);
10134     } else {
10135       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10136           false, ParamTy, false);
10137       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10138     }
10139
10140     // Add any parameter attributes.
10141     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10142       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10143   }
10144
10145   // If the function takes more arguments than the call was taking, add them
10146   // now.
10147   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10148     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10149
10150   // If we are removing arguments to the function, emit an obnoxious warning.
10151   if (FT->getNumParams() < NumActualArgs) {
10152     if (!FT->isVarArg()) {
10153       errs() << "WARNING: While resolving call to function '"
10154              << Callee->getName() << "' arguments were dropped!\n";
10155     } else {
10156       // Add all of the arguments in their promoted form to the arg list.
10157       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10158         const Type *PTy = getPromotedType((*AI)->getType());
10159         if (PTy != (*AI)->getType()) {
10160           // Must promote to pass through va_arg area!
10161           Instruction::CastOps opcode =
10162             CastInst::getCastOpcode(*AI, false, PTy, false);
10163           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10164         } else {
10165           Args.push_back(*AI);
10166         }
10167
10168         // Add any parameter attributes.
10169         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10170           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10171       }
10172     }
10173   }
10174
10175   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10176     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10177
10178   if (NewRetTy == Type::getVoidTy(*Context))
10179     Caller->setName("");   // Void type should not have a name.
10180
10181   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10182                                                      attrVec.end());
10183
10184   Instruction *NC;
10185   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10186     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10187                             Args.begin(), Args.end(),
10188                             Caller->getName(), Caller);
10189     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10190     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10191   } else {
10192     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10193                           Caller->getName(), Caller);
10194     CallInst *CI = cast<CallInst>(Caller);
10195     if (CI->isTailCall())
10196       cast<CallInst>(NC)->setTailCall();
10197     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10198     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10199   }
10200
10201   // Insert a cast of the return type as necessary.
10202   Value *NV = NC;
10203   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10204     if (NV->getType() != Type::getVoidTy(*Context)) {
10205       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10206                                                             OldRetTy, false);
10207       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10208
10209       // If this is an invoke instruction, we should insert it after the first
10210       // non-phi, instruction in the normal successor block.
10211       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10212         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10213         InsertNewInstBefore(NC, *I);
10214       } else {
10215         // Otherwise, it's a call, just insert cast right after the call instr
10216         InsertNewInstBefore(NC, *Caller);
10217       }
10218       Worklist.AddUsersToWorkList(*Caller);
10219     } else {
10220       NV = UndefValue::get(Caller->getType());
10221     }
10222   }
10223
10224   
10225   if (!Caller->use_empty())
10226     Caller->replaceAllUsesWith(NV);
10227   
10228   EraseInstFromFunction(*Caller);
10229   return true;
10230 }
10231
10232 // transformCallThroughTrampoline - Turn a call to a function created by the
10233 // init_trampoline intrinsic into a direct call to the underlying function.
10234 //
10235 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10236   Value *Callee = CS.getCalledValue();
10237   const PointerType *PTy = cast<PointerType>(Callee->getType());
10238   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10239   const AttrListPtr &Attrs = CS.getAttributes();
10240
10241   // If the call already has the 'nest' attribute somewhere then give up -
10242   // otherwise 'nest' would occur twice after splicing in the chain.
10243   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10244     return 0;
10245
10246   IntrinsicInst *Tramp =
10247     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10248
10249   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10250   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10251   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10252
10253   const AttrListPtr &NestAttrs = NestF->getAttributes();
10254   if (!NestAttrs.isEmpty()) {
10255     unsigned NestIdx = 1;
10256     const Type *NestTy = 0;
10257     Attributes NestAttr = Attribute::None;
10258
10259     // Look for a parameter marked with the 'nest' attribute.
10260     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10261          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10262       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10263         // Record the parameter type and any other attributes.
10264         NestTy = *I;
10265         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10266         break;
10267       }
10268
10269     if (NestTy) {
10270       Instruction *Caller = CS.getInstruction();
10271       std::vector<Value*> NewArgs;
10272       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10273
10274       SmallVector<AttributeWithIndex, 8> NewAttrs;
10275       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10276
10277       // Insert the nest argument into the call argument list, which may
10278       // mean appending it.  Likewise for attributes.
10279
10280       // Add any result attributes.
10281       if (Attributes Attr = Attrs.getRetAttributes())
10282         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10283
10284       {
10285         unsigned Idx = 1;
10286         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10287         do {
10288           if (Idx == NestIdx) {
10289             // Add the chain argument and attributes.
10290             Value *NestVal = Tramp->getOperand(3);
10291             if (NestVal->getType() != NestTy)
10292               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10293             NewArgs.push_back(NestVal);
10294             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10295           }
10296
10297           if (I == E)
10298             break;
10299
10300           // Add the original argument and attributes.
10301           NewArgs.push_back(*I);
10302           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10303             NewAttrs.push_back
10304               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10305
10306           ++Idx, ++I;
10307         } while (1);
10308       }
10309
10310       // Add any function attributes.
10311       if (Attributes Attr = Attrs.getFnAttributes())
10312         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10313
10314       // The trampoline may have been bitcast to a bogus type (FTy).
10315       // Handle this by synthesizing a new function type, equal to FTy
10316       // with the chain parameter inserted.
10317
10318       std::vector<const Type*> NewTypes;
10319       NewTypes.reserve(FTy->getNumParams()+1);
10320
10321       // Insert the chain's type into the list of parameter types, which may
10322       // mean appending it.
10323       {
10324         unsigned Idx = 1;
10325         FunctionType::param_iterator I = FTy->param_begin(),
10326           E = FTy->param_end();
10327
10328         do {
10329           if (Idx == NestIdx)
10330             // Add the chain's type.
10331             NewTypes.push_back(NestTy);
10332
10333           if (I == E)
10334             break;
10335
10336           // Add the original type.
10337           NewTypes.push_back(*I);
10338
10339           ++Idx, ++I;
10340         } while (1);
10341       }
10342
10343       // Replace the trampoline call with a direct call.  Let the generic
10344       // code sort out any function type mismatches.
10345       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10346                                                 FTy->isVarArg());
10347       Constant *NewCallee =
10348         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10349         NestF : ConstantExpr::getBitCast(NestF, 
10350                                          PointerType::getUnqual(NewFTy));
10351       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10352                                                    NewAttrs.end());
10353
10354       Instruction *NewCaller;
10355       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10356         NewCaller = InvokeInst::Create(NewCallee,
10357                                        II->getNormalDest(), II->getUnwindDest(),
10358                                        NewArgs.begin(), NewArgs.end(),
10359                                        Caller->getName(), Caller);
10360         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10361         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10362       } else {
10363         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10364                                      Caller->getName(), Caller);
10365         if (cast<CallInst>(Caller)->isTailCall())
10366           cast<CallInst>(NewCaller)->setTailCall();
10367         cast<CallInst>(NewCaller)->
10368           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10369         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10370       }
10371       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10372         Caller->replaceAllUsesWith(NewCaller);
10373       Caller->eraseFromParent();
10374       Worklist.Remove(Caller);
10375       return 0;
10376     }
10377   }
10378
10379   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10380   // parameter, there is no need to adjust the argument list.  Let the generic
10381   // code sort out any function type mismatches.
10382   Constant *NewCallee =
10383     NestF->getType() == PTy ? NestF : 
10384                               ConstantExpr::getBitCast(NestF, PTy);
10385   CS.setCalledFunction(NewCallee);
10386   return CS.getInstruction();
10387 }
10388
10389 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10390 /// and if a/b/c and the add's all have a single use, turn this into a phi
10391 /// and a single binop.
10392 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10393   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10394   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10395   unsigned Opc = FirstInst->getOpcode();
10396   Value *LHSVal = FirstInst->getOperand(0);
10397   Value *RHSVal = FirstInst->getOperand(1);
10398     
10399   const Type *LHSType = LHSVal->getType();
10400   const Type *RHSType = RHSVal->getType();
10401   
10402   // Scan to see if all operands are the same opcode, and all have one use.
10403   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10404     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10405     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10406         // Verify type of the LHS matches so we don't fold cmp's of different
10407         // types or GEP's with different index types.
10408         I->getOperand(0)->getType() != LHSType ||
10409         I->getOperand(1)->getType() != RHSType)
10410       return 0;
10411
10412     // If they are CmpInst instructions, check their predicates
10413     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10414       if (cast<CmpInst>(I)->getPredicate() !=
10415           cast<CmpInst>(FirstInst)->getPredicate())
10416         return 0;
10417     
10418     // Keep track of which operand needs a phi node.
10419     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10420     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10421   }
10422
10423   // If both LHS and RHS would need a PHI, don't do this transformation,
10424   // because it would increase the number of PHIs entering the block,
10425   // which leads to higher register pressure. This is especially
10426   // bad when the PHIs are in the header of a loop.
10427   if (!LHSVal && !RHSVal)
10428     return 0;
10429   
10430   // Otherwise, this is safe to transform!
10431   
10432   Value *InLHS = FirstInst->getOperand(0);
10433   Value *InRHS = FirstInst->getOperand(1);
10434   PHINode *NewLHS = 0, *NewRHS = 0;
10435   if (LHSVal == 0) {
10436     NewLHS = PHINode::Create(LHSType,
10437                              FirstInst->getOperand(0)->getName() + ".pn");
10438     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10439     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10440     InsertNewInstBefore(NewLHS, PN);
10441     LHSVal = NewLHS;
10442   }
10443   
10444   if (RHSVal == 0) {
10445     NewRHS = PHINode::Create(RHSType,
10446                              FirstInst->getOperand(1)->getName() + ".pn");
10447     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10448     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10449     InsertNewInstBefore(NewRHS, PN);
10450     RHSVal = NewRHS;
10451   }
10452   
10453   // Add all operands to the new PHIs.
10454   if (NewLHS || NewRHS) {
10455     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10456       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10457       if (NewLHS) {
10458         Value *NewInLHS = InInst->getOperand(0);
10459         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10460       }
10461       if (NewRHS) {
10462         Value *NewInRHS = InInst->getOperand(1);
10463         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10464       }
10465     }
10466   }
10467     
10468   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10469     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10470   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10471   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10472                          LHSVal, RHSVal);
10473 }
10474
10475 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10476   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10477   
10478   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10479                                         FirstInst->op_end());
10480   // This is true if all GEP bases are allocas and if all indices into them are
10481   // constants.
10482   bool AllBasePointersAreAllocas = true;
10483
10484   // We don't want to replace this phi if the replacement would require
10485   // more than one phi, which leads to higher register pressure. This is
10486   // especially bad when the PHIs are in the header of a loop.
10487   bool NeededPhi = false;
10488   
10489   // Scan to see if all operands are the same opcode, and all have one use.
10490   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10491     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10492     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10493       GEP->getNumOperands() != FirstInst->getNumOperands())
10494       return 0;
10495
10496     // Keep track of whether or not all GEPs are of alloca pointers.
10497     if (AllBasePointersAreAllocas &&
10498         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10499          !GEP->hasAllConstantIndices()))
10500       AllBasePointersAreAllocas = false;
10501     
10502     // Compare the operand lists.
10503     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10504       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10505         continue;
10506       
10507       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10508       // if one of the PHIs has a constant for the index.  The index may be
10509       // substantially cheaper to compute for the constants, so making it a
10510       // variable index could pessimize the path.  This also handles the case
10511       // for struct indices, which must always be constant.
10512       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10513           isa<ConstantInt>(GEP->getOperand(op)))
10514         return 0;
10515       
10516       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10517         return 0;
10518
10519       // If we already needed a PHI for an earlier operand, and another operand
10520       // also requires a PHI, we'd be introducing more PHIs than we're
10521       // eliminating, which increases register pressure on entry to the PHI's
10522       // block.
10523       if (NeededPhi)
10524         return 0;
10525
10526       FixedOperands[op] = 0;  // Needs a PHI.
10527       NeededPhi = true;
10528     }
10529   }
10530   
10531   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10532   // bother doing this transformation.  At best, this will just save a bit of
10533   // offset calculation, but all the predecessors will have to materialize the
10534   // stack address into a register anyway.  We'd actually rather *clone* the
10535   // load up into the predecessors so that we have a load of a gep of an alloca,
10536   // which can usually all be folded into the load.
10537   if (AllBasePointersAreAllocas)
10538     return 0;
10539   
10540   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10541   // that is variable.
10542   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10543   
10544   bool HasAnyPHIs = false;
10545   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10546     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10547     Value *FirstOp = FirstInst->getOperand(i);
10548     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10549                                      FirstOp->getName()+".pn");
10550     InsertNewInstBefore(NewPN, PN);
10551     
10552     NewPN->reserveOperandSpace(e);
10553     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10554     OperandPhis[i] = NewPN;
10555     FixedOperands[i] = NewPN;
10556     HasAnyPHIs = true;
10557   }
10558
10559   
10560   // Add all operands to the new PHIs.
10561   if (HasAnyPHIs) {
10562     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10563       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10564       BasicBlock *InBB = PN.getIncomingBlock(i);
10565       
10566       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10567         if (PHINode *OpPhi = OperandPhis[op])
10568           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10569     }
10570   }
10571   
10572   Value *Base = FixedOperands[0];
10573   return cast<GEPOperator>(FirstInst)->isInBounds() ?
10574     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10575                                       FixedOperands.end()) :
10576     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10577                               FixedOperands.end());
10578 }
10579
10580
10581 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10582 /// sink the load out of the block that defines it.  This means that it must be
10583 /// obvious the value of the load is not changed from the point of the load to
10584 /// the end of the block it is in.
10585 ///
10586 /// Finally, it is safe, but not profitable, to sink a load targetting a
10587 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10588 /// to a register.
10589 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10590   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10591   
10592   for (++BBI; BBI != E; ++BBI)
10593     if (BBI->mayWriteToMemory())
10594       return false;
10595   
10596   // Check for non-address taken alloca.  If not address-taken already, it isn't
10597   // profitable to do this xform.
10598   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10599     bool isAddressTaken = false;
10600     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10601          UI != E; ++UI) {
10602       if (isa<LoadInst>(UI)) continue;
10603       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10604         // If storing TO the alloca, then the address isn't taken.
10605         if (SI->getOperand(1) == AI) continue;
10606       }
10607       isAddressTaken = true;
10608       break;
10609     }
10610     
10611     if (!isAddressTaken && AI->isStaticAlloca())
10612       return false;
10613   }
10614   
10615   // If this load is a load from a GEP with a constant offset from an alloca,
10616   // then we don't want to sink it.  In its present form, it will be
10617   // load [constant stack offset].  Sinking it will cause us to have to
10618   // materialize the stack addresses in each predecessor in a register only to
10619   // do a shared load from register in the successor.
10620   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10621     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10622       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10623         return false;
10624   
10625   return true;
10626 }
10627
10628
10629 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10630 // operator and they all are only used by the PHI, PHI together their
10631 // inputs, and do the operation once, to the result of the PHI.
10632 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10633   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10634
10635   // Scan the instruction, looking for input operations that can be folded away.
10636   // If all input operands to the phi are the same instruction (e.g. a cast from
10637   // the same type or "+42") we can pull the operation through the PHI, reducing
10638   // code size and simplifying code.
10639   Constant *ConstantOp = 0;
10640   const Type *CastSrcTy = 0;
10641   bool isVolatile = false;
10642   if (isa<CastInst>(FirstInst)) {
10643     CastSrcTy = FirstInst->getOperand(0)->getType();
10644   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10645     // Can fold binop, compare or shift here if the RHS is a constant, 
10646     // otherwise call FoldPHIArgBinOpIntoPHI.
10647     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10648     if (ConstantOp == 0)
10649       return FoldPHIArgBinOpIntoPHI(PN);
10650   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10651     isVolatile = LI->isVolatile();
10652     // We can't sink the load if the loaded value could be modified between the
10653     // load and the PHI.
10654     if (LI->getParent() != PN.getIncomingBlock(0) ||
10655         !isSafeAndProfitableToSinkLoad(LI))
10656       return 0;
10657     
10658     // If the PHI is of volatile loads and the load block has multiple
10659     // successors, sinking it would remove a load of the volatile value from
10660     // the path through the other successor.
10661     if (isVolatile &&
10662         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10663       return 0;
10664     
10665   } else if (isa<GetElementPtrInst>(FirstInst)) {
10666     return FoldPHIArgGEPIntoPHI(PN);
10667   } else {
10668     return 0;  // Cannot fold this operation.
10669   }
10670
10671   // Check to see if all arguments are the same operation.
10672   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10673     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10674     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10675     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10676       return 0;
10677     if (CastSrcTy) {
10678       if (I->getOperand(0)->getType() != CastSrcTy)
10679         return 0;  // Cast operation must match.
10680     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10681       // We can't sink the load if the loaded value could be modified between 
10682       // the load and the PHI.
10683       if (LI->isVolatile() != isVolatile ||
10684           LI->getParent() != PN.getIncomingBlock(i) ||
10685           !isSafeAndProfitableToSinkLoad(LI))
10686         return 0;
10687       
10688       // If the PHI is of volatile loads and the load block has multiple
10689       // successors, sinking it would remove a load of the volatile value from
10690       // the path through the other successor.
10691       if (isVolatile &&
10692           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10693         return 0;
10694       
10695     } else if (I->getOperand(1) != ConstantOp) {
10696       return 0;
10697     }
10698   }
10699
10700   // Okay, they are all the same operation.  Create a new PHI node of the
10701   // correct type, and PHI together all of the LHS's of the instructions.
10702   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10703                                    PN.getName()+".in");
10704   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10705
10706   Value *InVal = FirstInst->getOperand(0);
10707   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10708
10709   // Add all operands to the new PHI.
10710   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10711     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10712     if (NewInVal != InVal)
10713       InVal = 0;
10714     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10715   }
10716
10717   Value *PhiVal;
10718   if (InVal) {
10719     // The new PHI unions all of the same values together.  This is really
10720     // common, so we handle it intelligently here for compile-time speed.
10721     PhiVal = InVal;
10722     delete NewPN;
10723   } else {
10724     InsertNewInstBefore(NewPN, PN);
10725     PhiVal = NewPN;
10726   }
10727
10728   // Insert and return the new operation.
10729   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10730     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10731   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10732     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10733   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10734     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10735                            PhiVal, ConstantOp);
10736   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10737   
10738   // If this was a volatile load that we are merging, make sure to loop through
10739   // and mark all the input loads as non-volatile.  If we don't do this, we will
10740   // insert a new volatile load and the old ones will not be deletable.
10741   if (isVolatile)
10742     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10743       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10744   
10745   return new LoadInst(PhiVal, "", isVolatile);
10746 }
10747
10748 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10749 /// that is dead.
10750 static bool DeadPHICycle(PHINode *PN,
10751                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10752   if (PN->use_empty()) return true;
10753   if (!PN->hasOneUse()) return false;
10754
10755   // Remember this node, and if we find the cycle, return.
10756   if (!PotentiallyDeadPHIs.insert(PN))
10757     return true;
10758   
10759   // Don't scan crazily complex things.
10760   if (PotentiallyDeadPHIs.size() == 16)
10761     return false;
10762
10763   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10764     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10765
10766   return false;
10767 }
10768
10769 /// PHIsEqualValue - Return true if this phi node is always equal to
10770 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10771 ///   z = some value; x = phi (y, z); y = phi (x, z)
10772 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10773                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10774   // See if we already saw this PHI node.
10775   if (!ValueEqualPHIs.insert(PN))
10776     return true;
10777   
10778   // Don't scan crazily complex things.
10779   if (ValueEqualPHIs.size() == 16)
10780     return false;
10781  
10782   // Scan the operands to see if they are either phi nodes or are equal to
10783   // the value.
10784   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10785     Value *Op = PN->getIncomingValue(i);
10786     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10787       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10788         return false;
10789     } else if (Op != NonPhiInVal)
10790       return false;
10791   }
10792   
10793   return true;
10794 }
10795
10796
10797 // PHINode simplification
10798 //
10799 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10800   // If LCSSA is around, don't mess with Phi nodes
10801   if (MustPreserveLCSSA) return 0;
10802   
10803   if (Value *V = PN.hasConstantValue())
10804     return ReplaceInstUsesWith(PN, V);
10805
10806   // If all PHI operands are the same operation, pull them through the PHI,
10807   // reducing code size.
10808   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10809       isa<Instruction>(PN.getIncomingValue(1)) &&
10810       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10811       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10812       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10813       // than themselves more than once.
10814       PN.getIncomingValue(0)->hasOneUse())
10815     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10816       return Result;
10817
10818   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10819   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10820   // PHI)... break the cycle.
10821   if (PN.hasOneUse()) {
10822     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10823     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10824       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10825       PotentiallyDeadPHIs.insert(&PN);
10826       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10827         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10828     }
10829    
10830     // If this phi has a single use, and if that use just computes a value for
10831     // the next iteration of a loop, delete the phi.  This occurs with unused
10832     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10833     // common case here is good because the only other things that catch this
10834     // are induction variable analysis (sometimes) and ADCE, which is only run
10835     // late.
10836     if (PHIUser->hasOneUse() &&
10837         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10838         PHIUser->use_back() == &PN) {
10839       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10840     }
10841   }
10842
10843   // We sometimes end up with phi cycles that non-obviously end up being the
10844   // same value, for example:
10845   //   z = some value; x = phi (y, z); y = phi (x, z)
10846   // where the phi nodes don't necessarily need to be in the same block.  Do a
10847   // quick check to see if the PHI node only contains a single non-phi value, if
10848   // so, scan to see if the phi cycle is actually equal to that value.
10849   {
10850     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10851     // Scan for the first non-phi operand.
10852     while (InValNo != NumOperandVals && 
10853            isa<PHINode>(PN.getIncomingValue(InValNo)))
10854       ++InValNo;
10855
10856     if (InValNo != NumOperandVals) {
10857       Value *NonPhiInVal = PN.getOperand(InValNo);
10858       
10859       // Scan the rest of the operands to see if there are any conflicts, if so
10860       // there is no need to recursively scan other phis.
10861       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10862         Value *OpVal = PN.getIncomingValue(InValNo);
10863         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10864           break;
10865       }
10866       
10867       // If we scanned over all operands, then we have one unique value plus
10868       // phi values.  Scan PHI nodes to see if they all merge in each other or
10869       // the value.
10870       if (InValNo == NumOperandVals) {
10871         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10872         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10873           return ReplaceInstUsesWith(PN, NonPhiInVal);
10874       }
10875     }
10876   }
10877   return 0;
10878 }
10879
10880 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10881   Value *PtrOp = GEP.getOperand(0);
10882   // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10883   if (GEP.getNumOperands() == 1)
10884     return ReplaceInstUsesWith(GEP, PtrOp);
10885
10886   if (isa<UndefValue>(GEP.getOperand(0)))
10887     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10888
10889   bool HasZeroPointerIndex = false;
10890   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10891     HasZeroPointerIndex = C->isNullValue();
10892
10893   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10894     return ReplaceInstUsesWith(GEP, PtrOp);
10895
10896   // Eliminate unneeded casts for indices.
10897   if (TD) {
10898     bool MadeChange = false;
10899     unsigned PtrSize = TD->getPointerSizeInBits();
10900     
10901     gep_type_iterator GTI = gep_type_begin(GEP);
10902     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10903          I != E; ++I, ++GTI) {
10904       if (!isa<SequentialType>(*GTI)) continue;
10905       
10906       // If we are using a wider index than needed for this platform, shrink it
10907       // to what we need.  If narrower, sign-extend it to what we need.  This
10908       // explicit cast can make subsequent optimizations more obvious.
10909       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10910       if (OpBits == PtrSize)
10911         continue;
10912       
10913       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10914       MadeChange = true;
10915     }
10916     if (MadeChange) return &GEP;
10917   }
10918
10919   // Combine Indices - If the source pointer to this getelementptr instruction
10920   // is a getelementptr instruction, combine the indices of the two
10921   // getelementptr instructions into a single instruction.
10922   //
10923   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10924     // Note that if our source is a gep chain itself that we wait for that
10925     // chain to be resolved before we perform this transformation.  This
10926     // avoids us creating a TON of code in some cases.
10927     //
10928     if (GetElementPtrInst *SrcGEP =
10929           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10930       if (SrcGEP->getNumOperands() == 2)
10931         return 0;   // Wait until our source is folded to completion.
10932
10933     SmallVector<Value*, 8> Indices;
10934
10935     // Find out whether the last index in the source GEP is a sequential idx.
10936     bool EndsWithSequential = false;
10937     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10938          I != E; ++I)
10939       EndsWithSequential = !isa<StructType>(*I);
10940
10941     // Can we combine the two pointer arithmetics offsets?
10942     if (EndsWithSequential) {
10943       // Replace: gep (gep %P, long B), long A, ...
10944       // With:    T = long A+B; gep %P, T, ...
10945       //
10946       Value *Sum;
10947       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10948       Value *GO1 = GEP.getOperand(1);
10949       if (SO1 == Constant::getNullValue(SO1->getType())) {
10950         Sum = GO1;
10951       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10952         Sum = SO1;
10953       } else {
10954         // If they aren't the same type, then the input hasn't been processed
10955         // by the loop above yet (which canonicalizes sequential index types to
10956         // intptr_t).  Just avoid transforming this until the input has been
10957         // normalized.
10958         if (SO1->getType() != GO1->getType())
10959           return 0;
10960         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10961       }
10962
10963       // Update the GEP in place if possible.
10964       if (Src->getNumOperands() == 2) {
10965         GEP.setOperand(0, Src->getOperand(0));
10966         GEP.setOperand(1, Sum);
10967         return &GEP;
10968       }
10969       Indices.append(Src->op_begin()+1, Src->op_end()-1);
10970       Indices.push_back(Sum);
10971       Indices.append(GEP.op_begin()+2, GEP.op_end());
10972     } else if (isa<Constant>(*GEP.idx_begin()) &&
10973                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10974                Src->getNumOperands() != 1) {
10975       // Otherwise we can do the fold if the first index of the GEP is a zero
10976       Indices.append(Src->op_begin()+1, Src->op_end());
10977       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10978     }
10979
10980     if (!Indices.empty())
10981       return (cast<GEPOperator>(&GEP)->isInBounds() &&
10982               Src->isInBounds()) ?
10983         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10984                                           Indices.end(), GEP.getName()) :
10985         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10986                                   Indices.end(), GEP.getName());
10987   }
10988   
10989   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10990   if (Value *X = getBitCastOperand(PtrOp)) {
10991     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10992
10993     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
10994     // want to change the gep until the bitcasts are eliminated.
10995     if (getBitCastOperand(X)) {
10996       Worklist.AddValue(PtrOp);
10997       return 0;
10998     }
10999     
11000     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11001     // into     : GEP [10 x i8]* X, i32 0, ...
11002     //
11003     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11004     //           into     : GEP i8* X, ...
11005     // 
11006     // This occurs when the program declares an array extern like "int X[];"
11007     if (HasZeroPointerIndex) {
11008       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11009       const PointerType *XTy = cast<PointerType>(X->getType());
11010       if (const ArrayType *CATy =
11011           dyn_cast<ArrayType>(CPTy->getElementType())) {
11012         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11013         if (CATy->getElementType() == XTy->getElementType()) {
11014           // -> GEP i8* X, ...
11015           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11016           return cast<GEPOperator>(&GEP)->isInBounds() ?
11017             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11018                                               GEP.getName()) :
11019             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11020                                       GEP.getName());
11021         }
11022         
11023         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11024           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11025           if (CATy->getElementType() == XATy->getElementType()) {
11026             // -> GEP [10 x i8]* X, i32 0, ...
11027             // At this point, we know that the cast source type is a pointer
11028             // to an array of the same type as the destination pointer
11029             // array.  Because the array type is never stepped over (there
11030             // is a leading zero) we can fold the cast into this GEP.
11031             GEP.setOperand(0, X);
11032             return &GEP;
11033           }
11034         }
11035       }
11036     } else if (GEP.getNumOperands() == 2) {
11037       // Transform things like:
11038       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11039       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11040       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11041       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11042       if (TD && isa<ArrayType>(SrcElTy) &&
11043           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11044           TD->getTypeAllocSize(ResElTy)) {
11045         Value *Idx[2];
11046         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11047         Idx[1] = GEP.getOperand(1);
11048         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11049           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11050           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11051         // V and GEP are both pointer types --> BitCast
11052         return new BitCastInst(NewGEP, GEP.getType());
11053       }
11054       
11055       // Transform things like:
11056       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11057       //   (where tmp = 8*tmp2) into:
11058       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11059       
11060       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11061         uint64_t ArrayEltSize =
11062             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11063         
11064         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11065         // allow either a mul, shift, or constant here.
11066         Value *NewIdx = 0;
11067         ConstantInt *Scale = 0;
11068         if (ArrayEltSize == 1) {
11069           NewIdx = GEP.getOperand(1);
11070           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11071         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11072           NewIdx = ConstantInt::get(CI->getType(), 1);
11073           Scale = CI;
11074         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11075           if (Inst->getOpcode() == Instruction::Shl &&
11076               isa<ConstantInt>(Inst->getOperand(1))) {
11077             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11078             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11079             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11080                                      1ULL << ShAmtVal);
11081             NewIdx = Inst->getOperand(0);
11082           } else if (Inst->getOpcode() == Instruction::Mul &&
11083                      isa<ConstantInt>(Inst->getOperand(1))) {
11084             Scale = cast<ConstantInt>(Inst->getOperand(1));
11085             NewIdx = Inst->getOperand(0);
11086           }
11087         }
11088         
11089         // If the index will be to exactly the right offset with the scale taken
11090         // out, perform the transformation. Note, we don't know whether Scale is
11091         // signed or not. We'll use unsigned version of division/modulo
11092         // operation after making sure Scale doesn't have the sign bit set.
11093         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11094             Scale->getZExtValue() % ArrayEltSize == 0) {
11095           Scale = ConstantInt::get(Scale->getType(),
11096                                    Scale->getZExtValue() / ArrayEltSize);
11097           if (Scale->getZExtValue() != 1) {
11098             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11099                                                        false /*ZExt*/);
11100             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11101           }
11102
11103           // Insert the new GEP instruction.
11104           Value *Idx[2];
11105           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11106           Idx[1] = NewIdx;
11107           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11108             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11109             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11110           // The NewGEP must be pointer typed, so must the old one -> BitCast
11111           return new BitCastInst(NewGEP, GEP.getType());
11112         }
11113       }
11114     }
11115   }
11116   
11117   /// See if we can simplify:
11118   ///   X = bitcast A* to B*
11119   ///   Y = gep X, <...constant indices...>
11120   /// into a gep of the original struct.  This is important for SROA and alias
11121   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11122   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11123     if (TD &&
11124         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11125       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11126       // a constant back from EmitGEPOffset.
11127       ConstantInt *OffsetV =
11128                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11129       int64_t Offset = OffsetV->getSExtValue();
11130       
11131       // If this GEP instruction doesn't move the pointer, just replace the GEP
11132       // with a bitcast of the real input to the dest type.
11133       if (Offset == 0) {
11134         // If the bitcast is of an allocation, and the allocation will be
11135         // converted to match the type of the cast, don't touch this.
11136         if (isa<AllocationInst>(BCI->getOperand(0)) ||
11137             isMalloc(BCI->getOperand(0))) {
11138           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11139           if (Instruction *I = visitBitCast(*BCI)) {
11140             if (I != BCI) {
11141               I->takeName(BCI);
11142               BCI->getParent()->getInstList().insert(BCI, I);
11143               ReplaceInstUsesWith(*BCI, I);
11144             }
11145             return &GEP;
11146           }
11147         }
11148         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11149       }
11150       
11151       // Otherwise, if the offset is non-zero, we need to find out if there is a
11152       // field at Offset in 'A's type.  If so, we can pull the cast through the
11153       // GEP.
11154       SmallVector<Value*, 8> NewIndices;
11155       const Type *InTy =
11156         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11157       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11158         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11159           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11160                                      NewIndices.end()) :
11161           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11162                              NewIndices.end());
11163         
11164         if (NGEP->getType() == GEP.getType())
11165           return ReplaceInstUsesWith(GEP, NGEP);
11166         NGEP->takeName(&GEP);
11167         return new BitCastInst(NGEP, GEP.getType());
11168       }
11169     }
11170   }    
11171     
11172   return 0;
11173 }
11174
11175 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11176   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11177   if (AI.isArrayAllocation()) {  // Check C != 1
11178     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11179       const Type *NewTy = 
11180         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11181       AllocationInst *New = 0;
11182
11183       // Create and insert the replacement instruction...
11184       if (isa<MallocInst>(AI))
11185         New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11186       else {
11187         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11188         New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11189       }
11190       New->setAlignment(AI.getAlignment());
11191
11192       // Scan to the end of the allocation instructions, to skip over a block of
11193       // allocas if possible...also skip interleaved debug info
11194       //
11195       BasicBlock::iterator It = New;
11196       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11197
11198       // Now that I is pointing to the first non-allocation-inst in the block,
11199       // insert our getelementptr instruction...
11200       //
11201       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11202       Value *Idx[2];
11203       Idx[0] = NullIdx;
11204       Idx[1] = NullIdx;
11205       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11206                                                    New->getName()+".sub", It);
11207
11208       // Now make everything use the getelementptr instead of the original
11209       // allocation.
11210       return ReplaceInstUsesWith(AI, V);
11211     } else if (isa<UndefValue>(AI.getArraySize())) {
11212       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11213     }
11214   }
11215
11216   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11217     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11218     // Note that we only do this for alloca's, because malloc should allocate
11219     // and return a unique pointer, even for a zero byte allocation.
11220     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11221       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11222
11223     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11224     if (AI.getAlignment() == 0)
11225       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11226   }
11227
11228   return 0;
11229 }
11230
11231 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11232   Value *Op = FI.getOperand(0);
11233
11234   // free undef -> unreachable.
11235   if (isa<UndefValue>(Op)) {
11236     // Insert a new store to null because we cannot modify the CFG here.
11237     new StoreInst(ConstantInt::getTrue(*Context),
11238            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11239     return EraseInstFromFunction(FI);
11240   }
11241   
11242   // If we have 'free null' delete the instruction.  This can happen in stl code
11243   // when lots of inlining happens.
11244   if (isa<ConstantPointerNull>(Op))
11245     return EraseInstFromFunction(FI);
11246   
11247   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11248   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11249     FI.setOperand(0, CI->getOperand(0));
11250     return &FI;
11251   }
11252   
11253   // Change free (gep X, 0,0,0,0) into free(X)
11254   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11255     if (GEPI->hasAllZeroIndices()) {
11256       Worklist.Add(GEPI);
11257       FI.setOperand(0, GEPI->getOperand(0));
11258       return &FI;
11259     }
11260   }
11261   
11262   // Change free(malloc) into nothing, if the malloc has a single use.
11263   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11264     if (MI->hasOneUse()) {
11265       EraseInstFromFunction(FI);
11266       return EraseInstFromFunction(*MI);
11267     }
11268   if (isMalloc(Op)) {
11269     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11270       if (Op->hasOneUse() && CI->hasOneUse()) {
11271         EraseInstFromFunction(FI);
11272         EraseInstFromFunction(*CI);
11273         return EraseInstFromFunction(*cast<Instruction>(Op));
11274       }
11275     } else {
11276       // Op is a call to malloc
11277       if (Op->hasOneUse()) {
11278         EraseInstFromFunction(FI);
11279         return EraseInstFromFunction(*cast<Instruction>(Op));
11280       }
11281     }
11282   }
11283
11284   return 0;
11285 }
11286
11287
11288 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11289 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11290                                         const TargetData *TD) {
11291   User *CI = cast<User>(LI.getOperand(0));
11292   Value *CastOp = CI->getOperand(0);
11293   LLVMContext *Context = IC.getContext();
11294
11295   if (TD) {
11296     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11297       // Instead of loading constant c string, use corresponding integer value
11298       // directly if string length is small enough.
11299       std::string Str;
11300       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11301         unsigned len = Str.length();
11302         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11303         unsigned numBits = Ty->getPrimitiveSizeInBits();
11304         // Replace LI with immediate integer store.
11305         if ((numBits >> 3) == len + 1) {
11306           APInt StrVal(numBits, 0);
11307           APInt SingleChar(numBits, 0);
11308           if (TD->isLittleEndian()) {
11309             for (signed i = len-1; i >= 0; i--) {
11310               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11311               StrVal = (StrVal << 8) | SingleChar;
11312             }
11313           } else {
11314             for (unsigned i = 0; i < len; i++) {
11315               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11316               StrVal = (StrVal << 8) | SingleChar;
11317             }
11318             // Append NULL at the end.
11319             SingleChar = 0;
11320             StrVal = (StrVal << 8) | SingleChar;
11321           }
11322           Value *NL = ConstantInt::get(*Context, StrVal);
11323           return IC.ReplaceInstUsesWith(LI, NL);
11324         }
11325       }
11326     }
11327   }
11328
11329   const PointerType *DestTy = cast<PointerType>(CI->getType());
11330   const Type *DestPTy = DestTy->getElementType();
11331   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11332
11333     // If the address spaces don't match, don't eliminate the cast.
11334     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11335       return 0;
11336
11337     const Type *SrcPTy = SrcTy->getElementType();
11338
11339     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11340          isa<VectorType>(DestPTy)) {
11341       // If the source is an array, the code below will not succeed.  Check to
11342       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11343       // constants.
11344       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11345         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11346           if (ASrcTy->getNumElements() != 0) {
11347             Value *Idxs[2];
11348             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11349             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11350             SrcTy = cast<PointerType>(CastOp->getType());
11351             SrcPTy = SrcTy->getElementType();
11352           }
11353
11354       if (IC.getTargetData() &&
11355           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11356             isa<VectorType>(SrcPTy)) &&
11357           // Do not allow turning this into a load of an integer, which is then
11358           // casted to a pointer, this pessimizes pointer analysis a lot.
11359           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11360           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11361                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11362
11363         // Okay, we are casting from one integer or pointer type to another of
11364         // the same size.  Instead of casting the pointer before the load, cast
11365         // the result of the loaded value.
11366         Value *NewLoad = 
11367           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11368         // Now cast the result of the load.
11369         return new BitCastInst(NewLoad, LI.getType());
11370       }
11371     }
11372   }
11373   return 0;
11374 }
11375
11376 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11377   Value *Op = LI.getOperand(0);
11378
11379   // Attempt to improve the alignment.
11380   if (TD) {
11381     unsigned KnownAlign =
11382       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11383     if (KnownAlign >
11384         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11385                                   LI.getAlignment()))
11386       LI.setAlignment(KnownAlign);
11387   }
11388
11389   // load (cast X) --> cast (load X) iff safe.
11390   if (isa<CastInst>(Op))
11391     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11392       return Res;
11393
11394   // None of the following transforms are legal for volatile loads.
11395   if (LI.isVolatile()) return 0;
11396   
11397   // Do really simple store-to-load forwarding and load CSE, to catch cases
11398   // where there are several consequtive memory accesses to the same location,
11399   // separated by a few arithmetic operations.
11400   BasicBlock::iterator BBI = &LI;
11401   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11402     return ReplaceInstUsesWith(LI, AvailableVal);
11403
11404   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11405     const Value *GEPI0 = GEPI->getOperand(0);
11406     // TODO: Consider a target hook for valid address spaces for this xform.
11407     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11408       // Insert a new store to null instruction before the load to indicate
11409       // that this code is not reachable.  We do this instead of inserting
11410       // an unreachable instruction directly because we cannot modify the
11411       // CFG.
11412       new StoreInst(UndefValue::get(LI.getType()),
11413                     Constant::getNullValue(Op->getType()), &LI);
11414       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11415     }
11416   } 
11417
11418   if (Constant *C = dyn_cast<Constant>(Op)) {
11419     // load null/undef -> undef
11420     // TODO: Consider a target hook for valid address spaces for this xform.
11421     if (isa<UndefValue>(C) ||
11422         (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11423       // Insert a new store to null instruction before the load to indicate that
11424       // this code is not reachable.  We do this instead of inserting an
11425       // unreachable instruction directly because we cannot modify the CFG.
11426       new StoreInst(UndefValue::get(LI.getType()),
11427                     Constant::getNullValue(Op->getType()), &LI);
11428       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11429     }
11430
11431     // Instcombine load (constant global) into the value loaded.
11432     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11433       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11434         return ReplaceInstUsesWith(LI, GV->getInitializer());
11435
11436     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11437     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11438       if (CE->getOpcode() == Instruction::GetElementPtr) {
11439         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11440           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11441             if (Constant *V = 
11442                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11443                                                       *Context))
11444               return ReplaceInstUsesWith(LI, V);
11445         if (CE->getOperand(0)->isNullValue()) {
11446           // Insert a new store to null instruction before the load to indicate
11447           // that this code is not reachable.  We do this instead of inserting
11448           // an unreachable instruction directly because we cannot modify the
11449           // CFG.
11450           new StoreInst(UndefValue::get(LI.getType()),
11451                         Constant::getNullValue(Op->getType()), &LI);
11452           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11453         }
11454
11455       } else if (CE->isCast()) {
11456         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11457           return Res;
11458       }
11459     }
11460   }
11461     
11462   // If this load comes from anywhere in a constant global, and if the global
11463   // is all undef or zero, we know what it loads.
11464   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11465     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11466       if (GV->getInitializer()->isNullValue())
11467         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11468       else if (isa<UndefValue>(GV->getInitializer()))
11469         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11470     }
11471   }
11472
11473   if (Op->hasOneUse()) {
11474     // Change select and PHI nodes to select values instead of addresses: this
11475     // helps alias analysis out a lot, allows many others simplifications, and
11476     // exposes redundancy in the code.
11477     //
11478     // Note that we cannot do the transformation unless we know that the
11479     // introduced loads cannot trap!  Something like this is valid as long as
11480     // the condition is always false: load (select bool %C, int* null, int* %G),
11481     // but it would not be valid if we transformed it to load from null
11482     // unconditionally.
11483     //
11484     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11485       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11486       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11487           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11488         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11489                                         SI->getOperand(1)->getName()+".val");
11490         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11491                                         SI->getOperand(2)->getName()+".val");
11492         return SelectInst::Create(SI->getCondition(), V1, V2);
11493       }
11494
11495       // load (select (cond, null, P)) -> load P
11496       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11497         if (C->isNullValue()) {
11498           LI.setOperand(0, SI->getOperand(2));
11499           return &LI;
11500         }
11501
11502       // load (select (cond, P, null)) -> load P
11503       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11504         if (C->isNullValue()) {
11505           LI.setOperand(0, SI->getOperand(1));
11506           return &LI;
11507         }
11508     }
11509   }
11510   return 0;
11511 }
11512
11513 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11514 /// when possible.  This makes it generally easy to do alias analysis and/or
11515 /// SROA/mem2reg of the memory object.
11516 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11517   User *CI = cast<User>(SI.getOperand(1));
11518   Value *CastOp = CI->getOperand(0);
11519
11520   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11521   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11522   if (SrcTy == 0) return 0;
11523   
11524   const Type *SrcPTy = SrcTy->getElementType();
11525
11526   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11527     return 0;
11528   
11529   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11530   /// to its first element.  This allows us to handle things like:
11531   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11532   /// on 32-bit hosts.
11533   SmallVector<Value*, 4> NewGEPIndices;
11534   
11535   // If the source is an array, the code below will not succeed.  Check to
11536   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11537   // constants.
11538   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11539     // Index through pointer.
11540     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11541     NewGEPIndices.push_back(Zero);
11542     
11543     while (1) {
11544       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11545         if (!STy->getNumElements()) /* Struct can be empty {} */
11546           break;
11547         NewGEPIndices.push_back(Zero);
11548         SrcPTy = STy->getElementType(0);
11549       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11550         NewGEPIndices.push_back(Zero);
11551         SrcPTy = ATy->getElementType();
11552       } else {
11553         break;
11554       }
11555     }
11556     
11557     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11558   }
11559
11560   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11561     return 0;
11562   
11563   // If the pointers point into different address spaces or if they point to
11564   // values with different sizes, we can't do the transformation.
11565   if (!IC.getTargetData() ||
11566       SrcTy->getAddressSpace() != 
11567         cast<PointerType>(CI->getType())->getAddressSpace() ||
11568       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11569       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11570     return 0;
11571
11572   // Okay, we are casting from one integer or pointer type to another of
11573   // the same size.  Instead of casting the pointer before 
11574   // the store, cast the value to be stored.
11575   Value *NewCast;
11576   Value *SIOp0 = SI.getOperand(0);
11577   Instruction::CastOps opcode = Instruction::BitCast;
11578   const Type* CastSrcTy = SIOp0->getType();
11579   const Type* CastDstTy = SrcPTy;
11580   if (isa<PointerType>(CastDstTy)) {
11581     if (CastSrcTy->isInteger())
11582       opcode = Instruction::IntToPtr;
11583   } else if (isa<IntegerType>(CastDstTy)) {
11584     if (isa<PointerType>(SIOp0->getType()))
11585       opcode = Instruction::PtrToInt;
11586   }
11587   
11588   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11589   // emit a GEP to index into its first field.
11590   if (!NewGEPIndices.empty())
11591     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11592                                            NewGEPIndices.end());
11593   
11594   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11595                                    SIOp0->getName()+".c");
11596   return new StoreInst(NewCast, CastOp);
11597 }
11598
11599 /// equivalentAddressValues - Test if A and B will obviously have the same
11600 /// value. This includes recognizing that %t0 and %t1 will have the same
11601 /// value in code like this:
11602 ///   %t0 = getelementptr \@a, 0, 3
11603 ///   store i32 0, i32* %t0
11604 ///   %t1 = getelementptr \@a, 0, 3
11605 ///   %t2 = load i32* %t1
11606 ///
11607 static bool equivalentAddressValues(Value *A, Value *B) {
11608   // Test if the values are trivially equivalent.
11609   if (A == B) return true;
11610   
11611   // Test if the values come form identical arithmetic instructions.
11612   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11613   // its only used to compare two uses within the same basic block, which
11614   // means that they'll always either have the same value or one of them
11615   // will have an undefined value.
11616   if (isa<BinaryOperator>(A) ||
11617       isa<CastInst>(A) ||
11618       isa<PHINode>(A) ||
11619       isa<GetElementPtrInst>(A))
11620     if (Instruction *BI = dyn_cast<Instruction>(B))
11621       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11622         return true;
11623   
11624   // Otherwise they may not be equivalent.
11625   return false;
11626 }
11627
11628 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11629 // return the llvm.dbg.declare.
11630 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11631   if (!V->hasNUses(2))
11632     return 0;
11633   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11634        UI != E; ++UI) {
11635     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11636       return DI;
11637     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11638       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11639         return DI;
11640       }
11641   }
11642   return 0;
11643 }
11644
11645 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11646   Value *Val = SI.getOperand(0);
11647   Value *Ptr = SI.getOperand(1);
11648
11649   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11650     EraseInstFromFunction(SI);
11651     ++NumCombined;
11652     return 0;
11653   }
11654   
11655   // If the RHS is an alloca with a single use, zapify the store, making the
11656   // alloca dead.
11657   // If the RHS is an alloca with a two uses, the other one being a 
11658   // llvm.dbg.declare, zapify the store and the declare, making the
11659   // alloca dead.  We must do this to prevent declare's from affecting
11660   // codegen.
11661   if (!SI.isVolatile()) {
11662     if (Ptr->hasOneUse()) {
11663       if (isa<AllocaInst>(Ptr)) {
11664         EraseInstFromFunction(SI);
11665         ++NumCombined;
11666         return 0;
11667       }
11668       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11669         if (isa<AllocaInst>(GEP->getOperand(0))) {
11670           if (GEP->getOperand(0)->hasOneUse()) {
11671             EraseInstFromFunction(SI);
11672             ++NumCombined;
11673             return 0;
11674           }
11675           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11676             EraseInstFromFunction(*DI);
11677             EraseInstFromFunction(SI);
11678             ++NumCombined;
11679             return 0;
11680           }
11681         }
11682       }
11683     }
11684     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11685       EraseInstFromFunction(*DI);
11686       EraseInstFromFunction(SI);
11687       ++NumCombined;
11688       return 0;
11689     }
11690   }
11691
11692   // Attempt to improve the alignment.
11693   if (TD) {
11694     unsigned KnownAlign =
11695       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11696     if (KnownAlign >
11697         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11698                                   SI.getAlignment()))
11699       SI.setAlignment(KnownAlign);
11700   }
11701
11702   // Do really simple DSE, to catch cases where there are several consecutive
11703   // stores to the same location, separated by a few arithmetic operations. This
11704   // situation often occurs with bitfield accesses.
11705   BasicBlock::iterator BBI = &SI;
11706   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11707        --ScanInsts) {
11708     --BBI;
11709     // Don't count debug info directives, lest they affect codegen,
11710     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11711     // It is necessary for correctness to skip those that feed into a
11712     // llvm.dbg.declare, as these are not present when debugging is off.
11713     if (isa<DbgInfoIntrinsic>(BBI) ||
11714         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11715       ScanInsts++;
11716       continue;
11717     }    
11718     
11719     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11720       // Prev store isn't volatile, and stores to the same location?
11721       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11722                                                           SI.getOperand(1))) {
11723         ++NumDeadStore;
11724         ++BBI;
11725         EraseInstFromFunction(*PrevSI);
11726         continue;
11727       }
11728       break;
11729     }
11730     
11731     // If this is a load, we have to stop.  However, if the loaded value is from
11732     // the pointer we're loading and is producing the pointer we're storing,
11733     // then *this* store is dead (X = load P; store X -> P).
11734     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11735       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11736           !SI.isVolatile()) {
11737         EraseInstFromFunction(SI);
11738         ++NumCombined;
11739         return 0;
11740       }
11741       // Otherwise, this is a load from some other location.  Stores before it
11742       // may not be dead.
11743       break;
11744     }
11745     
11746     // Don't skip over loads or things that can modify memory.
11747     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11748       break;
11749   }
11750   
11751   
11752   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11753
11754   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11755   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11756     if (!isa<UndefValue>(Val)) {
11757       SI.setOperand(0, UndefValue::get(Val->getType()));
11758       if (Instruction *U = dyn_cast<Instruction>(Val))
11759         Worklist.Add(U);  // Dropped a use.
11760       ++NumCombined;
11761     }
11762     return 0;  // Do not modify these!
11763   }
11764
11765   // store undef, Ptr -> noop
11766   if (isa<UndefValue>(Val)) {
11767     EraseInstFromFunction(SI);
11768     ++NumCombined;
11769     return 0;
11770   }
11771
11772   // If the pointer destination is a cast, see if we can fold the cast into the
11773   // source instead.
11774   if (isa<CastInst>(Ptr))
11775     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11776       return Res;
11777   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11778     if (CE->isCast())
11779       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11780         return Res;
11781
11782   
11783   // If this store is the last instruction in the basic block (possibly
11784   // excepting debug info instructions and the pointer bitcasts that feed
11785   // into them), and if the block ends with an unconditional branch, try
11786   // to move it to the successor block.
11787   BBI = &SI; 
11788   do {
11789     ++BBI;
11790   } while (isa<DbgInfoIntrinsic>(BBI) ||
11791            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11792   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11793     if (BI->isUnconditional())
11794       if (SimplifyStoreAtEndOfBlock(SI))
11795         return 0;  // xform done!
11796   
11797   return 0;
11798 }
11799
11800 /// SimplifyStoreAtEndOfBlock - Turn things like:
11801 ///   if () { *P = v1; } else { *P = v2 }
11802 /// into a phi node with a store in the successor.
11803 ///
11804 /// Simplify things like:
11805 ///   *P = v1; if () { *P = v2; }
11806 /// into a phi node with a store in the successor.
11807 ///
11808 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11809   BasicBlock *StoreBB = SI.getParent();
11810   
11811   // Check to see if the successor block has exactly two incoming edges.  If
11812   // so, see if the other predecessor contains a store to the same location.
11813   // if so, insert a PHI node (if needed) and move the stores down.
11814   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11815   
11816   // Determine whether Dest has exactly two predecessors and, if so, compute
11817   // the other predecessor.
11818   pred_iterator PI = pred_begin(DestBB);
11819   BasicBlock *OtherBB = 0;
11820   if (*PI != StoreBB)
11821     OtherBB = *PI;
11822   ++PI;
11823   if (PI == pred_end(DestBB))
11824     return false;
11825   
11826   if (*PI != StoreBB) {
11827     if (OtherBB)
11828       return false;
11829     OtherBB = *PI;
11830   }
11831   if (++PI != pred_end(DestBB))
11832     return false;
11833
11834   // Bail out if all the relevant blocks aren't distinct (this can happen,
11835   // for example, if SI is in an infinite loop)
11836   if (StoreBB == DestBB || OtherBB == DestBB)
11837     return false;
11838
11839   // Verify that the other block ends in a branch and is not otherwise empty.
11840   BasicBlock::iterator BBI = OtherBB->getTerminator();
11841   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11842   if (!OtherBr || BBI == OtherBB->begin())
11843     return false;
11844   
11845   // If the other block ends in an unconditional branch, check for the 'if then
11846   // else' case.  there is an instruction before the branch.
11847   StoreInst *OtherStore = 0;
11848   if (OtherBr->isUnconditional()) {
11849     --BBI;
11850     // Skip over debugging info.
11851     while (isa<DbgInfoIntrinsic>(BBI) ||
11852            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11853       if (BBI==OtherBB->begin())
11854         return false;
11855       --BBI;
11856     }
11857     // If this isn't a store, or isn't a store to the same location, bail out.
11858     OtherStore = dyn_cast<StoreInst>(BBI);
11859     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11860       return false;
11861   } else {
11862     // Otherwise, the other block ended with a conditional branch. If one of the
11863     // destinations is StoreBB, then we have the if/then case.
11864     if (OtherBr->getSuccessor(0) != StoreBB && 
11865         OtherBr->getSuccessor(1) != StoreBB)
11866       return false;
11867     
11868     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11869     // if/then triangle.  See if there is a store to the same ptr as SI that
11870     // lives in OtherBB.
11871     for (;; --BBI) {
11872       // Check to see if we find the matching store.
11873       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11874         if (OtherStore->getOperand(1) != SI.getOperand(1))
11875           return false;
11876         break;
11877       }
11878       // If we find something that may be using or overwriting the stored
11879       // value, or if we run out of instructions, we can't do the xform.
11880       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11881           BBI == OtherBB->begin())
11882         return false;
11883     }
11884     
11885     // In order to eliminate the store in OtherBr, we have to
11886     // make sure nothing reads or overwrites the stored value in
11887     // StoreBB.
11888     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11889       // FIXME: This should really be AA driven.
11890       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11891         return false;
11892     }
11893   }
11894   
11895   // Insert a PHI node now if we need it.
11896   Value *MergedVal = OtherStore->getOperand(0);
11897   if (MergedVal != SI.getOperand(0)) {
11898     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11899     PN->reserveOperandSpace(2);
11900     PN->addIncoming(SI.getOperand(0), SI.getParent());
11901     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11902     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11903   }
11904   
11905   // Advance to a place where it is safe to insert the new store and
11906   // insert it.
11907   BBI = DestBB->getFirstNonPHI();
11908   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11909                                     OtherStore->isVolatile()), *BBI);
11910   
11911   // Nuke the old stores.
11912   EraseInstFromFunction(SI);
11913   EraseInstFromFunction(*OtherStore);
11914   ++NumCombined;
11915   return true;
11916 }
11917
11918
11919 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11920   // Change br (not X), label True, label False to: br X, label False, True
11921   Value *X = 0;
11922   BasicBlock *TrueDest;
11923   BasicBlock *FalseDest;
11924   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11925       !isa<Constant>(X)) {
11926     // Swap Destinations and condition...
11927     BI.setCondition(X);
11928     BI.setSuccessor(0, FalseDest);
11929     BI.setSuccessor(1, TrueDest);
11930     return &BI;
11931   }
11932
11933   // Cannonicalize fcmp_one -> fcmp_oeq
11934   FCmpInst::Predicate FPred; Value *Y;
11935   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11936                              TrueDest, FalseDest)) &&
11937       BI.getCondition()->hasOneUse())
11938     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11939         FPred == FCmpInst::FCMP_OGE) {
11940       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11941       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11942       
11943       // Swap Destinations and condition.
11944       BI.setSuccessor(0, FalseDest);
11945       BI.setSuccessor(1, TrueDest);
11946       Worklist.Add(Cond);
11947       return &BI;
11948     }
11949
11950   // Cannonicalize icmp_ne -> icmp_eq
11951   ICmpInst::Predicate IPred;
11952   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11953                       TrueDest, FalseDest)) &&
11954       BI.getCondition()->hasOneUse())
11955     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11956         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11957         IPred == ICmpInst::ICMP_SGE) {
11958       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11959       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11960       // Swap Destinations and condition.
11961       BI.setSuccessor(0, FalseDest);
11962       BI.setSuccessor(1, TrueDest);
11963       Worklist.Add(Cond);
11964       return &BI;
11965     }
11966
11967   return 0;
11968 }
11969
11970 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11971   Value *Cond = SI.getCondition();
11972   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11973     if (I->getOpcode() == Instruction::Add)
11974       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11975         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11976         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11977           SI.setOperand(i,
11978                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11979                                                 AddRHS));
11980         SI.setOperand(0, I->getOperand(0));
11981         Worklist.Add(I);
11982         return &SI;
11983       }
11984   }
11985   return 0;
11986 }
11987
11988 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11989   Value *Agg = EV.getAggregateOperand();
11990
11991   if (!EV.hasIndices())
11992     return ReplaceInstUsesWith(EV, Agg);
11993
11994   if (Constant *C = dyn_cast<Constant>(Agg)) {
11995     if (isa<UndefValue>(C))
11996       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11997       
11998     if (isa<ConstantAggregateZero>(C))
11999       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12000
12001     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12002       // Extract the element indexed by the first index out of the constant
12003       Value *V = C->getOperand(*EV.idx_begin());
12004       if (EV.getNumIndices() > 1)
12005         // Extract the remaining indices out of the constant indexed by the
12006         // first index
12007         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12008       else
12009         return ReplaceInstUsesWith(EV, V);
12010     }
12011     return 0; // Can't handle other constants
12012   } 
12013   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12014     // We're extracting from an insertvalue instruction, compare the indices
12015     const unsigned *exti, *exte, *insi, *inse;
12016     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12017          exte = EV.idx_end(), inse = IV->idx_end();
12018          exti != exte && insi != inse;
12019          ++exti, ++insi) {
12020       if (*insi != *exti)
12021         // The insert and extract both reference distinctly different elements.
12022         // This means the extract is not influenced by the insert, and we can
12023         // replace the aggregate operand of the extract with the aggregate
12024         // operand of the insert. i.e., replace
12025         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12026         // %E = extractvalue { i32, { i32 } } %I, 0
12027         // with
12028         // %E = extractvalue { i32, { i32 } } %A, 0
12029         return ExtractValueInst::Create(IV->getAggregateOperand(),
12030                                         EV.idx_begin(), EV.idx_end());
12031     }
12032     if (exti == exte && insi == inse)
12033       // Both iterators are at the end: Index lists are identical. Replace
12034       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12035       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12036       // with "i32 42"
12037       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12038     if (exti == exte) {
12039       // The extract list is a prefix of the insert list. i.e. replace
12040       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12041       // %E = extractvalue { i32, { i32 } } %I, 1
12042       // with
12043       // %X = extractvalue { i32, { i32 } } %A, 1
12044       // %E = insertvalue { i32 } %X, i32 42, 0
12045       // by switching the order of the insert and extract (though the
12046       // insertvalue should be left in, since it may have other uses).
12047       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12048                                                  EV.idx_begin(), EV.idx_end());
12049       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12050                                      insi, inse);
12051     }
12052     if (insi == inse)
12053       // The insert list is a prefix of the extract list
12054       // We can simply remove the common indices from the extract and make it
12055       // operate on the inserted value instead of the insertvalue result.
12056       // i.e., replace
12057       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12058       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12059       // with
12060       // %E extractvalue { i32 } { i32 42 }, 0
12061       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12062                                       exti, exte);
12063   }
12064   // Can't simplify extracts from other values. Note that nested extracts are
12065   // already simplified implicitely by the above (extract ( extract (insert) )
12066   // will be translated into extract ( insert ( extract ) ) first and then just
12067   // the value inserted, if appropriate).
12068   return 0;
12069 }
12070
12071 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12072 /// is to leave as a vector operation.
12073 static bool CheapToScalarize(Value *V, bool isConstant) {
12074   if (isa<ConstantAggregateZero>(V)) 
12075     return true;
12076   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12077     if (isConstant) return true;
12078     // If all elts are the same, we can extract.
12079     Constant *Op0 = C->getOperand(0);
12080     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12081       if (C->getOperand(i) != Op0)
12082         return false;
12083     return true;
12084   }
12085   Instruction *I = dyn_cast<Instruction>(V);
12086   if (!I) return false;
12087   
12088   // Insert element gets simplified to the inserted element or is deleted if
12089   // this is constant idx extract element and its a constant idx insertelt.
12090   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12091       isa<ConstantInt>(I->getOperand(2)))
12092     return true;
12093   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12094     return true;
12095   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12096     if (BO->hasOneUse() &&
12097         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12098          CheapToScalarize(BO->getOperand(1), isConstant)))
12099       return true;
12100   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12101     if (CI->hasOneUse() &&
12102         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12103          CheapToScalarize(CI->getOperand(1), isConstant)))
12104       return true;
12105   
12106   return false;
12107 }
12108
12109 /// Read and decode a shufflevector mask.
12110 ///
12111 /// It turns undef elements into values that are larger than the number of
12112 /// elements in the input.
12113 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12114   unsigned NElts = SVI->getType()->getNumElements();
12115   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12116     return std::vector<unsigned>(NElts, 0);
12117   if (isa<UndefValue>(SVI->getOperand(2)))
12118     return std::vector<unsigned>(NElts, 2*NElts);
12119
12120   std::vector<unsigned> Result;
12121   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12122   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12123     if (isa<UndefValue>(*i))
12124       Result.push_back(NElts*2);  // undef -> 8
12125     else
12126       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12127   return Result;
12128 }
12129
12130 /// FindScalarElement - Given a vector and an element number, see if the scalar
12131 /// value is already around as a register, for example if it were inserted then
12132 /// extracted from the vector.
12133 static Value *FindScalarElement(Value *V, unsigned EltNo,
12134                                 LLVMContext *Context) {
12135   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12136   const VectorType *PTy = cast<VectorType>(V->getType());
12137   unsigned Width = PTy->getNumElements();
12138   if (EltNo >= Width)  // Out of range access.
12139     return UndefValue::get(PTy->getElementType());
12140   
12141   if (isa<UndefValue>(V))
12142     return UndefValue::get(PTy->getElementType());
12143   else if (isa<ConstantAggregateZero>(V))
12144     return Constant::getNullValue(PTy->getElementType());
12145   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12146     return CP->getOperand(EltNo);
12147   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12148     // If this is an insert to a variable element, we don't know what it is.
12149     if (!isa<ConstantInt>(III->getOperand(2))) 
12150       return 0;
12151     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12152     
12153     // If this is an insert to the element we are looking for, return the
12154     // inserted value.
12155     if (EltNo == IIElt) 
12156       return III->getOperand(1);
12157     
12158     // Otherwise, the insertelement doesn't modify the value, recurse on its
12159     // vector input.
12160     return FindScalarElement(III->getOperand(0), EltNo, Context);
12161   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12162     unsigned LHSWidth =
12163       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12164     unsigned InEl = getShuffleMask(SVI)[EltNo];
12165     if (InEl < LHSWidth)
12166       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12167     else if (InEl < LHSWidth*2)
12168       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12169     else
12170       return UndefValue::get(PTy->getElementType());
12171   }
12172   
12173   // Otherwise, we don't know.
12174   return 0;
12175 }
12176
12177 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12178   // If vector val is undef, replace extract with scalar undef.
12179   if (isa<UndefValue>(EI.getOperand(0)))
12180     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12181
12182   // If vector val is constant 0, replace extract with scalar 0.
12183   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12184     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12185   
12186   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12187     // If vector val is constant with all elements the same, replace EI with
12188     // that element. When the elements are not identical, we cannot replace yet
12189     // (we do that below, but only when the index is constant).
12190     Constant *op0 = C->getOperand(0);
12191     for (unsigned i = 1; i != C->getNumOperands(); ++i)
12192       if (C->getOperand(i) != op0) {
12193         op0 = 0; 
12194         break;
12195       }
12196     if (op0)
12197       return ReplaceInstUsesWith(EI, op0);
12198   }
12199   
12200   // If extracting a specified index from the vector, see if we can recursively
12201   // find a previously computed scalar that was inserted into the vector.
12202   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12203     unsigned IndexVal = IdxC->getZExtValue();
12204     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12205       
12206     // If this is extracting an invalid index, turn this into undef, to avoid
12207     // crashing the code below.
12208     if (IndexVal >= VectorWidth)
12209       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12210     
12211     // This instruction only demands the single element from the input vector.
12212     // If the input vector has a single use, simplify it based on this use
12213     // property.
12214     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12215       APInt UndefElts(VectorWidth, 0);
12216       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12217       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12218                                                 DemandedMask, UndefElts)) {
12219         EI.setOperand(0, V);
12220         return &EI;
12221       }
12222     }
12223     
12224     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12225       return ReplaceInstUsesWith(EI, Elt);
12226     
12227     // If the this extractelement is directly using a bitcast from a vector of
12228     // the same number of elements, see if we can find the source element from
12229     // it.  In this case, we will end up needing to bitcast the scalars.
12230     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12231       if (const VectorType *VT = 
12232               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12233         if (VT->getNumElements() == VectorWidth)
12234           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12235                                              IndexVal, Context))
12236             return new BitCastInst(Elt, EI.getType());
12237     }
12238   }
12239   
12240   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12241     // Push extractelement into predecessor operation if legal and
12242     // profitable to do so
12243     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12244       if (I->hasOneUse() &&
12245           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12246         Value *newEI0 =
12247           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12248                                         EI.getName()+".lhs");
12249         Value *newEI1 =
12250           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12251                                         EI.getName()+".rhs");
12252         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12253       }
12254     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12255       // Extracting the inserted element?
12256       if (IE->getOperand(2) == EI.getOperand(1))
12257         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12258       // If the inserted and extracted elements are constants, they must not
12259       // be the same value, extract from the pre-inserted value instead.
12260       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12261         Worklist.AddValue(EI.getOperand(0));
12262         EI.setOperand(0, IE->getOperand(0));
12263         return &EI;
12264       }
12265     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12266       // If this is extracting an element from a shufflevector, figure out where
12267       // it came from and extract from the appropriate input element instead.
12268       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12269         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12270         Value *Src;
12271         unsigned LHSWidth =
12272           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12273
12274         if (SrcIdx < LHSWidth)
12275           Src = SVI->getOperand(0);
12276         else if (SrcIdx < LHSWidth*2) {
12277           SrcIdx -= LHSWidth;
12278           Src = SVI->getOperand(1);
12279         } else {
12280           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12281         }
12282         return ExtractElementInst::Create(Src,
12283                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12284                                           false));
12285       }
12286     }
12287     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12288   }
12289   return 0;
12290 }
12291
12292 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12293 /// elements from either LHS or RHS, return the shuffle mask and true. 
12294 /// Otherwise, return false.
12295 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12296                                          std::vector<Constant*> &Mask,
12297                                          LLVMContext *Context) {
12298   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12299          "Invalid CollectSingleShuffleElements");
12300   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12301
12302   if (isa<UndefValue>(V)) {
12303     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12304     return true;
12305   } else if (V == LHS) {
12306     for (unsigned i = 0; i != NumElts; ++i)
12307       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12308     return true;
12309   } else if (V == RHS) {
12310     for (unsigned i = 0; i != NumElts; ++i)
12311       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12312     return true;
12313   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12314     // If this is an insert of an extract from some other vector, include it.
12315     Value *VecOp    = IEI->getOperand(0);
12316     Value *ScalarOp = IEI->getOperand(1);
12317     Value *IdxOp    = IEI->getOperand(2);
12318     
12319     if (!isa<ConstantInt>(IdxOp))
12320       return false;
12321     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12322     
12323     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12324       // Okay, we can handle this if the vector we are insertinting into is
12325       // transitively ok.
12326       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12327         // If so, update the mask to reflect the inserted undef.
12328         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12329         return true;
12330       }      
12331     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12332       if (isa<ConstantInt>(EI->getOperand(1)) &&
12333           EI->getOperand(0)->getType() == V->getType()) {
12334         unsigned ExtractedIdx =
12335           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12336         
12337         // This must be extracting from either LHS or RHS.
12338         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12339           // Okay, we can handle this if the vector we are insertinting into is
12340           // transitively ok.
12341           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12342             // If so, update the mask to reflect the inserted value.
12343             if (EI->getOperand(0) == LHS) {
12344               Mask[InsertedIdx % NumElts] = 
12345                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12346             } else {
12347               assert(EI->getOperand(0) == RHS);
12348               Mask[InsertedIdx % NumElts] = 
12349                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12350               
12351             }
12352             return true;
12353           }
12354         }
12355       }
12356     }
12357   }
12358   // TODO: Handle shufflevector here!
12359   
12360   return false;
12361 }
12362
12363 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12364 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12365 /// that computes V and the LHS value of the shuffle.
12366 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12367                                      Value *&RHS, LLVMContext *Context) {
12368   assert(isa<VectorType>(V->getType()) && 
12369          (RHS == 0 || V->getType() == RHS->getType()) &&
12370          "Invalid shuffle!");
12371   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12372
12373   if (isa<UndefValue>(V)) {
12374     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12375     return V;
12376   } else if (isa<ConstantAggregateZero>(V)) {
12377     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12378     return V;
12379   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12380     // If this is an insert of an extract from some other vector, include it.
12381     Value *VecOp    = IEI->getOperand(0);
12382     Value *ScalarOp = IEI->getOperand(1);
12383     Value *IdxOp    = IEI->getOperand(2);
12384     
12385     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12386       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12387           EI->getOperand(0)->getType() == V->getType()) {
12388         unsigned ExtractedIdx =
12389           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12390         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12391         
12392         // Either the extracted from or inserted into vector must be RHSVec,
12393         // otherwise we'd end up with a shuffle of three inputs.
12394         if (EI->getOperand(0) == RHS || RHS == 0) {
12395           RHS = EI->getOperand(0);
12396           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12397           Mask[InsertedIdx % NumElts] = 
12398             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12399           return V;
12400         }
12401         
12402         if (VecOp == RHS) {
12403           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12404                                             RHS, Context);
12405           // Everything but the extracted element is replaced with the RHS.
12406           for (unsigned i = 0; i != NumElts; ++i) {
12407             if (i != InsertedIdx)
12408               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12409           }
12410           return V;
12411         }
12412         
12413         // If this insertelement is a chain that comes from exactly these two
12414         // vectors, return the vector and the effective shuffle.
12415         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12416                                          Context))
12417           return EI->getOperand(0);
12418         
12419       }
12420     }
12421   }
12422   // TODO: Handle shufflevector here!
12423   
12424   // Otherwise, can't do anything fancy.  Return an identity vector.
12425   for (unsigned i = 0; i != NumElts; ++i)
12426     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12427   return V;
12428 }
12429
12430 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12431   Value *VecOp    = IE.getOperand(0);
12432   Value *ScalarOp = IE.getOperand(1);
12433   Value *IdxOp    = IE.getOperand(2);
12434   
12435   // Inserting an undef or into an undefined place, remove this.
12436   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12437     ReplaceInstUsesWith(IE, VecOp);
12438   
12439   // If the inserted element was extracted from some other vector, and if the 
12440   // indexes are constant, try to turn this into a shufflevector operation.
12441   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12442     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12443         EI->getOperand(0)->getType() == IE.getType()) {
12444       unsigned NumVectorElts = IE.getType()->getNumElements();
12445       unsigned ExtractedIdx =
12446         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12447       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12448       
12449       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12450         return ReplaceInstUsesWith(IE, VecOp);
12451       
12452       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12453         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12454       
12455       // If we are extracting a value from a vector, then inserting it right
12456       // back into the same place, just use the input vector.
12457       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12458         return ReplaceInstUsesWith(IE, VecOp);      
12459       
12460       // We could theoretically do this for ANY input.  However, doing so could
12461       // turn chains of insertelement instructions into a chain of shufflevector
12462       // instructions, and right now we do not merge shufflevectors.  As such,
12463       // only do this in a situation where it is clear that there is benefit.
12464       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12465         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12466         // the values of VecOp, except then one read from EIOp0.
12467         // Build a new shuffle mask.
12468         std::vector<Constant*> Mask;
12469         if (isa<UndefValue>(VecOp))
12470           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12471         else {
12472           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12473           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12474                                                        NumVectorElts));
12475         } 
12476         Mask[InsertedIdx] = 
12477                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12478         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12479                                      ConstantVector::get(Mask));
12480       }
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 void AddReachableCodeToWorklist(BasicBlock *BB, 
12668                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12669                                        InstCombiner &IC,
12670                                        const TargetData *TD) {
12671   SmallVector<BasicBlock*, 256> Worklist;
12672   Worklist.push_back(BB);
12673
12674   while (!Worklist.empty()) {
12675     BB = Worklist.back();
12676     Worklist.pop_back();
12677     
12678     // We have now visited this block!  If we've already been here, ignore it.
12679     if (!Visited.insert(BB)) continue;
12680
12681     DbgInfoIntrinsic *DBI_Prev = NULL;
12682     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12683       Instruction *Inst = BBI++;
12684       
12685       // DCE instruction if trivially dead.
12686       if (isInstructionTriviallyDead(Inst)) {
12687         ++NumDeadInst;
12688         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12689         Inst->eraseFromParent();
12690         continue;
12691       }
12692       
12693       // ConstantProp instruction if trivially constant.
12694       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12695         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12696                      << *Inst << '\n');
12697         Inst->replaceAllUsesWith(C);
12698         ++NumConstProp;
12699         Inst->eraseFromParent();
12700         continue;
12701       }
12702      
12703       // If there are two consecutive llvm.dbg.stoppoint calls then
12704       // it is likely that the optimizer deleted code in between these
12705       // two intrinsics. 
12706       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12707       if (DBI_Next) {
12708         if (DBI_Prev
12709             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12710             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12711           IC.Worklist.Remove(DBI_Prev);
12712           DBI_Prev->eraseFromParent();
12713         }
12714         DBI_Prev = DBI_Next;
12715       } else {
12716         DBI_Prev = 0;
12717       }
12718
12719       IC.Worklist.Add(Inst);
12720     }
12721
12722     // Recursively visit successors.  If this is a branch or switch on a
12723     // constant, only visit the reachable successor.
12724     TerminatorInst *TI = BB->getTerminator();
12725     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12726       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12727         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12728         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12729         Worklist.push_back(ReachableBB);
12730         continue;
12731       }
12732     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12733       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12734         // See if this is an explicit destination.
12735         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12736           if (SI->getCaseValue(i) == Cond) {
12737             BasicBlock *ReachableBB = SI->getSuccessor(i);
12738             Worklist.push_back(ReachableBB);
12739             continue;
12740           }
12741         
12742         // Otherwise it is the default destination.
12743         Worklist.push_back(SI->getSuccessor(0));
12744         continue;
12745       }
12746     }
12747     
12748     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12749       Worklist.push_back(TI->getSuccessor(i));
12750   }
12751 }
12752
12753 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12754   MadeIRChange = false;
12755   TD = getAnalysisIfAvailable<TargetData>();
12756   
12757   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12758         << F.getNameStr() << "\n");
12759
12760   {
12761     // Do a depth-first traversal of the function, populate the worklist with
12762     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12763     // track of which blocks we visit.
12764     SmallPtrSet<BasicBlock*, 64> Visited;
12765     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12766
12767     // Do a quick scan over the function.  If we find any blocks that are
12768     // unreachable, remove any instructions inside of them.  This prevents
12769     // the instcombine code from having to deal with some bad special cases.
12770     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12771       if (!Visited.count(BB)) {
12772         Instruction *Term = BB->getTerminator();
12773         while (Term != BB->begin()) {   // Remove instrs bottom-up
12774           BasicBlock::iterator I = Term; --I;
12775
12776           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12777           // A debug intrinsic shouldn't force another iteration if we weren't
12778           // going to do one without it.
12779           if (!isa<DbgInfoIntrinsic>(I)) {
12780             ++NumDeadInst;
12781             MadeIRChange = true;
12782           }
12783           if (!I->use_empty())
12784             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12785           I->eraseFromParent();
12786         }
12787       }
12788   }
12789
12790   while (!Worklist.isEmpty()) {
12791     Instruction *I = Worklist.RemoveOne();
12792     if (I == 0) continue;  // skip null values.
12793
12794     // Check to see if we can DCE the instruction.
12795     if (isInstructionTriviallyDead(I)) {
12796       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12797       EraseInstFromFunction(*I);
12798       ++NumDeadInst;
12799       MadeIRChange = true;
12800       continue;
12801     }
12802
12803     // Instruction isn't dead, see if we can constant propagate it.
12804     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12805       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12806
12807       // Add operands to the worklist.
12808       ReplaceInstUsesWith(*I, C);
12809       ++NumConstProp;
12810       EraseInstFromFunction(*I);
12811       MadeIRChange = true;
12812       continue;
12813     }
12814
12815     if (TD) {
12816       // See if we can constant fold its operands.
12817       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12818         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12819           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12820                                   F.getContext(), TD))
12821             if (NewC != CE) {
12822               i->set(NewC);
12823               MadeIRChange = true;
12824             }
12825     }
12826
12827     // See if we can trivially sink this instruction to a successor basic block.
12828     if (I->hasOneUse()) {
12829       BasicBlock *BB = I->getParent();
12830       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12831       if (UserParent != BB) {
12832         bool UserIsSuccessor = false;
12833         // See if the user is one of our successors.
12834         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12835           if (*SI == UserParent) {
12836             UserIsSuccessor = true;
12837             break;
12838           }
12839
12840         // If the user is one of our immediate successors, and if that successor
12841         // only has us as a predecessors (we'd have to split the critical edge
12842         // otherwise), we can keep going.
12843         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12844             next(pred_begin(UserParent)) == pred_end(UserParent))
12845           // Okay, the CFG is simple enough, try to sink this instruction.
12846           MadeIRChange |= TryToSinkInstruction(I, UserParent);
12847       }
12848     }
12849
12850     // Now that we have an instruction, try combining it to simplify it.
12851     Builder->SetInsertPoint(I->getParent(), I);
12852     
12853 #ifndef NDEBUG
12854     std::string OrigI;
12855 #endif
12856     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12857     
12858     if (Instruction *Result = visit(*I)) {
12859       ++NumCombined;
12860       // Should we replace the old instruction with a new one?
12861       if (Result != I) {
12862         DEBUG(errs() << "IC: Old = " << *I << '\n'
12863                      << "    New = " << *Result << '\n');
12864
12865         // Everything uses the new instruction now.
12866         I->replaceAllUsesWith(Result);
12867
12868         // Push the new instruction and any users onto the worklist.
12869         Worklist.Add(Result);
12870         Worklist.AddUsersToWorkList(*Result);
12871
12872         // Move the name to the new instruction first.
12873         Result->takeName(I);
12874
12875         // Insert the new instruction into the basic block...
12876         BasicBlock *InstParent = I->getParent();
12877         BasicBlock::iterator InsertPos = I;
12878
12879         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12880           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12881             ++InsertPos;
12882
12883         InstParent->getInstList().insert(InsertPos, Result);
12884
12885         EraseInstFromFunction(*I);
12886       } else {
12887 #ifndef NDEBUG
12888         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12889                      << "    New = " << *I << '\n');
12890 #endif
12891
12892         // If the instruction was modified, it's possible that it is now dead.
12893         // if so, remove it.
12894         if (isInstructionTriviallyDead(I)) {
12895           EraseInstFromFunction(*I);
12896         } else {
12897           Worklist.Add(I);
12898           Worklist.AddUsersToWorkList(*I);
12899         }
12900       }
12901       MadeIRChange = true;
12902     }
12903   }
12904
12905   Worklist.Zap();
12906   return MadeIRChange;
12907 }
12908
12909
12910 bool InstCombiner::runOnFunction(Function &F) {
12911   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12912   Context = &F.getContext();
12913   
12914   
12915   /// Builder - This is an IRBuilder that automatically inserts new
12916   /// instructions into the worklist when they are created.
12917   IRBuilder<true, ConstantFolder, InstCombineIRInserter> 
12918     TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12919                InstCombineIRInserter(Worklist));
12920   Builder = &TheBuilder;
12921   
12922   bool EverMadeChange = false;
12923
12924   // Iterate while there is work to do.
12925   unsigned Iteration = 0;
12926   while (DoOneIteration(F, Iteration++))
12927     EverMadeChange = true;
12928   
12929   Builder = 0;
12930   return EverMadeChange;
12931 }
12932
12933 FunctionPass *llvm::createInstructionCombiningPass() {
12934   return new InstCombiner();
12935 }