pull my debug hooks out, I'm done with this xform for now.
[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/InstructionSimplify.h"
46 #include "llvm/Analysis/MemoryBuiltins.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Target/TargetData.h"
49 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
50 #include "llvm/Transforms/Utils/Local.h"
51 #include "llvm/Support/CallSite.h"
52 #include "llvm/Support/ConstantRange.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/GetElementPtrTypeIterator.h"
56 #include "llvm/Support/InstVisitor.h"
57 #include "llvm/Support/IRBuilder.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/PatternMatch.h"
60 #include "llvm/Support/TargetFolder.h"
61 #include "llvm/Support/raw_ostream.h"
62 #include "llvm/ADT/DenseMap.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/ADT/SmallPtrSet.h"
65 #include "llvm/ADT/Statistic.h"
66 #include "llvm/ADT/STLExtras.h"
67 #include <algorithm>
68 #include <climits>
69 using namespace llvm;
70 using namespace llvm::PatternMatch;
71
72 STATISTIC(NumCombined , "Number of insts combined");
73 STATISTIC(NumConstProp, "Number of constant folds");
74 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76 STATISTIC(NumSunkInst , "Number of instructions sunk");
77
78 /// SelectPatternFlavor - We can match a variety of different patterns for
79 /// select operations.
80 enum SelectPatternFlavor {
81   SPF_UNKNOWN = 0,
82   SPF_SMIN, SPF_UMIN,
83   SPF_SMAX, SPF_UMAX
84   //SPF_ABS - TODO.
85 };
86
87 namespace {
88   /// InstCombineWorklist - This is the worklist management logic for
89   /// InstCombine.
90   class InstCombineWorklist {
91     SmallVector<Instruction*, 256> Worklist;
92     DenseMap<Instruction*, unsigned> WorklistMap;
93     
94     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
95     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
96   public:
97     InstCombineWorklist() {}
98     
99     bool isEmpty() const { return Worklist.empty(); }
100     
101     /// Add - Add the specified instruction to the worklist if it isn't already
102     /// in it.
103     void Add(Instruction *I) {
104       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
105         DEBUG(errs() << "IC: ADD: " << *I << '\n');
106         Worklist.push_back(I);
107       }
108     }
109     
110     void AddValue(Value *V) {
111       if (Instruction *I = dyn_cast<Instruction>(V))
112         Add(I);
113     }
114     
115     /// AddInitialGroup - Add the specified batch of stuff in reverse order.
116     /// which should only be done when the worklist is empty and when the group
117     /// has no duplicates.
118     void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
119       assert(Worklist.empty() && "Worklist must be empty to add initial group");
120       Worklist.reserve(NumEntries+16);
121       DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
122       for (; NumEntries; --NumEntries) {
123         Instruction *I = List[NumEntries-1];
124         WorklistMap.insert(std::make_pair(I, Worklist.size()));
125         Worklist.push_back(I);
126       }
127     }
128     
129     // Remove - remove I from the worklist if it exists.
130     void Remove(Instruction *I) {
131       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
132       if (It == WorklistMap.end()) return; // Not in worklist.
133       
134       // Don't bother moving everything down, just null out the slot.
135       Worklist[It->second] = 0;
136       
137       WorklistMap.erase(It);
138     }
139     
140     Instruction *RemoveOne() {
141       Instruction *I = Worklist.back();
142       Worklist.pop_back();
143       WorklistMap.erase(I);
144       return I;
145     }
146
147     /// AddUsersToWorkList - When an instruction is simplified, add all users of
148     /// the instruction to the work lists because they might get more simplified
149     /// now.
150     ///
151     void AddUsersToWorkList(Instruction &I) {
152       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
153            UI != UE; ++UI)
154         Add(cast<Instruction>(*UI));
155     }
156     
157     
158     /// Zap - check that the worklist is empty and nuke the backing store for
159     /// the map if it is large.
160     void Zap() {
161       assert(WorklistMap.empty() && "Worklist empty, but map not?");
162       
163       // Do an explicit clear, this shrinks the map if needed.
164       WorklistMap.clear();
165     }
166   };
167 } // end anonymous namespace.
168
169
170 namespace {
171   /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
172   /// just like the normal insertion helper, but also adds any new instructions
173   /// to the instcombine worklist.
174   class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
175     InstCombineWorklist &Worklist;
176   public:
177     InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
178     
179     void InsertHelper(Instruction *I, const Twine &Name,
180                       BasicBlock *BB, BasicBlock::iterator InsertPt) const {
181       IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
182       Worklist.Add(I);
183     }
184   };
185 } // end anonymous namespace
186
187
188 namespace {
189   class InstCombiner : public FunctionPass,
190                        public InstVisitor<InstCombiner, Instruction*> {
191     TargetData *TD;
192     bool MustPreserveLCSSA;
193     bool MadeIRChange;
194   public:
195     /// Worklist - All of the instructions that need to be simplified.
196     InstCombineWorklist Worklist;
197
198     /// Builder - This is an IRBuilder that automatically inserts new
199     /// instructions into the worklist when they are created.
200     typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
201     BuilderTy *Builder;
202         
203     static char ID; // Pass identification, replacement for typeid
204     InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
205
206     LLVMContext *Context;
207     LLVMContext *getContext() const { return Context; }
208
209   public:
210     virtual bool runOnFunction(Function &F);
211     
212     bool DoOneIteration(Function &F, unsigned ItNum);
213
214     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
215       AU.addPreservedID(LCSSAID);
216       AU.setPreservesCFG();
217     }
218
219     TargetData *getTargetData() const { return TD; }
220
221     // Visitation implementation - Implement instruction combining for different
222     // instruction types.  The semantics are as follows:
223     // Return Value:
224     //    null        - No change was made
225     //     I          - Change was made, I is still valid, I may be dead though
226     //   otherwise    - Change was made, replace I with returned instruction
227     //
228     Instruction *visitAdd(BinaryOperator &I);
229     Instruction *visitFAdd(BinaryOperator &I);
230     Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
231     Instruction *visitSub(BinaryOperator &I);
232     Instruction *visitFSub(BinaryOperator &I);
233     Instruction *visitMul(BinaryOperator &I);
234     Instruction *visitFMul(BinaryOperator &I);
235     Instruction *visitURem(BinaryOperator &I);
236     Instruction *visitSRem(BinaryOperator &I);
237     Instruction *visitFRem(BinaryOperator &I);
238     bool SimplifyDivRemOfSelect(BinaryOperator &I);
239     Instruction *commonRemTransforms(BinaryOperator &I);
240     Instruction *commonIRemTransforms(BinaryOperator &I);
241     Instruction *commonDivTransforms(BinaryOperator &I);
242     Instruction *commonIDivTransforms(BinaryOperator &I);
243     Instruction *visitUDiv(BinaryOperator &I);
244     Instruction *visitSDiv(BinaryOperator &I);
245     Instruction *visitFDiv(BinaryOperator &I);
246     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
247     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
248     Instruction *visitAnd(BinaryOperator &I);
249     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
250     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
251     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
252                                      Value *A, Value *B, Value *C);
253     Instruction *visitOr (BinaryOperator &I);
254     Instruction *visitXor(BinaryOperator &I);
255     Instruction *visitShl(BinaryOperator &I);
256     Instruction *visitAShr(BinaryOperator &I);
257     Instruction *visitLShr(BinaryOperator &I);
258     Instruction *commonShiftTransforms(BinaryOperator &I);
259     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
260                                       Constant *RHSC);
261     Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
262                                               GlobalVariable *GV, CmpInst &ICI,
263                                               ConstantInt *AndCst = 0);
264     Instruction *visitFCmpInst(FCmpInst &I);
265     Instruction *visitICmpInst(ICmpInst &I);
266     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
267     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
268                                                 Instruction *LHS,
269                                                 ConstantInt *RHS);
270     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
271                                 ConstantInt *DivRHS);
272     Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
273                                   ICmpInst::Predicate Pred, Value *TheAdd);
274     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
275                              ICmpInst::Predicate Cond, Instruction &I);
276     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
277                                      BinaryOperator &I);
278     Instruction *commonCastTransforms(CastInst &CI);
279     Instruction *commonIntCastTransforms(CastInst &CI);
280     Instruction *commonPointerCastTransforms(CastInst &CI);
281     Instruction *visitTrunc(TruncInst &CI);
282     Instruction *visitZExt(ZExtInst &CI);
283     Instruction *visitSExt(SExtInst &CI);
284     Instruction *visitFPTrunc(FPTruncInst &CI);
285     Instruction *visitFPExt(CastInst &CI);
286     Instruction *visitFPToUI(FPToUIInst &FI);
287     Instruction *visitFPToSI(FPToSIInst &FI);
288     Instruction *visitUIToFP(CastInst &CI);
289     Instruction *visitSIToFP(CastInst &CI);
290     Instruction *visitPtrToInt(PtrToIntInst &CI);
291     Instruction *visitIntToPtr(IntToPtrInst &CI);
292     Instruction *visitBitCast(BitCastInst &CI);
293     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
294                                 Instruction *FI);
295     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
296     Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
297                               Value *A, Value *B, Instruction &Outer,
298                               SelectPatternFlavor SPF2, Value *C);
299     Instruction *visitSelectInst(SelectInst &SI);
300     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
301     Instruction *visitCallInst(CallInst &CI);
302     Instruction *visitInvokeInst(InvokeInst &II);
303
304     Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
305     Instruction *visitPHINode(PHINode &PN);
306     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
307     Instruction *visitAllocaInst(AllocaInst &AI);
308     Instruction *visitFree(Instruction &FI);
309     Instruction *visitLoadInst(LoadInst &LI);
310     Instruction *visitStoreInst(StoreInst &SI);
311     Instruction *visitBranchInst(BranchInst &BI);
312     Instruction *visitSwitchInst(SwitchInst &SI);
313     Instruction *visitInsertElementInst(InsertElementInst &IE);
314     Instruction *visitExtractElementInst(ExtractElementInst &EI);
315     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
316     Instruction *visitExtractValueInst(ExtractValueInst &EV);
317
318     // visitInstruction - Specify what to return for unhandled instructions...
319     Instruction *visitInstruction(Instruction &I) { return 0; }
320
321   private:
322     Instruction *visitCallSite(CallSite CS);
323     bool transformConstExprCastCall(CallSite CS);
324     Instruction *transformCallThroughTrampoline(CallSite CS);
325     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
326                                    bool DoXform = true);
327     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
328     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
329
330
331   public:
332     // InsertNewInstBefore - insert an instruction New before instruction Old
333     // in the program.  Add the new instruction to the worklist.
334     //
335     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
336       assert(New && New->getParent() == 0 &&
337              "New instruction already inserted into a basic block!");
338       BasicBlock *BB = Old.getParent();
339       BB->getInstList().insert(&Old, New);  // Insert inst
340       Worklist.Add(New);
341       return New;
342     }
343         
344     // ReplaceInstUsesWith - This method is to be used when an instruction is
345     // found to be dead, replacable with another preexisting expression.  Here
346     // we add all uses of I to the worklist, replace all uses of I with the new
347     // value, then return I, so that the inst combiner will know that I was
348     // modified.
349     //
350     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
351       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
352       
353       // If we are replacing the instruction with itself, this must be in a
354       // segment of unreachable code, so just clobber the instruction.
355       if (&I == V) 
356         V = UndefValue::get(I.getType());
357         
358       I.replaceAllUsesWith(V);
359       return &I;
360     }
361
362     // EraseInstFromFunction - When dealing with an instruction that has side
363     // effects or produces a void value, we can't rely on DCE to delete the
364     // instruction.  Instead, visit methods should return the value returned by
365     // this function.
366     Instruction *EraseInstFromFunction(Instruction &I) {
367       DEBUG(errs() << "IC: ERASE " << I << '\n');
368
369       assert(I.use_empty() && "Cannot erase instruction that is used!");
370       // Make sure that we reprocess all operands now that we reduced their
371       // use counts.
372       if (I.getNumOperands() < 8) {
373         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
374           if (Instruction *Op = dyn_cast<Instruction>(*i))
375             Worklist.Add(Op);
376       }
377       Worklist.Remove(&I);
378       I.eraseFromParent();
379       MadeIRChange = true;
380       return 0;  // Don't do anything with FI
381     }
382         
383     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
384                            APInt &KnownOne, unsigned Depth = 0) const {
385       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
386     }
387     
388     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
389                            unsigned Depth = 0) const {
390       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
391     }
392     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
393       return llvm::ComputeNumSignBits(Op, TD, Depth);
394     }
395
396   private:
397
398     /// SimplifyCommutative - This performs a few simplifications for 
399     /// commutative operators.
400     bool SimplifyCommutative(BinaryOperator &I);
401
402     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
403     /// based on the demanded bits.
404     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
405                                    APInt& KnownZero, APInt& KnownOne,
406                                    unsigned Depth);
407     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
408                               APInt& KnownZero, APInt& KnownOne,
409                               unsigned Depth=0);
410         
411     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
412     /// SimplifyDemandedBits knows about.  See if the instruction has any
413     /// properties that allow us to simplify its operands.
414     bool SimplifyDemandedInstructionBits(Instruction &Inst);
415         
416     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
417                                       APInt& UndefElts, unsigned Depth = 0);
418       
419     // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
420     // which has a PHI node as operand #0, see if we can fold the instruction
421     // into the PHI (which is only possible if all operands to the PHI are
422     // constants).
423     //
424     // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
425     // that would normally be unprofitable because they strongly encourage jump
426     // threading.
427     Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
428
429     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
430     // operator and they all are only used by the PHI, PHI together their
431     // inputs, and do the operation once, to the result of the PHI.
432     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
433     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
434     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
435     Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
436
437     
438     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
439                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
440     
441     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
442                               bool isSub, Instruction &I);
443     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
444                                  bool isSigned, bool Inside, Instruction &IB);
445     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
446     Instruction *MatchBSwap(BinaryOperator &I);
447     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
448     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
449     Instruction *SimplifyMemSet(MemSetInst *MI);
450
451
452     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
453
454     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
455                                     unsigned CastOpc, int &NumCastsRemoved);
456     unsigned GetOrEnforceKnownAlignment(Value *V,
457                                         unsigned PrefAlign = 0);
458
459   };
460 } // end anonymous namespace
461
462 char InstCombiner::ID = 0;
463 static RegisterPass<InstCombiner>
464 X("instcombine", "Combine redundant instructions");
465
466 // getComplexity:  Assign a complexity or rank value to LLVM Values...
467 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
468 static unsigned getComplexity(Value *V) {
469   if (isa<Instruction>(V)) {
470     if (BinaryOperator::isNeg(V) ||
471         BinaryOperator::isFNeg(V) ||
472         BinaryOperator::isNot(V))
473       return 3;
474     return 4;
475   }
476   if (isa<Argument>(V)) return 3;
477   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
478 }
479
480 // isOnlyUse - Return true if this instruction will be deleted if we stop using
481 // it.
482 static bool isOnlyUse(Value *V) {
483   return V->hasOneUse() || isa<Constant>(V);
484 }
485
486 // getPromotedType - Return the specified type promoted as it would be to pass
487 // though a va_arg area...
488 static const Type *getPromotedType(const Type *Ty) {
489   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
490     if (ITy->getBitWidth() < 32)
491       return Type::getInt32Ty(Ty->getContext());
492   }
493   return Ty;
494 }
495
496 /// ShouldChangeType - Return true if it is desirable to convert a computation
497 /// from 'From' to 'To'.  We don't want to convert from a legal to an illegal
498 /// type for example, or from a smaller to a larger illegal type.
499 static bool ShouldChangeType(const Type *From, const Type *To,
500                              const TargetData *TD) {
501   assert(isa<IntegerType>(From) && isa<IntegerType>(To));
502   
503   // If we don't have TD, we don't know if the source/dest are legal.
504   if (!TD) return false;
505   
506   unsigned FromWidth = From->getPrimitiveSizeInBits();
507   unsigned ToWidth = To->getPrimitiveSizeInBits();
508   bool FromLegal = TD->isLegalInteger(FromWidth);
509   bool ToLegal = TD->isLegalInteger(ToWidth);
510   
511   // If this is a legal integer from type, and the result would be an illegal
512   // type, don't do the transformation.
513   if (FromLegal && !ToLegal)
514     return false;
515   
516   // Otherwise, if both are illegal, do not increase the size of the result. We
517   // do allow things like i160 -> i64, but not i64 -> i160.
518   if (!FromLegal && !ToLegal && ToWidth > FromWidth)
519     return false;
520   
521   return true;
522 }
523
524 /// getBitCastOperand - If the specified operand is a CastInst, a constant
525 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
526 /// operand value, otherwise return null.
527 static Value *getBitCastOperand(Value *V) {
528   if (Operator *O = dyn_cast<Operator>(V)) {
529     if (O->getOpcode() == Instruction::BitCast)
530       return O->getOperand(0);
531     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
532       if (GEP->hasAllZeroIndices())
533         return GEP->getPointerOperand();
534   }
535   return 0;
536 }
537
538 /// This function is a wrapper around CastInst::isEliminableCastPair. It
539 /// simply extracts arguments and returns what that function returns.
540 static Instruction::CastOps 
541 isEliminableCastPair(
542   const CastInst *CI, ///< The first cast instruction
543   unsigned opcode,       ///< The opcode of the second cast instruction
544   const Type *DstTy,     ///< The target type for the second cast instruction
545   TargetData *TD         ///< The target data for pointer size
546 ) {
547
548   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
549   const Type *MidTy = CI->getType();                  // B from above
550
551   // Get the opcodes of the two Cast instructions
552   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
553   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
554
555   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
556                                                 DstTy,
557                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
558   
559   // We don't want to form an inttoptr or ptrtoint that converts to an integer
560   // type that differs from the pointer size.
561   if ((Res == Instruction::IntToPtr &&
562           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
563       (Res == Instruction::PtrToInt &&
564           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
565     Res = 0;
566   
567   return Instruction::CastOps(Res);
568 }
569
570 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
571 /// in any code being generated.  It does not require codegen if V is simple
572 /// enough or if the cast can be folded into other casts.
573 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
574                               const Type *Ty, TargetData *TD) {
575   if (V->getType() == Ty || isa<Constant>(V)) return false;
576   
577   // If this is another cast that can be eliminated, it isn't codegen either.
578   if (const CastInst *CI = dyn_cast<CastInst>(V))
579     if (isEliminableCastPair(CI, opcode, Ty, TD))
580       return false;
581   return true;
582 }
583
584 // SimplifyCommutative - This performs a few simplifications for commutative
585 // operators:
586 //
587 //  1. Order operands such that they are listed from right (least complex) to
588 //     left (most complex).  This puts constants before unary operators before
589 //     binary operators.
590 //
591 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
592 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
593 //
594 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
595   bool Changed = false;
596   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
597     Changed = !I.swapOperands();
598
599   if (!I.isAssociative()) return Changed;
600   Instruction::BinaryOps Opcode = I.getOpcode();
601   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
602     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
603       if (isa<Constant>(I.getOperand(1))) {
604         Constant *Folded = ConstantExpr::get(I.getOpcode(),
605                                              cast<Constant>(I.getOperand(1)),
606                                              cast<Constant>(Op->getOperand(1)));
607         I.setOperand(0, Op->getOperand(0));
608         I.setOperand(1, Folded);
609         return true;
610       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
611         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
612             isOnlyUse(Op) && isOnlyUse(Op1)) {
613           Constant *C1 = cast<Constant>(Op->getOperand(1));
614           Constant *C2 = cast<Constant>(Op1->getOperand(1));
615
616           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
617           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
618           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
619                                                     Op1->getOperand(0),
620                                                     Op1->getName(), &I);
621           Worklist.Add(New);
622           I.setOperand(0, New);
623           I.setOperand(1, Folded);
624           return true;
625         }
626     }
627   return Changed;
628 }
629
630 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
631 // if the LHS is a constant zero (which is the 'negate' form).
632 //
633 static inline Value *dyn_castNegVal(Value *V) {
634   if (BinaryOperator::isNeg(V))
635     return BinaryOperator::getNegArgument(V);
636
637   // Constants can be considered to be negated values if they can be folded.
638   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
639     return ConstantExpr::getNeg(C);
640
641   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
642     if (C->getType()->getElementType()->isInteger())
643       return ConstantExpr::getNeg(C);
644
645   return 0;
646 }
647
648 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
649 // instruction if the LHS is a constant negative zero (which is the 'negate'
650 // form).
651 //
652 static inline Value *dyn_castFNegVal(Value *V) {
653   if (BinaryOperator::isFNeg(V))
654     return BinaryOperator::getFNegArgument(V);
655
656   // Constants can be considered to be negated values if they can be folded.
657   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
658     return ConstantExpr::getFNeg(C);
659
660   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
661     if (C->getType()->getElementType()->isFloatingPoint())
662       return ConstantExpr::getFNeg(C);
663
664   return 0;
665 }
666
667 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
668 /// returning the kind and providing the out parameter results if we
669 /// successfully match.
670 static SelectPatternFlavor
671 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
672   SelectInst *SI = dyn_cast<SelectInst>(V);
673   if (SI == 0) return SPF_UNKNOWN;
674   
675   ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
676   if (ICI == 0) return SPF_UNKNOWN;
677   
678   LHS = ICI->getOperand(0);
679   RHS = ICI->getOperand(1);
680   
681   // (icmp X, Y) ? X : Y 
682   if (SI->getTrueValue() == ICI->getOperand(0) &&
683       SI->getFalseValue() == ICI->getOperand(1)) {
684     switch (ICI->getPredicate()) {
685     default: return SPF_UNKNOWN; // Equality.
686     case ICmpInst::ICMP_UGT:
687     case ICmpInst::ICMP_UGE: return SPF_UMAX;
688     case ICmpInst::ICMP_SGT:
689     case ICmpInst::ICMP_SGE: return SPF_SMAX;
690     case ICmpInst::ICMP_ULT:
691     case ICmpInst::ICMP_ULE: return SPF_UMIN;
692     case ICmpInst::ICMP_SLT:
693     case ICmpInst::ICMP_SLE: return SPF_SMIN;
694     }
695   }
696   
697   // (icmp X, Y) ? Y : X 
698   if (SI->getTrueValue() == ICI->getOperand(1) &&
699       SI->getFalseValue() == ICI->getOperand(0)) {
700     switch (ICI->getPredicate()) {
701       default: return SPF_UNKNOWN; // Equality.
702       case ICmpInst::ICMP_UGT:
703       case ICmpInst::ICMP_UGE: return SPF_UMIN;
704       case ICmpInst::ICMP_SGT:
705       case ICmpInst::ICMP_SGE: return SPF_SMIN;
706       case ICmpInst::ICMP_ULT:
707       case ICmpInst::ICMP_ULE: return SPF_UMAX;
708       case ICmpInst::ICMP_SLT:
709       case ICmpInst::ICMP_SLE: return SPF_SMAX;
710     }
711   }
712   
713   // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
714   
715   return SPF_UNKNOWN;
716 }
717
718 /// isFreeToInvert - Return true if the specified value is free to invert (apply
719 /// ~ to).  This happens in cases where the ~ can be eliminated.
720 static inline bool isFreeToInvert(Value *V) {
721   // ~(~(X)) -> X.
722   if (BinaryOperator::isNot(V))
723     return true;
724   
725   // Constants can be considered to be not'ed values.
726   if (isa<ConstantInt>(V))
727     return true;
728   
729   // Compares can be inverted if they have a single use.
730   if (CmpInst *CI = dyn_cast<CmpInst>(V))
731     return CI->hasOneUse();
732   
733   return false;
734 }
735
736 static inline Value *dyn_castNotVal(Value *V) {
737   // If this is not(not(x)) don't return that this is a not: we want the two
738   // not's to be folded first.
739   if (BinaryOperator::isNot(V)) {
740     Value *Operand = BinaryOperator::getNotArgument(V);
741     if (!isFreeToInvert(Operand))
742       return Operand;
743   }
744
745   // Constants can be considered to be not'ed values...
746   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
747     return ConstantInt::get(C->getType(), ~C->getValue());
748   return 0;
749 }
750
751
752
753 // dyn_castFoldableMul - If this value is a multiply that can be folded into
754 // other computations (because it has a constant operand), return the
755 // non-constant operand of the multiply, and set CST to point to the multiplier.
756 // Otherwise, return null.
757 //
758 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
759   if (V->hasOneUse() && V->getType()->isInteger())
760     if (Instruction *I = dyn_cast<Instruction>(V)) {
761       if (I->getOpcode() == Instruction::Mul)
762         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
763           return I->getOperand(0);
764       if (I->getOpcode() == Instruction::Shl)
765         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
766           // The multiplier is really 1 << CST.
767           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
768           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
769           CST = ConstantInt::get(V->getType()->getContext(),
770                                  APInt(BitWidth, 1).shl(CSTVal));
771           return I->getOperand(0);
772         }
773     }
774   return 0;
775 }
776
777 /// AddOne - Add one to a ConstantInt
778 static Constant *AddOne(Constant *C) {
779   return ConstantExpr::getAdd(C, 
780     ConstantInt::get(C->getType(), 1));
781 }
782 /// SubOne - Subtract one from a ConstantInt
783 static Constant *SubOne(ConstantInt *C) {
784   return ConstantExpr::getSub(C, 
785     ConstantInt::get(C->getType(), 1));
786 }
787 /// MultiplyOverflows - True if the multiply can not be expressed in an int
788 /// this size.
789 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
790   uint32_t W = C1->getBitWidth();
791   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
792   if (sign) {
793     LHSExt.sext(W * 2);
794     RHSExt.sext(W * 2);
795   } else {
796     LHSExt.zext(W * 2);
797     RHSExt.zext(W * 2);
798   }
799
800   APInt MulExt = LHSExt * RHSExt;
801
802   if (!sign)
803     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
804   
805   APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
806   APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
807   return MulExt.slt(Min) || MulExt.sgt(Max);
808 }
809
810
811 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
812 /// specified instruction is a constant integer.  If so, check to see if there
813 /// are any bits set in the constant that are not demanded.  If so, shrink the
814 /// constant and return true.
815 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
816                                    APInt Demanded) {
817   assert(I && "No instruction?");
818   assert(OpNo < I->getNumOperands() && "Operand index too large");
819
820   // If the operand is not a constant integer, nothing to do.
821   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
822   if (!OpC) return false;
823
824   // If there are no bits set that aren't demanded, nothing to do.
825   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
826   if ((~Demanded & OpC->getValue()) == 0)
827     return false;
828
829   // This instruction is producing bits that are not demanded. Shrink the RHS.
830   Demanded &= OpC->getValue();
831   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
832   return true;
833 }
834
835 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
836 // set of known zero and one bits, compute the maximum and minimum values that
837 // could have the specified known zero and known one bits, returning them in
838 // min/max.
839 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
840                                                    const APInt& KnownOne,
841                                                    APInt& Min, APInt& Max) {
842   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
843          KnownZero.getBitWidth() == Min.getBitWidth() &&
844          KnownZero.getBitWidth() == Max.getBitWidth() &&
845          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
846   APInt UnknownBits = ~(KnownZero|KnownOne);
847
848   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
849   // bit if it is unknown.
850   Min = KnownOne;
851   Max = KnownOne|UnknownBits;
852   
853   if (UnknownBits.isNegative()) { // Sign bit is unknown
854     Min.set(Min.getBitWidth()-1);
855     Max.clear(Max.getBitWidth()-1);
856   }
857 }
858
859 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
860 // a set of known zero and one bits, compute the maximum and minimum values that
861 // could have the specified known zero and known one bits, returning them in
862 // min/max.
863 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
864                                                      const APInt &KnownOne,
865                                                      APInt &Min, APInt &Max) {
866   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
867          KnownZero.getBitWidth() == Min.getBitWidth() &&
868          KnownZero.getBitWidth() == Max.getBitWidth() &&
869          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
870   APInt UnknownBits = ~(KnownZero|KnownOne);
871   
872   // The minimum value is when the unknown bits are all zeros.
873   Min = KnownOne;
874   // The maximum value is when the unknown bits are all ones.
875   Max = KnownOne|UnknownBits;
876 }
877
878 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
879 /// SimplifyDemandedBits knows about.  See if the instruction has any
880 /// properties that allow us to simplify its operands.
881 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
882   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
883   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
884   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
885   
886   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
887                                      KnownZero, KnownOne, 0);
888   if (V == 0) return false;
889   if (V == &Inst) return true;
890   ReplaceInstUsesWith(Inst, V);
891   return true;
892 }
893
894 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
895 /// specified instruction operand if possible, updating it in place.  It returns
896 /// true if it made any change and false otherwise.
897 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
898                                         APInt &KnownZero, APInt &KnownOne,
899                                         unsigned Depth) {
900   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
901                                           KnownZero, KnownOne, Depth);
902   if (NewVal == 0) return false;
903   U = NewVal;
904   return true;
905 }
906
907
908 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
909 /// value based on the demanded bits.  When this function is called, it is known
910 /// that only the bits set in DemandedMask of the result of V are ever used
911 /// downstream. Consequently, depending on the mask and V, it may be possible
912 /// to replace V with a constant or one of its operands. In such cases, this
913 /// function does the replacement and returns true. In all other cases, it
914 /// returns false after analyzing the expression and setting KnownOne and known
915 /// to be one in the expression.  KnownZero contains all the bits that are known
916 /// to be zero in the expression. These are provided to potentially allow the
917 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
918 /// the expression. KnownOne and KnownZero always follow the invariant that 
919 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
920 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
921 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
922 /// and KnownOne must all be the same.
923 ///
924 /// This returns null if it did not change anything and it permits no
925 /// simplification.  This returns V itself if it did some simplification of V's
926 /// operands based on the information about what bits are demanded. This returns
927 /// some other non-null value if it found out that V is equal to another value
928 /// in the context where the specified bits are demanded, but not for all users.
929 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
930                                              APInt &KnownZero, APInt &KnownOne,
931                                              unsigned Depth) {
932   assert(V != 0 && "Null pointer of Value???");
933   assert(Depth <= 6 && "Limit Search Depth");
934   uint32_t BitWidth = DemandedMask.getBitWidth();
935   const Type *VTy = V->getType();
936   assert((TD || !isa<PointerType>(VTy)) &&
937          "SimplifyDemandedBits needs to know bit widths!");
938   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
939          (!VTy->isIntOrIntVector() ||
940           VTy->getScalarSizeInBits() == BitWidth) &&
941          KnownZero.getBitWidth() == BitWidth &&
942          KnownOne.getBitWidth() == BitWidth &&
943          "Value *V, DemandedMask, KnownZero and KnownOne "
944          "must have same BitWidth");
945   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
946     // We know all of the bits for a constant!
947     KnownOne = CI->getValue() & DemandedMask;
948     KnownZero = ~KnownOne & DemandedMask;
949     return 0;
950   }
951   if (isa<ConstantPointerNull>(V)) {
952     // We know all of the bits for a constant!
953     KnownOne.clear();
954     KnownZero = DemandedMask;
955     return 0;
956   }
957
958   KnownZero.clear();
959   KnownOne.clear();
960   if (DemandedMask == 0) {   // Not demanding any bits from V.
961     if (isa<UndefValue>(V))
962       return 0;
963     return UndefValue::get(VTy);
964   }
965   
966   if (Depth == 6)        // Limit search depth.
967     return 0;
968   
969   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
970   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
971
972   Instruction *I = dyn_cast<Instruction>(V);
973   if (!I) {
974     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
975     return 0;        // Only analyze instructions.
976   }
977
978   // If there are multiple uses of this value and we aren't at the root, then
979   // we can't do any simplifications of the operands, because DemandedMask
980   // only reflects the bits demanded by *one* of the users.
981   if (Depth != 0 && !I->hasOneUse()) {
982     // Despite the fact that we can't simplify this instruction in all User's
983     // context, we can at least compute the knownzero/knownone bits, and we can
984     // do simplifications that apply to *just* the one user if we know that
985     // this instruction has a simpler value in that context.
986     if (I->getOpcode() == Instruction::And) {
987       // If either the LHS or the RHS are Zero, the result is zero.
988       ComputeMaskedBits(I->getOperand(1), DemandedMask,
989                         RHSKnownZero, RHSKnownOne, Depth+1);
990       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
991                         LHSKnownZero, LHSKnownOne, Depth+1);
992       
993       // If all of the demanded bits are known 1 on one side, return the other.
994       // These bits cannot contribute to the result of the 'and' in this
995       // context.
996       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
997           (DemandedMask & ~LHSKnownZero))
998         return I->getOperand(0);
999       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1000           (DemandedMask & ~RHSKnownZero))
1001         return I->getOperand(1);
1002       
1003       // If all of the demanded bits in the inputs are known zeros, return zero.
1004       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1005         return Constant::getNullValue(VTy);
1006       
1007     } else if (I->getOpcode() == Instruction::Or) {
1008       // We can simplify (X|Y) -> X or Y in the user's context if we know that
1009       // only bits from X or Y are demanded.
1010       
1011       // If either the LHS or the RHS are One, the result is One.
1012       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
1013                         RHSKnownZero, RHSKnownOne, Depth+1);
1014       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1015                         LHSKnownZero, LHSKnownOne, Depth+1);
1016       
1017       // If all of the demanded bits are known zero on one side, return the
1018       // other.  These bits cannot contribute to the result of the 'or' in this
1019       // context.
1020       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1021           (DemandedMask & ~LHSKnownOne))
1022         return I->getOperand(0);
1023       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1024           (DemandedMask & ~RHSKnownOne))
1025         return I->getOperand(1);
1026       
1027       // If all of the potentially set bits on one side are known to be set on
1028       // the other side, just use the 'other' side.
1029       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1030           (DemandedMask & (~RHSKnownZero)))
1031         return I->getOperand(0);
1032       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1033           (DemandedMask & (~LHSKnownZero)))
1034         return I->getOperand(1);
1035     }
1036     
1037     // Compute the KnownZero/KnownOne bits to simplify things downstream.
1038     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1039     return 0;
1040   }
1041   
1042   // If this is the root being simplified, allow it to have multiple uses,
1043   // just set the DemandedMask to all bits so that we can try to simplify the
1044   // operands.  This allows visitTruncInst (for example) to simplify the
1045   // operand of a trunc without duplicating all the logic below.
1046   if (Depth == 0 && !V->hasOneUse())
1047     DemandedMask = APInt::getAllOnesValue(BitWidth);
1048   
1049   switch (I->getOpcode()) {
1050   default:
1051     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1052     break;
1053   case Instruction::And:
1054     // If either the LHS or the RHS are Zero, the result is zero.
1055     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1056                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1057         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
1058                              LHSKnownZero, LHSKnownOne, Depth+1))
1059       return I;
1060     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1061     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1062
1063     // If all of the demanded bits are known 1 on one side, return the other.
1064     // These bits cannot contribute to the result of the 'and'.
1065     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1066         (DemandedMask & ~LHSKnownZero))
1067       return I->getOperand(0);
1068     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1069         (DemandedMask & ~RHSKnownZero))
1070       return I->getOperand(1);
1071     
1072     // If all of the demanded bits in the inputs are known zeros, return zero.
1073     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1074       return Constant::getNullValue(VTy);
1075       
1076     // If the RHS is a constant, see if we can simplify it.
1077     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1078       return I;
1079       
1080     // Output known-1 bits are only known if set in both the LHS & RHS.
1081     RHSKnownOne &= LHSKnownOne;
1082     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1083     RHSKnownZero |= LHSKnownZero;
1084     break;
1085   case Instruction::Or:
1086     // If either the LHS or the RHS are One, the result is One.
1087     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1088                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1089         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
1090                              LHSKnownZero, LHSKnownOne, Depth+1))
1091       return I;
1092     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1093     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1094     
1095     // If all of the demanded bits are known zero on one side, return the other.
1096     // These bits cannot contribute to the result of the 'or'.
1097     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1098         (DemandedMask & ~LHSKnownOne))
1099       return I->getOperand(0);
1100     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1101         (DemandedMask & ~RHSKnownOne))
1102       return I->getOperand(1);
1103
1104     // If all of the potentially set bits on one side are known to be set on
1105     // the other side, just use the 'other' side.
1106     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1107         (DemandedMask & (~RHSKnownZero)))
1108       return I->getOperand(0);
1109     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1110         (DemandedMask & (~LHSKnownZero)))
1111       return I->getOperand(1);
1112         
1113     // If the RHS is a constant, see if we can simplify it.
1114     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1115       return I;
1116           
1117     // Output known-0 bits are only known if clear in both the LHS & RHS.
1118     RHSKnownZero &= LHSKnownZero;
1119     // Output known-1 are known to be set if set in either the LHS | RHS.
1120     RHSKnownOne |= LHSKnownOne;
1121     break;
1122   case Instruction::Xor: {
1123     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1124                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1125         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1126                              LHSKnownZero, LHSKnownOne, Depth+1))
1127       return I;
1128     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1129     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1130     
1131     // If all of the demanded bits are known zero on one side, return the other.
1132     // These bits cannot contribute to the result of the 'xor'.
1133     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1134       return I->getOperand(0);
1135     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1136       return I->getOperand(1);
1137     
1138     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1139     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1140                          (RHSKnownOne & LHSKnownOne);
1141     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1142     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1143                         (RHSKnownOne & LHSKnownZero);
1144     
1145     // If all of the demanded bits are known to be zero on one side or the
1146     // other, turn this into an *inclusive* or.
1147     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1148     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1149       Instruction *Or = 
1150         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1151                                  I->getName());
1152       return InsertNewInstBefore(Or, *I);
1153     }
1154     
1155     // If all of the demanded bits on one side are known, and all of the set
1156     // bits on that side are also known to be set on the other side, turn this
1157     // into an AND, as we know the bits will be cleared.
1158     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1159     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1160       // all known
1161       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1162         Constant *AndC = Constant::getIntegerValue(VTy,
1163                                                    ~RHSKnownOne & DemandedMask);
1164         Instruction *And = 
1165           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1166         return InsertNewInstBefore(And, *I);
1167       }
1168     }
1169     
1170     // If the RHS is a constant, see if we can simplify it.
1171     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1172     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1173       return I;
1174     
1175     // If our LHS is an 'and' and if it has one use, and if any of the bits we
1176     // are flipping are known to be set, then the xor is just resetting those
1177     // bits to zero.  We can just knock out bits from the 'and' and the 'xor',
1178     // simplifying both of them.
1179     if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1180       if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1181           isa<ConstantInt>(I->getOperand(1)) &&
1182           isa<ConstantInt>(LHSInst->getOperand(1)) &&
1183           (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1184         ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1185         ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1186         APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1187         
1188         Constant *AndC =
1189           ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1190         Instruction *NewAnd = 
1191           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1192         InsertNewInstBefore(NewAnd, *I);
1193         
1194         Constant *XorC =
1195           ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1196         Instruction *NewXor =
1197           BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1198         return InsertNewInstBefore(NewXor, *I);
1199       }
1200           
1201           
1202     RHSKnownZero = KnownZeroOut;
1203     RHSKnownOne  = KnownOneOut;
1204     break;
1205   }
1206   case Instruction::Select:
1207     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1208                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1209         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1210                              LHSKnownZero, LHSKnownOne, Depth+1))
1211       return I;
1212     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1213     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1214     
1215     // If the operands are constants, see if we can simplify them.
1216     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1217         ShrinkDemandedConstant(I, 2, DemandedMask))
1218       return I;
1219     
1220     // Only known if known in both the LHS and RHS.
1221     RHSKnownOne &= LHSKnownOne;
1222     RHSKnownZero &= LHSKnownZero;
1223     break;
1224   case Instruction::Trunc: {
1225     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1226     DemandedMask.zext(truncBf);
1227     RHSKnownZero.zext(truncBf);
1228     RHSKnownOne.zext(truncBf);
1229     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1230                              RHSKnownZero, RHSKnownOne, Depth+1))
1231       return I;
1232     DemandedMask.trunc(BitWidth);
1233     RHSKnownZero.trunc(BitWidth);
1234     RHSKnownOne.trunc(BitWidth);
1235     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1236     break;
1237   }
1238   case Instruction::BitCast:
1239     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1240       return false;  // vector->int or fp->int?
1241
1242     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1243       if (const VectorType *SrcVTy =
1244             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1245         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1246           // Don't touch a bitcast between vectors of different element counts.
1247           return false;
1248       } else
1249         // Don't touch a scalar-to-vector bitcast.
1250         return false;
1251     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1252       // Don't touch a vector-to-scalar bitcast.
1253       return false;
1254
1255     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1256                              RHSKnownZero, RHSKnownOne, Depth+1))
1257       return I;
1258     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1259     break;
1260   case Instruction::ZExt: {
1261     // Compute the bits in the result that are not present in the input.
1262     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1263     
1264     DemandedMask.trunc(SrcBitWidth);
1265     RHSKnownZero.trunc(SrcBitWidth);
1266     RHSKnownOne.trunc(SrcBitWidth);
1267     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1268                              RHSKnownZero, RHSKnownOne, Depth+1))
1269       return I;
1270     DemandedMask.zext(BitWidth);
1271     RHSKnownZero.zext(BitWidth);
1272     RHSKnownOne.zext(BitWidth);
1273     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1274     // The top bits are known to be zero.
1275     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1276     break;
1277   }
1278   case Instruction::SExt: {
1279     // Compute the bits in the result that are not present in the input.
1280     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1281     
1282     APInt InputDemandedBits = DemandedMask & 
1283                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1284
1285     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1286     // If any of the sign extended bits are demanded, we know that the sign
1287     // bit is demanded.
1288     if ((NewBits & DemandedMask) != 0)
1289       InputDemandedBits.set(SrcBitWidth-1);
1290       
1291     InputDemandedBits.trunc(SrcBitWidth);
1292     RHSKnownZero.trunc(SrcBitWidth);
1293     RHSKnownOne.trunc(SrcBitWidth);
1294     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1295                              RHSKnownZero, RHSKnownOne, Depth+1))
1296       return I;
1297     InputDemandedBits.zext(BitWidth);
1298     RHSKnownZero.zext(BitWidth);
1299     RHSKnownOne.zext(BitWidth);
1300     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1301       
1302     // If the sign bit of the input is known set or clear, then we know the
1303     // top bits of the result.
1304
1305     // If the input sign bit is known zero, or if the NewBits are not demanded
1306     // convert this into a zero extension.
1307     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1308       // Convert to ZExt cast
1309       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1310       return InsertNewInstBefore(NewCast, *I);
1311     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1312       RHSKnownOne |= NewBits;
1313     }
1314     break;
1315   }
1316   case Instruction::Add: {
1317     // Figure out what the input bits are.  If the top bits of the and result
1318     // are not demanded, then the add doesn't demand them from its input
1319     // either.
1320     unsigned NLZ = DemandedMask.countLeadingZeros();
1321       
1322     // If there is a constant on the RHS, there are a variety of xformations
1323     // we can do.
1324     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1325       // If null, this should be simplified elsewhere.  Some of the xforms here
1326       // won't work if the RHS is zero.
1327       if (RHS->isZero())
1328         break;
1329       
1330       // If the top bit of the output is demanded, demand everything from the
1331       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1332       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1333
1334       // Find information about known zero/one bits in the input.
1335       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1336                                LHSKnownZero, LHSKnownOne, Depth+1))
1337         return I;
1338
1339       // If the RHS of the add has bits set that can't affect the input, reduce
1340       // the constant.
1341       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1342         return I;
1343       
1344       // Avoid excess work.
1345       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1346         break;
1347       
1348       // Turn it into OR if input bits are zero.
1349       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1350         Instruction *Or =
1351           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1352                                    I->getName());
1353         return InsertNewInstBefore(Or, *I);
1354       }
1355       
1356       // We can say something about the output known-zero and known-one bits,
1357       // depending on potential carries from the input constant and the
1358       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1359       // bits set and the RHS constant is 0x01001, then we know we have a known
1360       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1361       
1362       // To compute this, we first compute the potential carry bits.  These are
1363       // the bits which may be modified.  I'm not aware of a better way to do
1364       // this scan.
1365       const APInt &RHSVal = RHS->getValue();
1366       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1367       
1368       // Now that we know which bits have carries, compute the known-1/0 sets.
1369       
1370       // Bits are known one if they are known zero in one operand and one in the
1371       // other, and there is no input carry.
1372       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1373                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1374       
1375       // Bits are known zero if they are known zero in both operands and there
1376       // is no input carry.
1377       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1378     } else {
1379       // If the high-bits of this ADD are not demanded, then it does not demand
1380       // the high bits of its LHS or RHS.
1381       if (DemandedMask[BitWidth-1] == 0) {
1382         // Right fill the mask of bits for this ADD to demand the most
1383         // significant bit and all those below it.
1384         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1385         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1386                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1387             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1388                                  LHSKnownZero, LHSKnownOne, Depth+1))
1389           return I;
1390       }
1391     }
1392     break;
1393   }
1394   case Instruction::Sub:
1395     // If the high-bits of this SUB are not demanded, then it does not demand
1396     // the high bits of its LHS or RHS.
1397     if (DemandedMask[BitWidth-1] == 0) {
1398       // Right fill the mask of bits for this SUB to demand the most
1399       // significant bit and all those below it.
1400       uint32_t NLZ = DemandedMask.countLeadingZeros();
1401       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1402       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1403                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1404           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1405                                LHSKnownZero, LHSKnownOne, Depth+1))
1406         return I;
1407     }
1408     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1409     // the known zeros and ones.
1410     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1411     break;
1412   case Instruction::Shl:
1413     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1414       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1415       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1416       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1417                                RHSKnownZero, RHSKnownOne, Depth+1))
1418         return I;
1419       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1420       RHSKnownZero <<= ShiftAmt;
1421       RHSKnownOne  <<= ShiftAmt;
1422       // low bits known zero.
1423       if (ShiftAmt)
1424         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1425     }
1426     break;
1427   case Instruction::LShr:
1428     // For a logical shift right
1429     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1430       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1431       
1432       // Unsigned shift right.
1433       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1434       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1435                                RHSKnownZero, RHSKnownOne, Depth+1))
1436         return I;
1437       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1438       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1439       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1440       if (ShiftAmt) {
1441         // Compute the new bits that are at the top now.
1442         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1443         RHSKnownZero |= HighBits;  // high bits known zero.
1444       }
1445     }
1446     break;
1447   case Instruction::AShr:
1448     // If this is an arithmetic shift right and only the low-bit is set, we can
1449     // always convert this into a logical shr, even if the shift amount is
1450     // variable.  The low bit of the shift cannot be an input sign bit unless
1451     // the shift amount is >= the size of the datatype, which is undefined.
1452     if (DemandedMask == 1) {
1453       // Perform the logical shift right.
1454       Instruction *NewVal = BinaryOperator::CreateLShr(
1455                         I->getOperand(0), I->getOperand(1), I->getName());
1456       return InsertNewInstBefore(NewVal, *I);
1457     }    
1458
1459     // If the sign bit is the only bit demanded by this ashr, then there is no
1460     // need to do it, the shift doesn't change the high bit.
1461     if (DemandedMask.isSignBit())
1462       return I->getOperand(0);
1463     
1464     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1465       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1466       
1467       // Signed shift right.
1468       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1469       // If any of the "high bits" are demanded, we should set the sign bit as
1470       // demanded.
1471       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1472         DemandedMaskIn.set(BitWidth-1);
1473       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1474                                RHSKnownZero, RHSKnownOne, Depth+1))
1475         return I;
1476       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1477       // Compute the new bits that are at the top now.
1478       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1479       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1480       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1481         
1482       // Handle the sign bits.
1483       APInt SignBit(APInt::getSignBit(BitWidth));
1484       // Adjust to where it is now in the mask.
1485       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1486         
1487       // If the input sign bit is known to be zero, or if none of the top bits
1488       // are demanded, turn this into an unsigned shift right.
1489       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1490           (HighBits & ~DemandedMask) == HighBits) {
1491         // Perform the logical shift right.
1492         Instruction *NewVal = BinaryOperator::CreateLShr(
1493                           I->getOperand(0), SA, I->getName());
1494         return InsertNewInstBefore(NewVal, *I);
1495       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1496         RHSKnownOne |= HighBits;
1497       }
1498     }
1499     break;
1500   case Instruction::SRem:
1501     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1502       APInt RA = Rem->getValue().abs();
1503       if (RA.isPowerOf2()) {
1504         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1505           return I->getOperand(0);
1506
1507         APInt LowBits = RA - 1;
1508         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1509         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1510                                  LHSKnownZero, LHSKnownOne, Depth+1))
1511           return I;
1512
1513         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1514           LHSKnownZero |= ~LowBits;
1515
1516         KnownZero |= LHSKnownZero & DemandedMask;
1517
1518         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1519       }
1520     }
1521     break;
1522   case Instruction::URem: {
1523     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1524     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1525     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1526                              KnownZero2, KnownOne2, Depth+1) ||
1527         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1528                              KnownZero2, KnownOne2, Depth+1))
1529       return I;
1530
1531     unsigned Leaders = KnownZero2.countLeadingOnes();
1532     Leaders = std::max(Leaders,
1533                        KnownZero2.countLeadingOnes());
1534     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1535     break;
1536   }
1537   case Instruction::Call:
1538     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1539       switch (II->getIntrinsicID()) {
1540       default: break;
1541       case Intrinsic::bswap: {
1542         // If the only bits demanded come from one byte of the bswap result,
1543         // just shift the input byte into position to eliminate the bswap.
1544         unsigned NLZ = DemandedMask.countLeadingZeros();
1545         unsigned NTZ = DemandedMask.countTrailingZeros();
1546           
1547         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1548         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1549         // have 14 leading zeros, round to 8.
1550         NLZ &= ~7;
1551         NTZ &= ~7;
1552         // If we need exactly one byte, we can do this transformation.
1553         if (BitWidth-NLZ-NTZ == 8) {
1554           unsigned ResultBit = NTZ;
1555           unsigned InputBit = BitWidth-NTZ-8;
1556           
1557           // Replace this with either a left or right shift to get the byte into
1558           // the right place.
1559           Instruction *NewVal;
1560           if (InputBit > ResultBit)
1561             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1562                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1563           else
1564             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1565                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1566           NewVal->takeName(I);
1567           return InsertNewInstBefore(NewVal, *I);
1568         }
1569           
1570         // TODO: Could compute known zero/one bits based on the input.
1571         break;
1572       }
1573       }
1574     }
1575     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1576     break;
1577   }
1578   
1579   // If the client is only demanding bits that we know, return the known
1580   // constant.
1581   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1582     return Constant::getIntegerValue(VTy, RHSKnownOne);
1583   return false;
1584 }
1585
1586
1587 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1588 /// any number of elements. DemandedElts contains the set of elements that are
1589 /// actually used by the caller.  This method analyzes which elements of the
1590 /// operand are undef and returns that information in UndefElts.
1591 ///
1592 /// If the information about demanded elements can be used to simplify the
1593 /// operation, the operation is simplified, then the resultant value is
1594 /// returned.  This returns null if no change was made.
1595 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1596                                                 APInt& UndefElts,
1597                                                 unsigned Depth) {
1598   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1599   APInt EltMask(APInt::getAllOnesValue(VWidth));
1600   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1601
1602   if (isa<UndefValue>(V)) {
1603     // If the entire vector is undefined, just return this info.
1604     UndefElts = EltMask;
1605     return 0;
1606   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1607     UndefElts = EltMask;
1608     return UndefValue::get(V->getType());
1609   }
1610
1611   UndefElts = 0;
1612   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1613     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1614     Constant *Undef = UndefValue::get(EltTy);
1615
1616     std::vector<Constant*> Elts;
1617     for (unsigned i = 0; i != VWidth; ++i)
1618       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1619         Elts.push_back(Undef);
1620         UndefElts.set(i);
1621       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1622         Elts.push_back(Undef);
1623         UndefElts.set(i);
1624       } else {                               // Otherwise, defined.
1625         Elts.push_back(CP->getOperand(i));
1626       }
1627
1628     // If we changed the constant, return it.
1629     Constant *NewCP = ConstantVector::get(Elts);
1630     return NewCP != CP ? NewCP : 0;
1631   } else if (isa<ConstantAggregateZero>(V)) {
1632     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1633     // set to undef.
1634     
1635     // Check if this is identity. If so, return 0 since we are not simplifying
1636     // anything.
1637     if (DemandedElts == ((1ULL << VWidth) -1))
1638       return 0;
1639     
1640     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1641     Constant *Zero = Constant::getNullValue(EltTy);
1642     Constant *Undef = UndefValue::get(EltTy);
1643     std::vector<Constant*> Elts;
1644     for (unsigned i = 0; i != VWidth; ++i) {
1645       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1646       Elts.push_back(Elt);
1647     }
1648     UndefElts = DemandedElts ^ EltMask;
1649     return ConstantVector::get(Elts);
1650   }
1651   
1652   // Limit search depth.
1653   if (Depth == 10)
1654     return 0;
1655
1656   // If multiple users are using the root value, procede with
1657   // simplification conservatively assuming that all elements
1658   // are needed.
1659   if (!V->hasOneUse()) {
1660     // Quit if we find multiple users of a non-root value though.
1661     // They'll be handled when it's their turn to be visited by
1662     // the main instcombine process.
1663     if (Depth != 0)
1664       // TODO: Just compute the UndefElts information recursively.
1665       return 0;
1666
1667     // Conservatively assume that all elements are needed.
1668     DemandedElts = EltMask;
1669   }
1670   
1671   Instruction *I = dyn_cast<Instruction>(V);
1672   if (!I) return 0;        // Only analyze instructions.
1673   
1674   bool MadeChange = false;
1675   APInt UndefElts2(VWidth, 0);
1676   Value *TmpV;
1677   switch (I->getOpcode()) {
1678   default: break;
1679     
1680   case Instruction::InsertElement: {
1681     // If this is a variable index, we don't know which element it overwrites.
1682     // demand exactly the same input as we produce.
1683     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1684     if (Idx == 0) {
1685       // Note that we can't propagate undef elt info, because we don't know
1686       // which elt is getting updated.
1687       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1688                                         UndefElts2, Depth+1);
1689       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1690       break;
1691     }
1692     
1693     // If this is inserting an element that isn't demanded, remove this
1694     // insertelement.
1695     unsigned IdxNo = Idx->getZExtValue();
1696     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1697       Worklist.Add(I);
1698       return I->getOperand(0);
1699     }
1700     
1701     // Otherwise, the element inserted overwrites whatever was there, so the
1702     // input demanded set is simpler than the output set.
1703     APInt DemandedElts2 = DemandedElts;
1704     DemandedElts2.clear(IdxNo);
1705     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1706                                       UndefElts, Depth+1);
1707     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1708
1709     // The inserted element is defined.
1710     UndefElts.clear(IdxNo);
1711     break;
1712   }
1713   case Instruction::ShuffleVector: {
1714     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1715     uint64_t LHSVWidth =
1716       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1717     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1718     for (unsigned i = 0; i < VWidth; i++) {
1719       if (DemandedElts[i]) {
1720         unsigned MaskVal = Shuffle->getMaskValue(i);
1721         if (MaskVal != -1u) {
1722           assert(MaskVal < LHSVWidth * 2 &&
1723                  "shufflevector mask index out of range!");
1724           if (MaskVal < LHSVWidth)
1725             LeftDemanded.set(MaskVal);
1726           else
1727             RightDemanded.set(MaskVal - LHSVWidth);
1728         }
1729       }
1730     }
1731
1732     APInt UndefElts4(LHSVWidth, 0);
1733     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1734                                       UndefElts4, Depth+1);
1735     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1736
1737     APInt UndefElts3(LHSVWidth, 0);
1738     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1739                                       UndefElts3, Depth+1);
1740     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1741
1742     bool NewUndefElts = false;
1743     for (unsigned i = 0; i < VWidth; i++) {
1744       unsigned MaskVal = Shuffle->getMaskValue(i);
1745       if (MaskVal == -1u) {
1746         UndefElts.set(i);
1747       } else if (MaskVal < LHSVWidth) {
1748         if (UndefElts4[MaskVal]) {
1749           NewUndefElts = true;
1750           UndefElts.set(i);
1751         }
1752       } else {
1753         if (UndefElts3[MaskVal - LHSVWidth]) {
1754           NewUndefElts = true;
1755           UndefElts.set(i);
1756         }
1757       }
1758     }
1759
1760     if (NewUndefElts) {
1761       // Add additional discovered undefs.
1762       std::vector<Constant*> Elts;
1763       for (unsigned i = 0; i < VWidth; ++i) {
1764         if (UndefElts[i])
1765           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1766         else
1767           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1768                                           Shuffle->getMaskValue(i)));
1769       }
1770       I->setOperand(2, ConstantVector::get(Elts));
1771       MadeChange = true;
1772     }
1773     break;
1774   }
1775   case Instruction::BitCast: {
1776     // Vector->vector casts only.
1777     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1778     if (!VTy) break;
1779     unsigned InVWidth = VTy->getNumElements();
1780     APInt InputDemandedElts(InVWidth, 0);
1781     unsigned Ratio;
1782
1783     if (VWidth == InVWidth) {
1784       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1785       // elements as are demanded of us.
1786       Ratio = 1;
1787       InputDemandedElts = DemandedElts;
1788     } else if (VWidth > InVWidth) {
1789       // Untested so far.
1790       break;
1791       
1792       // If there are more elements in the result than there are in the source,
1793       // then an input element is live if any of the corresponding output
1794       // elements are live.
1795       Ratio = VWidth/InVWidth;
1796       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1797         if (DemandedElts[OutIdx])
1798           InputDemandedElts.set(OutIdx/Ratio);
1799       }
1800     } else {
1801       // Untested so far.
1802       break;
1803       
1804       // If there are more elements in the source than there are in the result,
1805       // then an input element is live if the corresponding output element is
1806       // live.
1807       Ratio = InVWidth/VWidth;
1808       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1809         if (DemandedElts[InIdx/Ratio])
1810           InputDemandedElts.set(InIdx);
1811     }
1812     
1813     // div/rem demand all inputs, because they don't want divide by zero.
1814     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1815                                       UndefElts2, Depth+1);
1816     if (TmpV) {
1817       I->setOperand(0, TmpV);
1818       MadeChange = true;
1819     }
1820     
1821     UndefElts = UndefElts2;
1822     if (VWidth > InVWidth) {
1823       llvm_unreachable("Unimp");
1824       // If there are more elements in the result than there are in the source,
1825       // then an output element is undef if the corresponding input element is
1826       // undef.
1827       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1828         if (UndefElts2[OutIdx/Ratio])
1829           UndefElts.set(OutIdx);
1830     } else if (VWidth < InVWidth) {
1831       llvm_unreachable("Unimp");
1832       // If there are more elements in the source than there are in the result,
1833       // then a result element is undef if all of the corresponding input
1834       // elements are undef.
1835       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1836       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1837         if (!UndefElts2[InIdx])            // Not undef?
1838           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1839     }
1840     break;
1841   }
1842   case Instruction::And:
1843   case Instruction::Or:
1844   case Instruction::Xor:
1845   case Instruction::Add:
1846   case Instruction::Sub:
1847   case Instruction::Mul:
1848     // div/rem demand all inputs, because they don't want divide by zero.
1849     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1850                                       UndefElts, Depth+1);
1851     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1852     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1853                                       UndefElts2, Depth+1);
1854     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1855       
1856     // Output elements are undefined if both are undefined.  Consider things
1857     // like undef&0.  The result is known zero, not undef.
1858     UndefElts &= UndefElts2;
1859     break;
1860     
1861   case Instruction::Call: {
1862     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1863     if (!II) break;
1864     switch (II->getIntrinsicID()) {
1865     default: break;
1866       
1867     // Binary vector operations that work column-wise.  A dest element is a
1868     // function of the corresponding input elements from the two inputs.
1869     case Intrinsic::x86_sse_sub_ss:
1870     case Intrinsic::x86_sse_mul_ss:
1871     case Intrinsic::x86_sse_min_ss:
1872     case Intrinsic::x86_sse_max_ss:
1873     case Intrinsic::x86_sse2_sub_sd:
1874     case Intrinsic::x86_sse2_mul_sd:
1875     case Intrinsic::x86_sse2_min_sd:
1876     case Intrinsic::x86_sse2_max_sd:
1877       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1878                                         UndefElts, Depth+1);
1879       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1880       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1881                                         UndefElts2, Depth+1);
1882       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1883
1884       // If only the low elt is demanded and this is a scalarizable intrinsic,
1885       // scalarize it now.
1886       if (DemandedElts == 1) {
1887         switch (II->getIntrinsicID()) {
1888         default: break;
1889         case Intrinsic::x86_sse_sub_ss:
1890         case Intrinsic::x86_sse_mul_ss:
1891         case Intrinsic::x86_sse2_sub_sd:
1892         case Intrinsic::x86_sse2_mul_sd:
1893           // TODO: Lower MIN/MAX/ABS/etc
1894           Value *LHS = II->getOperand(1);
1895           Value *RHS = II->getOperand(2);
1896           // Extract the element as scalars.
1897           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1898             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1899           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1900             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1901           
1902           switch (II->getIntrinsicID()) {
1903           default: llvm_unreachable("Case stmts out of sync!");
1904           case Intrinsic::x86_sse_sub_ss:
1905           case Intrinsic::x86_sse2_sub_sd:
1906             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1907                                                         II->getName()), *II);
1908             break;
1909           case Intrinsic::x86_sse_mul_ss:
1910           case Intrinsic::x86_sse2_mul_sd:
1911             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1912                                                          II->getName()), *II);
1913             break;
1914           }
1915           
1916           Instruction *New =
1917             InsertElementInst::Create(
1918               UndefValue::get(II->getType()), TmpV,
1919               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1920           InsertNewInstBefore(New, *II);
1921           return New;
1922         }            
1923       }
1924         
1925       // Output elements are undefined if both are undefined.  Consider things
1926       // like undef&0.  The result is known zero, not undef.
1927       UndefElts &= UndefElts2;
1928       break;
1929     }
1930     break;
1931   }
1932   }
1933   return MadeChange ? I : 0;
1934 }
1935
1936
1937 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1938 /// function is designed to check a chain of associative operators for a
1939 /// potential to apply a certain optimization.  Since the optimization may be
1940 /// applicable if the expression was reassociated, this checks the chain, then
1941 /// reassociates the expression as necessary to expose the optimization
1942 /// opportunity.  This makes use of a special Functor, which must define
1943 /// 'shouldApply' and 'apply' methods.
1944 ///
1945 template<typename Functor>
1946 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1947   unsigned Opcode = Root.getOpcode();
1948   Value *LHS = Root.getOperand(0);
1949
1950   // Quick check, see if the immediate LHS matches...
1951   if (F.shouldApply(LHS))
1952     return F.apply(Root);
1953
1954   // Otherwise, if the LHS is not of the same opcode as the root, return.
1955   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1956   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1957     // Should we apply this transform to the RHS?
1958     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1959
1960     // If not to the RHS, check to see if we should apply to the LHS...
1961     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1962       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1963       ShouldApply = true;
1964     }
1965
1966     // If the functor wants to apply the optimization to the RHS of LHSI,
1967     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1968     if (ShouldApply) {
1969       // Now all of the instructions are in the current basic block, go ahead
1970       // and perform the reassociation.
1971       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1972
1973       // First move the selected RHS to the LHS of the root...
1974       Root.setOperand(0, LHSI->getOperand(1));
1975
1976       // Make what used to be the LHS of the root be the user of the root...
1977       Value *ExtraOperand = TmpLHSI->getOperand(1);
1978       if (&Root == TmpLHSI) {
1979         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1980         return 0;
1981       }
1982       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1983       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1984       BasicBlock::iterator ARI = &Root; ++ARI;
1985       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1986       ARI = Root;
1987
1988       // Now propagate the ExtraOperand down the chain of instructions until we
1989       // get to LHSI.
1990       while (TmpLHSI != LHSI) {
1991         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1992         // Move the instruction to immediately before the chain we are
1993         // constructing to avoid breaking dominance properties.
1994         NextLHSI->moveBefore(ARI);
1995         ARI = NextLHSI;
1996
1997         Value *NextOp = NextLHSI->getOperand(1);
1998         NextLHSI->setOperand(1, ExtraOperand);
1999         TmpLHSI = NextLHSI;
2000         ExtraOperand = NextOp;
2001       }
2002
2003       // Now that the instructions are reassociated, have the functor perform
2004       // the transformation...
2005       return F.apply(Root);
2006     }
2007
2008     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2009   }
2010   return 0;
2011 }
2012
2013 namespace {
2014
2015 // AddRHS - Implements: X + X --> X << 1
2016 struct AddRHS {
2017   Value *RHS;
2018   explicit AddRHS(Value *rhs) : RHS(rhs) {}
2019   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2020   Instruction *apply(BinaryOperator &Add) const {
2021     return BinaryOperator::CreateShl(Add.getOperand(0),
2022                                      ConstantInt::get(Add.getType(), 1));
2023   }
2024 };
2025
2026 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2027 //                 iff C1&C2 == 0
2028 struct AddMaskingAnd {
2029   Constant *C2;
2030   explicit AddMaskingAnd(Constant *c) : C2(c) {}
2031   bool shouldApply(Value *LHS) const {
2032     ConstantInt *C1;
2033     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2034            ConstantExpr::getAnd(C1, C2)->isNullValue();
2035   }
2036   Instruction *apply(BinaryOperator &Add) const {
2037     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2038   }
2039 };
2040
2041 }
2042
2043 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2044                                              InstCombiner *IC) {
2045   if (CastInst *CI = dyn_cast<CastInst>(&I))
2046     return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
2047
2048   // Figure out if the constant is the left or the right argument.
2049   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2050   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2051
2052   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2053     if (ConstIsRHS)
2054       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2055     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2056   }
2057
2058   Value *Op0 = SO, *Op1 = ConstOperand;
2059   if (!ConstIsRHS)
2060     std::swap(Op0, Op1);
2061   
2062   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2063     return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2064                                     SO->getName()+".op");
2065   if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2066     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2067                                    SO->getName()+".cmp");
2068   if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2069     return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2070                                    SO->getName()+".cmp");
2071   llvm_unreachable("Unknown binary instruction type!");
2072 }
2073
2074 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2075 // constant as the other operand, try to fold the binary operator into the
2076 // select arguments.  This also works for Cast instructions, which obviously do
2077 // not have a second operand.
2078 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2079                                      InstCombiner *IC) {
2080   // Don't modify shared select instructions
2081   if (!SI->hasOneUse()) return 0;
2082   Value *TV = SI->getOperand(1);
2083   Value *FV = SI->getOperand(2);
2084
2085   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2086     // Bool selects with constant operands can be folded to logical ops.
2087     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2088
2089     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2090     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2091
2092     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2093                               SelectFalseVal);
2094   }
2095   return 0;
2096 }
2097
2098
2099 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2100 /// has a PHI node as operand #0, see if we can fold the instruction into the
2101 /// PHI (which is only possible if all operands to the PHI are constants).
2102 ///
2103 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2104 /// that would normally be unprofitable because they strongly encourage jump
2105 /// threading.
2106 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2107                                          bool AllowAggressive) {
2108   AllowAggressive = false;
2109   PHINode *PN = cast<PHINode>(I.getOperand(0));
2110   unsigned NumPHIValues = PN->getNumIncomingValues();
2111   if (NumPHIValues == 0 ||
2112       // We normally only transform phis with a single use, unless we're trying
2113       // hard to make jump threading happen.
2114       (!PN->hasOneUse() && !AllowAggressive))
2115     return 0;
2116   
2117   
2118   // Check to see if all of the operands of the PHI are simple constants
2119   // (constantint/constantfp/undef).  If there is one non-constant value,
2120   // remember the BB it is in.  If there is more than one or if *it* is a PHI,
2121   // bail out.  We don't do arbitrary constant expressions here because moving
2122   // their computation can be expensive without a cost model.
2123   BasicBlock *NonConstBB = 0;
2124   for (unsigned i = 0; i != NumPHIValues; ++i)
2125     if (!isa<Constant>(PN->getIncomingValue(i)) ||
2126         isa<ConstantExpr>(PN->getIncomingValue(i))) {
2127       if (NonConstBB) return 0;  // More than one non-const value.
2128       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2129       NonConstBB = PN->getIncomingBlock(i);
2130       
2131       // If the incoming non-constant value is in I's block, we have an infinite
2132       // loop.
2133       if (NonConstBB == I.getParent())
2134         return 0;
2135     }
2136   
2137   // If there is exactly one non-constant value, we can insert a copy of the
2138   // operation in that block.  However, if this is a critical edge, we would be
2139   // inserting the computation one some other paths (e.g. inside a loop).  Only
2140   // do this if the pred block is unconditionally branching into the phi block.
2141   if (NonConstBB != 0 && !AllowAggressive) {
2142     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2143     if (!BI || !BI->isUnconditional()) return 0;
2144   }
2145
2146   // Okay, we can do the transformation: create the new PHI node.
2147   PHINode *NewPN = PHINode::Create(I.getType(), "");
2148   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2149   InsertNewInstBefore(NewPN, *PN);
2150   NewPN->takeName(PN);
2151
2152   // Next, add all of the operands to the PHI.
2153   if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2154     // We only currently try to fold the condition of a select when it is a phi,
2155     // not the true/false values.
2156     Value *TrueV = SI->getTrueValue();
2157     Value *FalseV = SI->getFalseValue();
2158     BasicBlock *PhiTransBB = PN->getParent();
2159     for (unsigned i = 0; i != NumPHIValues; ++i) {
2160       BasicBlock *ThisBB = PN->getIncomingBlock(i);
2161       Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2162       Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2163       Value *InV = 0;
2164       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2165         InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2166       } else {
2167         assert(PN->getIncomingBlock(i) == NonConstBB);
2168         InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2169                                  FalseVInPred,
2170                                  "phitmp", NonConstBB->getTerminator());
2171         Worklist.Add(cast<Instruction>(InV));
2172       }
2173       NewPN->addIncoming(InV, ThisBB);
2174     }
2175   } else if (I.getNumOperands() == 2) {
2176     Constant *C = cast<Constant>(I.getOperand(1));
2177     for (unsigned i = 0; i != NumPHIValues; ++i) {
2178       Value *InV = 0;
2179       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2180         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2181           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2182         else
2183           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2184       } else {
2185         assert(PN->getIncomingBlock(i) == NonConstBB);
2186         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2187           InV = BinaryOperator::Create(BO->getOpcode(),
2188                                        PN->getIncomingValue(i), C, "phitmp",
2189                                        NonConstBB->getTerminator());
2190         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2191           InV = CmpInst::Create(CI->getOpcode(),
2192                                 CI->getPredicate(),
2193                                 PN->getIncomingValue(i), C, "phitmp",
2194                                 NonConstBB->getTerminator());
2195         else
2196           llvm_unreachable("Unknown binop!");
2197         
2198         Worklist.Add(cast<Instruction>(InV));
2199       }
2200       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2201     }
2202   } else { 
2203     CastInst *CI = cast<CastInst>(&I);
2204     const Type *RetTy = CI->getType();
2205     for (unsigned i = 0; i != NumPHIValues; ++i) {
2206       Value *InV;
2207       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2208         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2209       } else {
2210         assert(PN->getIncomingBlock(i) == NonConstBB);
2211         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2212                                I.getType(), "phitmp", 
2213                                NonConstBB->getTerminator());
2214         Worklist.Add(cast<Instruction>(InV));
2215       }
2216       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2217     }
2218   }
2219   return ReplaceInstUsesWith(I, NewPN);
2220 }
2221
2222
2223 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2224 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2225 /// This basically requires proving that the add in the original type would not
2226 /// overflow to change the sign bit or have a carry out.
2227 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2228   // There are different heuristics we can use for this.  Here are some simple
2229   // ones.
2230   
2231   // Add has the property that adding any two 2's complement numbers can only 
2232   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2233   // have at least two sign bits, we know that the addition of the two values
2234   // will sign extend fine.
2235   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2236     return true;
2237   
2238   
2239   // If one of the operands only has one non-zero bit, and if the other operand
2240   // has a known-zero bit in a more significant place than it (not including the
2241   // sign bit) the ripple may go up to and fill the zero, but won't change the
2242   // sign.  For example, (X & ~4) + 1.
2243   
2244   // TODO: Implement.
2245   
2246   return false;
2247 }
2248
2249
2250 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2251   bool Changed = SimplifyCommutative(I);
2252   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2253
2254   if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2255                                  I.hasNoUnsignedWrap(), TD))
2256     return ReplaceInstUsesWith(I, V);
2257
2258   
2259   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2260     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2261       // X + (signbit) --> X ^ signbit
2262       const APInt& Val = CI->getValue();
2263       uint32_t BitWidth = Val.getBitWidth();
2264       if (Val == APInt::getSignBit(BitWidth))
2265         return BinaryOperator::CreateXor(LHS, RHS);
2266       
2267       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2268       // (X & 254)+1 -> (X&254)|1
2269       if (SimplifyDemandedInstructionBits(I))
2270         return &I;
2271
2272       // zext(bool) + C -> bool ? C + 1 : C
2273       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2274         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2275           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2276     }
2277
2278     if (isa<PHINode>(LHS))
2279       if (Instruction *NV = FoldOpIntoPhi(I))
2280         return NV;
2281     
2282     ConstantInt *XorRHS = 0;
2283     Value *XorLHS = 0;
2284     if (isa<ConstantInt>(RHSC) &&
2285         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2286       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2287       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2288       
2289       uint32_t Size = TySizeBits / 2;
2290       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2291       APInt CFF80Val(-C0080Val);
2292       do {
2293         if (TySizeBits > Size) {
2294           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2295           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2296           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2297               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2298             // This is a sign extend if the top bits are known zero.
2299             if (!MaskedValueIsZero(XorLHS, 
2300                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2301               Size = 0;  // Not a sign ext, but can't be any others either.
2302             break;
2303           }
2304         }
2305         Size >>= 1;
2306         C0080Val = APIntOps::lshr(C0080Val, Size);
2307         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2308       } while (Size >= 1);
2309       
2310       // FIXME: This shouldn't be necessary. When the backends can handle types
2311       // with funny bit widths then this switch statement should be removed. It
2312       // is just here to get the size of the "middle" type back up to something
2313       // that the back ends can handle.
2314       const Type *MiddleType = 0;
2315       switch (Size) {
2316         default: break;
2317         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2318         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2319         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2320       }
2321       if (MiddleType) {
2322         Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2323         return new SExtInst(NewTrunc, I.getType(), I.getName());
2324       }
2325     }
2326   }
2327
2328   if (I.getType() == Type::getInt1Ty(*Context))
2329     return BinaryOperator::CreateXor(LHS, RHS);
2330
2331   // X + X --> X << 1
2332   if (I.getType()->isInteger()) {
2333     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2334       return Result;
2335
2336     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2337       if (RHSI->getOpcode() == Instruction::Sub)
2338         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2339           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2340     }
2341     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2342       if (LHSI->getOpcode() == Instruction::Sub)
2343         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2344           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2345     }
2346   }
2347
2348   // -A + B  -->  B - A
2349   // -A + -B  -->  -(A + B)
2350   if (Value *LHSV = dyn_castNegVal(LHS)) {
2351     if (LHS->getType()->isIntOrIntVector()) {
2352       if (Value *RHSV = dyn_castNegVal(RHS)) {
2353         Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2354         return BinaryOperator::CreateNeg(NewAdd);
2355       }
2356     }
2357     
2358     return BinaryOperator::CreateSub(RHS, LHSV);
2359   }
2360
2361   // A + -B  -->  A - B
2362   if (!isa<Constant>(RHS))
2363     if (Value *V = dyn_castNegVal(RHS))
2364       return BinaryOperator::CreateSub(LHS, V);
2365
2366
2367   ConstantInt *C2;
2368   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2369     if (X == RHS)   // X*C + X --> X * (C+1)
2370       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2371
2372     // X*C1 + X*C2 --> X * (C1+C2)
2373     ConstantInt *C1;
2374     if (X == dyn_castFoldableMul(RHS, C1))
2375       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2376   }
2377
2378   // X + X*C --> X * (C+1)
2379   if (dyn_castFoldableMul(RHS, C2) == LHS)
2380     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2381
2382   // X + ~X --> -1   since   ~X = -X-1
2383   if (dyn_castNotVal(LHS) == RHS ||
2384       dyn_castNotVal(RHS) == LHS)
2385     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2386   
2387
2388   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2389   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2390     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2391       return R;
2392   
2393   // A+B --> A|B iff A and B have no bits set in common.
2394   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2395     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2396     APInt LHSKnownOne(IT->getBitWidth(), 0);
2397     APInt LHSKnownZero(IT->getBitWidth(), 0);
2398     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2399     if (LHSKnownZero != 0) {
2400       APInt RHSKnownOne(IT->getBitWidth(), 0);
2401       APInt RHSKnownZero(IT->getBitWidth(), 0);
2402       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2403       
2404       // No bits in common -> bitwise or.
2405       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2406         return BinaryOperator::CreateOr(LHS, RHS);
2407     }
2408   }
2409
2410   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2411   if (I.getType()->isIntOrIntVector()) {
2412     Value *W, *X, *Y, *Z;
2413     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2414         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2415       if (W != Y) {
2416         if (W == Z) {
2417           std::swap(Y, Z);
2418         } else if (Y == X) {
2419           std::swap(W, X);
2420         } else if (X == Z) {
2421           std::swap(Y, Z);
2422           std::swap(W, X);
2423         }
2424       }
2425
2426       if (W == Y) {
2427         Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2428         return BinaryOperator::CreateMul(W, NewAdd);
2429       }
2430     }
2431   }
2432
2433   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2434     Value *X = 0;
2435     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2436       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2437
2438     // (X & FF00) + xx00  -> (X+xx00) & FF00
2439     if (LHS->hasOneUse() &&
2440         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2441       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2442       if (Anded == CRHS) {
2443         // See if all bits from the first bit set in the Add RHS up are included
2444         // in the mask.  First, get the rightmost bit.
2445         const APInt& AddRHSV = CRHS->getValue();
2446
2447         // Form a mask of all bits from the lowest bit added through the top.
2448         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2449
2450         // See if the and mask includes all of these bits.
2451         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2452
2453         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2454           // Okay, the xform is safe.  Insert the new add pronto.
2455           Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2456           return BinaryOperator::CreateAnd(NewAdd, C2);
2457         }
2458       }
2459     }
2460
2461     // Try to fold constant add into select arguments.
2462     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2463       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2464         return R;
2465   }
2466
2467   // add (select X 0 (sub n A)) A  -->  select X A n
2468   {
2469     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2470     Value *A = RHS;
2471     if (!SI) {
2472       SI = dyn_cast<SelectInst>(RHS);
2473       A = LHS;
2474     }
2475     if (SI && SI->hasOneUse()) {
2476       Value *TV = SI->getTrueValue();
2477       Value *FV = SI->getFalseValue();
2478       Value *N;
2479
2480       // Can we fold the add into the argument of the select?
2481       // We check both true and false select arguments for a matching subtract.
2482       if (match(FV, m_Zero()) &&
2483           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2484         // Fold the add into the true select value.
2485         return SelectInst::Create(SI->getCondition(), N, A);
2486       if (match(TV, m_Zero()) &&
2487           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2488         // Fold the add into the false select value.
2489         return SelectInst::Create(SI->getCondition(), A, N);
2490     }
2491   }
2492
2493   // Check for (add (sext x), y), see if we can merge this into an
2494   // integer add followed by a sext.
2495   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2496     // (add (sext x), cst) --> (sext (add x, cst'))
2497     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2498       Constant *CI = 
2499         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2500       if (LHSConv->hasOneUse() &&
2501           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2502           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2503         // Insert the new, smaller add.
2504         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2505                                               CI, "addconv");
2506         return new SExtInst(NewAdd, I.getType());
2507       }
2508     }
2509     
2510     // (add (sext x), (sext y)) --> (sext (add int x, y))
2511     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2512       // Only do this if x/y have the same type, if at last one of them has a
2513       // single use (so we don't increase the number of sexts), and if the
2514       // integer add will not overflow.
2515       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2516           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2517           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2518                                    RHSConv->getOperand(0))) {
2519         // Insert the new integer add.
2520         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2521                                               RHSConv->getOperand(0), "addconv");
2522         return new SExtInst(NewAdd, I.getType());
2523       }
2524     }
2525   }
2526
2527   return Changed ? &I : 0;
2528 }
2529
2530 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2531   bool Changed = SimplifyCommutative(I);
2532   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2533
2534   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2535     // X + 0 --> X
2536     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2537       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2538                               (I.getType())->getValueAPF()))
2539         return ReplaceInstUsesWith(I, LHS);
2540     }
2541
2542     if (isa<PHINode>(LHS))
2543       if (Instruction *NV = FoldOpIntoPhi(I))
2544         return NV;
2545   }
2546
2547   // -A + B  -->  B - A
2548   // -A + -B  -->  -(A + B)
2549   if (Value *LHSV = dyn_castFNegVal(LHS))
2550     return BinaryOperator::CreateFSub(RHS, LHSV);
2551
2552   // A + -B  -->  A - B
2553   if (!isa<Constant>(RHS))
2554     if (Value *V = dyn_castFNegVal(RHS))
2555       return BinaryOperator::CreateFSub(LHS, V);
2556
2557   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2558   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2559     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2560       return ReplaceInstUsesWith(I, LHS);
2561
2562   // Check for (add double (sitofp x), y), see if we can merge this into an
2563   // integer add followed by a promotion.
2564   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2565     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2566     // ... if the constant fits in the integer value.  This is useful for things
2567     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2568     // requires a constant pool load, and generally allows the add to be better
2569     // instcombined.
2570     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2571       Constant *CI = 
2572       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2573       if (LHSConv->hasOneUse() &&
2574           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2575           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2576         // Insert the new integer add.
2577         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2578                                               CI, "addconv");
2579         return new SIToFPInst(NewAdd, I.getType());
2580       }
2581     }
2582     
2583     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2584     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2585       // Only do this if x/y have the same type, if at last one of them has a
2586       // single use (so we don't increase the number of int->fp conversions),
2587       // and if the integer add will not overflow.
2588       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2589           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2590           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2591                                    RHSConv->getOperand(0))) {
2592         // Insert the new integer add.
2593         Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0), 
2594                                               RHSConv->getOperand(0),"addconv");
2595         return new SIToFPInst(NewAdd, I.getType());
2596       }
2597     }
2598   }
2599   
2600   return Changed ? &I : 0;
2601 }
2602
2603
2604 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2605 /// code necessary to compute the offset from the base pointer (without adding
2606 /// in the base pointer).  Return the result as a signed integer of intptr size.
2607 static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2608   TargetData &TD = *IC.getTargetData();
2609   gep_type_iterator GTI = gep_type_begin(GEP);
2610   const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2611   Value *Result = Constant::getNullValue(IntPtrTy);
2612
2613   // Build a mask for high order bits.
2614   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2615   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2616
2617   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2618        ++i, ++GTI) {
2619     Value *Op = *i;
2620     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2621     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2622       if (OpC->isZero()) continue;
2623       
2624       // Handle a struct index, which adds its field offset to the pointer.
2625       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2626         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2627         
2628         Result = IC.Builder->CreateAdd(Result,
2629                                        ConstantInt::get(IntPtrTy, Size),
2630                                        GEP->getName()+".offs");
2631         continue;
2632       }
2633       
2634       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2635       Constant *OC =
2636               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2637       Scale = ConstantExpr::getMul(OC, Scale);
2638       // Emit an add instruction.
2639       Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2640       continue;
2641     }
2642     // Convert to correct type.
2643     if (Op->getType() != IntPtrTy)
2644       Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2645     if (Size != 1) {
2646       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2647       // We'll let instcombine(mul) convert this to a shl if possible.
2648       Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2649     }
2650
2651     // Emit an add instruction.
2652     Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2653   }
2654   return Result;
2655 }
2656
2657
2658 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2659 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
2660 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
2661 /// be complex, and scales are involved.  The above expression would also be
2662 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2663 /// This later form is less amenable to optimization though, and we are allowed
2664 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
2665 ///
2666 /// If we can't emit an optimized form for this expression, this returns null.
2667 /// 
2668 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2669                                           InstCombiner &IC) {
2670   TargetData &TD = *IC.getTargetData();
2671   gep_type_iterator GTI = gep_type_begin(GEP);
2672
2673   // Check to see if this gep only has a single variable index.  If so, and if
2674   // any constant indices are a multiple of its scale, then we can compute this
2675   // in terms of the scale of the variable index.  For example, if the GEP
2676   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2677   // because the expression will cross zero at the same point.
2678   unsigned i, e = GEP->getNumOperands();
2679   int64_t Offset = 0;
2680   for (i = 1; i != e; ++i, ++GTI) {
2681     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2682       // Compute the aggregate offset of constant indices.
2683       if (CI->isZero()) continue;
2684
2685       // Handle a struct index, which adds its field offset to the pointer.
2686       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2687         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2688       } else {
2689         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2690         Offset += Size*CI->getSExtValue();
2691       }
2692     } else {
2693       // Found our variable index.
2694       break;
2695     }
2696   }
2697   
2698   // If there are no variable indices, we must have a constant offset, just
2699   // evaluate it the general way.
2700   if (i == e) return 0;
2701   
2702   Value *VariableIdx = GEP->getOperand(i);
2703   // Determine the scale factor of the variable element.  For example, this is
2704   // 4 if the variable index is into an array of i32.
2705   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2706   
2707   // Verify that there are no other variable indices.  If so, emit the hard way.
2708   for (++i, ++GTI; i != e; ++i, ++GTI) {
2709     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2710     if (!CI) return 0;
2711    
2712     // Compute the aggregate offset of constant indices.
2713     if (CI->isZero()) continue;
2714     
2715     // Handle a struct index, which adds its field offset to the pointer.
2716     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2717       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2718     } else {
2719       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2720       Offset += Size*CI->getSExtValue();
2721     }
2722   }
2723   
2724   // Okay, we know we have a single variable index, which must be a
2725   // pointer/array/vector index.  If there is no offset, life is simple, return
2726   // the index.
2727   unsigned IntPtrWidth = TD.getPointerSizeInBits();
2728   if (Offset == 0) {
2729     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
2730     // we don't need to bother extending: the extension won't affect where the
2731     // computation crosses zero.
2732     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2733       VariableIdx = new TruncInst(VariableIdx, 
2734                                   TD.getIntPtrType(VariableIdx->getContext()),
2735                                   VariableIdx->getName(), &I);
2736     return VariableIdx;
2737   }
2738   
2739   // Otherwise, there is an index.  The computation we will do will be modulo
2740   // the pointer size, so get it.
2741   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2742   
2743   Offset &= PtrSizeMask;
2744   VariableScale &= PtrSizeMask;
2745
2746   // To do this transformation, any constant index must be a multiple of the
2747   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
2748   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
2749   // multiple of the variable scale.
2750   int64_t NewOffs = Offset / (int64_t)VariableScale;
2751   if (Offset != NewOffs*(int64_t)VariableScale)
2752     return 0;
2753
2754   // Okay, we can do this evaluation.  Start by converting the index to intptr.
2755   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2756   if (VariableIdx->getType() != IntPtrTy)
2757     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2758                                               true /*SExt*/, 
2759                                               VariableIdx->getName(), &I);
2760   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2761   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2762 }
2763
2764
2765 /// Optimize pointer differences into the same array into a size.  Consider:
2766 ///  &A[10] - &A[0]: we should compile this to "10".  LHS/RHS are the pointer
2767 /// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2768 ///
2769 Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2770                                                const Type *Ty) {
2771   assert(TD && "Must have target data info for this");
2772   
2773   // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2774   // this.
2775   bool Swapped;
2776   GetElementPtrInst *GEP = 0;
2777   ConstantExpr *CstGEP = 0;
2778   
2779   // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2780   // For now we require one side to be the base pointer "A" or a constant
2781   // expression derived from it.
2782   if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2783     // (gep X, ...) - X
2784     if (LHSGEP->getOperand(0) == RHS) {
2785       GEP = LHSGEP;
2786       Swapped = false;
2787     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2788       // (gep X, ...) - (ce_gep X, ...)
2789       if (CE->getOpcode() == Instruction::GetElementPtr &&
2790           LHSGEP->getOperand(0) == CE->getOperand(0)) {
2791         CstGEP = CE;
2792         GEP = LHSGEP;
2793         Swapped = false;
2794       }
2795     }
2796   }
2797   
2798   if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2799     // X - (gep X, ...)
2800     if (RHSGEP->getOperand(0) == LHS) {
2801       GEP = RHSGEP;
2802       Swapped = true;
2803     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2804       // (ce_gep X, ...) - (gep X, ...)
2805       if (CE->getOpcode() == Instruction::GetElementPtr &&
2806           RHSGEP->getOperand(0) == CE->getOperand(0)) {
2807         CstGEP = CE;
2808         GEP = RHSGEP;
2809         Swapped = true;
2810       }
2811     }
2812   }
2813   
2814   if (GEP == 0)
2815     return 0;
2816   
2817   // Emit the offset of the GEP and an intptr_t.
2818   Value *Result = EmitGEPOffset(GEP, *this);
2819   
2820   // If we had a constant expression GEP on the other side offsetting the
2821   // pointer, subtract it from the offset we have.
2822   if (CstGEP) {
2823     Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2824     Result = Builder->CreateSub(Result, CstOffset);
2825   }
2826   
2827
2828   // If we have p - gep(p, ...)  then we have to negate the result.
2829   if (Swapped)
2830     Result = Builder->CreateNeg(Result, "diff.neg");
2831
2832   return Builder->CreateIntCast(Result, Ty, true);
2833 }
2834
2835
2836 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2837   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2838
2839   if (Op0 == Op1)                        // sub X, X  -> 0
2840     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2841
2842   // If this is a 'B = x-(-A)', change to B = x+A.  This preserves NSW/NUW.
2843   if (Value *V = dyn_castNegVal(Op1)) {
2844     BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2845     Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2846     Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2847     return Res;
2848   }
2849
2850   if (isa<UndefValue>(Op0))
2851     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2852   if (isa<UndefValue>(Op1))
2853     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2854   if (I.getType() == Type::getInt1Ty(*Context))
2855     return BinaryOperator::CreateXor(Op0, Op1);
2856   
2857   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2858     // Replace (-1 - A) with (~A).
2859     if (C->isAllOnesValue())
2860       return BinaryOperator::CreateNot(Op1);
2861
2862     // C - ~X == X + (1+C)
2863     Value *X = 0;
2864     if (match(Op1, m_Not(m_Value(X))))
2865       return BinaryOperator::CreateAdd(X, AddOne(C));
2866
2867     // -(X >>u 31) -> (X >>s 31)
2868     // -(X >>s 31) -> (X >>u 31)
2869     if (C->isZero()) {
2870       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2871         if (SI->getOpcode() == Instruction::LShr) {
2872           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2873             // Check to see if we are shifting out everything but the sign bit.
2874             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2875                 SI->getType()->getPrimitiveSizeInBits()-1) {
2876               // Ok, the transformation is safe.  Insert AShr.
2877               return BinaryOperator::Create(Instruction::AShr, 
2878                                           SI->getOperand(0), CU, SI->getName());
2879             }
2880           }
2881         } else if (SI->getOpcode() == Instruction::AShr) {
2882           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2883             // Check to see if we are shifting out everything but the sign bit.
2884             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2885                 SI->getType()->getPrimitiveSizeInBits()-1) {
2886               // Ok, the transformation is safe.  Insert LShr. 
2887               return BinaryOperator::CreateLShr(
2888                                           SI->getOperand(0), CU, SI->getName());
2889             }
2890           }
2891         }
2892       }
2893     }
2894
2895     // Try to fold constant sub into select arguments.
2896     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2897       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2898         return R;
2899
2900     // C - zext(bool) -> bool ? C - 1 : C
2901     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2902       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2903         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2904   }
2905
2906   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2907     if (Op1I->getOpcode() == Instruction::Add) {
2908       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2909         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2910                                          I.getName());
2911       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2912         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2913                                          I.getName());
2914       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2915         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2916           // C1-(X+C2) --> (C1-C2)-X
2917           return BinaryOperator::CreateSub(
2918             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2919       }
2920     }
2921
2922     if (Op1I->hasOneUse()) {
2923       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2924       // is not used by anyone else...
2925       //
2926       if (Op1I->getOpcode() == Instruction::Sub) {
2927         // Swap the two operands of the subexpr...
2928         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2929         Op1I->setOperand(0, IIOp1);
2930         Op1I->setOperand(1, IIOp0);
2931
2932         // Create the new top level add instruction...
2933         return BinaryOperator::CreateAdd(Op0, Op1);
2934       }
2935
2936       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2937       //
2938       if (Op1I->getOpcode() == Instruction::And &&
2939           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2940         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2941
2942         Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2943         return BinaryOperator::CreateAnd(Op0, NewNot);
2944       }
2945
2946       // 0 - (X sdiv C)  -> (X sdiv -C)
2947       if (Op1I->getOpcode() == Instruction::SDiv)
2948         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2949           if (CSI->isZero())
2950             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2951               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2952                                           ConstantExpr::getNeg(DivRHS));
2953
2954       // X - X*C --> X * (1-C)
2955       ConstantInt *C2 = 0;
2956       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2957         Constant *CP1 = 
2958           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2959                                              C2);
2960         return BinaryOperator::CreateMul(Op0, CP1);
2961       }
2962     }
2963   }
2964
2965   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2966     if (Op0I->getOpcode() == Instruction::Add) {
2967       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2968         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2969       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2970         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2971     } else if (Op0I->getOpcode() == Instruction::Sub) {
2972       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2973         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2974                                          I.getName());
2975     }
2976   }
2977
2978   ConstantInt *C1;
2979   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2980     if (X == Op1)  // X*C - X --> X * (C-1)
2981       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2982
2983     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2984     if (X == dyn_castFoldableMul(Op1, C2))
2985       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2986   }
2987   
2988   // Optimize pointer differences into the same array into a size.  Consider:
2989   //  &A[10] - &A[0]: we should compile this to "10".
2990   if (TD) {
2991     Value *LHSOp, *RHSOp;
2992     if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2993         match(Op1, m_PtrToInt(m_Value(RHSOp))))
2994       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2995         return ReplaceInstUsesWith(I, Res);
2996     
2997     // trunc(p)-trunc(q) -> trunc(p-q)
2998     if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2999         match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
3000       if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
3001         return ReplaceInstUsesWith(I, Res);
3002   }
3003   
3004   return 0;
3005 }
3006
3007 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
3008   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3009
3010   // If this is a 'B = x-(-A)', change to B = x+A...
3011   if (Value *V = dyn_castFNegVal(Op1))
3012     return BinaryOperator::CreateFAdd(Op0, V);
3013
3014   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3015     if (Op1I->getOpcode() == Instruction::FAdd) {
3016       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
3017         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
3018                                           I.getName());
3019       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
3020         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
3021                                           I.getName());
3022     }
3023   }
3024
3025   return 0;
3026 }
3027
3028 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3029 /// comparison only checks the sign bit.  If it only checks the sign bit, set
3030 /// TrueIfSigned if the result of the comparison is true when the input value is
3031 /// signed.
3032 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3033                            bool &TrueIfSigned) {
3034   switch (pred) {
3035   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
3036     TrueIfSigned = true;
3037     return RHS->isZero();
3038   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
3039     TrueIfSigned = true;
3040     return RHS->isAllOnesValue();
3041   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
3042     TrueIfSigned = false;
3043     return RHS->isAllOnesValue();
3044   case ICmpInst::ICMP_UGT:
3045     // True if LHS u> RHS and RHS == high-bit-mask - 1
3046     TrueIfSigned = true;
3047     return RHS->getValue() ==
3048       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3049   case ICmpInst::ICMP_UGE: 
3050     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3051     TrueIfSigned = true;
3052     return RHS->getValue().isSignBit();
3053   default:
3054     return false;
3055   }
3056 }
3057
3058 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3059   bool Changed = SimplifyCommutative(I);
3060   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3061
3062   if (isa<UndefValue>(Op1))              // undef * X -> 0
3063     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3064
3065   // Simplify mul instructions with a constant RHS.
3066   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3067     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
3068
3069       // ((X << C1)*C2) == (X * (C2 << C1))
3070       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3071         if (SI->getOpcode() == Instruction::Shl)
3072           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3073             return BinaryOperator::CreateMul(SI->getOperand(0),
3074                                         ConstantExpr::getShl(CI, ShOp));
3075
3076       if (CI->isZero())
3077         return ReplaceInstUsesWith(I, Op1C);  // X * 0  == 0
3078       if (CI->equalsInt(1))                  // X * 1  == X
3079         return ReplaceInstUsesWith(I, Op0);
3080       if (CI->isAllOnesValue())              // X * -1 == 0 - X
3081         return BinaryOperator::CreateNeg(Op0, I.getName());
3082
3083       const APInt& Val = cast<ConstantInt>(CI)->getValue();
3084       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
3085         return BinaryOperator::CreateShl(Op0,
3086                  ConstantInt::get(Op0->getType(), Val.logBase2()));
3087       }
3088     } else if (isa<VectorType>(Op1C->getType())) {
3089       if (Op1C->isNullValue())
3090         return ReplaceInstUsesWith(I, Op1C);
3091
3092       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3093         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
3094           return BinaryOperator::CreateNeg(Op0, I.getName());
3095
3096         // As above, vector X*splat(1.0) -> X in all defined cases.
3097         if (Constant *Splat = Op1V->getSplatValue()) {
3098           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3099             if (CI->equalsInt(1))
3100               return ReplaceInstUsesWith(I, Op0);
3101         }
3102       }
3103     }
3104     
3105     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3106       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3107           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
3108         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3109         Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3110         Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
3111         return BinaryOperator::CreateAdd(Add, C1C2);
3112         
3113       }
3114
3115     // Try to fold constant mul into select arguments.
3116     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3117       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3118         return R;
3119
3120     if (isa<PHINode>(Op0))
3121       if (Instruction *NV = FoldOpIntoPhi(I))
3122         return NV;
3123   }
3124
3125   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3126     if (Value *Op1v = dyn_castNegVal(Op1))
3127       return BinaryOperator::CreateMul(Op0v, Op1v);
3128
3129   // (X / Y) *  Y = X - (X % Y)
3130   // (X / Y) * -Y = (X % Y) - X
3131   {
3132     Value *Op1C = Op1;
3133     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3134     if (!BO ||
3135         (BO->getOpcode() != Instruction::UDiv && 
3136          BO->getOpcode() != Instruction::SDiv)) {
3137       Op1C = Op0;
3138       BO = dyn_cast<BinaryOperator>(Op1);
3139     }
3140     Value *Neg = dyn_castNegVal(Op1C);
3141     if (BO && BO->hasOneUse() &&
3142         (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
3143         (BO->getOpcode() == Instruction::UDiv ||
3144          BO->getOpcode() == Instruction::SDiv)) {
3145       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3146
3147       // If the division is exact, X % Y is zero.
3148       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3149         if (SDiv->isExact()) {
3150           if (Op1BO == Op1C)
3151             return ReplaceInstUsesWith(I, Op0BO);
3152           return BinaryOperator::CreateNeg(Op0BO);
3153         }
3154
3155       Value *Rem;
3156       if (BO->getOpcode() == Instruction::UDiv)
3157         Rem = Builder->CreateURem(Op0BO, Op1BO);
3158       else
3159         Rem = Builder->CreateSRem(Op0BO, Op1BO);
3160       Rem->takeName(BO);
3161
3162       if (Op1BO == Op1C)
3163         return BinaryOperator::CreateSub(Op0BO, Rem);
3164       return BinaryOperator::CreateSub(Rem, Op0BO);
3165     }
3166   }
3167
3168   /// i1 mul -> i1 and.
3169   if (I.getType() == Type::getInt1Ty(*Context))
3170     return BinaryOperator::CreateAnd(Op0, Op1);
3171
3172   // X*(1 << Y) --> X << Y
3173   // (1 << Y)*X --> X << Y
3174   {
3175     Value *Y;
3176     if (match(Op0, m_Shl(m_One(), m_Value(Y))))
3177       return BinaryOperator::CreateShl(Op1, Y);
3178     if (match(Op1, m_Shl(m_One(), m_Value(Y))))
3179       return BinaryOperator::CreateShl(Op0, Y);
3180   }
3181   
3182   // If one of the operands of the multiply is a cast from a boolean value, then
3183   // we know the bool is either zero or one, so this is a 'masking' multiply.
3184   //   X * Y (where Y is 0 or 1) -> X & (0-Y)
3185   if (!isa<VectorType>(I.getType())) {
3186     // -2 is "-1 << 1" so it is all bits set except the low one.
3187     APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
3188     
3189     Value *BoolCast = 0, *OtherOp = 0;
3190     if (MaskedValueIsZero(Op0, Negative2))
3191       BoolCast = Op0, OtherOp = Op1;
3192     else if (MaskedValueIsZero(Op1, Negative2))
3193       BoolCast = Op1, OtherOp = Op0;
3194
3195     if (BoolCast) {
3196       Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3197                                     BoolCast, "tmp");
3198       return BinaryOperator::CreateAnd(V, OtherOp);
3199     }
3200   }
3201
3202   return Changed ? &I : 0;
3203 }
3204
3205 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3206   bool Changed = SimplifyCommutative(I);
3207   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3208
3209   // Simplify mul instructions with a constant RHS...
3210   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3211     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
3212       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3213       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3214       if (Op1F->isExactlyValue(1.0))
3215         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3216     } else if (isa<VectorType>(Op1C->getType())) {
3217       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
3218         // As above, vector X*splat(1.0) -> X in all defined cases.
3219         if (Constant *Splat = Op1V->getSplatValue()) {
3220           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3221             if (F->isExactlyValue(1.0))
3222               return ReplaceInstUsesWith(I, Op0);
3223         }
3224       }
3225     }
3226
3227     // Try to fold constant mul into select arguments.
3228     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3229       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3230         return R;
3231
3232     if (isa<PHINode>(Op0))
3233       if (Instruction *NV = FoldOpIntoPhi(I))
3234         return NV;
3235   }
3236
3237   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
3238     if (Value *Op1v = dyn_castFNegVal(Op1))
3239       return BinaryOperator::CreateFMul(Op0v, Op1v);
3240
3241   return Changed ? &I : 0;
3242 }
3243
3244 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3245 /// instruction.
3246 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3247   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3248   
3249   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3250   int NonNullOperand = -1;
3251   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3252     if (ST->isNullValue())
3253       NonNullOperand = 2;
3254   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3255   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3256     if (ST->isNullValue())
3257       NonNullOperand = 1;
3258   
3259   if (NonNullOperand == -1)
3260     return false;
3261   
3262   Value *SelectCond = SI->getOperand(0);
3263   
3264   // Change the div/rem to use 'Y' instead of the select.
3265   I.setOperand(1, SI->getOperand(NonNullOperand));
3266   
3267   // Okay, we know we replace the operand of the div/rem with 'Y' with no
3268   // problem.  However, the select, or the condition of the select may have
3269   // multiple uses.  Based on our knowledge that the operand must be non-zero,
3270   // propagate the known value for the select into other uses of it, and
3271   // propagate a known value of the condition into its other users.
3272   
3273   // If the select and condition only have a single use, don't bother with this,
3274   // early exit.
3275   if (SI->use_empty() && SelectCond->hasOneUse())
3276     return true;
3277   
3278   // Scan the current block backward, looking for other uses of SI.
3279   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3280   
3281   while (BBI != BBFront) {
3282     --BBI;
3283     // If we found a call to a function, we can't assume it will return, so
3284     // information from below it cannot be propagated above it.
3285     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3286       break;
3287     
3288     // Replace uses of the select or its condition with the known values.
3289     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3290          I != E; ++I) {
3291       if (*I == SI) {
3292         *I = SI->getOperand(NonNullOperand);
3293         Worklist.Add(BBI);
3294       } else if (*I == SelectCond) {
3295         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3296                                    ConstantInt::getFalse(*Context);
3297         Worklist.Add(BBI);
3298       }
3299     }
3300     
3301     // If we past the instruction, quit looking for it.
3302     if (&*BBI == SI)
3303       SI = 0;
3304     if (&*BBI == SelectCond)
3305       SelectCond = 0;
3306     
3307     // If we ran out of things to eliminate, break out of the loop.
3308     if (SelectCond == 0 && SI == 0)
3309       break;
3310     
3311   }
3312   return true;
3313 }
3314
3315
3316 /// This function implements the transforms on div instructions that work
3317 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3318 /// used by the visitors to those instructions.
3319 /// @brief Transforms common to all three div instructions
3320 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3321   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3322
3323   // undef / X -> 0        for integer.
3324   // undef / X -> undef    for FP (the undef could be a snan).
3325   if (isa<UndefValue>(Op0)) {
3326     if (Op0->getType()->isFPOrFPVector())
3327       return ReplaceInstUsesWith(I, Op0);
3328     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3329   }
3330
3331   // X / undef -> undef
3332   if (isa<UndefValue>(Op1))
3333     return ReplaceInstUsesWith(I, Op1);
3334
3335   return 0;
3336 }
3337
3338 /// This function implements the transforms common to both integer division
3339 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3340 /// division instructions.
3341 /// @brief Common integer divide transforms
3342 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3343   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3344
3345   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3346   if (Op0 == Op1) {
3347     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3348       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3349       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3350       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3351     }
3352
3353     Constant *CI = ConstantInt::get(I.getType(), 1);
3354     return ReplaceInstUsesWith(I, CI);
3355   }
3356   
3357   if (Instruction *Common = commonDivTransforms(I))
3358     return Common;
3359   
3360   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3361   // This does not apply for fdiv.
3362   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3363     return &I;
3364
3365   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3366     // div X, 1 == X
3367     if (RHS->equalsInt(1))
3368       return ReplaceInstUsesWith(I, Op0);
3369
3370     // (X / C1) / C2  -> X / (C1*C2)
3371     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3372       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3373         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3374           if (MultiplyOverflows(RHS, LHSRHS,
3375                                 I.getOpcode()==Instruction::SDiv))
3376             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3377           else 
3378             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3379                                       ConstantExpr::getMul(RHS, LHSRHS));
3380         }
3381
3382     if (!RHS->isZero()) { // avoid X udiv 0
3383       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3384         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3385           return R;
3386       if (isa<PHINode>(Op0))
3387         if (Instruction *NV = FoldOpIntoPhi(I))
3388           return NV;
3389     }
3390   }
3391
3392   // 0 / X == 0, we don't need to preserve faults!
3393   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3394     if (LHS->equalsInt(0))
3395       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3396
3397   // It can't be division by zero, hence it must be division by one.
3398   if (I.getType() == Type::getInt1Ty(*Context))
3399     return ReplaceInstUsesWith(I, Op0);
3400
3401   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3402     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3403       // div X, 1 == X
3404       if (X->isOne())
3405         return ReplaceInstUsesWith(I, Op0);
3406   }
3407
3408   return 0;
3409 }
3410
3411 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3412   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3413
3414   // Handle the integer div common cases
3415   if (Instruction *Common = commonIDivTransforms(I))
3416     return Common;
3417
3418   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3419     // X udiv C^2 -> X >> C
3420     // Check to see if this is an unsigned division with an exact power of 2,
3421     // if so, convert to a right shift.
3422     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3423       return BinaryOperator::CreateLShr(Op0, 
3424             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3425
3426     // X udiv C, where C >= signbit
3427     if (C->getValue().isNegative()) {
3428       Value *IC = Builder->CreateICmpULT( Op0, C);
3429       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3430                                 ConstantInt::get(I.getType(), 1));
3431     }
3432   }
3433
3434   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3435   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3436     if (RHSI->getOpcode() == Instruction::Shl &&
3437         isa<ConstantInt>(RHSI->getOperand(0))) {
3438       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3439       if (C1.isPowerOf2()) {
3440         Value *N = RHSI->getOperand(1);
3441         const Type *NTy = N->getType();
3442         if (uint32_t C2 = C1.logBase2())
3443           N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3444         return BinaryOperator::CreateLShr(Op0, N);
3445       }
3446     }
3447   }
3448   
3449   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3450   // where C1&C2 are powers of two.
3451   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3452     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3453       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3454         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3455         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3456           // Compute the shift amounts
3457           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3458           // Construct the "on true" case of the select
3459           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3460           Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3461   
3462           // Construct the "on false" case of the select
3463           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3464           Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3465
3466           // construct the select instruction and return it.
3467           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3468         }
3469       }
3470   return 0;
3471 }
3472
3473 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3474   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3475
3476   // Handle the integer div common cases
3477   if (Instruction *Common = commonIDivTransforms(I))
3478     return Common;
3479
3480   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3481     // sdiv X, -1 == -X
3482     if (RHS->isAllOnesValue())
3483       return BinaryOperator::CreateNeg(Op0);
3484
3485     // sdiv X, C  -->  ashr X, log2(C)
3486     if (cast<SDivOperator>(&I)->isExact() &&
3487         RHS->getValue().isNonNegative() &&
3488         RHS->getValue().isPowerOf2()) {
3489       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3490                                             RHS->getValue().exactLogBase2());
3491       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3492     }
3493
3494     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3495     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3496       if (isa<Constant>(Sub->getOperand(0)) &&
3497           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3498           Sub->hasNoSignedWrap())
3499         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3500                                           ConstantExpr::getNeg(RHS));
3501   }
3502
3503   // If the sign bits of both operands are zero (i.e. we can prove they are
3504   // unsigned inputs), turn this into a udiv.
3505   if (I.getType()->isInteger()) {
3506     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3507     if (MaskedValueIsZero(Op0, Mask)) {
3508       if (MaskedValueIsZero(Op1, Mask)) {
3509         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3510         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3511       }
3512       ConstantInt *ShiftedInt;
3513       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3514           ShiftedInt->getValue().isPowerOf2()) {
3515         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3516         // Safe because the only negative value (1 << Y) can take on is
3517         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3518         // the sign bit set.
3519         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3520       }
3521     }
3522   }
3523   
3524   return 0;
3525 }
3526
3527 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3528   return commonDivTransforms(I);
3529 }
3530
3531 /// This function implements the transforms on rem instructions that work
3532 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3533 /// is used by the visitors to those instructions.
3534 /// @brief Transforms common to all three rem instructions
3535 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3536   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3537
3538   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3539     if (I.getType()->isFPOrFPVector())
3540       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3541     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3542   }
3543   if (isa<UndefValue>(Op1))
3544     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3545
3546   // Handle cases involving: rem X, (select Cond, Y, Z)
3547   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3548     return &I;
3549
3550   return 0;
3551 }
3552
3553 /// This function implements the transforms common to both integer remainder
3554 /// instructions (urem and srem). It is called by the visitors to those integer
3555 /// remainder instructions.
3556 /// @brief Common integer remainder transforms
3557 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3558   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3559
3560   if (Instruction *common = commonRemTransforms(I))
3561     return common;
3562
3563   // 0 % X == 0 for integer, we don't need to preserve faults!
3564   if (Constant *LHS = dyn_cast<Constant>(Op0))
3565     if (LHS->isNullValue())
3566       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3567
3568   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3569     // X % 0 == undef, we don't need to preserve faults!
3570     if (RHS->equalsInt(0))
3571       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3572     
3573     if (RHS->equalsInt(1))  // X % 1 == 0
3574       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3575
3576     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3577       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3578         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3579           return R;
3580       } else if (isa<PHINode>(Op0I)) {
3581         if (Instruction *NV = FoldOpIntoPhi(I))
3582           return NV;
3583       }
3584
3585       // See if we can fold away this rem instruction.
3586       if (SimplifyDemandedInstructionBits(I))
3587         return &I;
3588     }
3589   }
3590
3591   return 0;
3592 }
3593
3594 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3595   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3596
3597   if (Instruction *common = commonIRemTransforms(I))
3598     return common;
3599   
3600   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3601     // X urem C^2 -> X and C
3602     // Check to see if this is an unsigned remainder with an exact power of 2,
3603     // if so, convert to a bitwise and.
3604     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3605       if (C->getValue().isPowerOf2())
3606         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3607   }
3608
3609   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3610     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3611     if (RHSI->getOpcode() == Instruction::Shl &&
3612         isa<ConstantInt>(RHSI->getOperand(0))) {
3613       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3614         Constant *N1 = Constant::getAllOnesValue(I.getType());
3615         Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3616         return BinaryOperator::CreateAnd(Op0, Add);
3617       }
3618     }
3619   }
3620
3621   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3622   // where C1&C2 are powers of two.
3623   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3624     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3625       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3626         // STO == 0 and SFO == 0 handled above.
3627         if ((STO->getValue().isPowerOf2()) && 
3628             (SFO->getValue().isPowerOf2())) {
3629           Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3630                                               SI->getName()+".t");
3631           Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3632                                                SI->getName()+".f");
3633           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3634         }
3635       }
3636   }
3637   
3638   return 0;
3639 }
3640
3641 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3642   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3643
3644   // Handle the integer rem common cases
3645   if (Instruction *Common = commonIRemTransforms(I))
3646     return Common;
3647   
3648   if (Value *RHSNeg = dyn_castNegVal(Op1))
3649     if (!isa<Constant>(RHSNeg) ||
3650         (isa<ConstantInt>(RHSNeg) &&
3651          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3652       // X % -Y -> X % Y
3653       Worklist.AddValue(I.getOperand(1));
3654       I.setOperand(1, RHSNeg);
3655       return &I;
3656     }
3657
3658   // If the sign bits of both operands are zero (i.e. we can prove they are
3659   // unsigned inputs), turn this into a urem.
3660   if (I.getType()->isInteger()) {
3661     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3662     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3663       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3664       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3665     }
3666   }
3667
3668   // If it's a constant vector, flip any negative values positive.
3669   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3670     unsigned VWidth = RHSV->getNumOperands();
3671
3672     bool hasNegative = false;
3673     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3674       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3675         if (RHS->getValue().isNegative())
3676           hasNegative = true;
3677
3678     if (hasNegative) {
3679       std::vector<Constant *> Elts(VWidth);
3680       for (unsigned i = 0; i != VWidth; ++i) {
3681         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3682           if (RHS->getValue().isNegative())
3683             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3684           else
3685             Elts[i] = RHS;
3686         }
3687       }
3688
3689       Constant *NewRHSV = ConstantVector::get(Elts);
3690       if (NewRHSV != RHSV) {
3691         Worklist.AddValue(I.getOperand(1));
3692         I.setOperand(1, NewRHSV);
3693         return &I;
3694       }
3695     }
3696   }
3697
3698   return 0;
3699 }
3700
3701 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3702   return commonRemTransforms(I);
3703 }
3704
3705 // isOneBitSet - Return true if there is exactly one bit set in the specified
3706 // constant.
3707 static bool isOneBitSet(const ConstantInt *CI) {
3708   return CI->getValue().isPowerOf2();
3709 }
3710
3711 // isHighOnes - Return true if the constant is of the form 1+0+.
3712 // This is the same as lowones(~X).
3713 static bool isHighOnes(const ConstantInt *CI) {
3714   return (~CI->getValue() + 1).isPowerOf2();
3715 }
3716
3717 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3718 /// are carefully arranged to allow folding of expressions such as:
3719 ///
3720 ///      (A < B) | (A > B) --> (A != B)
3721 ///
3722 /// Note that this is only valid if the first and second predicates have the
3723 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3724 ///
3725 /// Three bits are used to represent the condition, as follows:
3726 ///   0  A > B
3727 ///   1  A == B
3728 ///   2  A < B
3729 ///
3730 /// <=>  Value  Definition
3731 /// 000     0   Always false
3732 /// 001     1   A >  B
3733 /// 010     2   A == B
3734 /// 011     3   A >= B
3735 /// 100     4   A <  B
3736 /// 101     5   A != B
3737 /// 110     6   A <= B
3738 /// 111     7   Always true
3739 ///  
3740 static unsigned getICmpCode(const ICmpInst *ICI) {
3741   switch (ICI->getPredicate()) {
3742     // False -> 0
3743   case ICmpInst::ICMP_UGT: return 1;  // 001
3744   case ICmpInst::ICMP_SGT: return 1;  // 001
3745   case ICmpInst::ICMP_EQ:  return 2;  // 010
3746   case ICmpInst::ICMP_UGE: return 3;  // 011
3747   case ICmpInst::ICMP_SGE: return 3;  // 011
3748   case ICmpInst::ICMP_ULT: return 4;  // 100
3749   case ICmpInst::ICMP_SLT: return 4;  // 100
3750   case ICmpInst::ICMP_NE:  return 5;  // 101
3751   case ICmpInst::ICMP_ULE: return 6;  // 110
3752   case ICmpInst::ICMP_SLE: return 6;  // 110
3753     // True -> 7
3754   default:
3755     llvm_unreachable("Invalid ICmp predicate!");
3756     return 0;
3757   }
3758 }
3759
3760 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3761 /// predicate into a three bit mask. It also returns whether it is an ordered
3762 /// predicate by reference.
3763 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3764   isOrdered = false;
3765   switch (CC) {
3766   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3767   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3768   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3769   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3770   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3771   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3772   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3773   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3774   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3775   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3776   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3777   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3778   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3779   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3780     // True -> 7
3781   default:
3782     // Not expecting FCMP_FALSE and FCMP_TRUE;
3783     llvm_unreachable("Unexpected FCmp predicate!");
3784     return 0;
3785   }
3786 }
3787
3788 /// getICmpValue - This is the complement of getICmpCode, which turns an
3789 /// opcode and two operands into either a constant true or false, or a brand 
3790 /// new ICmp instruction. The sign is passed in to determine which kind
3791 /// of predicate to use in the new icmp instruction.
3792 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3793                            LLVMContext *Context) {
3794   switch (code) {
3795   default: llvm_unreachable("Illegal ICmp code!");
3796   case  0: return ConstantInt::getFalse(*Context);
3797   case  1: 
3798     if (sign)
3799       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3800     else
3801       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3802   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3803   case  3: 
3804     if (sign)
3805       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3806     else
3807       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3808   case  4: 
3809     if (sign)
3810       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3811     else
3812       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3813   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3814   case  6: 
3815     if (sign)
3816       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3817     else
3818       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3819   case  7: return ConstantInt::getTrue(*Context);
3820   }
3821 }
3822
3823 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3824 /// opcode and two operands into either a FCmp instruction. isordered is passed
3825 /// in to determine which kind of predicate to use in the new fcmp instruction.
3826 static Value *getFCmpValue(bool isordered, unsigned code,
3827                            Value *LHS, Value *RHS, LLVMContext *Context) {
3828   switch (code) {
3829   default: llvm_unreachable("Illegal FCmp code!");
3830   case  0:
3831     if (isordered)
3832       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3833     else
3834       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3835   case  1: 
3836     if (isordered)
3837       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3838     else
3839       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3840   case  2: 
3841     if (isordered)
3842       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3843     else
3844       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3845   case  3: 
3846     if (isordered)
3847       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3848     else
3849       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3850   case  4: 
3851     if (isordered)
3852       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3853     else
3854       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3855   case  5: 
3856     if (isordered)
3857       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3858     else
3859       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3860   case  6: 
3861     if (isordered)
3862       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3863     else
3864       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3865   case  7: return ConstantInt::getTrue(*Context);
3866   }
3867 }
3868
3869 /// PredicatesFoldable - Return true if both predicates match sign or if at
3870 /// least one of them is an equality comparison (which is signless).
3871 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3872   return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3873          (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3874          (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3875 }
3876
3877 namespace { 
3878 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3879 struct FoldICmpLogical {
3880   InstCombiner &IC;
3881   Value *LHS, *RHS;
3882   ICmpInst::Predicate pred;
3883   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3884     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3885       pred(ICI->getPredicate()) {}
3886   bool shouldApply(Value *V) const {
3887     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3888       if (PredicatesFoldable(pred, ICI->getPredicate()))
3889         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3890                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3891     return false;
3892   }
3893   Instruction *apply(Instruction &Log) const {
3894     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3895     if (ICI->getOperand(0) != LHS) {
3896       assert(ICI->getOperand(1) == LHS);
3897       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3898     }
3899
3900     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3901     unsigned LHSCode = getICmpCode(ICI);
3902     unsigned RHSCode = getICmpCode(RHSICI);
3903     unsigned Code;
3904     switch (Log.getOpcode()) {
3905     case Instruction::And: Code = LHSCode & RHSCode; break;
3906     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3907     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3908     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3909     }
3910
3911     bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3912     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3913     if (Instruction *I = dyn_cast<Instruction>(RV))
3914       return I;
3915     // Otherwise, it's a constant boolean value...
3916     return IC.ReplaceInstUsesWith(Log, RV);
3917   }
3918 };
3919 } // end anonymous namespace
3920
3921 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3922 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3923 // guaranteed to be a binary operator.
3924 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3925                                     ConstantInt *OpRHS,
3926                                     ConstantInt *AndRHS,
3927                                     BinaryOperator &TheAnd) {
3928   Value *X = Op->getOperand(0);
3929   Constant *Together = 0;
3930   if (!Op->isShift())
3931     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3932
3933   switch (Op->getOpcode()) {
3934   case Instruction::Xor:
3935     if (Op->hasOneUse()) {
3936       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3937       Value *And = Builder->CreateAnd(X, AndRHS);
3938       And->takeName(Op);
3939       return BinaryOperator::CreateXor(And, Together);
3940     }
3941     break;
3942   case Instruction::Or:
3943     if (Together == AndRHS) // (X | C) & C --> C
3944       return ReplaceInstUsesWith(TheAnd, AndRHS);
3945
3946     if (Op->hasOneUse() && Together != OpRHS) {
3947       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3948       Value *Or = Builder->CreateOr(X, Together);
3949       Or->takeName(Op);
3950       return BinaryOperator::CreateAnd(Or, AndRHS);
3951     }
3952     break;
3953   case Instruction::Add:
3954     if (Op->hasOneUse()) {
3955       // Adding a one to a single bit bit-field should be turned into an XOR
3956       // of the bit.  First thing to check is to see if this AND is with a
3957       // single bit constant.
3958       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3959
3960       // If there is only one bit set...
3961       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3962         // Ok, at this point, we know that we are masking the result of the
3963         // ADD down to exactly one bit.  If the constant we are adding has
3964         // no bits set below this bit, then we can eliminate the ADD.
3965         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3966
3967         // Check to see if any bits below the one bit set in AndRHSV are set.
3968         if ((AddRHS & (AndRHSV-1)) == 0) {
3969           // If not, the only thing that can effect the output of the AND is
3970           // the bit specified by AndRHSV.  If that bit is set, the effect of
3971           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3972           // no effect.
3973           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3974             TheAnd.setOperand(0, X);
3975             return &TheAnd;
3976           } else {
3977             // Pull the XOR out of the AND.
3978             Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3979             NewAnd->takeName(Op);
3980             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3981           }
3982         }
3983       }
3984     }
3985     break;
3986
3987   case Instruction::Shl: {
3988     // We know that the AND will not produce any of the bits shifted in, so if
3989     // the anded constant includes them, clear them now!
3990     //
3991     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3992     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3993     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3994     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3995
3996     if (CI->getValue() == ShlMask) { 
3997     // Masking out bits that the shift already masks
3998       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3999     } else if (CI != AndRHS) {                  // Reducing bits set in and.
4000       TheAnd.setOperand(1, CI);
4001       return &TheAnd;
4002     }
4003     break;
4004   }
4005   case Instruction::LShr:
4006   {
4007     // We know that the AND will not produce any of the bits shifted in, so if
4008     // the anded constant includes them, clear them now!  This only applies to
4009     // unsigned shifts, because a signed shr may bring in set bits!
4010     //
4011     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4012     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4013     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
4014     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
4015
4016     if (CI->getValue() == ShrMask) {   
4017     // Masking out bits that the shift already masks.
4018       return ReplaceInstUsesWith(TheAnd, Op);
4019     } else if (CI != AndRHS) {
4020       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
4021       return &TheAnd;
4022     }
4023     break;
4024   }
4025   case Instruction::AShr:
4026     // Signed shr.
4027     // See if this is shifting in some sign extension, then masking it out
4028     // with an and.
4029     if (Op->hasOneUse()) {
4030       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
4031       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
4032       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
4033       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
4034       if (C == AndRHS) {          // Masking out bits shifted in.
4035         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
4036         // Make the argument unsigned.
4037         Value *ShVal = Op->getOperand(0);
4038         ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
4039         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
4040       }
4041     }
4042     break;
4043   }
4044   return 0;
4045 }
4046
4047
4048 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4049 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
4050 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
4051 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
4052 /// insert new instructions.
4053 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
4054                                            bool isSigned, bool Inside, 
4055                                            Instruction &IB) {
4056   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
4057             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
4058          "Lo is not <= Hi in range emission code!");
4059     
4060   if (Inside) {
4061     if (Lo == Hi)  // Trivially false.
4062       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
4063
4064     // V >= Min && V < Hi --> V < Hi
4065     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4066       ICmpInst::Predicate pred = (isSigned ? 
4067         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
4068       return new ICmpInst(pred, V, Hi);
4069     }
4070
4071     // Emit V-Lo <u Hi-Lo
4072     Constant *NegLo = ConstantExpr::getNeg(Lo);
4073     Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
4074     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
4075     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
4076   }
4077
4078   if (Lo == Hi)  // Trivially true.
4079     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
4080
4081   // V < Min || V >= Hi -> V > Hi-1
4082   Hi = SubOne(cast<ConstantInt>(Hi));
4083   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
4084     ICmpInst::Predicate pred = (isSigned ? 
4085         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
4086     return new ICmpInst(pred, V, Hi);
4087   }
4088
4089   // Emit V-Lo >u Hi-1-Lo
4090   // Note that Hi has already had one subtracted from it, above.
4091   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
4092   Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
4093   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
4094   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
4095 }
4096
4097 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4098 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
4099 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
4100 // not, since all 1s are not contiguous.
4101 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
4102   const APInt& V = Val->getValue();
4103   uint32_t BitWidth = Val->getType()->getBitWidth();
4104   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
4105
4106   // look for the first zero bit after the run of ones
4107   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
4108   // look for the first non-zero bit
4109   ME = V.getActiveBits(); 
4110   return true;
4111 }
4112
4113 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4114 /// where isSub determines whether the operator is a sub.  If we can fold one of
4115 /// the following xforms:
4116 /// 
4117 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4118 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4119 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4120 ///
4121 /// return (A +/- B).
4122 ///
4123 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
4124                                         ConstantInt *Mask, bool isSub,
4125                                         Instruction &I) {
4126   Instruction *LHSI = dyn_cast<Instruction>(LHS);
4127   if (!LHSI || LHSI->getNumOperands() != 2 ||
4128       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4129
4130   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4131
4132   switch (LHSI->getOpcode()) {
4133   default: return 0;
4134   case Instruction::And:
4135     if (ConstantExpr::getAnd(N, Mask) == Mask) {
4136       // If the AndRHS is a power of two minus one (0+1+), this is simple.
4137       if ((Mask->getValue().countLeadingZeros() + 
4138            Mask->getValue().countPopulation()) == 
4139           Mask->getValue().getBitWidth())
4140         break;
4141
4142       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4143       // part, we don't need any explicit masks to take them out of A.  If that
4144       // is all N is, ignore it.
4145       uint32_t MB = 0, ME = 0;
4146       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
4147         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4148         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4149         if (MaskedValueIsZero(RHS, Mask))
4150           break;
4151       }
4152     }
4153     return 0;
4154   case Instruction::Or:
4155   case Instruction::Xor:
4156     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4157     if ((Mask->getValue().countLeadingZeros() + 
4158          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4159         && ConstantExpr::getAnd(N, Mask)->isNullValue())
4160       break;
4161     return 0;
4162   }
4163   
4164   if (isSub)
4165     return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4166   return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
4167 }
4168
4169 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4170 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4171                                           ICmpInst *LHS, ICmpInst *RHS) {
4172   Value *Val, *Val2;
4173   ConstantInt *LHSCst, *RHSCst;
4174   ICmpInst::Predicate LHSCC, RHSCC;
4175   
4176   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
4177   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4178                          m_ConstantInt(LHSCst))) ||
4179       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4180                          m_ConstantInt(RHSCst))))
4181     return 0;
4182   
4183   if (LHSCst == RHSCst && LHSCC == RHSCC) {
4184     // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4185     // where C is a power of 2
4186     if (LHSCC == ICmpInst::ICMP_ULT &&
4187         LHSCst->getValue().isPowerOf2()) {
4188       Value *NewOr = Builder->CreateOr(Val, Val2);
4189       return new ICmpInst(LHSCC, NewOr, LHSCst);
4190     }
4191     
4192     // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4193     if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4194       Value *NewOr = Builder->CreateOr(Val, Val2);
4195       return new ICmpInst(LHSCC, NewOr, LHSCst);
4196     }
4197   }
4198   
4199   // From here on, we only handle:
4200   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4201   if (Val != Val2) return 0;
4202   
4203   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4204   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4205       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4206       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4207       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4208     return 0;
4209   
4210   // We can't fold (ugt x, C) & (sgt x, C2).
4211   if (!PredicatesFoldable(LHSCC, RHSCC))
4212     return 0;
4213     
4214   // Ensure that the larger constant is on the RHS.
4215   bool ShouldSwap;
4216   if (CmpInst::isSigned(LHSCC) ||
4217       (ICmpInst::isEquality(LHSCC) && 
4218        CmpInst::isSigned(RHSCC)))
4219     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4220   else
4221     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4222     
4223   if (ShouldSwap) {
4224     std::swap(LHS, RHS);
4225     std::swap(LHSCst, RHSCst);
4226     std::swap(LHSCC, RHSCC);
4227   }
4228
4229   // At this point, we know we have have two icmp instructions
4230   // comparing a value against two constants and and'ing the result
4231   // together.  Because of the above check, we know that we only have
4232   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4233   // (from the FoldICmpLogical check above), that the two constants 
4234   // are not equal and that the larger constant is on the RHS
4235   assert(LHSCst != RHSCst && "Compares not folded above?");
4236
4237   switch (LHSCC) {
4238   default: llvm_unreachable("Unknown integer condition code!");
4239   case ICmpInst::ICMP_EQ:
4240     switch (RHSCC) {
4241     default: llvm_unreachable("Unknown integer condition code!");
4242     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4243     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4244     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4245       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4246     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4247     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4248     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4249       return ReplaceInstUsesWith(I, LHS);
4250     }
4251   case ICmpInst::ICMP_NE:
4252     switch (RHSCC) {
4253     default: llvm_unreachable("Unknown integer condition code!");
4254     case ICmpInst::ICMP_ULT:
4255       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4256         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
4257       break;                        // (X != 13 & X u< 15) -> no change
4258     case ICmpInst::ICMP_SLT:
4259       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4260         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
4261       break;                        // (X != 13 & X s< 15) -> no change
4262     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4263     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4264     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4265       return ReplaceInstUsesWith(I, RHS);
4266     case ICmpInst::ICMP_NE:
4267       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4268         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4269         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4270         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4271                             ConstantInt::get(Add->getType(), 1));
4272       }
4273       break;                        // (X != 13 & X != 15) -> no change
4274     }
4275     break;
4276   case ICmpInst::ICMP_ULT:
4277     switch (RHSCC) {
4278     default: llvm_unreachable("Unknown integer condition code!");
4279     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4280     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4281       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4282     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4283       break;
4284     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4285     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4286       return ReplaceInstUsesWith(I, LHS);
4287     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4288       break;
4289     }
4290     break;
4291   case ICmpInst::ICMP_SLT:
4292     switch (RHSCC) {
4293     default: llvm_unreachable("Unknown integer condition code!");
4294     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4295     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4296       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4297     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4298       break;
4299     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4300     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4301       return ReplaceInstUsesWith(I, LHS);
4302     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4303       break;
4304     }
4305     break;
4306   case ICmpInst::ICMP_UGT:
4307     switch (RHSCC) {
4308     default: llvm_unreachable("Unknown integer condition code!");
4309     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
4310     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4311       return ReplaceInstUsesWith(I, RHS);
4312     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4313       break;
4314     case ICmpInst::ICMP_NE:
4315       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4316         return new ICmpInst(LHSCC, Val, RHSCst);
4317       break;                        // (X u> 13 & X != 15) -> no change
4318     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
4319       return InsertRangeTest(Val, AddOne(LHSCst),
4320                              RHSCst, false, true, I);
4321     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4322       break;
4323     }
4324     break;
4325   case ICmpInst::ICMP_SGT:
4326     switch (RHSCC) {
4327     default: llvm_unreachable("Unknown integer condition code!");
4328     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4329     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4330       return ReplaceInstUsesWith(I, RHS);
4331     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4332       break;
4333     case ICmpInst::ICMP_NE:
4334       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4335         return new ICmpInst(LHSCC, Val, RHSCst);
4336       break;                        // (X s> 13 & X != 15) -> no change
4337     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
4338       return InsertRangeTest(Val, AddOne(LHSCst),
4339                              RHSCst, true, true, I);
4340     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4341       break;
4342     }
4343     break;
4344   }
4345  
4346   return 0;
4347 }
4348
4349 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4350                                           FCmpInst *RHS) {
4351   
4352   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4353       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4354     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4355     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4356       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4357         // If either of the constants are nans, then the whole thing returns
4358         // false.
4359         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4360           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4361         return new FCmpInst(FCmpInst::FCMP_ORD,
4362                             LHS->getOperand(0), RHS->getOperand(0));
4363       }
4364     
4365     // Handle vector zeros.  This occurs because the canonical form of
4366     // "fcmp ord x,x" is "fcmp ord x, 0".
4367     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4368         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4369       return new FCmpInst(FCmpInst::FCMP_ORD,
4370                           LHS->getOperand(0), RHS->getOperand(0));
4371     return 0;
4372   }
4373   
4374   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4375   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4376   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4377   
4378   
4379   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4380     // Swap RHS operands to match LHS.
4381     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4382     std::swap(Op1LHS, Op1RHS);
4383   }
4384   
4385   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4386     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4387     if (Op0CC == Op1CC)
4388       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4389     
4390     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4391       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4392     if (Op0CC == FCmpInst::FCMP_TRUE)
4393       return ReplaceInstUsesWith(I, RHS);
4394     if (Op1CC == FCmpInst::FCMP_TRUE)
4395       return ReplaceInstUsesWith(I, LHS);
4396     
4397     bool Op0Ordered;
4398     bool Op1Ordered;
4399     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4400     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4401     if (Op1Pred == 0) {
4402       std::swap(LHS, RHS);
4403       std::swap(Op0Pred, Op1Pred);
4404       std::swap(Op0Ordered, Op1Ordered);
4405     }
4406     if (Op0Pred == 0) {
4407       // uno && ueq -> uno && (uno || eq) -> ueq
4408       // ord && olt -> ord && (ord && lt) -> olt
4409       if (Op0Ordered == Op1Ordered)
4410         return ReplaceInstUsesWith(I, RHS);
4411       
4412       // uno && oeq -> uno && (ord && eq) -> false
4413       // uno && ord -> false
4414       if (!Op0Ordered)
4415         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4416       // ord && ueq -> ord && (uno || eq) -> oeq
4417       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4418                                             Op0LHS, Op0RHS, Context));
4419     }
4420   }
4421
4422   return 0;
4423 }
4424
4425
4426 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4427   bool Changed = SimplifyCommutative(I);
4428   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4429
4430   if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4431     return ReplaceInstUsesWith(I, V);
4432
4433   // See if we can simplify any instructions used by the instruction whose sole 
4434   // purpose is to compute bits we don't care about.
4435   if (SimplifyDemandedInstructionBits(I))
4436     return &I;  
4437
4438   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4439     const APInt &AndRHSMask = AndRHS->getValue();
4440     APInt NotAndRHS(~AndRHSMask);
4441
4442     // Optimize a variety of ((val OP C1) & C2) combinations...
4443     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4444       Value *Op0LHS = Op0I->getOperand(0);
4445       Value *Op0RHS = Op0I->getOperand(1);
4446       switch (Op0I->getOpcode()) {
4447       default: break;
4448       case Instruction::Xor:
4449       case Instruction::Or:
4450         // If the mask is only needed on one incoming arm, push it up.
4451         if (!Op0I->hasOneUse()) break;
4452           
4453         if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4454           // Not masking anything out for the LHS, move to RHS.
4455           Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4456                                              Op0RHS->getName()+".masked");
4457           return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4458         }
4459         if (!isa<Constant>(Op0RHS) &&
4460             MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4461           // Not masking anything out for the RHS, move to LHS.
4462           Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4463                                              Op0LHS->getName()+".masked");
4464           return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4465         }
4466
4467         break;
4468       case Instruction::Add:
4469         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4470         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4471         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4472         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4473           return BinaryOperator::CreateAnd(V, AndRHS);
4474         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4475           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4476         break;
4477
4478       case Instruction::Sub:
4479         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4480         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4481         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4482         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4483           return BinaryOperator::CreateAnd(V, AndRHS);
4484
4485         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4486         // has 1's for all bits that the subtraction with A might affect.
4487         if (Op0I->hasOneUse()) {
4488           uint32_t BitWidth = AndRHSMask.getBitWidth();
4489           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4490           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4491
4492           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4493           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4494               MaskedValueIsZero(Op0LHS, Mask)) {
4495             Value *NewNeg = Builder->CreateNeg(Op0RHS);
4496             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4497           }
4498         }
4499         break;
4500
4501       case Instruction::Shl:
4502       case Instruction::LShr:
4503         // (1 << x) & 1 --> zext(x == 0)
4504         // (1 >> x) & 1 --> zext(x == 0)
4505         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4506           Value *NewICmp =
4507             Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4508           return new ZExtInst(NewICmp, I.getType());
4509         }
4510         break;
4511       }
4512
4513       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4514         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4515           return Res;
4516     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4517       // If this is an integer truncation or change from signed-to-unsigned, and
4518       // if the source is an and/or with immediate, transform it.  This
4519       // frequently occurs for bitfield accesses.
4520       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4521         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4522             CastOp->getNumOperands() == 2)
4523           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4524             if (CastOp->getOpcode() == Instruction::And) {
4525               // Change: and (cast (and X, C1) to T), C2
4526               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4527               // This will fold the two constants together, which may allow 
4528               // other simplifications.
4529               Value *NewCast = Builder->CreateTruncOrBitCast(
4530                 CastOp->getOperand(0), I.getType(), 
4531                 CastOp->getName()+".shrunk");
4532               // trunc_or_bitcast(C1)&C2
4533               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4534               C3 = ConstantExpr::getAnd(C3, AndRHS);
4535               return BinaryOperator::CreateAnd(NewCast, C3);
4536             } else if (CastOp->getOpcode() == Instruction::Or) {
4537               // Change: and (cast (or X, C1) to T), C2
4538               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4539               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4540               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4541                 // trunc(C1)&C2
4542                 return ReplaceInstUsesWith(I, AndRHS);
4543             }
4544           }
4545       }
4546     }
4547
4548     // Try to fold constant and into select arguments.
4549     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4550       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4551         return R;
4552     if (isa<PHINode>(Op0))
4553       if (Instruction *NV = FoldOpIntoPhi(I))
4554         return NV;
4555   }
4556
4557
4558   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4559   if (Value *Op0NotVal = dyn_castNotVal(Op0))
4560     if (Value *Op1NotVal = dyn_castNotVal(Op1))
4561       if (Op0->hasOneUse() && Op1->hasOneUse()) {
4562         Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4563                                       I.getName()+".demorgan");
4564         return BinaryOperator::CreateNot(Or);
4565       }
4566
4567   {
4568     Value *A = 0, *B = 0, *C = 0, *D = 0;
4569     // (A|B) & ~(A&B) -> A^B
4570     if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4571         match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4572         ((A == C && B == D) || (A == D && B == C)))
4573       return BinaryOperator::CreateXor(A, B);
4574     
4575     // ~(A&B) & (A|B) -> A^B
4576     if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4577         match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4578         ((A == C && B == D) || (A == D && B == C)))
4579       return BinaryOperator::CreateXor(A, B);
4580     
4581     if (Op0->hasOneUse() &&
4582         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4583       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4584         I.swapOperands();     // Simplify below
4585         std::swap(Op0, Op1);
4586       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4587         cast<BinaryOperator>(Op0)->swapOperands();
4588         I.swapOperands();     // Simplify below
4589         std::swap(Op0, Op1);
4590       }
4591     }
4592
4593     if (Op1->hasOneUse() &&
4594         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4595       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4596         cast<BinaryOperator>(Op1)->swapOperands();
4597         std::swap(A, B);
4598       }
4599       if (A == Op0)                                // A&(A^B) -> A & ~B
4600         return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4601     }
4602
4603     // (A&((~A)|B)) -> A&B
4604     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4605         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4606       return BinaryOperator::CreateAnd(A, Op1);
4607     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4608         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4609       return BinaryOperator::CreateAnd(A, Op0);
4610   }
4611   
4612   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4613     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4614     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4615       return R;
4616
4617     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4618       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4619         return Res;
4620   }
4621
4622   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4623   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4624     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4625       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4626         const Type *SrcTy = Op0C->getOperand(0)->getType();
4627         if (SrcTy == Op1C->getOperand(0)->getType() &&
4628             SrcTy->isIntOrIntVector() &&
4629             // Only do this if the casts both really cause code to be generated.
4630             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4631                               I.getType(), TD) &&
4632             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4633                               I.getType(), TD)) {
4634           Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4635                                             Op1C->getOperand(0), I.getName());
4636           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4637         }
4638       }
4639     
4640   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4641   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4642     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4643       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4644           SI0->getOperand(1) == SI1->getOperand(1) &&
4645           (SI0->hasOneUse() || SI1->hasOneUse())) {
4646         Value *NewOp =
4647           Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4648                              SI0->getName());
4649         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4650                                       SI1->getOperand(1));
4651       }
4652   }
4653
4654   // If and'ing two fcmp, try combine them into one.
4655   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4656     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4657       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4658         return Res;
4659   }
4660
4661   return Changed ? &I : 0;
4662 }
4663
4664 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4665 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4666 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4667 /// the expression came from the corresponding "byte swapped" byte in some other
4668 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4669 /// we know that the expression deposits the low byte of %X into the high byte
4670 /// of the bswap result and that all other bytes are zero.  This expression is
4671 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4672 /// match.
4673 ///
4674 /// This function returns true if the match was unsuccessful and false if so.
4675 /// On entry to the function the "OverallLeftShift" is a signed integer value
4676 /// indicating the number of bytes that the subexpression is later shifted.  For
4677 /// example, if the expression is later right shifted by 16 bits, the
4678 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4679 /// byte of ByteValues is actually being set.
4680 ///
4681 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4682 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4683 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4684 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4685 /// always in the local (OverallLeftShift) coordinate space.
4686 ///
4687 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4688                               SmallVector<Value*, 8> &ByteValues) {
4689   if (Instruction *I = dyn_cast<Instruction>(V)) {
4690     // If this is an or instruction, it may be an inner node of the bswap.
4691     if (I->getOpcode() == Instruction::Or) {
4692       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4693                                ByteValues) ||
4694              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4695                                ByteValues);
4696     }
4697   
4698     // If this is a logical shift by a constant multiple of 8, recurse with
4699     // OverallLeftShift and ByteMask adjusted.
4700     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4701       unsigned ShAmt = 
4702         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4703       // Ensure the shift amount is defined and of a byte value.
4704       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4705         return true;
4706
4707       unsigned ByteShift = ShAmt >> 3;
4708       if (I->getOpcode() == Instruction::Shl) {
4709         // X << 2 -> collect(X, +2)
4710         OverallLeftShift += ByteShift;
4711         ByteMask >>= ByteShift;
4712       } else {
4713         // X >>u 2 -> collect(X, -2)
4714         OverallLeftShift -= ByteShift;
4715         ByteMask <<= ByteShift;
4716         ByteMask &= (~0U >> (32-ByteValues.size()));
4717       }
4718
4719       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4720       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4721
4722       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4723                                ByteValues);
4724     }
4725
4726     // If this is a logical 'and' with a mask that clears bytes, clear the
4727     // corresponding bytes in ByteMask.
4728     if (I->getOpcode() == Instruction::And &&
4729         isa<ConstantInt>(I->getOperand(1))) {
4730       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4731       unsigned NumBytes = ByteValues.size();
4732       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4733       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4734       
4735       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4736         // If this byte is masked out by a later operation, we don't care what
4737         // the and mask is.
4738         if ((ByteMask & (1 << i)) == 0)
4739           continue;
4740         
4741         // If the AndMask is all zeros for this byte, clear the bit.
4742         APInt MaskB = AndMask & Byte;
4743         if (MaskB == 0) {
4744           ByteMask &= ~(1U << i);
4745           continue;
4746         }
4747         
4748         // If the AndMask is not all ones for this byte, it's not a bytezap.
4749         if (MaskB != Byte)
4750           return true;
4751
4752         // Otherwise, this byte is kept.
4753       }
4754
4755       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4756                                ByteValues);
4757     }
4758   }
4759   
4760   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4761   // the input value to the bswap.  Some observations: 1) if more than one byte
4762   // is demanded from this input, then it could not be successfully assembled
4763   // into a byteswap.  At least one of the two bytes would not be aligned with
4764   // their ultimate destination.
4765   if (!isPowerOf2_32(ByteMask)) return true;
4766   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4767   
4768   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4769   // is demanded, it needs to go into byte 0 of the result.  This means that the
4770   // byte needs to be shifted until it lands in the right byte bucket.  The
4771   // shift amount depends on the position: if the byte is coming from the high
4772   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4773   // low part, it must be shifted left.
4774   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4775   if (InputByteNo < ByteValues.size()/2) {
4776     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4777       return true;
4778   } else {
4779     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4780       return true;
4781   }
4782   
4783   // If the destination byte value is already defined, the values are or'd
4784   // together, which isn't a bswap (unless it's an or of the same bits).
4785   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4786     return true;
4787   ByteValues[DestByteNo] = V;
4788   return false;
4789 }
4790
4791 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4792 /// If so, insert the new bswap intrinsic and return it.
4793 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4794   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4795   if (!ITy || ITy->getBitWidth() % 16 || 
4796       // ByteMask only allows up to 32-byte values.
4797       ITy->getBitWidth() > 32*8) 
4798     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4799   
4800   /// ByteValues - For each byte of the result, we keep track of which value
4801   /// defines each byte.
4802   SmallVector<Value*, 8> ByteValues;
4803   ByteValues.resize(ITy->getBitWidth()/8);
4804     
4805   // Try to find all the pieces corresponding to the bswap.
4806   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4807   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4808     return 0;
4809   
4810   // Check to see if all of the bytes come from the same value.
4811   Value *V = ByteValues[0];
4812   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4813   
4814   // Check to make sure that all of the bytes come from the same value.
4815   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4816     if (ByteValues[i] != V)
4817       return 0;
4818   const Type *Tys[] = { ITy };
4819   Module *M = I.getParent()->getParent()->getParent();
4820   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4821   return CallInst::Create(F, V);
4822 }
4823
4824 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4825 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4826 /// we can simplify this expression to "cond ? C : D or B".
4827 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4828                                          Value *C, Value *D,
4829                                          LLVMContext *Context) {
4830   // If A is not a select of -1/0, this cannot match.
4831   Value *Cond = 0;
4832   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4833     return 0;
4834
4835   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4836   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4837     return SelectInst::Create(Cond, C, B);
4838   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4839     return SelectInst::Create(Cond, C, B);
4840   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4841   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4842     return SelectInst::Create(Cond, C, D);
4843   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4844     return SelectInst::Create(Cond, C, D);
4845   return 0;
4846 }
4847
4848 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4849 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4850                                          ICmpInst *LHS, ICmpInst *RHS) {
4851   Value *Val, *Val2;
4852   ConstantInt *LHSCst, *RHSCst;
4853   ICmpInst::Predicate LHSCC, RHSCC;
4854   
4855   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4856   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4857       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4858     return 0;
4859
4860   
4861   // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4862   if (LHSCst == RHSCst && LHSCC == RHSCC &&
4863       LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4864     Value *NewOr = Builder->CreateOr(Val, Val2);
4865     return new ICmpInst(LHSCC, NewOr, LHSCst);
4866   }
4867   
4868   // From here on, we only handle:
4869   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4870   if (Val != Val2) return 0;
4871   
4872   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4873   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4874       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4875       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4876       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4877     return 0;
4878   
4879   // We can't fold (ugt x, C) | (sgt x, C2).
4880   if (!PredicatesFoldable(LHSCC, RHSCC))
4881     return 0;
4882   
4883   // Ensure that the larger constant is on the RHS.
4884   bool ShouldSwap;
4885   if (CmpInst::isSigned(LHSCC) ||
4886       (ICmpInst::isEquality(LHSCC) && 
4887        CmpInst::isSigned(RHSCC)))
4888     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4889   else
4890     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4891   
4892   if (ShouldSwap) {
4893     std::swap(LHS, RHS);
4894     std::swap(LHSCst, RHSCst);
4895     std::swap(LHSCC, RHSCC);
4896   }
4897   
4898   // At this point, we know we have have two icmp instructions
4899   // comparing a value against two constants and or'ing the result
4900   // together.  Because of the above check, we know that we only have
4901   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4902   // FoldICmpLogical check above), that the two constants are not
4903   // equal.
4904   assert(LHSCst != RHSCst && "Compares not folded above?");
4905
4906   switch (LHSCC) {
4907   default: llvm_unreachable("Unknown integer condition code!");
4908   case ICmpInst::ICMP_EQ:
4909     switch (RHSCC) {
4910     default: llvm_unreachable("Unknown integer condition code!");
4911     case ICmpInst::ICMP_EQ:
4912       if (LHSCst == SubOne(RHSCst)) {
4913         // (X == 13 | X == 14) -> X-13 <u 2
4914         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4915         Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4916         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4917         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4918       }
4919       break;                         // (X == 13 | X == 15) -> no change
4920     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4921     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4922       break;
4923     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4924     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4925     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4926       return ReplaceInstUsesWith(I, RHS);
4927     }
4928     break;
4929   case ICmpInst::ICMP_NE:
4930     switch (RHSCC) {
4931     default: llvm_unreachable("Unknown integer condition code!");
4932     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4933     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4934     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4935       return ReplaceInstUsesWith(I, LHS);
4936     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4937     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4938     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4939       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4940     }
4941     break;
4942   case ICmpInst::ICMP_ULT:
4943     switch (RHSCC) {
4944     default: llvm_unreachable("Unknown integer condition code!");
4945     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4946       break;
4947     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4948       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4949       // this can cause overflow.
4950       if (RHSCst->isMaxValue(false))
4951         return ReplaceInstUsesWith(I, LHS);
4952       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4953                              false, false, I);
4954     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4955       break;
4956     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4957     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4958       return ReplaceInstUsesWith(I, RHS);
4959     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4960       break;
4961     }
4962     break;
4963   case ICmpInst::ICMP_SLT:
4964     switch (RHSCC) {
4965     default: llvm_unreachable("Unknown integer condition code!");
4966     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4967       break;
4968     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4969       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4970       // this can cause overflow.
4971       if (RHSCst->isMaxValue(true))
4972         return ReplaceInstUsesWith(I, LHS);
4973       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4974                              true, false, I);
4975     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4976       break;
4977     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4978     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4979       return ReplaceInstUsesWith(I, RHS);
4980     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4981       break;
4982     }
4983     break;
4984   case ICmpInst::ICMP_UGT:
4985     switch (RHSCC) {
4986     default: llvm_unreachable("Unknown integer condition code!");
4987     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4988     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4989       return ReplaceInstUsesWith(I, LHS);
4990     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4991       break;
4992     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4993     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4994       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4995     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4996       break;
4997     }
4998     break;
4999   case ICmpInst::ICMP_SGT:
5000     switch (RHSCC) {
5001     default: llvm_unreachable("Unknown integer condition code!");
5002     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
5003     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
5004       return ReplaceInstUsesWith(I, LHS);
5005     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
5006       break;
5007     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
5008     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
5009       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5010     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
5011       break;
5012     }
5013     break;
5014   }
5015   return 0;
5016 }
5017
5018 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5019                                          FCmpInst *RHS) {
5020   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5021       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
5022       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5023     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5024       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5025         // If either of the constants are nans, then the whole thing returns
5026         // true.
5027         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
5028           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5029         
5030         // Otherwise, no need to compare the two constants, compare the
5031         // rest.
5032         return new FCmpInst(FCmpInst::FCMP_UNO,
5033                             LHS->getOperand(0), RHS->getOperand(0));
5034       }
5035     
5036     // Handle vector zeros.  This occurs because the canonical form of
5037     // "fcmp uno x,x" is "fcmp uno x, 0".
5038     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5039         isa<ConstantAggregateZero>(RHS->getOperand(1)))
5040       return new FCmpInst(FCmpInst::FCMP_UNO,
5041                           LHS->getOperand(0), RHS->getOperand(0));
5042     
5043     return 0;
5044   }
5045   
5046   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5047   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5048   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5049   
5050   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5051     // Swap RHS operands to match LHS.
5052     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5053     std::swap(Op1LHS, Op1RHS);
5054   }
5055   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5056     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5057     if (Op0CC == Op1CC)
5058       return new FCmpInst((FCmpInst::Predicate)Op0CC,
5059                           Op0LHS, Op0RHS);
5060     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
5061       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5062     if (Op0CC == FCmpInst::FCMP_FALSE)
5063       return ReplaceInstUsesWith(I, RHS);
5064     if (Op1CC == FCmpInst::FCMP_FALSE)
5065       return ReplaceInstUsesWith(I, LHS);
5066     bool Op0Ordered;
5067     bool Op1Ordered;
5068     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5069     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5070     if (Op0Ordered == Op1Ordered) {
5071       // If both are ordered or unordered, return a new fcmp with
5072       // or'ed predicates.
5073       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5074                                Op0LHS, Op0RHS, Context);
5075       if (Instruction *I = dyn_cast<Instruction>(RV))
5076         return I;
5077       // Otherwise, it's a constant boolean value...
5078       return ReplaceInstUsesWith(I, RV);
5079     }
5080   }
5081   return 0;
5082 }
5083
5084 /// FoldOrWithConstants - This helper function folds:
5085 ///
5086 ///     ((A | B) & C1) | (B & C2)
5087 ///
5088 /// into:
5089 /// 
5090 ///     (A & C1) | B
5091 ///
5092 /// when the XOR of the two constants is "all ones" (-1).
5093 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
5094                                                Value *A, Value *B, Value *C) {
5095   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5096   if (!CI1) return 0;
5097
5098   Value *V1 = 0;
5099   ConstantInt *CI2 = 0;
5100   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
5101
5102   APInt Xor = CI1->getValue() ^ CI2->getValue();
5103   if (!Xor.isAllOnesValue()) return 0;
5104
5105   if (V1 == A || V1 == B) {
5106     Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
5107     return BinaryOperator::CreateOr(NewOp, V1);
5108   }
5109
5110   return 0;
5111 }
5112
5113 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
5114   bool Changed = SimplifyCommutative(I);
5115   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5116
5117   if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5118     return ReplaceInstUsesWith(I, V);
5119   
5120   
5121   // See if we can simplify any instructions used by the instruction whose sole 
5122   // purpose is to compute bits we don't care about.
5123   if (SimplifyDemandedInstructionBits(I))
5124     return &I;
5125
5126   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5127     ConstantInt *C1 = 0; Value *X = 0;
5128     // (X & C1) | C2 --> (X | C2) & (C1|C2)
5129     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
5130         isOnlyUse(Op0)) {
5131       Value *Or = Builder->CreateOr(X, RHS);
5132       Or->takeName(Op0);
5133       return BinaryOperator::CreateAnd(Or, 
5134                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
5135     }
5136
5137     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
5138     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
5139         isOnlyUse(Op0)) {
5140       Value *Or = Builder->CreateOr(X, RHS);
5141       Or->takeName(Op0);
5142       return BinaryOperator::CreateXor(Or,
5143                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
5144     }
5145
5146     // Try to fold constant and into select arguments.
5147     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5148       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5149         return R;
5150     if (isa<PHINode>(Op0))
5151       if (Instruction *NV = FoldOpIntoPhi(I))
5152         return NV;
5153   }
5154
5155   Value *A = 0, *B = 0;
5156   ConstantInt *C1 = 0, *C2 = 0;
5157
5158   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
5159   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
5160   if (match(Op0, m_Or(m_Value(), m_Value())) ||
5161       match(Op1, m_Or(m_Value(), m_Value())) ||
5162       (match(Op0, m_Shift(m_Value(), m_Value())) &&
5163        match(Op1, m_Shift(m_Value(), m_Value())))) {
5164     if (Instruction *BSwap = MatchBSwap(I))
5165       return BSwap;
5166   }
5167   
5168   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
5169   if (Op0->hasOneUse() &&
5170       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5171       MaskedValueIsZero(Op1, C1->getValue())) {
5172     Value *NOr = Builder->CreateOr(A, Op1);
5173     NOr->takeName(Op0);
5174     return BinaryOperator::CreateXor(NOr, C1);
5175   }
5176
5177   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
5178   if (Op1->hasOneUse() &&
5179       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
5180       MaskedValueIsZero(Op0, C1->getValue())) {
5181     Value *NOr = Builder->CreateOr(A, Op0);
5182     NOr->takeName(Op0);
5183     return BinaryOperator::CreateXor(NOr, C1);
5184   }
5185
5186   // (A & C)|(B & D)
5187   Value *C = 0, *D = 0;
5188   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5189       match(Op1, m_And(m_Value(B), m_Value(D)))) {
5190     Value *V1 = 0, *V2 = 0, *V3 = 0;
5191     C1 = dyn_cast<ConstantInt>(C);
5192     C2 = dyn_cast<ConstantInt>(D);
5193     if (C1 && C2) {  // (A & C1)|(B & C2)
5194       // If we have: ((V + N) & C1) | (V & C2)
5195       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5196       // replace with V+N.
5197       if (C1->getValue() == ~C2->getValue()) {
5198         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
5199             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
5200           // Add commutes, try both ways.
5201           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5202             return ReplaceInstUsesWith(I, A);
5203           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5204             return ReplaceInstUsesWith(I, A);
5205         }
5206         // Or commutes, try both ways.
5207         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
5208             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
5209           // Add commutes, try both ways.
5210           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5211             return ReplaceInstUsesWith(I, B);
5212           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5213             return ReplaceInstUsesWith(I, B);
5214         }
5215       }
5216       V1 = 0; V2 = 0; V3 = 0;
5217     }
5218     
5219     // Check to see if we have any common things being and'ed.  If so, find the
5220     // terms for V1 & (V2|V3).
5221     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5222       if (A == B)      // (A & C)|(A & D) == A & (C|D)
5223         V1 = A, V2 = C, V3 = D;
5224       else if (A == D) // (A & C)|(B & A) == A & (B|C)
5225         V1 = A, V2 = B, V3 = C;
5226       else if (C == B) // (A & C)|(C & D) == C & (A|D)
5227         V1 = C, V2 = A, V3 = D;
5228       else if (C == D) // (A & C)|(B & C) == C & (A|B)
5229         V1 = C, V2 = A, V3 = B;
5230       
5231       if (V1) {
5232         Value *Or = Builder->CreateOr(V2, V3, "tmp");
5233         return BinaryOperator::CreateAnd(V1, Or);
5234       }
5235     }
5236
5237     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
5238     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
5239       return Match;
5240     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
5241       return Match;
5242     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
5243       return Match;
5244     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
5245       return Match;
5246
5247     // ((A&~B)|(~A&B)) -> A^B
5248     if ((match(C, m_Not(m_Specific(D))) &&
5249          match(B, m_Not(m_Specific(A)))))
5250       return BinaryOperator::CreateXor(A, D);
5251     // ((~B&A)|(~A&B)) -> A^B
5252     if ((match(A, m_Not(m_Specific(D))) &&
5253          match(B, m_Not(m_Specific(C)))))
5254       return BinaryOperator::CreateXor(C, D);
5255     // ((A&~B)|(B&~A)) -> A^B
5256     if ((match(C, m_Not(m_Specific(B))) &&
5257          match(D, m_Not(m_Specific(A)))))
5258       return BinaryOperator::CreateXor(A, B);
5259     // ((~B&A)|(B&~A)) -> A^B
5260     if ((match(A, m_Not(m_Specific(B))) &&
5261          match(D, m_Not(m_Specific(C)))))
5262       return BinaryOperator::CreateXor(C, B);
5263   }
5264   
5265   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
5266   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5267     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5268       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
5269           SI0->getOperand(1) == SI1->getOperand(1) &&
5270           (SI0->hasOneUse() || SI1->hasOneUse())) {
5271         Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5272                                          SI0->getName());
5273         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
5274                                       SI1->getOperand(1));
5275       }
5276   }
5277
5278   // ((A|B)&1)|(B&-2) -> (A&1) | B
5279   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5280       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5281     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
5282     if (Ret) return Ret;
5283   }
5284   // (B&-2)|((A|B)&1) -> (A&1) | B
5285   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5286       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
5287     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
5288     if (Ret) return Ret;
5289   }
5290
5291   // (~A | ~B) == (~(A & B)) - De Morgan's Law
5292   if (Value *Op0NotVal = dyn_castNotVal(Op0))
5293     if (Value *Op1NotVal = dyn_castNotVal(Op1))
5294       if (Op0->hasOneUse() && Op1->hasOneUse()) {
5295         Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5296                                         I.getName()+".demorgan");
5297         return BinaryOperator::CreateNot(And);
5298       }
5299
5300   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5301   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5302     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5303       return R;
5304
5305     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5306       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5307         return Res;
5308   }
5309     
5310   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5311   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5312     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5313       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5314         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5315             !isa<ICmpInst>(Op1C->getOperand(0))) {
5316           const Type *SrcTy = Op0C->getOperand(0)->getType();
5317           if (SrcTy == Op1C->getOperand(0)->getType() &&
5318               SrcTy->isIntOrIntVector() &&
5319               // Only do this if the casts both really cause code to be
5320               // generated.
5321               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5322                                 I.getType(), TD) &&
5323               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5324                                 I.getType(), TD)) {
5325             Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5326                                              Op1C->getOperand(0), I.getName());
5327             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5328           }
5329         }
5330       }
5331   }
5332   
5333     
5334   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5335   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5336     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5337       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5338         return Res;
5339   }
5340
5341   return Changed ? &I : 0;
5342 }
5343
5344 namespace {
5345
5346 // XorSelf - Implements: X ^ X --> 0
5347 struct XorSelf {
5348   Value *RHS;
5349   XorSelf(Value *rhs) : RHS(rhs) {}
5350   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5351   Instruction *apply(BinaryOperator &Xor) const {
5352     return &Xor;
5353   }
5354 };
5355
5356 }
5357
5358 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5359   bool Changed = SimplifyCommutative(I);
5360   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5361
5362   if (isa<UndefValue>(Op1)) {
5363     if (isa<UndefValue>(Op0))
5364       // Handle undef ^ undef -> 0 special case. This is a common
5365       // idiom (misuse).
5366       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5367     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5368   }
5369
5370   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5371   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5372     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5373     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5374   }
5375   
5376   // See if we can simplify any instructions used by the instruction whose sole 
5377   // purpose is to compute bits we don't care about.
5378   if (SimplifyDemandedInstructionBits(I))
5379     return &I;
5380   if (isa<VectorType>(I.getType()))
5381     if (isa<ConstantAggregateZero>(Op1))
5382       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5383
5384   // Is this a ~ operation?
5385   if (Value *NotOp = dyn_castNotVal(&I)) {
5386     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5387       if (Op0I->getOpcode() == Instruction::And || 
5388           Op0I->getOpcode() == Instruction::Or) {
5389         // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5390         // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5391         if (dyn_castNotVal(Op0I->getOperand(1)))
5392           Op0I->swapOperands();
5393         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5394           Value *NotY =
5395             Builder->CreateNot(Op0I->getOperand(1),
5396                                Op0I->getOperand(1)->getName()+".not");
5397           if (Op0I->getOpcode() == Instruction::And)
5398             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5399           return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5400         }
5401         
5402         // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5403         // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5404         if (isFreeToInvert(Op0I->getOperand(0)) && 
5405             isFreeToInvert(Op0I->getOperand(1))) {
5406           Value *NotX =
5407             Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5408           Value *NotY =
5409             Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5410           if (Op0I->getOpcode() == Instruction::And)
5411             return BinaryOperator::CreateOr(NotX, NotY);
5412           return BinaryOperator::CreateAnd(NotX, NotY);
5413         }
5414       }
5415     }
5416   }
5417   
5418   
5419   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5420     if (RHS->isOne() && Op0->hasOneUse()) {
5421       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5422       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5423         return new ICmpInst(ICI->getInversePredicate(),
5424                             ICI->getOperand(0), ICI->getOperand(1));
5425
5426       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5427         return new FCmpInst(FCI->getInversePredicate(),
5428                             FCI->getOperand(0), FCI->getOperand(1));
5429     }
5430
5431     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5432     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5433       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5434         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5435           Instruction::CastOps Opcode = Op0C->getOpcode();
5436           if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5437               (RHS == ConstantExpr::getCast(Opcode, 
5438                                             ConstantInt::getTrue(*Context),
5439                                             Op0C->getDestTy()))) {
5440             CI->setPredicate(CI->getInversePredicate());
5441             return CastInst::Create(Opcode, CI, Op0C->getType());
5442           }
5443         }
5444       }
5445     }
5446
5447     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5448       // ~(c-X) == X-c-1 == X+(-c-1)
5449       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5450         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5451           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5452           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5453                                       ConstantInt::get(I.getType(), 1));
5454           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5455         }
5456           
5457       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5458         if (Op0I->getOpcode() == Instruction::Add) {
5459           // ~(X-c) --> (-c-1)-X
5460           if (RHS->isAllOnesValue()) {
5461             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5462             return BinaryOperator::CreateSub(
5463                            ConstantExpr::getSub(NegOp0CI,
5464                                       ConstantInt::get(I.getType(), 1)),
5465                                       Op0I->getOperand(0));
5466           } else if (RHS->getValue().isSignBit()) {
5467             // (X + C) ^ signbit -> (X + C + signbit)
5468             Constant *C = ConstantInt::get(*Context,
5469                                            RHS->getValue() + Op0CI->getValue());
5470             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5471
5472           }
5473         } else if (Op0I->getOpcode() == Instruction::Or) {
5474           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5475           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5476             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5477             // Anything in both C1 and C2 is known to be zero, remove it from
5478             // NewRHS.
5479             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5480             NewRHS = ConstantExpr::getAnd(NewRHS, 
5481                                        ConstantExpr::getNot(CommonBits));
5482             Worklist.Add(Op0I);
5483             I.setOperand(0, Op0I->getOperand(0));
5484             I.setOperand(1, NewRHS);
5485             return &I;
5486           }
5487         }
5488       }
5489     }
5490
5491     // Try to fold constant and into select arguments.
5492     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5493       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5494         return R;
5495     if (isa<PHINode>(Op0))
5496       if (Instruction *NV = FoldOpIntoPhi(I))
5497         return NV;
5498   }
5499
5500   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5501     if (X == Op1)
5502       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5503
5504   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5505     if (X == Op0)
5506       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5507
5508   
5509   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5510   if (Op1I) {
5511     Value *A, *B;
5512     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5513       if (A == Op0) {              // B^(B|A) == (A|B)^B
5514         Op1I->swapOperands();
5515         I.swapOperands();
5516         std::swap(Op0, Op1);
5517       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5518         I.swapOperands();     // Simplified below.
5519         std::swap(Op0, Op1);
5520       }
5521     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5522       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5523     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5524       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5525     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5526                Op1I->hasOneUse()){
5527       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5528         Op1I->swapOperands();
5529         std::swap(A, B);
5530       }
5531       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5532         I.swapOperands();     // Simplified below.
5533         std::swap(Op0, Op1);
5534       }
5535     }
5536   }
5537   
5538   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5539   if (Op0I) {
5540     Value *A, *B;
5541     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5542         Op0I->hasOneUse()) {
5543       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5544         std::swap(A, B);
5545       if (B == Op1)                                  // (A|B)^B == A & ~B
5546         return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5547     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5548       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5549     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5550       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5551     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5552                Op0I->hasOneUse()){
5553       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5554         std::swap(A, B);
5555       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5556           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5557         return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5558       }
5559     }
5560   }
5561   
5562   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5563   if (Op0I && Op1I && Op0I->isShift() && 
5564       Op0I->getOpcode() == Op1I->getOpcode() && 
5565       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5566       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5567     Value *NewOp =
5568       Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5569                          Op0I->getName());
5570     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5571                                   Op1I->getOperand(1));
5572   }
5573     
5574   if (Op0I && Op1I) {
5575     Value *A, *B, *C, *D;
5576     // (A & B)^(A | B) -> A ^ B
5577     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5578         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5579       if ((A == C && B == D) || (A == D && B == C)) 
5580         return BinaryOperator::CreateXor(A, B);
5581     }
5582     // (A | B)^(A & B) -> A ^ B
5583     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5584         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5585       if ((A == C && B == D) || (A == D && B == C)) 
5586         return BinaryOperator::CreateXor(A, B);
5587     }
5588     
5589     // (A & B)^(C & D)
5590     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5591         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5592         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5593       // (X & Y)^(X & Y) -> (Y^Z) & X
5594       Value *X = 0, *Y = 0, *Z = 0;
5595       if (A == C)
5596         X = A, Y = B, Z = D;
5597       else if (A == D)
5598         X = A, Y = B, Z = C;
5599       else if (B == C)
5600         X = B, Y = A, Z = D;
5601       else if (B == D)
5602         X = B, Y = A, Z = C;
5603       
5604       if (X) {
5605         Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5606         return BinaryOperator::CreateAnd(NewOp, X);
5607       }
5608     }
5609   }
5610     
5611   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5612   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5613     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5614       return R;
5615
5616   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5617   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5618     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5619       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5620         const Type *SrcTy = Op0C->getOperand(0)->getType();
5621         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5622             // Only do this if the casts both really cause code to be generated.
5623             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5624                               I.getType(), TD) &&
5625             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5626                               I.getType(), TD)) {
5627           Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5628                                             Op1C->getOperand(0), I.getName());
5629           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5630         }
5631       }
5632   }
5633
5634   return Changed ? &I : 0;
5635 }
5636
5637 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5638                                    LLVMContext *Context) {
5639   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5640 }
5641
5642 static bool HasAddOverflow(ConstantInt *Result,
5643                            ConstantInt *In1, ConstantInt *In2,
5644                            bool IsSigned) {
5645   if (IsSigned)
5646     if (In2->getValue().isNegative())
5647       return Result->getValue().sgt(In1->getValue());
5648     else
5649       return Result->getValue().slt(In1->getValue());
5650   else
5651     return Result->getValue().ult(In1->getValue());
5652 }
5653
5654 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5655 /// overflowed for this type.
5656 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5657                             Constant *In2, LLVMContext *Context,
5658                             bool IsSigned = false) {
5659   Result = ConstantExpr::getAdd(In1, In2);
5660
5661   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5662     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5663       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5664       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5665                          ExtractElement(In1, Idx, Context),
5666                          ExtractElement(In2, Idx, Context),
5667                          IsSigned))
5668         return true;
5669     }
5670     return false;
5671   }
5672
5673   return HasAddOverflow(cast<ConstantInt>(Result),
5674                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5675                         IsSigned);
5676 }
5677
5678 static bool HasSubOverflow(ConstantInt *Result,
5679                            ConstantInt *In1, ConstantInt *In2,
5680                            bool IsSigned) {
5681   if (IsSigned)
5682     if (In2->getValue().isNegative())
5683       return Result->getValue().slt(In1->getValue());
5684     else
5685       return Result->getValue().sgt(In1->getValue());
5686   else
5687     return Result->getValue().ugt(In1->getValue());
5688 }
5689
5690 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5691 /// overflowed for this type.
5692 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5693                             Constant *In2, LLVMContext *Context,
5694                             bool IsSigned = false) {
5695   Result = ConstantExpr::getSub(In1, In2);
5696
5697   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5698     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5699       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5700       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5701                          ExtractElement(In1, Idx, Context),
5702                          ExtractElement(In2, Idx, Context),
5703                          IsSigned))
5704         return true;
5705     }
5706     return false;
5707   }
5708
5709   return HasSubOverflow(cast<ConstantInt>(Result),
5710                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5711                         IsSigned);
5712 }
5713
5714
5715 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5716 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5717 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5718                                        ICmpInst::Predicate Cond,
5719                                        Instruction &I) {
5720   // Look through bitcasts.
5721   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5722     RHS = BCI->getOperand(0);
5723
5724   Value *PtrBase = GEPLHS->getOperand(0);
5725   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5726     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5727     // This transformation (ignoring the base and scales) is valid because we
5728     // know pointers can't overflow since the gep is inbounds.  See if we can
5729     // output an optimized form.
5730     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5731     
5732     // If not, synthesize the offset the hard way.
5733     if (Offset == 0)
5734       Offset = EmitGEPOffset(GEPLHS, *this);
5735     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5736                         Constant::getNullValue(Offset->getType()));
5737   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5738     // If the base pointers are different, but the indices are the same, just
5739     // compare the base pointer.
5740     if (PtrBase != GEPRHS->getOperand(0)) {
5741       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5742       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5743                         GEPRHS->getOperand(0)->getType();
5744       if (IndicesTheSame)
5745         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5746           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5747             IndicesTheSame = false;
5748             break;
5749           }
5750
5751       // If all indices are the same, just compare the base pointers.
5752       if (IndicesTheSame)
5753         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5754                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5755
5756       // Otherwise, the base pointers are different and the indices are
5757       // different, bail out.
5758       return 0;
5759     }
5760
5761     // If one of the GEPs has all zero indices, recurse.
5762     bool AllZeros = true;
5763     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5764       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5765           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5766         AllZeros = false;
5767         break;
5768       }
5769     if (AllZeros)
5770       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5771                           ICmpInst::getSwappedPredicate(Cond), I);
5772
5773     // If the other GEP has all zero indices, recurse.
5774     AllZeros = true;
5775     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5776       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5777           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5778         AllZeros = false;
5779         break;
5780       }
5781     if (AllZeros)
5782       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5783
5784     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5785       // If the GEPs only differ by one index, compare it.
5786       unsigned NumDifferences = 0;  // Keep track of # differences.
5787       unsigned DiffOperand = 0;     // The operand that differs.
5788       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5789         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5790           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5791                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5792             // Irreconcilable differences.
5793             NumDifferences = 2;
5794             break;
5795           } else {
5796             if (NumDifferences++) break;
5797             DiffOperand = i;
5798           }
5799         }
5800
5801       if (NumDifferences == 0)   // SAME GEP?
5802         return ReplaceInstUsesWith(I, // No comparison is needed here.
5803                                    ConstantInt::get(Type::getInt1Ty(*Context),
5804                                              ICmpInst::isTrueWhenEqual(Cond)));
5805
5806       else if (NumDifferences == 1) {
5807         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5808         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5809         // Make sure we do a signed comparison here.
5810         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5811       }
5812     }
5813
5814     // Only lower this if the icmp is the only user of the GEP or if we expect
5815     // the result to fold to a constant!
5816     if (TD &&
5817         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5818         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5819       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5820       Value *L = EmitGEPOffset(GEPLHS, *this);
5821       Value *R = EmitGEPOffset(GEPRHS, *this);
5822       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5823     }
5824   }
5825   return 0;
5826 }
5827
5828 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5829 ///
5830 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5831                                                 Instruction *LHSI,
5832                                                 Constant *RHSC) {
5833   if (!isa<ConstantFP>(RHSC)) return 0;
5834   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5835   
5836   // Get the width of the mantissa.  We don't want to hack on conversions that
5837   // might lose information from the integer, e.g. "i64 -> float"
5838   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5839   if (MantissaWidth == -1) return 0;  // Unknown.
5840   
5841   // Check to see that the input is converted from an integer type that is small
5842   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5843   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5844   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5845   
5846   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5847   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5848   if (LHSUnsigned)
5849     ++InputSize;
5850   
5851   // If the conversion would lose info, don't hack on this.
5852   if ((int)InputSize > MantissaWidth)
5853     return 0;
5854   
5855   // Otherwise, we can potentially simplify the comparison.  We know that it
5856   // will always come through as an integer value and we know the constant is
5857   // not a NAN (it would have been previously simplified).
5858   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5859   
5860   ICmpInst::Predicate Pred;
5861   switch (I.getPredicate()) {
5862   default: llvm_unreachable("Unexpected predicate!");
5863   case FCmpInst::FCMP_UEQ:
5864   case FCmpInst::FCMP_OEQ:
5865     Pred = ICmpInst::ICMP_EQ;
5866     break;
5867   case FCmpInst::FCMP_UGT:
5868   case FCmpInst::FCMP_OGT:
5869     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5870     break;
5871   case FCmpInst::FCMP_UGE:
5872   case FCmpInst::FCMP_OGE:
5873     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5874     break;
5875   case FCmpInst::FCMP_ULT:
5876   case FCmpInst::FCMP_OLT:
5877     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5878     break;
5879   case FCmpInst::FCMP_ULE:
5880   case FCmpInst::FCMP_OLE:
5881     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5882     break;
5883   case FCmpInst::FCMP_UNE:
5884   case FCmpInst::FCMP_ONE:
5885     Pred = ICmpInst::ICMP_NE;
5886     break;
5887   case FCmpInst::FCMP_ORD:
5888     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5889   case FCmpInst::FCMP_UNO:
5890     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5891   }
5892   
5893   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5894   
5895   // Now we know that the APFloat is a normal number, zero or inf.
5896   
5897   // See if the FP constant is too large for the integer.  For example,
5898   // comparing an i8 to 300.0.
5899   unsigned IntWidth = IntTy->getScalarSizeInBits();
5900   
5901   if (!LHSUnsigned) {
5902     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5903     // and large values.
5904     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5905     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5906                           APFloat::rmNearestTiesToEven);
5907     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5908       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5909           Pred == ICmpInst::ICMP_SLE)
5910         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5911       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5912     }
5913   } else {
5914     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5915     // +INF and large values.
5916     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5917     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5918                           APFloat::rmNearestTiesToEven);
5919     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5920       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5921           Pred == ICmpInst::ICMP_ULE)
5922         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5923       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5924     }
5925   }
5926   
5927   if (!LHSUnsigned) {
5928     // See if the RHS value is < SignedMin.
5929     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5930     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5931                           APFloat::rmNearestTiesToEven);
5932     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5933       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5934           Pred == ICmpInst::ICMP_SGE)
5935         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5936       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5937     }
5938   }
5939
5940   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5941   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5942   // casting the FP value to the integer value and back, checking for equality.
5943   // Don't do this for zero, because -0.0 is not fractional.
5944   Constant *RHSInt = LHSUnsigned
5945     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5946     : ConstantExpr::getFPToSI(RHSC, IntTy);
5947   if (!RHS.isZero()) {
5948     bool Equal = LHSUnsigned
5949       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5950       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5951     if (!Equal) {
5952       // If we had a comparison against a fractional value, we have to adjust
5953       // the compare predicate and sometimes the value.  RHSC is rounded towards
5954       // zero at this point.
5955       switch (Pred) {
5956       default: llvm_unreachable("Unexpected integer comparison!");
5957       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5958         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5959       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5960         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5961       case ICmpInst::ICMP_ULE:
5962         // (float)int <= 4.4   --> int <= 4
5963         // (float)int <= -4.4  --> false
5964         if (RHS.isNegative())
5965           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5966         break;
5967       case ICmpInst::ICMP_SLE:
5968         // (float)int <= 4.4   --> int <= 4
5969         // (float)int <= -4.4  --> int < -4
5970         if (RHS.isNegative())
5971           Pred = ICmpInst::ICMP_SLT;
5972         break;
5973       case ICmpInst::ICMP_ULT:
5974         // (float)int < -4.4   --> false
5975         // (float)int < 4.4    --> int <= 4
5976         if (RHS.isNegative())
5977           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5978         Pred = ICmpInst::ICMP_ULE;
5979         break;
5980       case ICmpInst::ICMP_SLT:
5981         // (float)int < -4.4   --> int < -4
5982         // (float)int < 4.4    --> int <= 4
5983         if (!RHS.isNegative())
5984           Pred = ICmpInst::ICMP_SLE;
5985         break;
5986       case ICmpInst::ICMP_UGT:
5987         // (float)int > 4.4    --> int > 4
5988         // (float)int > -4.4   --> true
5989         if (RHS.isNegative())
5990           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5991         break;
5992       case ICmpInst::ICMP_SGT:
5993         // (float)int > 4.4    --> int > 4
5994         // (float)int > -4.4   --> int >= -4
5995         if (RHS.isNegative())
5996           Pred = ICmpInst::ICMP_SGE;
5997         break;
5998       case ICmpInst::ICMP_UGE:
5999         // (float)int >= -4.4   --> true
6000         // (float)int >= 4.4    --> int > 4
6001         if (!RHS.isNegative())
6002           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6003         Pred = ICmpInst::ICMP_UGT;
6004         break;
6005       case ICmpInst::ICMP_SGE:
6006         // (float)int >= -4.4   --> int >= -4
6007         // (float)int >= 4.4    --> int > 4
6008         if (!RHS.isNegative())
6009           Pred = ICmpInst::ICMP_SGT;
6010         break;
6011       }
6012     }
6013   }
6014
6015   // Lower this FP comparison into an appropriate integer version of the
6016   // comparison.
6017   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
6018 }
6019
6020 /// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
6021 ///   cmp pred (load (gep GV, ...)), cmpcst
6022 /// where GV is a global variable with a constant initializer.  Try to simplify
6023 /// this into some simple computation that does not need the load.  For example
6024 /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
6025 ///
6026 /// If AndCst is non-null, then the loaded value is masked with that constant
6027 /// before doing the comparison.  This handles cases like "A[i]&4 == 0".
6028 Instruction *InstCombiner::
6029 FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
6030                              CmpInst &ICI, ConstantInt *AndCst) {
6031   ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
6032   if (Init == 0 || Init->getNumOperands() > 1024) return 0;
6033   
6034   // There are many forms of this optimization we can handle, for now, just do
6035   // the simple index into a single-dimensional array.
6036   //
6037   // Require: GEP GV, 0, i {{, constant indices}}
6038   if (GEP->getNumOperands() < 3 ||
6039       !isa<ConstantInt>(GEP->getOperand(1)) ||
6040       !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
6041       isa<Constant>(GEP->getOperand(2)))
6042     return 0;
6043
6044   // Check that indices after the variable are constants and in-range for the
6045   // type they index.  Collect the indices.  This is typically for arrays of
6046   // structs.
6047   SmallVector<unsigned, 4> LaterIndices;
6048   
6049   const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
6050   for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
6051     ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
6052     if (Idx == 0) return 0;  // Variable index.
6053     
6054     uint64_t IdxVal = Idx->getZExtValue();
6055     if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
6056     
6057     if (const StructType *STy = dyn_cast<StructType>(EltTy))
6058       EltTy = STy->getElementType(IdxVal);
6059     else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
6060       if (IdxVal >= ATy->getNumElements()) return 0;
6061       EltTy = ATy->getElementType();
6062     } else {
6063       return 0; // Unknown type.
6064     }
6065     
6066     LaterIndices.push_back(IdxVal);
6067   }
6068   
6069   enum { Overdefined = -3, Undefined = -2 };
6070
6071   // Variables for our state machines.
6072   
6073   // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6074   // "i == 47 | i == 87", where 47 is the first index the condition is true for,
6075   // and 87 is the second (and last) index.  FirstTrueElement is -2 when
6076   // undefined, otherwise set to the first true element.  SecondTrueElement is
6077   // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
6078   int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
6079
6080   // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6081   // form "i != 47 & i != 87".  Same state transitions as for true elements.
6082   int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
6083   
6084   /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
6085   /// define a state machine that triggers for ranges of values that the index
6086   /// is true or false for.  This triggers on things like "abbbbc"[i] == 'b'.
6087   /// This is -2 when undefined, -3 when overdefined, and otherwise the last
6088   /// index in the range (inclusive).  We use -2 for undefined here because we
6089   /// use relative comparisons and don't want 0-1 to match -1.
6090   int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
6091   
6092   // MagicBitvector - This is a magic bitvector where we set a bit if the
6093   // comparison is true for element 'i'.  If there are 64 elements or less in
6094   // the array, this will fully represent all the comparison results.
6095   uint64_t MagicBitvector = 0;
6096   
6097   
6098   // Scan the array and see if one of our patterns matches.
6099   Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6100   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
6101     Constant *Elt = Init->getOperand(i);
6102     
6103     // If this is indexing an array of structures, get the structure element.
6104     if (!LaterIndices.empty())
6105       Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
6106                                           LaterIndices.size());
6107     
6108     // If the element is masked, handle it.
6109     if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
6110     
6111     // Find out if the comparison would be true or false for the i'th element.
6112     Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
6113                                                   CompareRHS, TD);
6114     // If the result is undef for this element, ignore it.
6115     if (isa<UndefValue>(C)) {
6116       // Extend range state machines to cover this element in case there is an
6117       // undef in the middle of the range.
6118       if (TrueRangeEnd == (int)i-1)
6119         TrueRangeEnd = i;
6120       if (FalseRangeEnd == (int)i-1)
6121         FalseRangeEnd = i;
6122       continue;
6123     }
6124     
6125     // If we can't compute the result for any of the elements, we have to give
6126     // up evaluating the entire conditional.
6127     if (!isa<ConstantInt>(C)) return 0;
6128     
6129     // Otherwise, we know if the comparison is true or false for this element,
6130     // update our state machines.
6131     bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6132     
6133     // State machine for single/double/range index comparison.
6134     if (IsTrueForElt) {
6135       // Update the TrueElement state machine.
6136       if (FirstTrueElement == Undefined)
6137         FirstTrueElement = TrueRangeEnd = i;  // First true element.
6138       else {
6139         // Update double-compare state machine.
6140         if (SecondTrueElement == Undefined)
6141           SecondTrueElement = i;
6142         else
6143           SecondTrueElement = Overdefined;
6144         
6145         // Update range state machine.
6146         if (TrueRangeEnd == (int)i-1)
6147           TrueRangeEnd = i;
6148         else
6149           TrueRangeEnd = Overdefined;
6150       }
6151     } else {
6152       // Update the FalseElement state machine.
6153       if (FirstFalseElement == Undefined)
6154         FirstFalseElement = FalseRangeEnd = i; // First false element.
6155       else {
6156         // Update double-compare state machine.
6157         if (SecondFalseElement == Undefined)
6158           SecondFalseElement = i;
6159         else
6160           SecondFalseElement = Overdefined;
6161         
6162         // Update range state machine.
6163         if (FalseRangeEnd == (int)i-1)
6164           FalseRangeEnd = i;
6165         else
6166           FalseRangeEnd = Overdefined;
6167       }
6168     }
6169     
6170     
6171     // If this element is in range, update our magic bitvector.
6172     if (i < 64 && IsTrueForElt)
6173       MagicBitvector |= 1ULL << i;
6174     
6175     // If all of our states become overdefined, bail out early.  Since the
6176     // predicate is expensive, only check it every 8 elements.  This is only
6177     // really useful for really huge arrays.
6178     if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
6179         SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
6180         FalseRangeEnd == Overdefined)
6181       return 0;
6182   }
6183
6184   // Now that we've scanned the entire array, emit our new comparison(s).  We
6185   // order the state machines in complexity of the generated code.
6186   Value *Idx = GEP->getOperand(2);
6187
6188   
6189   // If the comparison is only true for one or two elements, emit direct
6190   // comparisons.
6191   if (SecondTrueElement != Overdefined) {
6192     // None true -> false.
6193     if (FirstTrueElement == Undefined)
6194       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6195     
6196     Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6197     
6198     // True for one element -> 'i == 47'.
6199     if (SecondTrueElement == Undefined)
6200       return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6201     
6202     // True for two elements -> 'i == 47 | i == 72'.
6203     Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6204     Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6205     Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6206     return BinaryOperator::CreateOr(C1, C2);
6207   }
6208
6209   // If the comparison is only false for one or two elements, emit direct
6210   // comparisons.
6211   if (SecondFalseElement != Overdefined) {
6212     // None false -> true.
6213     if (FirstFalseElement == Undefined)
6214       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6215     
6216     Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6217
6218     // False for one element -> 'i != 47'.
6219     if (SecondFalseElement == Undefined)
6220       return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6221      
6222     // False for two elements -> 'i != 47 & i != 72'.
6223     Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6224     Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6225     Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6226     return BinaryOperator::CreateAnd(C1, C2);
6227   }
6228   
6229   // If the comparison can be replaced with a range comparison for the elements
6230   // where it is true, emit the range check.
6231   if (TrueRangeEnd != Overdefined) {
6232     assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
6233     
6234     // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
6235     if (FirstTrueElement) {
6236       Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
6237       Idx = Builder->CreateAdd(Idx, Offs);
6238     }
6239     
6240     Value *End = ConstantInt::get(Idx->getType(),
6241                                   TrueRangeEnd-FirstTrueElement+1);
6242     return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
6243   }
6244   
6245   // False range check.
6246   if (FalseRangeEnd != Overdefined) {
6247     assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
6248     // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
6249     if (FirstFalseElement) {
6250       Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
6251       Idx = Builder->CreateAdd(Idx, Offs);
6252     }
6253     
6254     Value *End = ConstantInt::get(Idx->getType(),
6255                                   FalseRangeEnd-FirstFalseElement);
6256     return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
6257   }
6258   
6259   
6260   // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6261   // of this load, replace it with computation that does:
6262   //   ((magic_cst >> i) & 1) != 0
6263   if (Init->getNumOperands() <= 32 ||
6264       (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6265     const Type *Ty;
6266     if (Init->getNumOperands() <= 32)
6267       Ty = Type::getInt32Ty(Init->getContext());
6268     else
6269       Ty = Type::getInt64Ty(Init->getContext());
6270     Value *V = Builder->CreateIntCast(Idx, Ty, false);
6271     V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6272     V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6273     return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6274   }
6275   
6276   return 0;
6277 }
6278
6279
6280 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
6281   bool Changed = false;
6282   
6283   /// Orders the operands of the compare so that they are listed from most
6284   /// complex to least complex.  This puts constants before unary operators,
6285   /// before binary operators.
6286   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6287     I.swapOperands();
6288     Changed = true;
6289   }
6290
6291   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6292   
6293   if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6294     return ReplaceInstUsesWith(I, V);
6295
6296   // Simplify 'fcmp pred X, X'
6297   if (Op0 == Op1) {
6298     switch (I.getPredicate()) {
6299     default: llvm_unreachable("Unknown predicate!");
6300     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
6301     case FCmpInst::FCMP_ULT:    // True if unordered or less than
6302     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
6303     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
6304       // Canonicalize these to be 'fcmp uno %X, 0.0'.
6305       I.setPredicate(FCmpInst::FCMP_UNO);
6306       I.setOperand(1, Constant::getNullValue(Op0->getType()));
6307       return &I;
6308       
6309     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
6310     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
6311     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
6312     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
6313       // Canonicalize these to be 'fcmp ord %X, 0.0'.
6314       I.setPredicate(FCmpInst::FCMP_ORD);
6315       I.setOperand(1, Constant::getNullValue(Op0->getType()));
6316       return &I;
6317     }
6318   }
6319     
6320   // Handle fcmp with constant RHS
6321   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6322     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6323       switch (LHSI->getOpcode()) {
6324       case Instruction::PHI:
6325         // Only fold fcmp into the PHI if the phi and fcmp are in the same
6326         // block.  If in the same block, we're encouraging jump threading.  If
6327         // not, we are just pessimizing the code by making an i1 phi.
6328         if (LHSI->getParent() == I.getParent())
6329           if (Instruction *NV = FoldOpIntoPhi(I, true))
6330             return NV;
6331         break;
6332       case Instruction::SIToFP:
6333       case Instruction::UIToFP:
6334         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6335           return NV;
6336         break;
6337       case Instruction::Select: {
6338         // If either operand of the select is a constant, we can fold the
6339         // comparison into the select arms, which will cause one to be
6340         // constant folded and the select turned into a bitwise or.
6341         Value *Op1 = 0, *Op2 = 0;
6342         if (LHSI->hasOneUse()) {
6343           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6344             // Fold the known value into the constant operand.
6345             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6346             // Insert a new FCmp of the other select operand.
6347             Op2 = Builder->CreateFCmp(I.getPredicate(),
6348                                       LHSI->getOperand(2), RHSC, I.getName());
6349           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6350             // Fold the known value into the constant operand.
6351             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6352             // Insert a new FCmp of the other select operand.
6353             Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6354                                       RHSC, I.getName());
6355           }
6356         }
6357
6358         if (Op1)
6359           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6360         break;
6361       }
6362     case Instruction::Load:
6363       if (GetElementPtrInst *GEP =
6364           dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6365         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6366           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
6367               !cast<LoadInst>(LHSI)->isVolatile())
6368             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6369               return Res;
6370       }
6371       break;
6372     }
6373   }
6374
6375   return Changed ? &I : 0;
6376 }
6377
6378 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6379   bool Changed = false;
6380   
6381   /// Orders the operands of the compare so that they are listed from most
6382   /// complex to least complex.  This puts constants before unary operators,
6383   /// before binary operators.
6384   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6385     I.swapOperands();
6386     Changed = true;
6387   }
6388   
6389   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6390   
6391   if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6392     return ReplaceInstUsesWith(I, V);
6393   
6394   const Type *Ty = Op0->getType();
6395
6396   // icmp's with boolean values can always be turned into bitwise operations
6397   if (Ty == Type::getInt1Ty(*Context)) {
6398     switch (I.getPredicate()) {
6399     default: llvm_unreachable("Invalid icmp instruction!");
6400     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6401       Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6402       return BinaryOperator::CreateNot(Xor);
6403     }
6404     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6405       return BinaryOperator::CreateXor(Op0, Op1);
6406
6407     case ICmpInst::ICMP_UGT:
6408       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6409       // FALL THROUGH
6410     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6411       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6412       return BinaryOperator::CreateAnd(Not, Op1);
6413     }
6414     case ICmpInst::ICMP_SGT:
6415       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6416       // FALL THROUGH
6417     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6418       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6419       return BinaryOperator::CreateAnd(Not, Op0);
6420     }
6421     case ICmpInst::ICMP_UGE:
6422       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6423       // FALL THROUGH
6424     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6425       Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6426       return BinaryOperator::CreateOr(Not, Op1);
6427     }
6428     case ICmpInst::ICMP_SGE:
6429       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6430       // FALL THROUGH
6431     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6432       Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6433       return BinaryOperator::CreateOr(Not, Op0);
6434     }
6435     }
6436   }
6437
6438   unsigned BitWidth = 0;
6439   if (TD)
6440     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6441   else if (Ty->isIntOrIntVector())
6442     BitWidth = Ty->getScalarSizeInBits();
6443
6444   bool isSignBit = false;
6445
6446   // See if we are doing a comparison with a constant.
6447   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6448     Value *A = 0, *B = 0;
6449     
6450     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6451     if (I.isEquality() && CI->isZero() &&
6452         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6453       // (icmp cond A B) if cond is equality
6454       return new ICmpInst(I.getPredicate(), A, B);
6455     }
6456     
6457     // If we have an icmp le or icmp ge instruction, turn it into the
6458     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6459     // them being folded in the code below.  The SimplifyICmpInst code has
6460     // already handled the edge cases for us, so we just assert on them.
6461     switch (I.getPredicate()) {
6462     default: break;
6463     case ICmpInst::ICMP_ULE:
6464       assert(!CI->isMaxValue(false));                 // A <=u MAX -> TRUE
6465       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6466                           AddOne(CI));
6467     case ICmpInst::ICMP_SLE:
6468       assert(!CI->isMaxValue(true));                  // A <=s MAX -> TRUE
6469       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6470                           AddOne(CI));
6471     case ICmpInst::ICMP_UGE:
6472       assert(!CI->isMinValue(false));                  // A >=u MIN -> TRUE
6473       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6474                           SubOne(CI));
6475     case ICmpInst::ICMP_SGE:
6476       assert(!CI->isMinValue(true));                   // A >=s MIN -> TRUE
6477       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6478                           SubOne(CI));
6479     }
6480     
6481     // If this comparison is a normal comparison, it demands all
6482     // bits, if it is a sign bit comparison, it only demands the sign bit.
6483     bool UnusedBit;
6484     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6485   }
6486
6487   // See if we can fold the comparison based on range information we can get
6488   // by checking whether bits are known to be zero or one in the input.
6489   if (BitWidth != 0) {
6490     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6491     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6492
6493     if (SimplifyDemandedBits(I.getOperandUse(0),
6494                              isSignBit ? APInt::getSignBit(BitWidth)
6495                                        : APInt::getAllOnesValue(BitWidth),
6496                              Op0KnownZero, Op0KnownOne, 0))
6497       return &I;
6498     if (SimplifyDemandedBits(I.getOperandUse(1),
6499                              APInt::getAllOnesValue(BitWidth),
6500                              Op1KnownZero, Op1KnownOne, 0))
6501       return &I;
6502
6503     // Given the known and unknown bits, compute a range that the LHS could be
6504     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6505     // EQ and NE we use unsigned values.
6506     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6507     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6508     if (I.isSigned()) {
6509       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6510                                              Op0Min, Op0Max);
6511       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6512                                              Op1Min, Op1Max);
6513     } else {
6514       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6515                                                Op0Min, Op0Max);
6516       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6517                                                Op1Min, Op1Max);
6518     }
6519
6520     // If Min and Max are known to be the same, then SimplifyDemandedBits
6521     // figured out that the LHS is a constant.  Just constant fold this now so
6522     // that code below can assume that Min != Max.
6523     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6524       return new ICmpInst(I.getPredicate(),
6525                           ConstantInt::get(*Context, Op0Min), Op1);
6526     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6527       return new ICmpInst(I.getPredicate(), Op0,
6528                           ConstantInt::get(*Context, Op1Min));
6529
6530     // Based on the range information we know about the LHS, see if we can
6531     // simplify this comparison.  For example, (x&4) < 8  is always true.
6532     switch (I.getPredicate()) {
6533     default: llvm_unreachable("Unknown icmp opcode!");
6534     case ICmpInst::ICMP_EQ:
6535       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6536         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6537       break;
6538     case ICmpInst::ICMP_NE:
6539       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6540         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6541       break;
6542     case ICmpInst::ICMP_ULT:
6543       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6544         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6545       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6546         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6547       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6548         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6549       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6550         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6551           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6552                               SubOne(CI));
6553
6554         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6555         if (CI->isMinValue(true))
6556           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6557                            Constant::getAllOnesValue(Op0->getType()));
6558       }
6559       break;
6560     case ICmpInst::ICMP_UGT:
6561       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6562         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6563       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6564         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6565
6566       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6567         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6568       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6569         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6570           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6571                               AddOne(CI));
6572
6573         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6574         if (CI->isMaxValue(true))
6575           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6576                               Constant::getNullValue(Op0->getType()));
6577       }
6578       break;
6579     case ICmpInst::ICMP_SLT:
6580       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6581         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6582       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6583         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6584       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6585         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6586       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6587         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6588           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6589                               SubOne(CI));
6590       }
6591       break;
6592     case ICmpInst::ICMP_SGT:
6593       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6594         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6595       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6596         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6597
6598       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6599         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6600       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6601         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6602           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6603                               AddOne(CI));
6604       }
6605       break;
6606     case ICmpInst::ICMP_SGE:
6607       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6608       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6609         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6610       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6611         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6612       break;
6613     case ICmpInst::ICMP_SLE:
6614       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6615       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6616         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6617       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6618         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6619       break;
6620     case ICmpInst::ICMP_UGE:
6621       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6622       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6623         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6624       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6625         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6626       break;
6627     case ICmpInst::ICMP_ULE:
6628       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6629       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6630         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6631       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6632         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6633       break;
6634     }
6635
6636     // Turn a signed comparison into an unsigned one if both operands
6637     // are known to have the same sign.
6638     if (I.isSigned() &&
6639         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6640          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6641       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6642   }
6643
6644   // Test if the ICmpInst instruction is used exclusively by a select as
6645   // part of a minimum or maximum operation. If so, refrain from doing
6646   // any other folding. This helps out other analyses which understand
6647   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6648   // and CodeGen. And in this case, at least one of the comparison
6649   // operands has at least one user besides the compare (the select),
6650   // which would often largely negate the benefit of folding anyway.
6651   if (I.hasOneUse())
6652     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6653       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6654           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6655         return 0;
6656
6657   // See if we are doing a comparison between a constant and an instruction that
6658   // can be folded into the comparison.
6659   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6660     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6661     // instruction, see if that instruction also has constants so that the 
6662     // instruction can be folded into the icmp 
6663     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6664       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6665         return Res;
6666   }
6667
6668   // Handle icmp with constant (but not simple integer constant) RHS
6669   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6670     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6671       switch (LHSI->getOpcode()) {
6672       case Instruction::GetElementPtr:
6673           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6674         if (RHSC->isNullValue() &&
6675             cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6676           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6677                   Constant::getNullValue(LHSI->getOperand(0)->getType()));
6678         break;
6679       case Instruction::PHI:
6680         // Only fold icmp into the PHI if the phi and icmp are in the same
6681         // block.  If in the same block, we're encouraging jump threading.  If
6682         // not, we are just pessimizing the code by making an i1 phi.
6683         if (LHSI->getParent() == I.getParent())
6684           if (Instruction *NV = FoldOpIntoPhi(I, true))
6685             return NV;
6686         break;
6687       case Instruction::Select: {
6688         // If either operand of the select is a constant, we can fold the
6689         // comparison into the select arms, which will cause one to be
6690         // constant folded and the select turned into a bitwise or.
6691         Value *Op1 = 0, *Op2 = 0;
6692         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6693           Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6694         if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6695           Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6696
6697         // We only want to perform this transformation if it will not lead to
6698         // additional code. This is true if either both sides of the select
6699         // fold to a constant (in which case the icmp is replaced with a select
6700         // which will usually simplify) or this is the only user of the
6701         // select (in which case we are trading a select+icmp for a simpler
6702         // select+icmp).
6703         if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6704           if (!Op1)
6705             Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6706                                       RHSC, I.getName());
6707           if (!Op2)
6708             Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6709                                       RHSC, I.getName());
6710           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6711         }
6712         break;
6713       }
6714       case Instruction::Call:
6715         // If we have (malloc != null), and if the malloc has a single use, we
6716         // can assume it is successful and remove the malloc.
6717         if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6718             isa<ConstantPointerNull>(RHSC)) {
6719           // Need to explicitly erase malloc call here, instead of adding it to
6720           // Worklist, because it won't get DCE'd from the Worklist since
6721           // isInstructionTriviallyDead() returns false for function calls.
6722           // It is OK to replace LHSI/MallocCall with Undef because the 
6723           // instruction that uses it will be erased via Worklist.
6724           if (extractMallocCall(LHSI)) {
6725             LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6726             EraseInstFromFunction(*LHSI);
6727             return ReplaceInstUsesWith(I,
6728                                      ConstantInt::get(Type::getInt1Ty(*Context),
6729                                                       !I.isTrueWhenEqual()));
6730           }
6731           if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6732             if (MallocCall->hasOneUse()) {
6733               MallocCall->replaceAllUsesWith(
6734                                         UndefValue::get(MallocCall->getType()));
6735               EraseInstFromFunction(*MallocCall);
6736               Worklist.Add(LHSI); // The malloc's bitcast use.
6737               return ReplaceInstUsesWith(I,
6738                                      ConstantInt::get(Type::getInt1Ty(*Context),
6739                                                       !I.isTrueWhenEqual()));
6740             }
6741         }
6742         break;
6743       case Instruction::IntToPtr:
6744         // icmp pred inttoptr(X), null -> icmp pred X, 0
6745         if (RHSC->isNullValue() && TD &&
6746             TD->getIntPtrType(RHSC->getContext()) == 
6747                LHSI->getOperand(0)->getType())
6748           return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6749                         Constant::getNullValue(LHSI->getOperand(0)->getType()));
6750         break;
6751
6752       case Instruction::Load:
6753         // Try to optimize things like "A[i] > 4" to index computations.
6754         if (GetElementPtrInst *GEP =
6755               dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6756           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6757             if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
6758                 !cast<LoadInst>(LHSI)->isVolatile())
6759               if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6760                 return Res;
6761         }
6762         break;
6763       }
6764   }
6765
6766   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6767   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6768     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6769       return NI;
6770   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6771     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6772                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6773       return NI;
6774
6775   // Test to see if the operands of the icmp are casted versions of other
6776   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6777   // now.
6778   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6779     if (isa<PointerType>(Op0->getType()) && 
6780         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6781       // We keep moving the cast from the left operand over to the right
6782       // operand, where it can often be eliminated completely.
6783       Op0 = CI->getOperand(0);
6784
6785       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6786       // so eliminate it as well.
6787       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6788         Op1 = CI2->getOperand(0);
6789
6790       // If Op1 is a constant, we can fold the cast into the constant.
6791       if (Op0->getType() != Op1->getType()) {
6792         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6793           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6794         } else {
6795           // Otherwise, cast the RHS right before the icmp
6796           Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6797         }
6798       }
6799       return new ICmpInst(I.getPredicate(), Op0, Op1);
6800     }
6801   }
6802   
6803   if (isa<CastInst>(Op0)) {
6804     // Handle the special case of: icmp (cast bool to X), <cst>
6805     // This comes up when you have code like
6806     //   int X = A < B;
6807     //   if (X) ...
6808     // For generality, we handle any zero-extension of any operand comparison
6809     // with a constant or another cast from the same type.
6810     if (isa<Constant>(Op1) || isa<CastInst>(Op1))
6811       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6812         return R;
6813   }
6814   
6815   // See if it's the same type of instruction on the left and right.
6816   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6817     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6818       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6819           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6820         switch (Op0I->getOpcode()) {
6821         default: break;
6822         case Instruction::Add:
6823         case Instruction::Sub:
6824         case Instruction::Xor:
6825           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6826             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6827                                 Op1I->getOperand(0));
6828           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6829           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6830             if (CI->getValue().isSignBit()) {
6831               ICmpInst::Predicate Pred = I.isSigned()
6832                                              ? I.getUnsignedPredicate()
6833                                              : I.getSignedPredicate();
6834               return new ICmpInst(Pred, Op0I->getOperand(0),
6835                                   Op1I->getOperand(0));
6836             }
6837             
6838             if (CI->getValue().isMaxSignedValue()) {
6839               ICmpInst::Predicate Pred = I.isSigned()
6840                                              ? I.getUnsignedPredicate()
6841                                              : I.getSignedPredicate();
6842               Pred = I.getSwappedPredicate(Pred);
6843               return new ICmpInst(Pred, Op0I->getOperand(0),
6844                                   Op1I->getOperand(0));
6845             }
6846           }
6847           break;
6848         case Instruction::Mul:
6849           if (!I.isEquality())
6850             break;
6851
6852           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6853             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6854             // Mask = -1 >> count-trailing-zeros(Cst).
6855             if (!CI->isZero() && !CI->isOne()) {
6856               const APInt &AP = CI->getValue();
6857               ConstantInt *Mask = ConstantInt::get(*Context, 
6858                                       APInt::getLowBitsSet(AP.getBitWidth(),
6859                                                            AP.getBitWidth() -
6860                                                       AP.countTrailingZeros()));
6861               Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6862               Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6863               return new ICmpInst(I.getPredicate(), And1, And2);
6864             }
6865           }
6866           break;
6867         }
6868       }
6869     }
6870   }
6871   
6872   // ~x < ~y --> y < x
6873   { Value *A, *B;
6874     if (match(Op0, m_Not(m_Value(A))) &&
6875         match(Op1, m_Not(m_Value(B))))
6876       return new ICmpInst(I.getPredicate(), B, A);
6877   }
6878   
6879   if (I.isEquality()) {
6880     Value *A, *B, *C, *D;
6881     
6882     // -x == -y --> x == y
6883     if (match(Op0, m_Neg(m_Value(A))) &&
6884         match(Op1, m_Neg(m_Value(B))))
6885       return new ICmpInst(I.getPredicate(), A, B);
6886     
6887     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6888       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6889         Value *OtherVal = A == Op1 ? B : A;
6890         return new ICmpInst(I.getPredicate(), OtherVal,
6891                             Constant::getNullValue(A->getType()));
6892       }
6893
6894       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6895         // A^c1 == C^c2 --> A == C^(c1^c2)
6896         ConstantInt *C1, *C2;
6897         if (match(B, m_ConstantInt(C1)) &&
6898             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6899           Constant *NC = 
6900                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6901           Value *Xor = Builder->CreateXor(C, NC, "tmp");
6902           return new ICmpInst(I.getPredicate(), A, Xor);
6903         }
6904         
6905         // A^B == A^D -> B == D
6906         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6907         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6908         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6909         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6910       }
6911     }
6912     
6913     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6914         (A == Op0 || B == Op0)) {
6915       // A == (A^B)  ->  B == 0
6916       Value *OtherVal = A == Op0 ? B : A;
6917       return new ICmpInst(I.getPredicate(), OtherVal,
6918                           Constant::getNullValue(A->getType()));
6919     }
6920
6921     // (A-B) == A  ->  B == 0
6922     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6923       return new ICmpInst(I.getPredicate(), B, 
6924                           Constant::getNullValue(B->getType()));
6925
6926     // A == (A-B)  ->  B == 0
6927     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6928       return new ICmpInst(I.getPredicate(), B,
6929                           Constant::getNullValue(B->getType()));
6930     
6931     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6932     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6933         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6934         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6935       Value *X = 0, *Y = 0, *Z = 0;
6936       
6937       if (A == C) {
6938         X = B; Y = D; Z = A;
6939       } else if (A == D) {
6940         X = B; Y = C; Z = A;
6941       } else if (B == C) {
6942         X = A; Y = D; Z = B;
6943       } else if (B == D) {
6944         X = A; Y = C; Z = B;
6945       }
6946       
6947       if (X) {   // Build (X^Y) & Z
6948         Op1 = Builder->CreateXor(X, Y, "tmp");
6949         Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6950         I.setOperand(0, Op1);
6951         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6952         return &I;
6953       }
6954     }
6955   }
6956   
6957   {
6958     Value *X; ConstantInt *Cst;
6959     // icmp X+Cst, X
6960     if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
6961       return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6962
6963     // icmp X, X+Cst
6964     if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
6965       return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
6966   }
6967   return Changed ? &I : 0;
6968 }
6969
6970 /// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6971 Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6972                                             Value *X, ConstantInt *CI,
6973                                             ICmpInst::Predicate Pred,
6974                                             Value *TheAdd) {
6975   // If we have X+0, exit early (simplifying logic below) and let it get folded
6976   // elsewhere.   icmp X+0, X  -> icmp X, X
6977   if (CI->isZero()) {
6978     bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6979     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6980   }
6981   
6982   // (X+4) == X -> false.
6983   if (Pred == ICmpInst::ICMP_EQ)
6984     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6985
6986   // (X+4) != X -> true.
6987   if (Pred == ICmpInst::ICMP_NE)
6988     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
6989
6990   // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6991   bool isNUW = false, isNSW = false;
6992   if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6993     isNUW = Add->hasNoUnsignedWrap();
6994     isNSW = Add->hasNoSignedWrap();
6995   }      
6996   
6997   // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6998   // so the values can never be equal.  Similiarly for all other "or equals"
6999   // operators.
7000   
7001   // (X+1) <u X        --> X >u (MAXUINT-1)        --> X != 255
7002   // (X+2) <u X        --> X >u (MAXUINT-2)        --> X > 253
7003   // (X+MAXUINT) <u X  --> X >u (MAXUINT-MAXUINT)  --> X != 0
7004   if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
7005     // If this is an NUW add, then this is always false.
7006     if (isNUW)
7007       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext())); 
7008     
7009     Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
7010     return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
7011   }
7012   
7013   // (X+1) >u X        --> X <u (0-1)        --> X != 255
7014   // (X+2) >u X        --> X <u (0-2)        --> X <u 254
7015   // (X+MAXUINT) >u X  --> X <u (0-MAXUINT)  --> X <u 1  --> X == 0
7016   if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
7017     // If this is an NUW add, then this is always true.
7018     if (isNUW)
7019       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext())); 
7020     return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
7021   }
7022   
7023   unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
7024   ConstantInt *SMax = ConstantInt::get(X->getContext(),
7025                                        APInt::getSignedMaxValue(BitWidth));
7026
7027   // (X+ 1) <s X       --> X >s (MAXSINT-1)          --> X == 127
7028   // (X+ 2) <s X       --> X >s (MAXSINT-2)          --> X >s 125
7029   // (X+MAXSINT) <s X  --> X >s (MAXSINT-MAXSINT)    --> X >s 0
7030   // (X+MINSINT) <s X  --> X >s (MAXSINT-MINSINT)    --> X >s -1
7031   // (X+ -2) <s X      --> X >s (MAXSINT- -2)        --> X >s 126
7032   // (X+ -1) <s X      --> X >s (MAXSINT- -1)        --> X != 127
7033   if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
7034     // If this is an NSW add, then we have two cases: if the constant is
7035     // positive, then this is always false, if negative, this is always true.
7036     if (isNSW) {
7037       bool isTrue = CI->getValue().isNegative();
7038       return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
7039     }
7040     
7041     return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
7042   }
7043   
7044   // (X+ 1) >s X       --> X <s (MAXSINT-(1-1))       --> X != 127
7045   // (X+ 2) >s X       --> X <s (MAXSINT-(2-1))       --> X <s 126
7046   // (X+MAXSINT) >s X  --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
7047   // (X+MINSINT) >s X  --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
7048   // (X+ -2) >s X      --> X <s (MAXSINT-(-2-1))      --> X <s -126
7049   // (X+ -1) >s X      --> X <s (MAXSINT-(-1-1))      --> X == -128
7050   
7051   // If this is an NSW add, then we have two cases: if the constant is
7052   // positive, then this is always true, if negative, this is always false.
7053   if (isNSW) {
7054     bool isTrue = !CI->getValue().isNegative();
7055     return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
7056   }
7057   
7058   assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
7059   Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
7060   return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
7061 }
7062
7063 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
7064 /// and CmpRHS are both known to be integer constants.
7065 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
7066                                           ConstantInt *DivRHS) {
7067   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
7068   const APInt &CmpRHSV = CmpRHS->getValue();
7069   
7070   // FIXME: If the operand types don't match the type of the divide 
7071   // then don't attempt this transform. The code below doesn't have the
7072   // logic to deal with a signed divide and an unsigned compare (and
7073   // vice versa). This is because (x /s C1) <s C2  produces different 
7074   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
7075   // (x /u C1) <u C2.  Simply casting the operands and result won't 
7076   // work. :(  The if statement below tests that condition and bails 
7077   // if it finds it. 
7078   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
7079   if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
7080     return 0;
7081   if (DivRHS->isZero())
7082     return 0; // The ProdOV computation fails on divide by zero.
7083   if (DivIsSigned && DivRHS->isAllOnesValue())
7084     return 0; // The overflow computation also screws up here
7085   if (DivRHS->isOne())
7086     return 0; // Not worth bothering, and eliminates some funny cases
7087               // with INT_MIN.
7088
7089   // Compute Prod = CI * DivRHS. We are essentially solving an equation
7090   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
7091   // C2 (CI). By solving for X we can turn this into a range check 
7092   // instead of computing a divide. 
7093   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
7094
7095   // Determine if the product overflows by seeing if the product is
7096   // not equal to the divide. Make sure we do the same kind of divide
7097   // as in the LHS instruction that we're folding. 
7098   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
7099                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
7100
7101   // Get the ICmp opcode
7102   ICmpInst::Predicate Pred = ICI.getPredicate();
7103
7104   // Figure out the interval that is being checked.  For example, a comparison
7105   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
7106   // Compute this interval based on the constants involved and the signedness of
7107   // the compare/divide.  This computes a half-open interval, keeping track of
7108   // whether either value in the interval overflows.  After analysis each
7109   // overflow variable is set to 0 if it's corresponding bound variable is valid
7110   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7111   int LoOverflow = 0, HiOverflow = 0;
7112   Constant *LoBound = 0, *HiBound = 0;
7113   
7114   if (!DivIsSigned) {  // udiv
7115     // e.g. X/5 op 3  --> [15, 20)
7116     LoBound = Prod;
7117     HiOverflow = LoOverflow = ProdOV;
7118     if (!HiOverflow)
7119       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
7120   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
7121     if (CmpRHSV == 0) {       // (X / pos) op 0
7122       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
7123       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
7124       HiBound = DivRHS;
7125     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
7126       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
7127       HiOverflow = LoOverflow = ProdOV;
7128       if (!HiOverflow)
7129         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
7130     } else {                       // (X / pos) op neg
7131       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
7132       HiBound = AddOne(Prod);
7133       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7134       if (!LoOverflow) {
7135         ConstantInt* DivNeg =
7136                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
7137         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
7138                                      true) ? -1 : 0;
7139        }
7140     }
7141   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
7142     if (CmpRHSV == 0) {       // (X / neg) op 0
7143       // e.g. X/-5 op 0  --> [-4, 5)
7144       LoBound = AddOne(DivRHS);
7145       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
7146       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
7147         HiOverflow = 1;            // [INTMIN+1, overflow)
7148         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
7149       }
7150     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
7151       // e.g. X/-5 op 3  --> [-19, -14)
7152       HiBound = AddOne(Prod);
7153       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
7154       if (!LoOverflow)
7155         LoOverflow = AddWithOverflow(LoBound, HiBound,
7156                                      DivRHS, Context, true) ? -1 : 0;
7157     } else {                       // (X / neg) op neg
7158       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
7159       LoOverflow = HiOverflow = ProdOV;
7160       if (!HiOverflow)
7161         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
7162     }
7163     
7164     // Dividing by a negative swaps the condition.  LT <-> GT
7165     Pred = ICmpInst::getSwappedPredicate(Pred);
7166   }
7167
7168   Value *X = DivI->getOperand(0);
7169   switch (Pred) {
7170   default: llvm_unreachable("Unhandled icmp opcode!");
7171   case ICmpInst::ICMP_EQ:
7172     if (LoOverflow && HiOverflow)
7173       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7174     else if (HiOverflow)
7175       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
7176                           ICmpInst::ICMP_UGE, X, LoBound);
7177     else if (LoOverflow)
7178       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
7179                           ICmpInst::ICMP_ULT, X, HiBound);
7180     else
7181       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
7182   case ICmpInst::ICMP_NE:
7183     if (LoOverflow && HiOverflow)
7184       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7185     else if (HiOverflow)
7186       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
7187                           ICmpInst::ICMP_ULT, X, LoBound);
7188     else if (LoOverflow)
7189       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
7190                           ICmpInst::ICMP_UGE, X, HiBound);
7191     else
7192       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
7193   case ICmpInst::ICMP_ULT:
7194   case ICmpInst::ICMP_SLT:
7195     if (LoOverflow == +1)   // Low bound is greater than input range.
7196       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7197     if (LoOverflow == -1)   // Low bound is less than input range.
7198       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7199     return new ICmpInst(Pred, X, LoBound);
7200   case ICmpInst::ICMP_UGT:
7201   case ICmpInst::ICMP_SGT:
7202     if (HiOverflow == +1)       // High bound greater than input range.
7203       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7204     else if (HiOverflow == -1)  // High bound less than input range.
7205       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7206     if (Pred == ICmpInst::ICMP_UGT)
7207       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
7208     else
7209       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
7210   }
7211 }
7212
7213
7214 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7215 ///
7216 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7217                                                           Instruction *LHSI,
7218                                                           ConstantInt *RHS) {
7219   const APInt &RHSV = RHS->getValue();
7220   
7221   switch (LHSI->getOpcode()) {
7222   case Instruction::Trunc:
7223     if (ICI.isEquality() && LHSI->hasOneUse()) {
7224       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7225       // of the high bits truncated out of x are known.
7226       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7227              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7228       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7229       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7230       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7231       
7232       // If all the high bits are known, we can do this xform.
7233       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7234         // Pull in the high bits from known-ones set.
7235         APInt NewRHS(RHS->getValue());
7236         NewRHS.zext(SrcBits);
7237         NewRHS |= KnownOne;
7238         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7239                             ConstantInt::get(*Context, NewRHS));
7240       }
7241     }
7242     break;
7243       
7244   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
7245     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7246       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7247       // fold the xor.
7248       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7249           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
7250         Value *CompareVal = LHSI->getOperand(0);
7251         
7252         // If the sign bit of the XorCST is not set, there is no change to
7253         // the operation, just stop using the Xor.
7254         if (!XorCST->getValue().isNegative()) {
7255           ICI.setOperand(0, CompareVal);
7256           Worklist.Add(LHSI);
7257           return &ICI;
7258         }
7259         
7260         // Was the old condition true if the operand is positive?
7261         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7262         
7263         // If so, the new one isn't.
7264         isTrueIfPositive ^= true;
7265         
7266         if (isTrueIfPositive)
7267           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
7268                               SubOne(RHS));
7269         else
7270           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
7271                               AddOne(RHS));
7272       }
7273
7274       if (LHSI->hasOneUse()) {
7275         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7276         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7277           const APInt &SignBit = XorCST->getValue();
7278           ICmpInst::Predicate Pred = ICI.isSigned()
7279                                          ? ICI.getUnsignedPredicate()
7280                                          : ICI.getSignedPredicate();
7281           return new ICmpInst(Pred, LHSI->getOperand(0),
7282                               ConstantInt::get(*Context, RHSV ^ SignBit));
7283         }
7284
7285         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
7286         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
7287           const APInt &NotSignBit = XorCST->getValue();
7288           ICmpInst::Predicate Pred = ICI.isSigned()
7289                                          ? ICI.getUnsignedPredicate()
7290                                          : ICI.getSignedPredicate();
7291           Pred = ICI.getSwappedPredicate(Pred);
7292           return new ICmpInst(Pred, LHSI->getOperand(0),
7293                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
7294         }
7295       }
7296     }
7297     break;
7298   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
7299     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7300         LHSI->getOperand(0)->hasOneUse()) {
7301       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7302       
7303       // If the LHS is an AND of a truncating cast, we can widen the
7304       // and/compare to be the input width without changing the value
7305       // produced, eliminating a cast.
7306       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7307         // We can do this transformation if either the AND constant does not
7308         // have its sign bit set or if it is an equality comparison. 
7309         // Extending a relational comparison when we're checking the sign
7310         // bit would not work.
7311         if (Cast->hasOneUse() &&
7312             (ICI.isEquality() ||
7313              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
7314           uint32_t BitWidth = 
7315             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7316           APInt NewCST = AndCST->getValue();
7317           NewCST.zext(BitWidth);
7318           APInt NewCI = RHSV;
7319           NewCI.zext(BitWidth);
7320           Value *NewAnd = 
7321             Builder->CreateAnd(Cast->getOperand(0),
7322                            ConstantInt::get(*Context, NewCST), LHSI->getName());
7323           return new ICmpInst(ICI.getPredicate(), NewAnd,
7324                               ConstantInt::get(*Context, NewCI));
7325         }
7326       }
7327       
7328       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7329       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
7330       // happens a LOT in code produced by the C front-end, for bitfield
7331       // access.
7332       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7333       if (Shift && !Shift->isShift())
7334         Shift = 0;
7335       
7336       ConstantInt *ShAmt;
7337       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7338       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
7339       const Type *AndTy = AndCST->getType();          // Type of the and.
7340       
7341       // We can fold this as long as we can't shift unknown bits
7342       // into the mask.  This can only happen with signed shift
7343       // rights, as they sign-extend.
7344       if (ShAmt) {
7345         bool CanFold = Shift->isLogicalShift();
7346         if (!CanFold) {
7347           // To test for the bad case of the signed shr, see if any
7348           // of the bits shifted in could be tested after the mask.
7349           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7350           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7351           
7352           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7353           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
7354                AndCST->getValue()) == 0)
7355             CanFold = true;
7356         }
7357         
7358         if (CanFold) {
7359           Constant *NewCst;
7360           if (Shift->getOpcode() == Instruction::Shl)
7361             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
7362           else
7363             NewCst = ConstantExpr::getShl(RHS, ShAmt);
7364           
7365           // Check to see if we are shifting out any of the bits being
7366           // compared.
7367           if (ConstantExpr::get(Shift->getOpcode(),
7368                                        NewCst, ShAmt) != RHS) {
7369             // If we shifted bits out, the fold is not going to work out.
7370             // As a special case, check to see if this means that the
7371             // result is always true or false now.
7372             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7373               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7374             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7375               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7376           } else {
7377             ICI.setOperand(1, NewCst);
7378             Constant *NewAndCST;
7379             if (Shift->getOpcode() == Instruction::Shl)
7380               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
7381             else
7382               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
7383             LHSI->setOperand(1, NewAndCST);
7384             LHSI->setOperand(0, Shift->getOperand(0));
7385             Worklist.Add(Shift); // Shift is dead.
7386             return &ICI;
7387           }
7388         }
7389       }
7390       
7391       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
7392       // preferable because it allows the C<<Y expression to be hoisted out
7393       // of a loop if Y is invariant and X is not.
7394       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
7395           ICI.isEquality() && !Shift->isArithmeticShift() &&
7396           !isa<Constant>(Shift->getOperand(0))) {
7397         // Compute C << Y.
7398         Value *NS;
7399         if (Shift->getOpcode() == Instruction::LShr) {
7400           NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
7401         } else {
7402           // Insert a logical shift.
7403           NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
7404         }
7405         
7406         // Compute X & (C << Y).
7407         Value *NewAnd = 
7408           Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
7409         
7410         ICI.setOperand(0, NewAnd);
7411         return &ICI;
7412       }
7413     }
7414       
7415     // Try to optimize things like "A[i]&42 == 0" to index computations.
7416     if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
7417       if (GetElementPtrInst *GEP =
7418           dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
7419         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7420           if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
7421               !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
7422             ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
7423             if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
7424               return Res;
7425           }
7426     }
7427     break;
7428
7429   case Instruction::Or: {
7430     if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7431       break;
7432     Value *P, *Q;
7433     if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7434       // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7435       // -> and (icmp eq P, null), (icmp eq Q, null).
7436
7437       Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7438                                         Constant::getNullValue(P->getType()));
7439       Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7440                                         Constant::getNullValue(Q->getType()));
7441       Instruction *Op;
7442       if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7443         Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
7444       else
7445         Op = BinaryOperator::CreateOr(ICIP, ICIQ);
7446       return Op;
7447     }
7448     break;
7449   }
7450     
7451   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
7452     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7453     if (!ShAmt) break;
7454     
7455     uint32_t TypeBits = RHSV.getBitWidth();
7456     
7457     // Check that the shift amount is in range.  If not, don't perform
7458     // undefined shifts.  When the shift is visited it will be
7459     // simplified.
7460     if (ShAmt->uge(TypeBits))
7461       break;
7462     
7463     if (ICI.isEquality()) {
7464       // If we are comparing against bits always shifted out, the
7465       // comparison cannot succeed.
7466       Constant *Comp =
7467         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
7468                                                                  ShAmt);
7469       if (Comp != RHS) {// Comparing against a bit that we know is zero.
7470         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7471         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7472         return ReplaceInstUsesWith(ICI, Cst);
7473       }
7474       
7475       if (LHSI->hasOneUse()) {
7476         // Otherwise strength reduce the shift into an and.
7477         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7478         Constant *Mask =
7479           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
7480                                                        TypeBits-ShAmtVal));
7481         
7482         Value *And =
7483           Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
7484         return new ICmpInst(ICI.getPredicate(), And,
7485                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
7486       }
7487     }
7488     
7489     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7490     bool TrueIfSigned = false;
7491     if (LHSI->hasOneUse() &&
7492         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7493       // (X << 31) <s 0  --> (X&1) != 0
7494       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
7495                                            (TypeBits-ShAmt->getZExtValue()-1));
7496       Value *And =
7497         Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
7498       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7499                           And, Constant::getNullValue(And->getType()));
7500     }
7501     break;
7502   }
7503     
7504   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7505   case Instruction::AShr: {
7506     // Only handle equality comparisons of shift-by-constant.
7507     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7508     if (!ShAmt || !ICI.isEquality()) break;
7509
7510     // Check that the shift amount is in range.  If not, don't perform
7511     // undefined shifts.  When the shift is visited it will be
7512     // simplified.
7513     uint32_t TypeBits = RHSV.getBitWidth();
7514     if (ShAmt->uge(TypeBits))
7515       break;
7516     
7517     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7518       
7519     // If we are comparing against bits always shifted out, the
7520     // comparison cannot succeed.
7521     APInt Comp = RHSV << ShAmtVal;
7522     if (LHSI->getOpcode() == Instruction::LShr)
7523       Comp = Comp.lshr(ShAmtVal);
7524     else
7525       Comp = Comp.ashr(ShAmtVal);
7526     
7527     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7528       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7529       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7530       return ReplaceInstUsesWith(ICI, Cst);
7531     }
7532     
7533     // Otherwise, check to see if the bits shifted out are known to be zero.
7534     // If so, we can compare against the unshifted value:
7535     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7536     if (LHSI->hasOneUse() &&
7537         MaskedValueIsZero(LHSI->getOperand(0), 
7538                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7539       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7540                           ConstantExpr::getShl(RHS, ShAmt));
7541     }
7542       
7543     if (LHSI->hasOneUse()) {
7544       // Otherwise strength reduce the shift into an and.
7545       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7546       Constant *Mask = ConstantInt::get(*Context, Val);
7547       
7548       Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7549                                       Mask, LHSI->getName()+".mask");
7550       return new ICmpInst(ICI.getPredicate(), And,
7551                           ConstantExpr::getShl(RHS, ShAmt));
7552     }
7553     break;
7554   }
7555     
7556   case Instruction::SDiv:
7557   case Instruction::UDiv:
7558     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7559     // Fold this div into the comparison, producing a range check. 
7560     // Determine, based on the divide type, what the range is being 
7561     // checked.  If there is an overflow on the low or high side, remember 
7562     // it, otherwise compute the range [low, hi) bounding the new value.
7563     // See: InsertRangeTest above for the kinds of replacements possible.
7564     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7565       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7566                                           DivRHS))
7567         return R;
7568     break;
7569
7570   case Instruction::Add:
7571     // Fold: icmp pred (add X, C1), C2
7572     if (!ICI.isEquality()) {
7573       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7574       if (!LHSC) break;
7575       const APInt &LHSV = LHSC->getValue();
7576
7577       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7578                             .subtract(LHSV);
7579
7580       if (ICI.isSigned()) {
7581         if (CR.getLower().isSignBit()) {
7582           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7583                               ConstantInt::get(*Context, CR.getUpper()));
7584         } else if (CR.getUpper().isSignBit()) {
7585           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7586                               ConstantInt::get(*Context, CR.getLower()));
7587         }
7588       } else {
7589         if (CR.getLower().isMinValue()) {
7590           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7591                               ConstantInt::get(*Context, CR.getUpper()));
7592         } else if (CR.getUpper().isMinValue()) {
7593           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7594                               ConstantInt::get(*Context, CR.getLower()));
7595         }
7596       }
7597     }
7598     break;
7599   }
7600   
7601   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7602   if (ICI.isEquality()) {
7603     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7604     
7605     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7606     // the second operand is a constant, simplify a bit.
7607     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7608       switch (BO->getOpcode()) {
7609       case Instruction::SRem:
7610         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7611         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7612           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7613           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7614             Value *NewRem =
7615               Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7616                                   BO->getName());
7617             return new ICmpInst(ICI.getPredicate(), NewRem,
7618                                 Constant::getNullValue(BO->getType()));
7619           }
7620         }
7621         break;
7622       case Instruction::Add:
7623         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7624         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7625           if (BO->hasOneUse())
7626             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7627                                 ConstantExpr::getSub(RHS, BOp1C));
7628         } else if (RHSV == 0) {
7629           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7630           // efficiently invertible, or if the add has just this one use.
7631           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7632           
7633           if (Value *NegVal = dyn_castNegVal(BOp1))
7634             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7635           else if (Value *NegVal = dyn_castNegVal(BOp0))
7636             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7637           else if (BO->hasOneUse()) {
7638             Value *Neg = Builder->CreateNeg(BOp1);
7639             Neg->takeName(BO);
7640             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7641           }
7642         }
7643         break;
7644       case Instruction::Xor:
7645         // For the xor case, we can xor two constants together, eliminating
7646         // the explicit xor.
7647         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7648           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7649                               ConstantExpr::getXor(RHS, BOC));
7650         
7651         // FALLTHROUGH
7652       case Instruction::Sub:
7653         // Replace (([sub|xor] A, B) != 0) with (A != B)
7654         if (RHSV == 0)
7655           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7656                               BO->getOperand(1));
7657         break;
7658         
7659       case Instruction::Or:
7660         // If bits are being or'd in that are not present in the constant we
7661         // are comparing against, then the comparison could never succeed!
7662         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7663           Constant *NotCI = ConstantExpr::getNot(RHS);
7664           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7665             return ReplaceInstUsesWith(ICI,
7666                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7667                                        isICMP_NE));
7668         }
7669         break;
7670         
7671       case Instruction::And:
7672         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7673           // If bits are being compared against that are and'd out, then the
7674           // comparison can never succeed!
7675           if ((RHSV & ~BOC->getValue()) != 0)
7676             return ReplaceInstUsesWith(ICI,
7677                                        ConstantInt::get(Type::getInt1Ty(*Context),
7678                                        isICMP_NE));
7679           
7680           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7681           if (RHS == BOC && RHSV.isPowerOf2())
7682             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7683                                 ICmpInst::ICMP_NE, LHSI,
7684                                 Constant::getNullValue(RHS->getType()));
7685           
7686           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7687           if (BOC->getValue().isSignBit()) {
7688             Value *X = BO->getOperand(0);
7689             Constant *Zero = Constant::getNullValue(X->getType());
7690             ICmpInst::Predicate pred = isICMP_NE ? 
7691               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7692             return new ICmpInst(pred, X, Zero);
7693           }
7694           
7695           // ((X & ~7) == 0) --> X < 8
7696           if (RHSV == 0 && isHighOnes(BOC)) {
7697             Value *X = BO->getOperand(0);
7698             Constant *NegX = ConstantExpr::getNeg(BOC);
7699             ICmpInst::Predicate pred = isICMP_NE ? 
7700               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7701             return new ICmpInst(pred, X, NegX);
7702           }
7703         }
7704       default: break;
7705       }
7706     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7707       // Handle icmp {eq|ne} <intrinsic>, intcst.
7708       if (II->getIntrinsicID() == Intrinsic::bswap) {
7709         Worklist.Add(II);
7710         ICI.setOperand(0, II->getOperand(1));
7711         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7712         return &ICI;
7713       }
7714     }
7715   }
7716   return 0;
7717 }
7718
7719 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7720 /// We only handle extending casts so far.
7721 ///
7722 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7723   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7724   Value *LHSCIOp        = LHSCI->getOperand(0);
7725   const Type *SrcTy     = LHSCIOp->getType();
7726   const Type *DestTy    = LHSCI->getType();
7727   Value *RHSCIOp;
7728
7729   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7730   // integer type is the same size as the pointer type.
7731   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7732       TD->getPointerSizeInBits() ==
7733          cast<IntegerType>(DestTy)->getBitWidth()) {
7734     Value *RHSOp = 0;
7735     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7736       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7737     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7738       RHSOp = RHSC->getOperand(0);
7739       // If the pointer types don't match, insert a bitcast.
7740       if (LHSCIOp->getType() != RHSOp->getType())
7741         RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7742     }
7743
7744     if (RHSOp)
7745       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7746   }
7747   
7748   // The code below only handles extension cast instructions, so far.
7749   // Enforce this.
7750   if (LHSCI->getOpcode() != Instruction::ZExt &&
7751       LHSCI->getOpcode() != Instruction::SExt)
7752     return 0;
7753
7754   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7755   bool isSignedCmp = ICI.isSigned();
7756
7757   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7758     // Not an extension from the same type?
7759     RHSCIOp = CI->getOperand(0);
7760     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7761       return 0;
7762     
7763     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7764     // and the other is a zext), then we can't handle this.
7765     if (CI->getOpcode() != LHSCI->getOpcode())
7766       return 0;
7767
7768     // Deal with equality cases early.
7769     if (ICI.isEquality())
7770       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7771
7772     // A signed comparison of sign extended values simplifies into a
7773     // signed comparison.
7774     if (isSignedCmp && isSignedExt)
7775       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7776
7777     // The other three cases all fold into an unsigned comparison.
7778     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7779   }
7780
7781   // If we aren't dealing with a constant on the RHS, exit early
7782   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7783   if (!CI)
7784     return 0;
7785
7786   // Compute the constant that would happen if we truncated to SrcTy then
7787   // reextended to DestTy.
7788   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7789   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7790                                                 Res1, DestTy);
7791
7792   // If the re-extended constant didn't change...
7793   if (Res2 == CI) {
7794     // Deal with equality cases early.
7795     if (ICI.isEquality())
7796       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7797
7798     // A signed comparison of sign extended values simplifies into a
7799     // signed comparison.
7800     if (isSignedExt && isSignedCmp)
7801       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7802
7803     // The other three cases all fold into an unsigned comparison.
7804     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
7805   }
7806
7807   // The re-extended constant changed so the constant cannot be represented 
7808   // in the shorter type. Consequently, we cannot emit a simple comparison.
7809
7810   // First, handle some easy cases. We know the result cannot be equal at this
7811   // point so handle the ICI.isEquality() cases
7812   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7813     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7814   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7815     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7816
7817   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7818   // should have been folded away previously and not enter in here.
7819   Value *Result;
7820   if (isSignedCmp) {
7821     // We're performing a signed comparison.
7822     if (cast<ConstantInt>(CI)->getValue().isNegative())
7823       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7824     else
7825       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7826   } else {
7827     // We're performing an unsigned comparison.
7828     if (isSignedExt) {
7829       // We're performing an unsigned comp with a sign extended value.
7830       // This is true if the input is >= 0. [aka >s -1]
7831       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7832       Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7833     } else {
7834       // Unsigned extend & unsigned compare -> always true.
7835       Result = ConstantInt::getTrue(*Context);
7836     }
7837   }
7838
7839   // Finally, return the value computed.
7840   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7841       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7842     return ReplaceInstUsesWith(ICI, Result);
7843
7844   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7845           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7846          "ICmp should be folded!");
7847   if (Constant *CI = dyn_cast<Constant>(Result))
7848     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7849   return BinaryOperator::CreateNot(Result);
7850 }
7851
7852 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7853   return commonShiftTransforms(I);
7854 }
7855
7856 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7857   return commonShiftTransforms(I);
7858 }
7859
7860 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7861   if (Instruction *R = commonShiftTransforms(I))
7862     return R;
7863   
7864   Value *Op0 = I.getOperand(0);
7865   
7866   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7867   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7868     if (CSI->isAllOnesValue())
7869       return ReplaceInstUsesWith(I, CSI);
7870
7871   // See if we can turn a signed shr into an unsigned shr.
7872   if (MaskedValueIsZero(Op0,
7873                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7874     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7875
7876   // Arithmetic shifting an all-sign-bit value is a no-op.
7877   unsigned NumSignBits = ComputeNumSignBits(Op0);
7878   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7879     return ReplaceInstUsesWith(I, Op0);
7880
7881   return 0;
7882 }
7883
7884 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7885   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7886   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7887
7888   // shl X, 0 == X and shr X, 0 == X
7889   // shl 0, X == 0 and shr 0, X == 0
7890   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7891       Op0 == Constant::getNullValue(Op0->getType()))
7892     return ReplaceInstUsesWith(I, Op0);
7893   
7894   if (isa<UndefValue>(Op0)) {            
7895     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7896       return ReplaceInstUsesWith(I, Op0);
7897     else                                    // undef << X -> 0, undef >>u X -> 0
7898       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7899   }
7900   if (isa<UndefValue>(Op1)) {
7901     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7902       return ReplaceInstUsesWith(I, Op0);          
7903     else                                     // X << undef, X >>u undef -> 0
7904       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7905   }
7906
7907   // See if we can fold away this shift.
7908   if (SimplifyDemandedInstructionBits(I))
7909     return &I;
7910
7911   // Try to fold constant and into select arguments.
7912   if (isa<Constant>(Op0))
7913     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7914       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7915         return R;
7916
7917   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7918     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7919       return Res;
7920   return 0;
7921 }
7922
7923 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7924                                                BinaryOperator &I) {
7925   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7926
7927   // See if we can simplify any instructions used by the instruction whose sole 
7928   // purpose is to compute bits we don't care about.
7929   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7930   
7931   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7932   // a signed shift.
7933   //
7934   if (Op1->uge(TypeBits)) {
7935     if (I.getOpcode() != Instruction::AShr)
7936       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7937     else {
7938       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7939       return &I;
7940     }
7941   }
7942   
7943   // ((X*C1) << C2) == (X * (C1 << C2))
7944   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7945     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7946       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7947         return BinaryOperator::CreateMul(BO->getOperand(0),
7948                                         ConstantExpr::getShl(BOOp, Op1));
7949   
7950   // Try to fold constant and into select arguments.
7951   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7952     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7953       return R;
7954   if (isa<PHINode>(Op0))
7955     if (Instruction *NV = FoldOpIntoPhi(I))
7956       return NV;
7957   
7958   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7959   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7960     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7961     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7962     // place.  Don't try to do this transformation in this case.  Also, we
7963     // require that the input operand is a shift-by-constant so that we have
7964     // confidence that the shifts will get folded together.  We could do this
7965     // xform in more cases, but it is unlikely to be profitable.
7966     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7967         isa<ConstantInt>(TrOp->getOperand(1))) {
7968       // Okay, we'll do this xform.  Make the shift of shift.
7969       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7970       // (shift2 (shift1 & 0x00FF), c2)
7971       Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7972
7973       // For logical shifts, the truncation has the effect of making the high
7974       // part of the register be zeros.  Emulate this by inserting an AND to
7975       // clear the top bits as needed.  This 'and' will usually be zapped by
7976       // other xforms later if dead.
7977       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7978       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7979       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7980       
7981       // The mask we constructed says what the trunc would do if occurring
7982       // between the shifts.  We want to know the effect *after* the second
7983       // shift.  We know that it is a logical shift by a constant, so adjust the
7984       // mask as appropriate.
7985       if (I.getOpcode() == Instruction::Shl)
7986         MaskV <<= Op1->getZExtValue();
7987       else {
7988         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7989         MaskV = MaskV.lshr(Op1->getZExtValue());
7990       }
7991
7992       // shift1 & 0x00FF
7993       Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7994                                       TI->getName());
7995
7996       // Return the value truncated to the interesting size.
7997       return new TruncInst(And, I.getType());
7998     }
7999   }
8000   
8001   if (Op0->hasOneUse()) {
8002     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
8003       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
8004       Value *V1, *V2;
8005       ConstantInt *CC;
8006       switch (Op0BO->getOpcode()) {
8007         default: break;
8008         case Instruction::Add:
8009         case Instruction::And:
8010         case Instruction::Or:
8011         case Instruction::Xor: {
8012           // These operators commute.
8013           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
8014           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
8015               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
8016                     m_Specific(Op1)))) {
8017             Value *YS =         // (Y << C)
8018               Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
8019             // (X + (Y << C))
8020             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
8021                                             Op0BO->getOperand(1)->getName());
8022             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
8023             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
8024                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
8025           }
8026           
8027           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
8028           Value *Op0BOOp1 = Op0BO->getOperand(1);
8029           if (isLeftShift && Op0BOOp1->hasOneUse() &&
8030               match(Op0BOOp1, 
8031                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
8032                           m_ConstantInt(CC))) &&
8033               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
8034             Value *YS =   // (Y << C)
8035               Builder->CreateShl(Op0BO->getOperand(0), Op1,
8036                                            Op0BO->getName());
8037             // X & (CC << C)
8038             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8039                                            V1->getName()+".mask");
8040             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
8041           }
8042         }
8043           
8044         // FALL THROUGH.
8045         case Instruction::Sub: {
8046           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
8047           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
8048               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
8049                     m_Specific(Op1)))) {
8050             Value *YS =  // (Y << C)
8051               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8052             // (X + (Y << C))
8053             Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
8054                                             Op0BO->getOperand(0)->getName());
8055             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
8056             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
8057                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
8058           }
8059           
8060           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
8061           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
8062               match(Op0BO->getOperand(0),
8063                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
8064                           m_ConstantInt(CC))) && V2 == Op1 &&
8065               cast<BinaryOperator>(Op0BO->getOperand(0))
8066                   ->getOperand(0)->hasOneUse()) {
8067             Value *YS = // (Y << C)
8068               Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8069             // X & (CC << C)
8070             Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8071                                            V1->getName()+".mask");
8072             
8073             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
8074           }
8075           
8076           break;
8077         }
8078       }
8079       
8080       
8081       // If the operand is an bitwise operator with a constant RHS, and the
8082       // shift is the only use, we can pull it out of the shift.
8083       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
8084         bool isValid = true;     // Valid only for And, Or, Xor
8085         bool highBitSet = false; // Transform if high bit of constant set?
8086         
8087         switch (Op0BO->getOpcode()) {
8088           default: isValid = false; break;   // Do not perform transform!
8089           case Instruction::Add:
8090             isValid = isLeftShift;
8091             break;
8092           case Instruction::Or:
8093           case Instruction::Xor:
8094             highBitSet = false;
8095             break;
8096           case Instruction::And:
8097             highBitSet = true;
8098             break;
8099         }
8100         
8101         // If this is a signed shift right, and the high bit is modified
8102         // by the logical operation, do not perform the transformation.
8103         // The highBitSet boolean indicates the value of the high bit of
8104         // the constant which would cause it to be modified for this
8105         // operation.
8106         //
8107         if (isValid && I.getOpcode() == Instruction::AShr)
8108           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
8109         
8110         if (isValid) {
8111           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
8112           
8113           Value *NewShift =
8114             Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
8115           NewShift->takeName(Op0BO);
8116           
8117           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
8118                                         NewRHS);
8119         }
8120       }
8121     }
8122   }
8123   
8124   // Find out if this is a shift of a shift by a constant.
8125   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
8126   if (ShiftOp && !ShiftOp->isShift())
8127     ShiftOp = 0;
8128   
8129   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
8130     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
8131     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
8132     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
8133     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
8134     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
8135     Value *X = ShiftOp->getOperand(0);
8136     
8137     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
8138     
8139     const IntegerType *Ty = cast<IntegerType>(I.getType());
8140     
8141     // Check for (X << c1) << c2  and  (X >> c1) >> c2
8142     if (I.getOpcode() == ShiftOp->getOpcode()) {
8143       // If this is oversized composite shift, then unsigned shifts get 0, ashr
8144       // saturates.
8145       if (AmtSum >= TypeBits) {
8146         if (I.getOpcode() != Instruction::AShr)
8147           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
8148         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
8149       }
8150       
8151       return BinaryOperator::Create(I.getOpcode(), X,
8152                                     ConstantInt::get(Ty, AmtSum));
8153     }
8154     
8155     if (ShiftOp->getOpcode() == Instruction::LShr &&
8156         I.getOpcode() == Instruction::AShr) {
8157       if (AmtSum >= TypeBits)
8158         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
8159       
8160       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
8161       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
8162     }
8163     
8164     if (ShiftOp->getOpcode() == Instruction::AShr &&
8165         I.getOpcode() == Instruction::LShr) {
8166       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
8167       if (AmtSum >= TypeBits)
8168         AmtSum = TypeBits-1;
8169       
8170       Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
8171
8172       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
8173       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
8174     }
8175     
8176     // Okay, if we get here, one shift must be left, and the other shift must be
8177     // right.  See if the amounts are equal.
8178     if (ShiftAmt1 == ShiftAmt2) {
8179       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8180       if (I.getOpcode() == Instruction::Shl) {
8181         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
8182         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
8183       }
8184       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8185       if (I.getOpcode() == Instruction::LShr) {
8186         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
8187         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
8188       }
8189       // We can simplify ((X << C) >>s C) into a trunc + sext.
8190       // NOTE: we could do this for any C, but that would make 'unusual' integer
8191       // types.  For now, just stick to ones well-supported by the code
8192       // generators.
8193       const Type *SExtType = 0;
8194       switch (Ty->getBitWidth() - ShiftAmt1) {
8195       case 1  :
8196       case 8  :
8197       case 16 :
8198       case 32 :
8199       case 64 :
8200       case 128:
8201         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
8202         break;
8203       default: break;
8204       }
8205       if (SExtType)
8206         return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
8207       // Otherwise, we can't handle it yet.
8208     } else if (ShiftAmt1 < ShiftAmt2) {
8209       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
8210       
8211       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
8212       if (I.getOpcode() == Instruction::Shl) {
8213         assert(ShiftOp->getOpcode() == Instruction::LShr ||
8214                ShiftOp->getOpcode() == Instruction::AShr);
8215         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
8216         
8217         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
8218         return BinaryOperator::CreateAnd(Shift,
8219                                          ConstantInt::get(*Context, Mask));
8220       }
8221       
8222       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
8223       if (I.getOpcode() == Instruction::LShr) {
8224         assert(ShiftOp->getOpcode() == Instruction::Shl);
8225         Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
8226         
8227         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
8228         return BinaryOperator::CreateAnd(Shift,
8229                                          ConstantInt::get(*Context, Mask));
8230       }
8231       
8232       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8233     } else {
8234       assert(ShiftAmt2 < ShiftAmt1);
8235       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
8236
8237       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
8238       if (I.getOpcode() == Instruction::Shl) {
8239         assert(ShiftOp->getOpcode() == Instruction::LShr ||
8240                ShiftOp->getOpcode() == Instruction::AShr);
8241         Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8242                                             ConstantInt::get(Ty, ShiftDiff));
8243         
8244         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
8245         return BinaryOperator::CreateAnd(Shift,
8246                                          ConstantInt::get(*Context, Mask));
8247       }
8248       
8249       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
8250       if (I.getOpcode() == Instruction::LShr) {
8251         assert(ShiftOp->getOpcode() == Instruction::Shl);
8252         Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
8253         
8254         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
8255         return BinaryOperator::CreateAnd(Shift,
8256                                          ConstantInt::get(*Context, Mask));
8257       }
8258       
8259       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
8260     }
8261   }
8262   return 0;
8263 }
8264
8265
8266 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8267 /// expression.  If so, decompose it, returning some value X, such that Val is
8268 /// X*Scale+Offset.
8269 ///
8270 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
8271                                         int &Offset, LLVMContext *Context) {
8272   assert(Val->getType() == Type::getInt32Ty(*Context) && 
8273          "Unexpected allocation size type!");
8274   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
8275     Offset = CI->getZExtValue();
8276     Scale  = 0;
8277     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
8278   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8279     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8280       if (I->getOpcode() == Instruction::Shl) {
8281         // This is a value scaled by '1 << the shift amt'.
8282         Scale = 1U << RHS->getZExtValue();
8283         Offset = 0;
8284         return I->getOperand(0);
8285       } else if (I->getOpcode() == Instruction::Mul) {
8286         // This value is scaled by 'RHS'.
8287         Scale = RHS->getZExtValue();
8288         Offset = 0;
8289         return I->getOperand(0);
8290       } else if (I->getOpcode() == Instruction::Add) {
8291         // We have X+C.  Check to see if we really have (X*C2)+C1, 
8292         // where C1 is divisible by C2.
8293         unsigned SubScale;
8294         Value *SubVal = 
8295           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8296                                     Offset, Context);
8297         Offset += RHS->getZExtValue();
8298         Scale = SubScale;
8299         return SubVal;
8300       }
8301     }
8302   }
8303
8304   // Otherwise, we can't look past this.
8305   Scale = 1;
8306   Offset = 0;
8307   return Val;
8308 }
8309
8310
8311 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8312 /// try to eliminate the cast by moving the type information into the alloc.
8313 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
8314                                                    AllocaInst &AI) {
8315   const PointerType *PTy = cast<PointerType>(CI.getType());
8316   
8317   BuilderTy AllocaBuilder(*Builder);
8318   AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8319   
8320   // Remove any uses of AI that are dead.
8321   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
8322   
8323   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8324     Instruction *User = cast<Instruction>(*UI++);
8325     if (isInstructionTriviallyDead(User)) {
8326       while (UI != E && *UI == User)
8327         ++UI; // If this instruction uses AI more than once, don't break UI.
8328       
8329       ++NumDeadInst;
8330       DEBUG(errs() << "IC: DCE: " << *User << '\n');
8331       EraseInstFromFunction(*User);
8332     }
8333   }
8334
8335   // This requires TargetData to get the alloca alignment and size information.
8336   if (!TD) return 0;
8337
8338   // Get the type really allocated and the type casted to.
8339   const Type *AllocElTy = AI.getAllocatedType();
8340   const Type *CastElTy = PTy->getElementType();
8341   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
8342
8343   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8344   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
8345   if (CastElTyAlign < AllocElTyAlign) return 0;
8346
8347   // If the allocation has multiple uses, only promote it if we are strictly
8348   // increasing the alignment of the resultant allocation.  If we keep it the
8349   // same, we open the door to infinite loops of various kinds.  (A reference
8350   // from a dbg.declare doesn't count as a use for this purpose.)
8351   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8352       CastElTyAlign == AllocElTyAlign) return 0;
8353
8354   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8355   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
8356   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
8357
8358   // See if we can satisfy the modulus by pulling a scale out of the array
8359   // size argument.
8360   unsigned ArraySizeScale;
8361   int ArrayOffset;
8362   Value *NumElements = // See if the array size is a decomposable linear expr.
8363     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8364                               ArrayOffset, Context);
8365  
8366   // If we can now satisfy the modulus, by using a non-1 scale, we really can
8367   // do the xform.
8368   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8369       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
8370
8371   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8372   Value *Amt = 0;
8373   if (Scale == 1) {
8374     Amt = NumElements;
8375   } else {
8376     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
8377     // Insert before the alloca, not before the cast.
8378     Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
8379   }
8380   
8381   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
8382     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
8383     Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
8384   }
8385   
8386   AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
8387   New->setAlignment(AI.getAlignment());
8388   New->takeName(&AI);
8389   
8390   // If the allocation has one real use plus a dbg.declare, just remove the
8391   // declare.
8392   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8393     EraseInstFromFunction(*DI);
8394   }
8395   // If the allocation has multiple real uses, insert a cast and change all
8396   // things that used it to use the new cast.  This will also hack on CI, but it
8397   // will die soon.
8398   else if (!AI.hasOneUse()) {
8399     // New is the allocation instruction, pointer typed. AI is the original
8400     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
8401     Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
8402     AI.replaceAllUsesWith(NewCast);
8403   }
8404   return ReplaceInstUsesWith(CI, New);
8405 }
8406
8407 /// CanEvaluateInDifferentType - Return true if we can take the specified value
8408 /// and return it as type Ty without inserting any new casts and without
8409 /// changing the computed value.  This is used by code that tries to decide
8410 /// whether promoting or shrinking integer operations to wider or smaller types
8411 /// will allow us to eliminate a truncate or extend.
8412 ///
8413 /// This is a truncation operation if Ty is smaller than V->getType(), or an
8414 /// extension operation if Ty is larger.
8415 ///
8416 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
8417 /// should return true if trunc(V) can be computed by computing V in the smaller
8418 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
8419 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8420 /// efficiently truncated.
8421 ///
8422 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8423 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8424 /// the final result.
8425 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
8426                                               unsigned CastOpc,
8427                                               int &NumCastsRemoved){
8428   // We can always evaluate constants in another type.
8429   if (isa<Constant>(V))
8430     return true;
8431   
8432   Instruction *I = dyn_cast<Instruction>(V);
8433   if (!I) return false;
8434   
8435   const Type *OrigTy = V->getType();
8436   
8437   // If this is an extension or truncate, we can often eliminate it.
8438   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8439     // If this is a cast from the destination type, we can trivially eliminate
8440     // it, and this will remove a cast overall.
8441     if (I->getOperand(0)->getType() == Ty) {
8442       // If the first operand is itself a cast, and is eliminable, do not count
8443       // this as an eliminable cast.  We would prefer to eliminate those two
8444       // casts first.
8445       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
8446         ++NumCastsRemoved;
8447       return true;
8448     }
8449   }
8450
8451   // We can't extend or shrink something that has multiple uses: doing so would
8452   // require duplicating the instruction in general, which isn't profitable.
8453   if (!I->hasOneUse()) return false;
8454
8455   unsigned Opc = I->getOpcode();
8456   switch (Opc) {
8457   case Instruction::Add:
8458   case Instruction::Sub:
8459   case Instruction::Mul:
8460   case Instruction::And:
8461   case Instruction::Or:
8462   case Instruction::Xor:
8463     // These operators can all arbitrarily be extended or truncated.
8464     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8465                                       NumCastsRemoved) &&
8466            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8467                                       NumCastsRemoved);
8468
8469   case Instruction::UDiv:
8470   case Instruction::URem: {
8471     // UDiv and URem can be truncated if all the truncated bits are zero.
8472     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8473     uint32_t BitWidth = Ty->getScalarSizeInBits();
8474     if (BitWidth < OrigBitWidth) {
8475       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8476       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8477           MaskedValueIsZero(I->getOperand(1), Mask)) {
8478         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8479                                           NumCastsRemoved) &&
8480                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8481                                           NumCastsRemoved);
8482       }
8483     }
8484     break;
8485   }
8486   case Instruction::Shl:
8487     // If we are truncating the result of this SHL, and if it's a shift of a
8488     // constant amount, we can always perform a SHL in a smaller type.
8489     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8490       uint32_t BitWidth = Ty->getScalarSizeInBits();
8491       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8492           CI->getLimitedValue(BitWidth) < BitWidth)
8493         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8494                                           NumCastsRemoved);
8495     }
8496     break;
8497   case Instruction::LShr:
8498     // If this is a truncate of a logical shr, we can truncate it to a smaller
8499     // lshr iff we know that the bits we would otherwise be shifting in are
8500     // already zeros.
8501     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8502       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8503       uint32_t BitWidth = Ty->getScalarSizeInBits();
8504       if (BitWidth < OrigBitWidth &&
8505           MaskedValueIsZero(I->getOperand(0),
8506             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8507           CI->getLimitedValue(BitWidth) < BitWidth) {
8508         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8509                                           NumCastsRemoved);
8510       }
8511     }
8512     break;
8513   case Instruction::ZExt:
8514   case Instruction::SExt:
8515   case Instruction::Trunc:
8516     // If this is the same kind of case as our original (e.g. zext+zext), we
8517     // can safely replace it.  Note that replacing it does not reduce the number
8518     // of casts in the input.
8519     if (Opc == CastOpc)
8520       return true;
8521
8522     // sext (zext ty1), ty2 -> zext ty2
8523     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8524       return true;
8525     break;
8526   case Instruction::Select: {
8527     SelectInst *SI = cast<SelectInst>(I);
8528     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8529                                       NumCastsRemoved) &&
8530            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8531                                       NumCastsRemoved);
8532   }
8533   case Instruction::PHI: {
8534     // We can change a phi if we can change all operands.
8535     PHINode *PN = cast<PHINode>(I);
8536     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8537       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8538                                       NumCastsRemoved))
8539         return false;
8540     return true;
8541   }
8542   default:
8543     // TODO: Can handle more cases here.
8544     break;
8545   }
8546   
8547   return false;
8548 }
8549
8550 /// EvaluateInDifferentType - Given an expression that 
8551 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8552 /// evaluate the expression.
8553 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8554                                              bool isSigned) {
8555   if (Constant *C = dyn_cast<Constant>(V))
8556     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
8557
8558   // Otherwise, it must be an instruction.
8559   Instruction *I = cast<Instruction>(V);
8560   Instruction *Res = 0;
8561   unsigned Opc = I->getOpcode();
8562   switch (Opc) {
8563   case Instruction::Add:
8564   case Instruction::Sub:
8565   case Instruction::Mul:
8566   case Instruction::And:
8567   case Instruction::Or:
8568   case Instruction::Xor:
8569   case Instruction::AShr:
8570   case Instruction::LShr:
8571   case Instruction::Shl:
8572   case Instruction::UDiv:
8573   case Instruction::URem: {
8574     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8575     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8576     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8577     break;
8578   }    
8579   case Instruction::Trunc:
8580   case Instruction::ZExt:
8581   case Instruction::SExt:
8582     // If the source type of the cast is the type we're trying for then we can
8583     // just return the source.  There's no need to insert it because it is not
8584     // new.
8585     if (I->getOperand(0)->getType() == Ty)
8586       return I->getOperand(0);
8587     
8588     // Otherwise, must be the same type of cast, so just reinsert a new one.
8589     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
8590     break;
8591   case Instruction::Select: {
8592     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8593     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8594     Res = SelectInst::Create(I->getOperand(0), True, False);
8595     break;
8596   }
8597   case Instruction::PHI: {
8598     PHINode *OPN = cast<PHINode>(I);
8599     PHINode *NPN = PHINode::Create(Ty);
8600     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8601       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8602       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8603     }
8604     Res = NPN;
8605     break;
8606   }
8607   default: 
8608     // TODO: Can handle more cases here.
8609     llvm_unreachable("Unreachable!");
8610     break;
8611   }
8612   
8613   Res->takeName(I);
8614   return InsertNewInstBefore(Res, *I);
8615 }
8616
8617 /// @brief Implement the transforms common to all CastInst visitors.
8618 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8619   Value *Src = CI.getOperand(0);
8620
8621   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8622   // eliminate it now.
8623   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8624     if (Instruction::CastOps opc = 
8625         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8626       // The first cast (CSrc) is eliminable so we need to fix up or replace
8627       // the second cast (CI). CSrc will then have a good chance of being dead.
8628       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8629     }
8630   }
8631
8632   // If we are casting a select then fold the cast into the select
8633   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8634     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8635       return NV;
8636
8637   // If we are casting a PHI then fold the cast into the PHI
8638   if (isa<PHINode>(Src)) {
8639     // We don't do this if this would create a PHI node with an illegal type if
8640     // it is currently legal.
8641     if (!isa<IntegerType>(Src->getType()) ||
8642         !isa<IntegerType>(CI.getType()) ||
8643         ShouldChangeType(CI.getType(), Src->getType(), TD))
8644       if (Instruction *NV = FoldOpIntoPhi(CI))
8645         return NV;
8646   }
8647   
8648   return 0;
8649 }
8650
8651 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8652 /// or not there is a sequence of GEP indices into the type that will land us at
8653 /// the specified offset.  If so, fill them into NewIndices and return the
8654 /// resultant element type, otherwise return null.
8655 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8656                                        SmallVectorImpl<Value*> &NewIndices,
8657                                        const TargetData *TD,
8658                                        LLVMContext *Context) {
8659   if (!TD) return 0;
8660   if (!Ty->isSized()) return 0;
8661   
8662   // Start with the index over the outer type.  Note that the type size
8663   // might be zero (even if the offset isn't zero) if the indexed type
8664   // is something like [0 x {int, int}]
8665   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8666   int64_t FirstIdx = 0;
8667   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8668     FirstIdx = Offset/TySize;
8669     Offset -= FirstIdx*TySize;
8670     
8671     // Handle hosts where % returns negative instead of values [0..TySize).
8672     if (Offset < 0) {
8673       --FirstIdx;
8674       Offset += TySize;
8675       assert(Offset >= 0);
8676     }
8677     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8678   }
8679   
8680   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8681     
8682   // Index into the types.  If we fail, set OrigBase to null.
8683   while (Offset) {
8684     // Indexing into tail padding between struct/array elements.
8685     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8686       return 0;
8687     
8688     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8689       const StructLayout *SL = TD->getStructLayout(STy);
8690       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8691              "Offset must stay within the indexed type");
8692       
8693       unsigned Elt = SL->getElementContainingOffset(Offset);
8694       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8695       
8696       Offset -= SL->getElementOffset(Elt);
8697       Ty = STy->getElementType(Elt);
8698     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8699       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8700       assert(EltSize && "Cannot index into a zero-sized array");
8701       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8702       Offset %= EltSize;
8703       Ty = AT->getElementType();
8704     } else {
8705       // Otherwise, we can't index into the middle of this atomic type, bail.
8706       return 0;
8707     }
8708   }
8709   
8710   return Ty;
8711 }
8712
8713 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8714 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8715   Value *Src = CI.getOperand(0);
8716   
8717   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8718     // If casting the result of a getelementptr instruction with no offset, turn
8719     // this into a cast of the original pointer!
8720     if (GEP->hasAllZeroIndices()) {
8721       // Changing the cast operand is usually not a good idea but it is safe
8722       // here because the pointer operand is being replaced with another 
8723       // pointer operand so the opcode doesn't need to change.
8724       Worklist.Add(GEP);
8725       CI.setOperand(0, GEP->getOperand(0));
8726       return &CI;
8727     }
8728     
8729     // If the GEP has a single use, and the base pointer is a bitcast, and the
8730     // GEP computes a constant offset, see if we can convert these three
8731     // instructions into fewer.  This typically happens with unions and other
8732     // non-type-safe code.
8733     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8734       if (GEP->hasAllConstantIndices()) {
8735         // We are guaranteed to get a constant from EmitGEPOffset.
8736         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
8737         int64_t Offset = OffsetV->getSExtValue();
8738         
8739         // Get the base pointer input of the bitcast, and the type it points to.
8740         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8741         const Type *GEPIdxTy =
8742           cast<PointerType>(OrigBase->getType())->getElementType();
8743         SmallVector<Value*, 8> NewIndices;
8744         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8745           // If we were able to index down into an element, create the GEP
8746           // and bitcast the result.  This eliminates one bitcast, potentially
8747           // two.
8748           Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8749             Builder->CreateInBoundsGEP(OrigBase,
8750                                        NewIndices.begin(), NewIndices.end()) :
8751             Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8752           NGEP->takeName(GEP);
8753           
8754           if (isa<BitCastInst>(CI))
8755             return new BitCastInst(NGEP, CI.getType());
8756           assert(isa<PtrToIntInst>(CI));
8757           return new PtrToIntInst(NGEP, CI.getType());
8758         }
8759       }      
8760     }
8761   }
8762     
8763   return commonCastTransforms(CI);
8764 }
8765
8766 /// commonIntCastTransforms - This function implements the common transforms
8767 /// for trunc, zext, and sext.
8768 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8769   if (Instruction *Result = commonCastTransforms(CI))
8770     return Result;
8771
8772   Value *Src = CI.getOperand(0);
8773   const Type *SrcTy = Src->getType();
8774   const Type *DestTy = CI.getType();
8775   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8776   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8777
8778   // See if we can simplify any instructions used by the LHS whose sole 
8779   // purpose is to compute bits we don't care about.
8780   if (SimplifyDemandedInstructionBits(CI))
8781     return &CI;
8782
8783   // If the source isn't an instruction or has more than one use then we
8784   // can't do anything more. 
8785   Instruction *SrcI = dyn_cast<Instruction>(Src);
8786   if (!SrcI || !Src->hasOneUse())
8787     return 0;
8788
8789   // Attempt to propagate the cast into the instruction for int->int casts.
8790   int NumCastsRemoved = 0;
8791   // Only do this if the dest type is a simple type, don't convert the
8792   // expression tree to something weird like i93 unless the source is also
8793   // strange.
8794   if ((isa<VectorType>(DestTy) ||
8795        ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8796       CanEvaluateInDifferentType(SrcI, DestTy,
8797                                  CI.getOpcode(), NumCastsRemoved)) {
8798     // If this cast is a truncate, evaluting in a different type always
8799     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8800     // we need to do an AND to maintain the clear top-part of the computation,
8801     // so we require that the input have eliminated at least one cast.  If this
8802     // is a sign extension, we insert two new casts (to do the extension) so we
8803     // require that two casts have been eliminated.
8804     bool DoXForm = false;
8805     bool JustReplace = false;
8806     switch (CI.getOpcode()) {
8807     default:
8808       // All the others use floating point so we shouldn't actually 
8809       // get here because of the check above.
8810       llvm_unreachable("Unknown cast type");
8811     case Instruction::Trunc:
8812       DoXForm = true;
8813       break;
8814     case Instruction::ZExt: {
8815       DoXForm = NumCastsRemoved >= 1;
8816       
8817       if (!DoXForm && 0) {
8818         // If it's unnecessary to issue an AND to clear the high bits, it's
8819         // always profitable to do this xform.
8820         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8821         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8822         if (MaskedValueIsZero(TryRes, Mask))
8823           return ReplaceInstUsesWith(CI, TryRes);
8824         
8825         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8826           if (TryI->use_empty())
8827             EraseInstFromFunction(*TryI);
8828       }
8829       break;
8830     }
8831     case Instruction::SExt: {
8832       DoXForm = NumCastsRemoved >= 2;
8833       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8834         // If we do not have to emit the truncate + sext pair, then it's always
8835         // profitable to do this xform.
8836         //
8837         // It's not safe to eliminate the trunc + sext pair if one of the
8838         // eliminated cast is a truncate. e.g.
8839         // t2 = trunc i32 t1 to i16
8840         // t3 = sext i16 t2 to i32
8841         // !=
8842         // i32 t1
8843         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8844         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8845         if (NumSignBits > (DestBitSize - SrcBitSize))
8846           return ReplaceInstUsesWith(CI, TryRes);
8847         
8848         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8849           if (TryI->use_empty())
8850             EraseInstFromFunction(*TryI);
8851       }
8852       break;
8853     }
8854     }
8855     
8856     if (DoXForm) {
8857       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8858             " to avoid cast: " << CI);
8859       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8860                                            CI.getOpcode() == Instruction::SExt);
8861       if (JustReplace)
8862         // Just replace this cast with the result.
8863         return ReplaceInstUsesWith(CI, Res);
8864
8865       assert(Res->getType() == DestTy);
8866       switch (CI.getOpcode()) {
8867       default: llvm_unreachable("Unknown cast type!");
8868       case Instruction::Trunc:
8869         // Just replace this cast with the result.
8870         return ReplaceInstUsesWith(CI, Res);
8871       case Instruction::ZExt: {
8872         assert(SrcBitSize < DestBitSize && "Not a zext?");
8873
8874         // If the high bits are already zero, just replace this cast with the
8875         // result.
8876         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8877         if (MaskedValueIsZero(Res, Mask))
8878           return ReplaceInstUsesWith(CI, Res);
8879
8880         // We need to emit an AND to clear the high bits.
8881         Constant *C = ConstantInt::get(*Context, 
8882                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8883         return BinaryOperator::CreateAnd(Res, C);
8884       }
8885       case Instruction::SExt: {
8886         // If the high bits are already filled with sign bit, just replace this
8887         // cast with the result.
8888         unsigned NumSignBits = ComputeNumSignBits(Res);
8889         if (NumSignBits > (DestBitSize - SrcBitSize))
8890           return ReplaceInstUsesWith(CI, Res);
8891
8892         // We need to emit a cast to truncate, then a cast to sext.
8893         return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8894       }
8895       }
8896     }
8897   }
8898   
8899   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8900   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8901
8902   switch (SrcI->getOpcode()) {
8903   case Instruction::Add:
8904   case Instruction::Mul:
8905   case Instruction::And:
8906   case Instruction::Or:
8907   case Instruction::Xor:
8908     // If we are discarding information, rewrite.
8909     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8910       // Don't insert two casts unless at least one can be eliminated.
8911       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8912           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8913         Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8914         Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8915         return BinaryOperator::Create(
8916             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8917       }
8918     }
8919
8920     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8921     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8922         SrcI->getOpcode() == Instruction::Xor &&
8923         Op1 == ConstantInt::getTrue(*Context) &&
8924         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8925       Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8926       return BinaryOperator::CreateXor(New,
8927                                       ConstantInt::get(CI.getType(), 1));
8928     }
8929     break;
8930
8931   case Instruction::Shl: {
8932     // Canonicalize trunc inside shl, if we can.
8933     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8934     if (CI && DestBitSize < SrcBitSize &&
8935         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8936       Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8937       Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8938       return BinaryOperator::CreateShl(Op0c, Op1c);
8939     }
8940     break;
8941   }
8942   }
8943   return 0;
8944 }
8945
8946 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8947   if (Instruction *Result = commonIntCastTransforms(CI))
8948     return Result;
8949   
8950   Value *Src = CI.getOperand(0);
8951   const Type *Ty = CI.getType();
8952   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8953   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8954
8955   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8956   if (DestBitWidth == 1) {
8957     Constant *One = ConstantInt::get(Src->getType(), 1);
8958     Src = Builder->CreateAnd(Src, One, "tmp");
8959     Value *Zero = Constant::getNullValue(Src->getType());
8960     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8961   }
8962
8963   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8964   ConstantInt *ShAmtV = 0;
8965   Value *ShiftOp = 0;
8966   if (Src->hasOneUse() &&
8967       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8968     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8969     
8970     // Get a mask for the bits shifting in.
8971     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8972     if (MaskedValueIsZero(ShiftOp, Mask)) {
8973       if (ShAmt >= DestBitWidth)        // All zeros.
8974         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8975       
8976       // Okay, we can shrink this.  Truncate the input, then return a new
8977       // shift.
8978       Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8979       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8980       return BinaryOperator::CreateLShr(V1, V2);
8981     }
8982   }
8983  
8984   return 0;
8985 }
8986
8987 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8988 /// in order to eliminate the icmp.
8989 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8990                                              bool DoXform) {
8991   // If we are just checking for a icmp eq of a single bit and zext'ing it
8992   // to an integer, then shift the bit to the appropriate place and then
8993   // cast to integer to avoid the comparison.
8994   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8995     const APInt &Op1CV = Op1C->getValue();
8996       
8997     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8998     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8999     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9000         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
9001       if (!DoXform) return ICI;
9002
9003       Value *In = ICI->getOperand(0);
9004       Value *Sh = ConstantInt::get(In->getType(),
9005                                    In->getType()->getScalarSizeInBits()-1);
9006       In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
9007       if (In->getType() != CI.getType())
9008         In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
9009
9010       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
9011         Constant *One = ConstantInt::get(In->getType(), 1);
9012         In = Builder->CreateXor(In, One, In->getName()+".not");
9013       }
9014
9015       return ReplaceInstUsesWith(CI, In);
9016     }
9017       
9018       
9019       
9020     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
9021     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
9022     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
9023     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
9024     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
9025     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
9026     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
9027     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
9028     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
9029         // This only works for EQ and NE
9030         ICI->isEquality()) {
9031       // If Op1C some other power of two, convert:
9032       uint32_t BitWidth = Op1C->getType()->getBitWidth();
9033       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9034       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9035       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
9036         
9037       APInt KnownZeroMask(~KnownZero);
9038       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
9039         if (!DoXform) return ICI;
9040
9041         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
9042         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
9043           // (X&4) == 2 --> false
9044           // (X&4) != 2 --> true
9045           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
9046           Res = ConstantExpr::getZExt(Res, CI.getType());
9047           return ReplaceInstUsesWith(CI, Res);
9048         }
9049           
9050         uint32_t ShiftAmt = KnownZeroMask.logBase2();
9051         Value *In = ICI->getOperand(0);
9052         if (ShiftAmt) {
9053           // Perform a logical shr by shiftamt.
9054           // Insert the shift to put the result in the low bit.
9055           In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
9056                                    In->getName()+".lobit");
9057         }
9058           
9059         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
9060           Constant *One = ConstantInt::get(In->getType(), 1);
9061           In = Builder->CreateXor(In, One, "tmp");
9062         }
9063           
9064         if (CI.getType() == In->getType())
9065           return ReplaceInstUsesWith(CI, In);
9066         else
9067           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
9068       }
9069     }
9070   }
9071
9072   // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
9073   // It is also profitable to transform icmp eq into not(xor(A, B)) because that
9074   // may lead to additional simplifications.
9075   if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
9076     if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
9077       uint32_t BitWidth = ITy->getBitWidth();
9078       Value *LHS = ICI->getOperand(0);
9079       Value *RHS = ICI->getOperand(1);
9080
9081       APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
9082       APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
9083       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9084       ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
9085       ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
9086
9087       if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
9088         APInt KnownBits = KnownZeroLHS | KnownOneLHS;
9089         APInt UnknownBit = ~KnownBits;
9090         if (UnknownBit.countPopulation() == 1) {
9091           if (!DoXform) return ICI;
9092
9093           Value *Result = Builder->CreateXor(LHS, RHS);
9094
9095           // Mask off any bits that are set and won't be shifted away.
9096           if (KnownOneLHS.uge(UnknownBit))
9097             Result = Builder->CreateAnd(Result,
9098                                         ConstantInt::get(ITy, UnknownBit));
9099
9100           // Shift the bit we're testing down to the lsb.
9101           Result = Builder->CreateLShr(
9102                Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
9103
9104           if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
9105             Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
9106           Result->takeName(ICI);
9107           return ReplaceInstUsesWith(CI, Result);
9108         }
9109       }
9110     }
9111   }
9112
9113   return 0;
9114 }
9115
9116 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
9117   // If one of the common conversion will work ..
9118   if (Instruction *Result = commonIntCastTransforms(CI))
9119     return Result;
9120
9121   Value *Src = CI.getOperand(0);
9122
9123   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
9124   // types and if the sizes are just right we can convert this into a logical
9125   // 'and' which will be much cheaper than the pair of casts.
9126   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
9127     // Get the sizes of the types involved.  We know that the intermediate type
9128     // will be smaller than A or C, but don't know the relation between A and C.
9129     Value *A = CSrc->getOperand(0);
9130     unsigned SrcSize = A->getType()->getScalarSizeInBits();
9131     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
9132     unsigned DstSize = CI.getType()->getScalarSizeInBits();
9133     // If we're actually extending zero bits, then if
9134     // SrcSize <  DstSize: zext(a & mask)
9135     // SrcSize == DstSize: a & mask
9136     // SrcSize  > DstSize: trunc(a) & mask
9137     if (SrcSize < DstSize) {
9138       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
9139       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
9140       Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
9141       return new ZExtInst(And, CI.getType());
9142     }
9143     
9144     if (SrcSize == DstSize) {
9145       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
9146       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
9147                                                            AndValue));
9148     }
9149     if (SrcSize > DstSize) {
9150       Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
9151       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
9152       return BinaryOperator::CreateAnd(Trunc, 
9153                                        ConstantInt::get(Trunc->getType(),
9154                                                                AndValue));
9155     }
9156   }
9157
9158   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9159     return transformZExtICmp(ICI, CI);
9160
9161   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9162   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9163     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9164     // of the (zext icmp) will be transformed.
9165     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9166     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9167     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9168         (transformZExtICmp(LHS, CI, false) ||
9169          transformZExtICmp(RHS, CI, false))) {
9170       Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9171       Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
9172       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
9173     }
9174   }
9175
9176   // zext(trunc(t) & C) -> (t & zext(C)).
9177   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9178     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9179       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9180         Value *TI0 = TI->getOperand(0);
9181         if (TI0->getType() == CI.getType())
9182           return
9183             BinaryOperator::CreateAnd(TI0,
9184                                 ConstantExpr::getZExt(C, CI.getType()));
9185       }
9186
9187   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9188   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9189     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9190       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9191         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9192             And->getOperand(1) == C)
9193           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9194             Value *TI0 = TI->getOperand(0);
9195             if (TI0->getType() == CI.getType()) {
9196               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
9197               Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
9198               return BinaryOperator::CreateXor(NewAnd, ZC);
9199             }
9200           }
9201
9202   return 0;
9203 }
9204
9205 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
9206   if (Instruction *I = commonIntCastTransforms(CI))
9207     return I;
9208   
9209   Value *Src = CI.getOperand(0);
9210   
9211   // Canonicalize sign-extend from i1 to a select.
9212   if (Src->getType() == Type::getInt1Ty(*Context))
9213     return SelectInst::Create(Src,
9214                               Constant::getAllOnesValue(CI.getType()),
9215                               Constant::getNullValue(CI.getType()));
9216
9217   // See if the value being truncated is already sign extended.  If so, just
9218   // eliminate the trunc/sext pair.
9219   if (Operator::getOpcode(Src) == Instruction::Trunc) {
9220     Value *Op = cast<User>(Src)->getOperand(0);
9221     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
9222     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
9223     unsigned DestBits = CI.getType()->getScalarSizeInBits();
9224     unsigned NumSignBits = ComputeNumSignBits(Op);
9225
9226     if (OpBits == DestBits) {
9227       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
9228       // bits, it is already ready.
9229       if (NumSignBits > DestBits-MidBits)
9230         return ReplaceInstUsesWith(CI, Op);
9231     } else if (OpBits < DestBits) {
9232       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
9233       // bits, just sext from i32.
9234       if (NumSignBits > OpBits-MidBits)
9235         return new SExtInst(Op, CI.getType(), "tmp");
9236     } else {
9237       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
9238       // bits, just truncate to i32.
9239       if (NumSignBits > OpBits-MidBits)
9240         return new TruncInst(Op, CI.getType(), "tmp");
9241     }
9242   }
9243
9244   // If the input is a shl/ashr pair of a same constant, then this is a sign
9245   // extension from a smaller value.  If we could trust arbitrary bitwidth
9246   // integers, we could turn this into a truncate to the smaller bit and then
9247   // use a sext for the whole extension.  Since we don't, look deeper and check
9248   // for a truncate.  If the source and dest are the same type, eliminate the
9249   // trunc and extend and just do shifts.  For example, turn:
9250   //   %a = trunc i32 %i to i8
9251   //   %b = shl i8 %a, 6
9252   //   %c = ashr i8 %b, 6
9253   //   %d = sext i8 %c to i32
9254   // into:
9255   //   %a = shl i32 %i, 30
9256   //   %d = ashr i32 %a, 30
9257   Value *A = 0;
9258   ConstantInt *BA = 0, *CA = 0;
9259   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
9260                         m_ConstantInt(CA))) &&
9261       BA == CA && isa<TruncInst>(A)) {
9262     Value *I = cast<TruncInst>(A)->getOperand(0);
9263     if (I->getType() == CI.getType()) {
9264       unsigned MidSize = Src->getType()->getScalarSizeInBits();
9265       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
9266       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
9267       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
9268       I = Builder->CreateShl(I, ShAmtV, CI.getName());
9269       return BinaryOperator::CreateAShr(I, ShAmtV);
9270     }
9271   }
9272   
9273   return 0;
9274 }
9275
9276 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9277 /// in the specified FP type without changing its value.
9278 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
9279                               LLVMContext *Context) {
9280   bool losesInfo;
9281   APFloat F = CFP->getValueAPF();
9282   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9283   if (!losesInfo)
9284     return ConstantFP::get(*Context, F);
9285   return 0;
9286 }
9287
9288 /// LookThroughFPExtensions - If this is an fp extension instruction, look
9289 /// through it until we get the source value.
9290 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
9291   if (Instruction *I = dyn_cast<Instruction>(V))
9292     if (I->getOpcode() == Instruction::FPExt)
9293       return LookThroughFPExtensions(I->getOperand(0), Context);
9294   
9295   // If this value is a constant, return the constant in the smallest FP type
9296   // that can accurately represent it.  This allows us to turn
9297   // (float)((double)X+2.0) into x+2.0f.
9298   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
9299     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
9300       return V;  // No constant folding of this.
9301     // See if the value can be truncated to float and then reextended.
9302     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
9303       return V;
9304     if (CFP->getType() == Type::getDoubleTy(*Context))
9305       return V;  // Won't shrink.
9306     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
9307       return V;
9308     // Don't try to shrink to various long double types.
9309   }
9310   
9311   return V;
9312 }
9313
9314 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9315   if (Instruction *I = commonCastTransforms(CI))
9316     return I;
9317   
9318   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
9319   // smaller than the destination type, we can eliminate the truncate by doing
9320   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
9321   // many builtins (sqrt, etc).
9322   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9323   if (OpI && OpI->hasOneUse()) {
9324     switch (OpI->getOpcode()) {
9325     default: break;
9326     case Instruction::FAdd:
9327     case Instruction::FSub:
9328     case Instruction::FMul:
9329     case Instruction::FDiv:
9330     case Instruction::FRem:
9331       const Type *SrcTy = OpI->getType();
9332       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9333       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
9334       if (LHSTrunc->getType() != SrcTy && 
9335           RHSTrunc->getType() != SrcTy) {
9336         unsigned DstSize = CI.getType()->getScalarSizeInBits();
9337         // If the source types were both smaller than the destination type of
9338         // the cast, do this xform.
9339         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9340             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
9341           LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9342           RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
9343           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
9344         }
9345       }
9346       break;  
9347     }
9348   }
9349   return 0;
9350 }
9351
9352 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9353   return commonCastTransforms(CI);
9354 }
9355
9356 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
9357   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9358   if (OpI == 0)
9359     return commonCastTransforms(FI);
9360
9361   // fptoui(uitofp(X)) --> X
9362   // fptoui(sitofp(X)) --> X
9363   // This is safe if the intermediate type has enough bits in its mantissa to
9364   // accurately represent all values of X.  For example, do not do this with
9365   // i64->float->i64.  This is also safe for sitofp case, because any negative
9366   // 'X' value would cause an undefined result for the fptoui. 
9367   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9368       OpI->getOperand(0)->getType() == FI.getType() &&
9369       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
9370                     OpI->getType()->getFPMantissaWidth())
9371     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
9372
9373   return commonCastTransforms(FI);
9374 }
9375
9376 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
9377   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9378   if (OpI == 0)
9379     return commonCastTransforms(FI);
9380   
9381   // fptosi(sitofp(X)) --> X
9382   // fptosi(uitofp(X)) --> X
9383   // This is safe if the intermediate type has enough bits in its mantissa to
9384   // accurately represent all values of X.  For example, do not do this with
9385   // i64->float->i64.  This is also safe for sitofp case, because any negative
9386   // 'X' value would cause an undefined result for the fptoui. 
9387   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9388       OpI->getOperand(0)->getType() == FI.getType() &&
9389       (int)FI.getType()->getScalarSizeInBits() <=
9390                     OpI->getType()->getFPMantissaWidth())
9391     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
9392   
9393   return commonCastTransforms(FI);
9394 }
9395
9396 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9397   return commonCastTransforms(CI);
9398 }
9399
9400 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9401   return commonCastTransforms(CI);
9402 }
9403
9404 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9405   // If the destination integer type is smaller than the intptr_t type for
9406   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
9407   // trunc to be exposed to other transforms.  Don't do this for extending
9408   // ptrtoint's, because we don't know if the target sign or zero extends its
9409   // pointers.
9410   if (TD &&
9411       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
9412     Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9413                                        TD->getIntPtrType(CI.getContext()),
9414                                        "tmp");
9415     return new TruncInst(P, CI.getType());
9416   }
9417   
9418   return commonPointerCastTransforms(CI);
9419 }
9420
9421 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
9422   // If the source integer type is larger than the intptr_t type for
9423   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
9424   // allows the trunc to be exposed to other transforms.  Don't do this for
9425   // extending inttoptr's, because we don't know if the target sign or zero
9426   // extends to pointers.
9427   if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
9428       TD->getPointerSizeInBits()) {
9429     Value *P = Builder->CreateTrunc(CI.getOperand(0),
9430                                     TD->getIntPtrType(CI.getContext()), "tmp");
9431     return new IntToPtrInst(P, CI.getType());
9432   }
9433   
9434   if (Instruction *I = commonCastTransforms(CI))
9435     return I;
9436
9437   return 0;
9438 }
9439
9440 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
9441   // If the operands are integer typed then apply the integer transforms,
9442   // otherwise just apply the common ones.
9443   Value *Src = CI.getOperand(0);
9444   const Type *SrcTy = Src->getType();
9445   const Type *DestTy = CI.getType();
9446
9447   if (isa<PointerType>(SrcTy)) {
9448     if (Instruction *I = commonPointerCastTransforms(CI))
9449       return I;
9450   } else {
9451     if (Instruction *Result = commonCastTransforms(CI))
9452       return Result;
9453   }
9454
9455
9456   // Get rid of casts from one type to the same type. These are useless and can
9457   // be replaced by the operand.
9458   if (DestTy == Src->getType())
9459     return ReplaceInstUsesWith(CI, Src);
9460
9461   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9462     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9463     const Type *DstElTy = DstPTy->getElementType();
9464     const Type *SrcElTy = SrcPTy->getElementType();
9465     
9466     // If the address spaces don't match, don't eliminate the bitcast, which is
9467     // required for changing types.
9468     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9469       return 0;
9470     
9471     // If we are casting a alloca to a pointer to a type of the same
9472     // size, rewrite the allocation instruction to allocate the "right" type.
9473     // There is no need to modify malloc calls because it is their bitcast that
9474     // needs to be cleaned up.
9475     if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
9476       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9477         return V;
9478     
9479     // If the source and destination are pointers, and this cast is equivalent
9480     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9481     // This can enhance SROA and other transforms that want type-safe pointers.
9482     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
9483     unsigned NumZeros = 0;
9484     while (SrcElTy != DstElTy && 
9485            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9486            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9487       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9488       ++NumZeros;
9489     }
9490
9491     // If we found a path from the src to dest, create the getelementptr now.
9492     if (SrcElTy == DstElTy) {
9493       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9494       return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9495                                                ((Instruction*) NULL));
9496     }
9497   }
9498
9499   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9500     if (DestVTy->getNumElements() == 1) {
9501       if (!isa<VectorType>(SrcTy)) {
9502         Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
9503         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9504                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9505       }
9506       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9507     }
9508   }
9509
9510   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9511     if (SrcVTy->getNumElements() == 1) {
9512       if (!isa<VectorType>(DestTy)) {
9513         Value *Elem = 
9514           Builder->CreateExtractElement(Src,
9515                             Constant::getNullValue(Type::getInt32Ty(*Context)));
9516         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9517       }
9518     }
9519   }
9520
9521   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9522     if (SVI->hasOneUse()) {
9523       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9524       // a bitconvert to a vector with the same # elts.
9525       if (isa<VectorType>(DestTy) && 
9526           cast<VectorType>(DestTy)->getNumElements() ==
9527                 SVI->getType()->getNumElements() &&
9528           SVI->getType()->getNumElements() ==
9529             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9530         CastInst *Tmp;
9531         // If either of the operands is a cast from CI.getType(), then
9532         // evaluating the shuffle in the casted destination's type will allow
9533         // us to eliminate at least one cast.
9534         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9535              Tmp->getOperand(0)->getType() == DestTy) ||
9536             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9537              Tmp->getOperand(0)->getType() == DestTy)) {
9538           Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9539           Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
9540           // Return a new shuffle vector.  Use the same element ID's, as we
9541           // know the vector types match #elts.
9542           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9543         }
9544       }
9545     }
9546   }
9547   return 0;
9548 }
9549
9550 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9551 ///   %C = or %A, %B
9552 ///   %D = select %cond, %C, %A
9553 /// into:
9554 ///   %C = select %cond, %B, 0
9555 ///   %D = or %A, %C
9556 ///
9557 /// Assuming that the specified instruction is an operand to the select, return
9558 /// a bitmask indicating which operands of this instruction are foldable if they
9559 /// equal the other incoming value of the select.
9560 ///
9561 static unsigned GetSelectFoldableOperands(Instruction *I) {
9562   switch (I->getOpcode()) {
9563   case Instruction::Add:
9564   case Instruction::Mul:
9565   case Instruction::And:
9566   case Instruction::Or:
9567   case Instruction::Xor:
9568     return 3;              // Can fold through either operand.
9569   case Instruction::Sub:   // Can only fold on the amount subtracted.
9570   case Instruction::Shl:   // Can only fold on the shift amount.
9571   case Instruction::LShr:
9572   case Instruction::AShr:
9573     return 1;
9574   default:
9575     return 0;              // Cannot fold
9576   }
9577 }
9578
9579 /// GetSelectFoldableConstant - For the same transformation as the previous
9580 /// function, return the identity constant that goes into the select.
9581 static Constant *GetSelectFoldableConstant(Instruction *I,
9582                                            LLVMContext *Context) {
9583   switch (I->getOpcode()) {
9584   default: llvm_unreachable("This cannot happen!");
9585   case Instruction::Add:
9586   case Instruction::Sub:
9587   case Instruction::Or:
9588   case Instruction::Xor:
9589   case Instruction::Shl:
9590   case Instruction::LShr:
9591   case Instruction::AShr:
9592     return Constant::getNullValue(I->getType());
9593   case Instruction::And:
9594     return Constant::getAllOnesValue(I->getType());
9595   case Instruction::Mul:
9596     return ConstantInt::get(I->getType(), 1);
9597   }
9598 }
9599
9600 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9601 /// have the same opcode and only one use each.  Try to simplify this.
9602 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9603                                           Instruction *FI) {
9604   if (TI->getNumOperands() == 1) {
9605     // If this is a non-volatile load or a cast from the same type,
9606     // merge.
9607     if (TI->isCast()) {
9608       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9609         return 0;
9610     } else {
9611       return 0;  // unknown unary op.
9612     }
9613
9614     // Fold this by inserting a select from the input values.
9615     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9616                                           FI->getOperand(0), SI.getName()+".v");
9617     InsertNewInstBefore(NewSI, SI);
9618     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9619                             TI->getType());
9620   }
9621
9622   // Only handle binary operators here.
9623   if (!isa<BinaryOperator>(TI))
9624     return 0;
9625
9626   // Figure out if the operations have any operands in common.
9627   Value *MatchOp, *OtherOpT, *OtherOpF;
9628   bool MatchIsOpZero;
9629   if (TI->getOperand(0) == FI->getOperand(0)) {
9630     MatchOp  = TI->getOperand(0);
9631     OtherOpT = TI->getOperand(1);
9632     OtherOpF = FI->getOperand(1);
9633     MatchIsOpZero = true;
9634   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9635     MatchOp  = TI->getOperand(1);
9636     OtherOpT = TI->getOperand(0);
9637     OtherOpF = FI->getOperand(0);
9638     MatchIsOpZero = false;
9639   } else if (!TI->isCommutative()) {
9640     return 0;
9641   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9642     MatchOp  = TI->getOperand(0);
9643     OtherOpT = TI->getOperand(1);
9644     OtherOpF = FI->getOperand(0);
9645     MatchIsOpZero = true;
9646   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9647     MatchOp  = TI->getOperand(1);
9648     OtherOpT = TI->getOperand(0);
9649     OtherOpF = FI->getOperand(1);
9650     MatchIsOpZero = true;
9651   } else {
9652     return 0;
9653   }
9654
9655   // If we reach here, they do have operations in common.
9656   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9657                                          OtherOpF, SI.getName()+".v");
9658   InsertNewInstBefore(NewSI, SI);
9659
9660   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9661     if (MatchIsOpZero)
9662       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9663     else
9664       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9665   }
9666   llvm_unreachable("Shouldn't get here");
9667   return 0;
9668 }
9669
9670 static bool isSelect01(Constant *C1, Constant *C2) {
9671   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9672   if (!C1I)
9673     return false;
9674   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9675   if (!C2I)
9676     return false;
9677   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9678 }
9679
9680 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9681 /// facilitate further optimization.
9682 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9683                                             Value *FalseVal) {
9684   // See the comment above GetSelectFoldableOperands for a description of the
9685   // transformation we are doing here.
9686   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9687     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9688         !isa<Constant>(FalseVal)) {
9689       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9690         unsigned OpToFold = 0;
9691         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9692           OpToFold = 1;
9693         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9694           OpToFold = 2;
9695         }
9696
9697         if (OpToFold) {
9698           Constant *C = GetSelectFoldableConstant(TVI, Context);
9699           Value *OOp = TVI->getOperand(2-OpToFold);
9700           // Avoid creating select between 2 constants unless it's selecting
9701           // between 0 and 1.
9702           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9703             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9704             InsertNewInstBefore(NewSel, SI);
9705             NewSel->takeName(TVI);
9706             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9707               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9708             llvm_unreachable("Unknown instruction!!");
9709           }
9710         }
9711       }
9712     }
9713   }
9714
9715   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9716     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9717         !isa<Constant>(TrueVal)) {
9718       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9719         unsigned OpToFold = 0;
9720         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9721           OpToFold = 1;
9722         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9723           OpToFold = 2;
9724         }
9725
9726         if (OpToFold) {
9727           Constant *C = GetSelectFoldableConstant(FVI, Context);
9728           Value *OOp = FVI->getOperand(2-OpToFold);
9729           // Avoid creating select between 2 constants unless it's selecting
9730           // between 0 and 1.
9731           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9732             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9733             InsertNewInstBefore(NewSel, SI);
9734             NewSel->takeName(FVI);
9735             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9736               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9737             llvm_unreachable("Unknown instruction!!");
9738           }
9739         }
9740       }
9741     }
9742   }
9743
9744   return 0;
9745 }
9746
9747 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9748 /// ICmpInst as its first operand.
9749 ///
9750 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9751                                                    ICmpInst *ICI) {
9752   bool Changed = false;
9753   ICmpInst::Predicate Pred = ICI->getPredicate();
9754   Value *CmpLHS = ICI->getOperand(0);
9755   Value *CmpRHS = ICI->getOperand(1);
9756   Value *TrueVal = SI.getTrueValue();
9757   Value *FalseVal = SI.getFalseValue();
9758
9759   // Check cases where the comparison is with a constant that
9760   // can be adjusted to fit the min/max idiom. We may edit ICI in
9761   // place here, so make sure the select is the only user.
9762   if (ICI->hasOneUse())
9763     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9764       switch (Pred) {
9765       default: break;
9766       case ICmpInst::ICMP_ULT:
9767       case ICmpInst::ICMP_SLT: {
9768         // X < MIN ? T : F  -->  F
9769         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9770           return ReplaceInstUsesWith(SI, FalseVal);
9771         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9772         Constant *AdjustedRHS = SubOne(CI);
9773         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9774             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9775           Pred = ICmpInst::getSwappedPredicate(Pred);
9776           CmpRHS = AdjustedRHS;
9777           std::swap(FalseVal, TrueVal);
9778           ICI->setPredicate(Pred);
9779           ICI->setOperand(1, CmpRHS);
9780           SI.setOperand(1, TrueVal);
9781           SI.setOperand(2, FalseVal);
9782           Changed = true;
9783         }
9784         break;
9785       }
9786       case ICmpInst::ICMP_UGT:
9787       case ICmpInst::ICMP_SGT: {
9788         // X > MAX ? T : F  -->  F
9789         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9790           return ReplaceInstUsesWith(SI, FalseVal);
9791         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9792         Constant *AdjustedRHS = AddOne(CI);
9793         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9794             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9795           Pred = ICmpInst::getSwappedPredicate(Pred);
9796           CmpRHS = AdjustedRHS;
9797           std::swap(FalseVal, TrueVal);
9798           ICI->setPredicate(Pred);
9799           ICI->setOperand(1, CmpRHS);
9800           SI.setOperand(1, TrueVal);
9801           SI.setOperand(2, FalseVal);
9802           Changed = true;
9803         }
9804         break;
9805       }
9806       }
9807
9808       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9809       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9810       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9811       if (match(TrueVal, m_ConstantInt<-1>()) &&
9812           match(FalseVal, m_ConstantInt<0>()))
9813         Pred = ICI->getPredicate();
9814       else if (match(TrueVal, m_ConstantInt<0>()) &&
9815                match(FalseVal, m_ConstantInt<-1>()))
9816         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9817       
9818       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9819         // If we are just checking for a icmp eq of a single bit and zext'ing it
9820         // to an integer, then shift the bit to the appropriate place and then
9821         // cast to integer to avoid the comparison.
9822         const APInt &Op1CV = CI->getValue();
9823     
9824         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9825         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9826         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9827             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9828           Value *In = ICI->getOperand(0);
9829           Value *Sh = ConstantInt::get(In->getType(),
9830                                        In->getType()->getScalarSizeInBits()-1);
9831           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9832                                                         In->getName()+".lobit"),
9833                                    *ICI);
9834           if (In->getType() != SI.getType())
9835             In = CastInst::CreateIntegerCast(In, SI.getType(),
9836                                              true/*SExt*/, "tmp", ICI);
9837     
9838           if (Pred == ICmpInst::ICMP_SGT)
9839             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9840                                        In->getName()+".not"), *ICI);
9841     
9842           return ReplaceInstUsesWith(SI, In);
9843         }
9844       }
9845     }
9846
9847   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9848     // Transform (X == Y) ? X : Y  -> Y
9849     if (Pred == ICmpInst::ICMP_EQ)
9850       return ReplaceInstUsesWith(SI, FalseVal);
9851     // Transform (X != Y) ? X : Y  -> X
9852     if (Pred == ICmpInst::ICMP_NE)
9853       return ReplaceInstUsesWith(SI, TrueVal);
9854     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9855
9856   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9857     // Transform (X == Y) ? Y : X  -> X
9858     if (Pred == ICmpInst::ICMP_EQ)
9859       return ReplaceInstUsesWith(SI, FalseVal);
9860     // Transform (X != Y) ? Y : X  -> Y
9861     if (Pred == ICmpInst::ICMP_NE)
9862       return ReplaceInstUsesWith(SI, TrueVal);
9863     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9864   }
9865   return Changed ? &SI : 0;
9866 }
9867
9868
9869 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9870 /// PHI node (but the two may be in different blocks).  See if the true/false
9871 /// values (V) are live in all of the predecessor blocks of the PHI.  For
9872 /// example, cases like this cannot be mapped:
9873 ///
9874 ///   X = phi [ C1, BB1], [C2, BB2]
9875 ///   Y = add
9876 ///   Z = select X, Y, 0
9877 ///
9878 /// because Y is not live in BB1/BB2.
9879 ///
9880 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9881                                                    const SelectInst &SI) {
9882   // If the value is a non-instruction value like a constant or argument, it
9883   // can always be mapped.
9884   const Instruction *I = dyn_cast<Instruction>(V);
9885   if (I == 0) return true;
9886   
9887   // If V is a PHI node defined in the same block as the condition PHI, we can
9888   // map the arguments.
9889   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9890   
9891   if (const PHINode *VP = dyn_cast<PHINode>(I))
9892     if (VP->getParent() == CondPHI->getParent())
9893       return true;
9894   
9895   // Otherwise, if the PHI and select are defined in the same block and if V is
9896   // defined in a different block, then we can transform it.
9897   if (SI.getParent() == CondPHI->getParent() &&
9898       I->getParent() != CondPHI->getParent())
9899     return true;
9900   
9901   // Otherwise we have a 'hard' case and we can't tell without doing more
9902   // detailed dominator based analysis, punt.
9903   return false;
9904 }
9905
9906 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9907 ///   SPF2(SPF1(A, B), C) 
9908 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9909                                         SelectPatternFlavor SPF1,
9910                                         Value *A, Value *B,
9911                                         Instruction &Outer,
9912                                         SelectPatternFlavor SPF2, Value *C) {
9913   if (C == A || C == B) {
9914     // MAX(MAX(A, B), B) -> MAX(A, B)
9915     // MIN(MIN(a, b), a) -> MIN(a, b)
9916     if (SPF1 == SPF2)
9917       return ReplaceInstUsesWith(Outer, Inner);
9918     
9919     // MAX(MIN(a, b), a) -> a
9920     // MIN(MAX(a, b), a) -> a
9921     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9922         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9923         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9924         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
9925       return ReplaceInstUsesWith(Outer, C);
9926   }
9927   
9928   // TODO: MIN(MIN(A, 23), 97)
9929   return 0;
9930 }
9931
9932
9933
9934
9935 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9936   Value *CondVal = SI.getCondition();
9937   Value *TrueVal = SI.getTrueValue();
9938   Value *FalseVal = SI.getFalseValue();
9939
9940   // select true, X, Y  -> X
9941   // select false, X, Y -> Y
9942   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9943     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9944
9945   // select C, X, X -> X
9946   if (TrueVal == FalseVal)
9947     return ReplaceInstUsesWith(SI, TrueVal);
9948
9949   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9950     return ReplaceInstUsesWith(SI, FalseVal);
9951   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9952     return ReplaceInstUsesWith(SI, TrueVal);
9953   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9954     if (isa<Constant>(TrueVal))
9955       return ReplaceInstUsesWith(SI, TrueVal);
9956     else
9957       return ReplaceInstUsesWith(SI, FalseVal);
9958   }
9959
9960   if (SI.getType() == Type::getInt1Ty(*Context)) {
9961     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9962       if (C->getZExtValue()) {
9963         // Change: A = select B, true, C --> A = or B, C
9964         return BinaryOperator::CreateOr(CondVal, FalseVal);
9965       } else {
9966         // Change: A = select B, false, C --> A = and !B, C
9967         Value *NotCond =
9968           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9969                                              "not."+CondVal->getName()), SI);
9970         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9971       }
9972     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9973       if (C->getZExtValue() == false) {
9974         // Change: A = select B, C, false --> A = and B, C
9975         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9976       } else {
9977         // Change: A = select B, C, true --> A = or !B, C
9978         Value *NotCond =
9979           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9980                                              "not."+CondVal->getName()), SI);
9981         return BinaryOperator::CreateOr(NotCond, TrueVal);
9982       }
9983     }
9984     
9985     // select a, b, a  -> a&b
9986     // select a, a, b  -> a|b
9987     if (CondVal == TrueVal)
9988       return BinaryOperator::CreateOr(CondVal, FalseVal);
9989     else if (CondVal == FalseVal)
9990       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9991   }
9992
9993   // Selecting between two integer constants?
9994   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9995     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9996       // select C, 1, 0 -> zext C to int
9997       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9998         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9999       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
10000         // select C, 0, 1 -> zext !C to int
10001         Value *NotCond =
10002           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
10003                                                "not."+CondVal->getName()), SI);
10004         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
10005       }
10006
10007       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
10008         // If one of the constants is zero (we know they can't both be) and we
10009         // have an icmp instruction with zero, and we have an 'and' with the
10010         // non-constant value, eliminate this whole mess.  This corresponds to
10011         // cases like this: ((X & 27) ? 27 : 0)
10012         if (TrueValC->isZero() || FalseValC->isZero())
10013           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
10014               cast<Constant>(IC->getOperand(1))->isNullValue())
10015             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
10016               if (ICA->getOpcode() == Instruction::And &&
10017                   isa<ConstantInt>(ICA->getOperand(1)) &&
10018                   (ICA->getOperand(1) == TrueValC ||
10019                    ICA->getOperand(1) == FalseValC) &&
10020                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
10021                 // Okay, now we know that everything is set up, we just don't
10022                 // know whether we have a icmp_ne or icmp_eq and whether the 
10023                 // true or false val is the zero.
10024                 bool ShouldNotVal = !TrueValC->isZero();
10025                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
10026                 Value *V = ICA;
10027                 if (ShouldNotVal)
10028                   V = InsertNewInstBefore(BinaryOperator::Create(
10029                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
10030                 return ReplaceInstUsesWith(SI, V);
10031               }
10032       }
10033     }
10034
10035   // See if we are selecting two values based on a comparison of the two values.
10036   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
10037     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
10038       // Transform (X == Y) ? X : Y  -> Y
10039       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
10040         // This is not safe in general for floating point:  
10041         // consider X== -0, Y== +0.
10042         // It becomes safe if either operand is a nonzero constant.
10043         ConstantFP *CFPt, *CFPf;
10044         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10045               !CFPt->getValueAPF().isZero()) ||
10046             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10047              !CFPf->getValueAPF().isZero()))
10048         return ReplaceInstUsesWith(SI, FalseVal);
10049       }
10050       // Transform (X != Y) ? X : Y  -> X
10051       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
10052         return ReplaceInstUsesWith(SI, TrueVal);
10053       // NOTE: if we wanted to, this is where to detect MIN/MAX
10054
10055     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
10056       // Transform (X == Y) ? Y : X  -> X
10057       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
10058         // This is not safe in general for floating point:  
10059         // consider X== -0, Y== +0.
10060         // It becomes safe if either operand is a nonzero constant.
10061         ConstantFP *CFPt, *CFPf;
10062         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10063               !CFPt->getValueAPF().isZero()) ||
10064             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10065              !CFPf->getValueAPF().isZero()))
10066           return ReplaceInstUsesWith(SI, FalseVal);
10067       }
10068       // Transform (X != Y) ? Y : X  -> Y
10069       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
10070         return ReplaceInstUsesWith(SI, TrueVal);
10071       // NOTE: if we wanted to, this is where to detect MIN/MAX
10072     }
10073     // NOTE: if we wanted to, this is where to detect ABS
10074   }
10075
10076   // See if we are selecting two values based on a comparison of the two values.
10077   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
10078     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
10079       return Result;
10080
10081   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
10082     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
10083       if (TI->hasOneUse() && FI->hasOneUse()) {
10084         Instruction *AddOp = 0, *SubOp = 0;
10085
10086         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
10087         if (TI->getOpcode() == FI->getOpcode())
10088           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
10089             return IV;
10090
10091         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
10092         // even legal for FP.
10093         if ((TI->getOpcode() == Instruction::Sub &&
10094              FI->getOpcode() == Instruction::Add) ||
10095             (TI->getOpcode() == Instruction::FSub &&
10096              FI->getOpcode() == Instruction::FAdd)) {
10097           AddOp = FI; SubOp = TI;
10098         } else if ((FI->getOpcode() == Instruction::Sub &&
10099                     TI->getOpcode() == Instruction::Add) ||
10100                    (FI->getOpcode() == Instruction::FSub &&
10101                     TI->getOpcode() == Instruction::FAdd)) {
10102           AddOp = TI; SubOp = FI;
10103         }
10104
10105         if (AddOp) {
10106           Value *OtherAddOp = 0;
10107           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
10108             OtherAddOp = AddOp->getOperand(1);
10109           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
10110             OtherAddOp = AddOp->getOperand(0);
10111           }
10112
10113           if (OtherAddOp) {
10114             // So at this point we know we have (Y -> OtherAddOp):
10115             //        select C, (add X, Y), (sub X, Z)
10116             Value *NegVal;  // Compute -Z
10117             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
10118               NegVal = ConstantExpr::getNeg(C);
10119             } else {
10120               NegVal = InsertNewInstBefore(
10121                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
10122                                               "tmp"), SI);
10123             }
10124
10125             Value *NewTrueOp = OtherAddOp;
10126             Value *NewFalseOp = NegVal;
10127             if (AddOp != TI)
10128               std::swap(NewTrueOp, NewFalseOp);
10129             Instruction *NewSel =
10130               SelectInst::Create(CondVal, NewTrueOp,
10131                                  NewFalseOp, SI.getName() + ".p");
10132
10133             NewSel = InsertNewInstBefore(NewSel, SI);
10134             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
10135           }
10136         }
10137       }
10138
10139   // See if we can fold the select into one of our operands.
10140   if (SI.getType()->isInteger()) {
10141     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
10142       return FoldI;
10143     
10144     // MAX(MAX(a, b), a) -> MAX(a, b)
10145     // MIN(MIN(a, b), a) -> MIN(a, b)
10146     // MAX(MIN(a, b), a) -> a
10147     // MIN(MAX(a, b), a) -> a
10148     Value *LHS, *RHS, *LHS2, *RHS2;
10149     if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10150       if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10151         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 
10152                                           SI, SPF, RHS))
10153           return R;
10154       if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10155         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10156                                           SI, SPF, LHS))
10157           return R;
10158     }
10159
10160     // TODO.
10161     // ABS(-X) -> ABS(X)
10162     // ABS(ABS(X)) -> ABS(X)
10163   }
10164
10165   // See if we can fold the select into a phi node if the condition is a select.
10166   if (isa<PHINode>(SI.getCondition())) 
10167     // The true/false values have to be live in the PHI predecessor's blocks.
10168     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10169         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10170       if (Instruction *NV = FoldOpIntoPhi(SI))
10171         return NV;
10172
10173   if (BinaryOperator::isNot(CondVal)) {
10174     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10175     SI.setOperand(1, FalseVal);
10176     SI.setOperand(2, TrueVal);
10177     return &SI;
10178   }
10179
10180   return 0;
10181 }
10182
10183 /// EnforceKnownAlignment - If the specified pointer points to an object that
10184 /// we control, modify the object's alignment to PrefAlign. This isn't
10185 /// often possible though. If alignment is important, a more reliable approach
10186 /// is to simply align all global variables and allocation instructions to
10187 /// their preferred alignment from the beginning.
10188 ///
10189 static unsigned EnforceKnownAlignment(Value *V,
10190                                       unsigned Align, unsigned PrefAlign) {
10191
10192   User *U = dyn_cast<User>(V);
10193   if (!U) return Align;
10194
10195   switch (Operator::getOpcode(U)) {
10196   default: break;
10197   case Instruction::BitCast:
10198     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10199   case Instruction::GetElementPtr: {
10200     // If all indexes are zero, it is just the alignment of the base pointer.
10201     bool AllZeroOperands = true;
10202     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
10203       if (!isa<Constant>(*i) ||
10204           !cast<Constant>(*i)->isNullValue()) {
10205         AllZeroOperands = false;
10206         break;
10207       }
10208
10209     if (AllZeroOperands) {
10210       // Treat this like a bitcast.
10211       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10212     }
10213     break;
10214   }
10215   }
10216
10217   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10218     // If there is a large requested alignment and we can, bump up the alignment
10219     // of the global.
10220     if (!GV->isDeclaration()) {
10221       if (GV->getAlignment() >= PrefAlign)
10222         Align = GV->getAlignment();
10223       else {
10224         GV->setAlignment(PrefAlign);
10225         Align = PrefAlign;
10226       }
10227     }
10228   } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10229     // If there is a requested alignment and if this is an alloca, round up.
10230     if (AI->getAlignment() >= PrefAlign)
10231       Align = AI->getAlignment();
10232     else {
10233       AI->setAlignment(PrefAlign);
10234       Align = PrefAlign;
10235     }
10236   }
10237
10238   return Align;
10239 }
10240
10241 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10242 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
10243 /// and it is more than the alignment of the ultimate object, see if we can
10244 /// increase the alignment of the ultimate object, making this check succeed.
10245 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10246                                                   unsigned PrefAlign) {
10247   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10248                       sizeof(PrefAlign) * CHAR_BIT;
10249   APInt Mask = APInt::getAllOnesValue(BitWidth);
10250   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10251   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10252   unsigned TrailZ = KnownZero.countTrailingOnes();
10253   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10254
10255   if (PrefAlign > Align)
10256     Align = EnforceKnownAlignment(V, Align, PrefAlign);
10257   
10258     // We don't need to make any adjustment.
10259   return Align;
10260 }
10261
10262 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
10263   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
10264   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
10265   unsigned MinAlign = std::min(DstAlign, SrcAlign);
10266   unsigned CopyAlign = MI->getAlignment();
10267
10268   if (CopyAlign < MinAlign) {
10269     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
10270                                              MinAlign, false));
10271     return MI;
10272   }
10273   
10274   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10275   // load/store.
10276   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10277   if (MemOpLength == 0) return 0;
10278   
10279   // Source and destination pointer types are always "i8*" for intrinsic.  See
10280   // if the size is something we can handle with a single primitive load/store.
10281   // A single load+store correctly handles overlapping memory in the memmove
10282   // case.
10283   unsigned Size = MemOpLength->getZExtValue();
10284   if (Size == 0) return MI;  // Delete this mem transfer.
10285   
10286   if (Size > 8 || (Size&(Size-1)))
10287     return 0;  // If not 1/2/4/8 bytes, exit.
10288   
10289   // Use an integer load+store unless we can find something better.
10290   Type *NewPtrTy =
10291                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
10292   
10293   // Memcpy forces the use of i8* for the source and destination.  That means
10294   // that if you're using memcpy to move one double around, you'll get a cast
10295   // from double* to i8*.  We'd much rather use a double load+store rather than
10296   // an i64 load+store, here because this improves the odds that the source or
10297   // dest address will be promotable.  See if we can find a better type than the
10298   // integer datatype.
10299   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10300     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
10301     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
10302       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
10303       // down through these levels if so.
10304       while (!SrcETy->isSingleValueType()) {
10305         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10306           if (STy->getNumElements() == 1)
10307             SrcETy = STy->getElementType(0);
10308           else
10309             break;
10310         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10311           if (ATy->getNumElements() == 1)
10312             SrcETy = ATy->getElementType();
10313           else
10314             break;
10315         } else
10316           break;
10317       }
10318       
10319       if (SrcETy->isSingleValueType())
10320         NewPtrTy = PointerType::getUnqual(SrcETy);
10321     }
10322   }
10323   
10324   
10325   // If the memcpy/memmove provides better alignment info than we can
10326   // infer, use it.
10327   SrcAlign = std::max(SrcAlign, CopyAlign);
10328   DstAlign = std::max(DstAlign, CopyAlign);
10329   
10330   Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10331   Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
10332   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10333   InsertNewInstBefore(L, *MI);
10334   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10335
10336   // Set the size of the copy to 0, it will be deleted on the next iteration.
10337   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
10338   return MI;
10339 }
10340
10341 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10342   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
10343   if (MI->getAlignment() < Alignment) {
10344     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
10345                                              Alignment, false));
10346     return MI;
10347   }
10348   
10349   // Extract the length and alignment and fill if they are constant.
10350   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10351   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
10352   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
10353     return 0;
10354   uint64_t Len = LenC->getZExtValue();
10355   Alignment = MI->getAlignment();
10356   
10357   // If the length is zero, this is a no-op
10358   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10359   
10360   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10361   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
10362     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
10363     
10364     Value *Dest = MI->getDest();
10365     Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
10366
10367     // Alignment 0 is identity for alignment 1 for memset, but not store.
10368     if (Alignment == 0) Alignment = 1;
10369     
10370     // Extract the fill value and store.
10371     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
10372     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
10373                                       Dest, false, Alignment), *MI);
10374     
10375     // Set the size of the copy to 0, it will be deleted on the next iteration.
10376     MI->setLength(Constant::getNullValue(LenC->getType()));
10377     return MI;
10378   }
10379
10380   return 0;
10381 }
10382
10383
10384 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
10385 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
10386 /// the heavy lifting.
10387 ///
10388 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
10389   if (isFreeCall(&CI))
10390     return visitFree(CI);
10391
10392   // If the caller function is nounwind, mark the call as nounwind, even if the
10393   // callee isn't.
10394   if (CI.getParent()->getParent()->doesNotThrow() &&
10395       !CI.doesNotThrow()) {
10396     CI.setDoesNotThrow();
10397     return &CI;
10398   }
10399   
10400   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10401   if (!II) return visitCallSite(&CI);
10402   
10403   // Intrinsics cannot occur in an invoke, so handle them here instead of in
10404   // visitCallSite.
10405   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
10406     bool Changed = false;
10407
10408     // memmove/cpy/set of zero bytes is a noop.
10409     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10410       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10411
10412       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
10413         if (CI->getZExtValue() == 1) {
10414           // Replace the instruction with just byte operations.  We would
10415           // transform other cases to loads/stores, but we don't know if
10416           // alignment is sufficient.
10417         }
10418     }
10419
10420     // If we have a memmove and the source operation is a constant global,
10421     // then the source and dest pointers can't alias, so we can change this
10422     // into a call to memcpy.
10423     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
10424       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10425         if (GVSrc->isConstant()) {
10426           Module *M = CI.getParent()->getParent()->getParent();
10427           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10428           const Type *Tys[1];
10429           Tys[0] = CI.getOperand(3)->getType();
10430           CI.setOperand(0, 
10431                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
10432           Changed = true;
10433         }
10434     }
10435
10436     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
10437       // memmove(x,x,size) -> noop.
10438       if (MTI->getSource() == MTI->getDest())
10439         return EraseInstFromFunction(CI);
10440     }
10441
10442     // If we can determine a pointer alignment that is bigger than currently
10443     // set, update the alignment.
10444     if (isa<MemTransferInst>(MI)) {
10445       if (Instruction *I = SimplifyMemTransfer(MI))
10446         return I;
10447     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10448       if (Instruction *I = SimplifyMemSet(MSI))
10449         return I;
10450     }
10451           
10452     if (Changed) return II;
10453   }
10454   
10455   switch (II->getIntrinsicID()) {
10456   default: break;
10457   case Intrinsic::bswap:
10458     // bswap(bswap(x)) -> x
10459     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10460       if (Operand->getIntrinsicID() == Intrinsic::bswap)
10461         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
10462       
10463     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10464     if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10465       if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10466         if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10467           unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10468                        TI->getType()->getPrimitiveSizeInBits();
10469           Value *CV = ConstantInt::get(Operand->getType(), C);
10470           Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10471           return new TruncInst(V, TI->getType());
10472         }
10473     }
10474       
10475     break;
10476   case Intrinsic::powi:
10477     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10478       // powi(x, 0) -> 1.0
10479       if (Power->isZero())
10480         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10481       // powi(x, 1) -> x
10482       if (Power->isOne())
10483         return ReplaceInstUsesWith(CI, II->getOperand(1));
10484       // powi(x, -1) -> 1/x
10485       if (Power->isAllOnesValue())
10486         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10487                                           II->getOperand(1));
10488     }
10489     break;
10490       
10491   case Intrinsic::uadd_with_overflow: {
10492     Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10493     const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10494     uint32_t BitWidth = IT->getBitWidth();
10495     APInt Mask = APInt::getSignBit(BitWidth);
10496     APInt LHSKnownZero(BitWidth, 0);
10497     APInt LHSKnownOne(BitWidth, 0);
10498     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10499     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10500     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10501
10502     if (LHSKnownNegative || LHSKnownPositive) {
10503       APInt RHSKnownZero(BitWidth, 0);
10504       APInt RHSKnownOne(BitWidth, 0);
10505       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10506       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10507       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10508       if (LHSKnownNegative && RHSKnownNegative) {
10509         // The sign bit is set in both cases: this MUST overflow.
10510         // Create a simple add instruction, and insert it into the struct.
10511         Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10512         Worklist.Add(Add);
10513         Constant *V[] = {
10514           UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10515         };
10516         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10517         return InsertValueInst::Create(Struct, Add, 0);
10518       }
10519       
10520       if (LHSKnownPositive && RHSKnownPositive) {
10521         // The sign bit is clear in both cases: this CANNOT overflow.
10522         // Create a simple add instruction, and insert it into the struct.
10523         Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10524         Worklist.Add(Add);
10525         Constant *V[] = {
10526           UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10527         };
10528         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10529         return InsertValueInst::Create(Struct, Add, 0);
10530       }
10531     }
10532   }
10533   // FALL THROUGH uadd into sadd
10534   case Intrinsic::sadd_with_overflow:
10535     // Canonicalize constants into the RHS.
10536     if (isa<Constant>(II->getOperand(1)) &&
10537         !isa<Constant>(II->getOperand(2))) {
10538       Value *LHS = II->getOperand(1);
10539       II->setOperand(1, II->getOperand(2));
10540       II->setOperand(2, LHS);
10541       return II;
10542     }
10543
10544     // X + undef -> undef
10545     if (isa<UndefValue>(II->getOperand(2)))
10546       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10547       
10548     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10549       // X + 0 -> {X, false}
10550       if (RHS->isZero()) {
10551         Constant *V[] = {
10552           UndefValue::get(II->getOperand(0)->getType()),
10553           ConstantInt::getFalse(*Context)
10554         };
10555         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10556         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10557       }
10558     }
10559     break;
10560   case Intrinsic::usub_with_overflow:
10561   case Intrinsic::ssub_with_overflow:
10562     // undef - X -> undef
10563     // X - undef -> undef
10564     if (isa<UndefValue>(II->getOperand(1)) ||
10565         isa<UndefValue>(II->getOperand(2)))
10566       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10567       
10568     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10569       // X - 0 -> {X, false}
10570       if (RHS->isZero()) {
10571         Constant *V[] = {
10572           UndefValue::get(II->getOperand(1)->getType()),
10573           ConstantInt::getFalse(*Context)
10574         };
10575         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10576         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10577       }
10578     }
10579     break;
10580   case Intrinsic::umul_with_overflow:
10581   case Intrinsic::smul_with_overflow:
10582     // Canonicalize constants into the RHS.
10583     if (isa<Constant>(II->getOperand(1)) &&
10584         !isa<Constant>(II->getOperand(2))) {
10585       Value *LHS = II->getOperand(1);
10586       II->setOperand(1, II->getOperand(2));
10587       II->setOperand(2, LHS);
10588       return II;
10589     }
10590
10591     // X * undef -> undef
10592     if (isa<UndefValue>(II->getOperand(2)))
10593       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10594       
10595     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10596       // X*0 -> {0, false}
10597       if (RHSI->isZero())
10598         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10599       
10600       // X * 1 -> {X, false}
10601       if (RHSI->equalsInt(1)) {
10602         Constant *V[] = {
10603           UndefValue::get(II->getOperand(1)->getType()),
10604           ConstantInt::getFalse(*Context)
10605         };
10606         Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10607         return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10608       }
10609     }
10610     break;
10611   case Intrinsic::ppc_altivec_lvx:
10612   case Intrinsic::ppc_altivec_lvxl:
10613   case Intrinsic::x86_sse_loadu_ps:
10614   case Intrinsic::x86_sse2_loadu_pd:
10615   case Intrinsic::x86_sse2_loadu_dq:
10616     // Turn PPC lvx     -> load if the pointer is known aligned.
10617     // Turn X86 loadups -> load if the pointer is known aligned.
10618     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10619       Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10620                                          PointerType::getUnqual(II->getType()));
10621       return new LoadInst(Ptr);
10622     }
10623     break;
10624   case Intrinsic::ppc_altivec_stvx:
10625   case Intrinsic::ppc_altivec_stvxl:
10626     // Turn stvx -> store if the pointer is known aligned.
10627     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10628       const Type *OpPtrTy = 
10629         PointerType::getUnqual(II->getOperand(1)->getType());
10630       Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
10631       return new StoreInst(II->getOperand(1), Ptr);
10632     }
10633     break;
10634   case Intrinsic::x86_sse_storeu_ps:
10635   case Intrinsic::x86_sse2_storeu_pd:
10636   case Intrinsic::x86_sse2_storeu_dq:
10637     // Turn X86 storeu -> store if the pointer is known aligned.
10638     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10639       const Type *OpPtrTy = 
10640         PointerType::getUnqual(II->getOperand(2)->getType());
10641       Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
10642       return new StoreInst(II->getOperand(2), Ptr);
10643     }
10644     break;
10645     
10646   case Intrinsic::x86_sse_cvttss2si: {
10647     // These intrinsics only demands the 0th element of its input vector.  If
10648     // we can simplify the input based on that, do so now.
10649     unsigned VWidth =
10650       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10651     APInt DemandedElts(VWidth, 1);
10652     APInt UndefElts(VWidth, 0);
10653     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
10654                                               UndefElts)) {
10655       II->setOperand(1, V);
10656       return II;
10657     }
10658     break;
10659   }
10660     
10661   case Intrinsic::ppc_altivec_vperm:
10662     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10663     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10664       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
10665       
10666       // Check that all of the elements are integer constants or undefs.
10667       bool AllEltsOk = true;
10668       for (unsigned i = 0; i != 16; ++i) {
10669         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
10670             !isa<UndefValue>(Mask->getOperand(i))) {
10671           AllEltsOk = false;
10672           break;
10673         }
10674       }
10675       
10676       if (AllEltsOk) {
10677         // Cast the input vectors to byte vectors.
10678         Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10679         Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
10680         Value *Result = UndefValue::get(Op0->getType());
10681         
10682         // Only extract each element once.
10683         Value *ExtractedElts[32];
10684         memset(ExtractedElts, 0, sizeof(ExtractedElts));
10685         
10686         for (unsigned i = 0; i != 16; ++i) {
10687           if (isa<UndefValue>(Mask->getOperand(i)))
10688             continue;
10689           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10690           Idx &= 31;  // Match the hardware behavior.
10691           
10692           if (ExtractedElts[Idx] == 0) {
10693             ExtractedElts[Idx] = 
10694               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 
10695                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10696                                             "tmp");
10697           }
10698         
10699           // Insert this value into the result vector.
10700           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10701                          ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10702                                                 "tmp");
10703         }
10704         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10705       }
10706     }
10707     break;
10708
10709   case Intrinsic::stackrestore: {
10710     // If the save is right next to the restore, remove the restore.  This can
10711     // happen when variable allocas are DCE'd.
10712     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10713       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10714         BasicBlock::iterator BI = SS;
10715         if (&*++BI == II)
10716           return EraseInstFromFunction(CI);
10717       }
10718     }
10719     
10720     // Scan down this block to see if there is another stack restore in the
10721     // same block without an intervening call/alloca.
10722     BasicBlock::iterator BI = II;
10723     TerminatorInst *TI = II->getParent()->getTerminator();
10724     bool CannotRemove = false;
10725     for (++BI; &*BI != TI; ++BI) {
10726       if (isa<AllocaInst>(BI) || isMalloc(BI)) {
10727         CannotRemove = true;
10728         break;
10729       }
10730       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10731         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10732           // If there is a stackrestore below this one, remove this one.
10733           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10734             return EraseInstFromFunction(CI);
10735           // Otherwise, ignore the intrinsic.
10736         } else {
10737           // If we found a non-intrinsic call, we can't remove the stack
10738           // restore.
10739           CannotRemove = true;
10740           break;
10741         }
10742       }
10743     }
10744     
10745     // If the stack restore is in a return/unwind block and if there are no
10746     // allocas or calls between the restore and the return, nuke the restore.
10747     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10748       return EraseInstFromFunction(CI);
10749     break;
10750   }
10751   }
10752
10753   return visitCallSite(II);
10754 }
10755
10756 // InvokeInst simplification
10757 //
10758 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10759   return visitCallSite(&II);
10760 }
10761
10762 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10763 /// passed through the varargs area, we can eliminate the use of the cast.
10764 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10765                                          const CastInst * const CI,
10766                                          const TargetData * const TD,
10767                                          const int ix) {
10768   if (!CI->isLosslessCast())
10769     return false;
10770
10771   // The size of ByVal arguments is derived from the type, so we
10772   // can't change to a type with a different size.  If the size were
10773   // passed explicitly we could avoid this check.
10774   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10775     return true;
10776
10777   const Type* SrcTy = 
10778             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10779   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10780   if (!SrcTy->isSized() || !DstTy->isSized())
10781     return false;
10782   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10783     return false;
10784   return true;
10785 }
10786
10787 // visitCallSite - Improvements for call and invoke instructions.
10788 //
10789 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10790   bool Changed = false;
10791
10792   // If the callee is a constexpr cast of a function, attempt to move the cast
10793   // to the arguments of the call/invoke.
10794   if (transformConstExprCastCall(CS)) return 0;
10795
10796   Value *Callee = CS.getCalledValue();
10797
10798   if (Function *CalleeF = dyn_cast<Function>(Callee))
10799     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10800       Instruction *OldCall = CS.getInstruction();
10801       // If the call and callee calling conventions don't match, this call must
10802       // be unreachable, as the call is undefined.
10803       new StoreInst(ConstantInt::getTrue(*Context),
10804                 UndefValue::get(Type::getInt1PtrTy(*Context)), 
10805                                   OldCall);
10806       // If OldCall dues not return void then replaceAllUsesWith undef.
10807       // This allows ValueHandlers and custom metadata to adjust itself.
10808       if (!OldCall->getType()->isVoidTy())
10809         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10810       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10811         return EraseInstFromFunction(*OldCall);
10812       return 0;
10813     }
10814
10815   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10816     // This instruction is not reachable, just remove it.  We insert a store to
10817     // undef so that we know that this code is not reachable, despite the fact
10818     // that we can't modify the CFG here.
10819     new StoreInst(ConstantInt::getTrue(*Context),
10820                UndefValue::get(Type::getInt1PtrTy(*Context)),
10821                   CS.getInstruction());
10822
10823     // If CS dues not return void then replaceAllUsesWith undef.
10824     // This allows ValueHandlers and custom metadata to adjust itself.
10825     if (!CS.getInstruction()->getType()->isVoidTy())
10826       CS.getInstruction()->
10827         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10828
10829     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10830       // Don't break the CFG, insert a dummy cond branch.
10831       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10832                          ConstantInt::getTrue(*Context), II);
10833     }
10834     return EraseInstFromFunction(*CS.getInstruction());
10835   }
10836
10837   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10838     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10839       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10840         return transformCallThroughTrampoline(CS);
10841
10842   const PointerType *PTy = cast<PointerType>(Callee->getType());
10843   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10844   if (FTy->isVarArg()) {
10845     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10846     // See if we can optimize any arguments passed through the varargs area of
10847     // the call.
10848     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10849            E = CS.arg_end(); I != E; ++I, ++ix) {
10850       CastInst *CI = dyn_cast<CastInst>(*I);
10851       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10852         *I = CI->getOperand(0);
10853         Changed = true;
10854       }
10855     }
10856   }
10857
10858   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10859     // Inline asm calls cannot throw - mark them 'nounwind'.
10860     CS.setDoesNotThrow();
10861     Changed = true;
10862   }
10863
10864   return Changed ? CS.getInstruction() : 0;
10865 }
10866
10867 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10868 // attempt to move the cast to the arguments of the call/invoke.
10869 //
10870 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10871   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10872   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10873   if (CE->getOpcode() != Instruction::BitCast || 
10874       !isa<Function>(CE->getOperand(0)))
10875     return false;
10876   Function *Callee = cast<Function>(CE->getOperand(0));
10877   Instruction *Caller = CS.getInstruction();
10878   const AttrListPtr &CallerPAL = CS.getAttributes();
10879
10880   // Okay, this is a cast from a function to a different type.  Unless doing so
10881   // would cause a type conversion of one of our arguments, change this call to
10882   // be a direct call with arguments casted to the appropriate types.
10883   //
10884   const FunctionType *FT = Callee->getFunctionType();
10885   const Type *OldRetTy = Caller->getType();
10886   const Type *NewRetTy = FT->getReturnType();
10887
10888   if (isa<StructType>(NewRetTy))
10889     return false; // TODO: Handle multiple return values.
10890
10891   // Check to see if we are changing the return type...
10892   if (OldRetTy != NewRetTy) {
10893     if (Callee->isDeclaration() &&
10894         // Conversion is ok if changing from one pointer type to another or from
10895         // a pointer to an integer of the same size.
10896         !((isa<PointerType>(OldRetTy) || !TD ||
10897            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10898           (isa<PointerType>(NewRetTy) || !TD ||
10899            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10900       return false;   // Cannot transform this return value.
10901
10902     if (!Caller->use_empty() &&
10903         // void -> non-void is handled specially
10904         !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10905       return false;   // Cannot transform this return value.
10906
10907     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10908       Attributes RAttrs = CallerPAL.getRetAttributes();
10909       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10910         return false;   // Attribute not compatible with transformed value.
10911     }
10912
10913     // If the callsite is an invoke instruction, and the return value is used by
10914     // a PHI node in a successor, we cannot change the return type of the call
10915     // because there is no place to put the cast instruction (without breaking
10916     // the critical edge).  Bail out in this case.
10917     if (!Caller->use_empty())
10918       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10919         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10920              UI != E; ++UI)
10921           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10922             if (PN->getParent() == II->getNormalDest() ||
10923                 PN->getParent() == II->getUnwindDest())
10924               return false;
10925   }
10926
10927   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10928   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10929
10930   CallSite::arg_iterator AI = CS.arg_begin();
10931   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10932     const Type *ParamTy = FT->getParamType(i);
10933     const Type *ActTy = (*AI)->getType();
10934
10935     if (!CastInst::isCastable(ActTy, ParamTy))
10936       return false;   // Cannot transform this parameter value.
10937
10938     if (CallerPAL.getParamAttributes(i + 1) 
10939         & Attribute::typeIncompatible(ParamTy))
10940       return false;   // Attribute not compatible with transformed value.
10941
10942     // Converting from one pointer type to another or between a pointer and an
10943     // integer of the same size is safe even if we do not have a body.
10944     bool isConvertible = ActTy == ParamTy ||
10945       (TD && ((isa<PointerType>(ParamTy) ||
10946       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10947               (isa<PointerType>(ActTy) ||
10948               ActTy == TD->getIntPtrType(Caller->getContext()))));
10949     if (Callee->isDeclaration() && !isConvertible) return false;
10950   }
10951
10952   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10953       Callee->isDeclaration())
10954     return false;   // Do not delete arguments unless we have a function body.
10955
10956   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10957       !CallerPAL.isEmpty())
10958     // In this case we have more arguments than the new function type, but we
10959     // won't be dropping them.  Check that these extra arguments have attributes
10960     // that are compatible with being a vararg call argument.
10961     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10962       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10963         break;
10964       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10965       if (PAttrs & Attribute::VarArgsIncompatible)
10966         return false;
10967     }
10968
10969   // Okay, we decided that this is a safe thing to do: go ahead and start
10970   // inserting cast instructions as necessary...
10971   std::vector<Value*> Args;
10972   Args.reserve(NumActualArgs);
10973   SmallVector<AttributeWithIndex, 8> attrVec;
10974   attrVec.reserve(NumCommonArgs);
10975
10976   // Get any return attributes.
10977   Attributes RAttrs = CallerPAL.getRetAttributes();
10978
10979   // If the return value is not being used, the type may not be compatible
10980   // with the existing attributes.  Wipe out any problematic attributes.
10981   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10982
10983   // Add the new return attributes.
10984   if (RAttrs)
10985     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10986
10987   AI = CS.arg_begin();
10988   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10989     const Type *ParamTy = FT->getParamType(i);
10990     if ((*AI)->getType() == ParamTy) {
10991       Args.push_back(*AI);
10992     } else {
10993       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10994           false, ParamTy, false);
10995       Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10996     }
10997
10998     // Add any parameter attributes.
10999     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
11000       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
11001   }
11002
11003   // If the function takes more arguments than the call was taking, add them
11004   // now.
11005   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
11006     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
11007
11008   // If we are removing arguments to the function, emit an obnoxious warning.
11009   if (FT->getNumParams() < NumActualArgs) {
11010     if (!FT->isVarArg()) {
11011       errs() << "WARNING: While resolving call to function '"
11012              << Callee->getName() << "' arguments were dropped!\n";
11013     } else {
11014       // Add all of the arguments in their promoted form to the arg list.
11015       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
11016         const Type *PTy = getPromotedType((*AI)->getType());
11017         if (PTy != (*AI)->getType()) {
11018           // Must promote to pass through va_arg area!
11019           Instruction::CastOps opcode =
11020             CastInst::getCastOpcode(*AI, false, PTy, false);
11021           Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
11022         } else {
11023           Args.push_back(*AI);
11024         }
11025
11026         // Add any parameter attributes.
11027         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
11028           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
11029       }
11030     }
11031   }
11032
11033   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
11034     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
11035
11036   if (NewRetTy->isVoidTy())
11037     Caller->setName("");   // Void type should not have a name.
11038
11039   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
11040                                                      attrVec.end());
11041
11042   Instruction *NC;
11043   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
11044     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
11045                             Args.begin(), Args.end(),
11046                             Caller->getName(), Caller);
11047     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
11048     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
11049   } else {
11050     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
11051                           Caller->getName(), Caller);
11052     CallInst *CI = cast<CallInst>(Caller);
11053     if (CI->isTailCall())
11054       cast<CallInst>(NC)->setTailCall();
11055     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
11056     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
11057   }
11058
11059   // Insert a cast of the return type as necessary.
11060   Value *NV = NC;
11061   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
11062     if (!NV->getType()->isVoidTy()) {
11063       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
11064                                                             OldRetTy, false);
11065       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
11066
11067       // If this is an invoke instruction, we should insert it after the first
11068       // non-phi, instruction in the normal successor block.
11069       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
11070         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
11071         InsertNewInstBefore(NC, *I);
11072       } else {
11073         // Otherwise, it's a call, just insert cast right after the call instr
11074         InsertNewInstBefore(NC, *Caller);
11075       }
11076       Worklist.AddUsersToWorkList(*Caller);
11077     } else {
11078       NV = UndefValue::get(Caller->getType());
11079     }
11080   }
11081
11082
11083   if (!Caller->use_empty())
11084     Caller->replaceAllUsesWith(NV);
11085   
11086   EraseInstFromFunction(*Caller);
11087   return true;
11088 }
11089
11090 // transformCallThroughTrampoline - Turn a call to a function created by the
11091 // init_trampoline intrinsic into a direct call to the underlying function.
11092 //
11093 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
11094   Value *Callee = CS.getCalledValue();
11095   const PointerType *PTy = cast<PointerType>(Callee->getType());
11096   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
11097   const AttrListPtr &Attrs = CS.getAttributes();
11098
11099   // If the call already has the 'nest' attribute somewhere then give up -
11100   // otherwise 'nest' would occur twice after splicing in the chain.
11101   if (Attrs.hasAttrSomewhere(Attribute::Nest))
11102     return 0;
11103
11104   IntrinsicInst *Tramp =
11105     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
11106
11107   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
11108   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
11109   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
11110
11111   const AttrListPtr &NestAttrs = NestF->getAttributes();
11112   if (!NestAttrs.isEmpty()) {
11113     unsigned NestIdx = 1;
11114     const Type *NestTy = 0;
11115     Attributes NestAttr = Attribute::None;
11116
11117     // Look for a parameter marked with the 'nest' attribute.
11118     for (FunctionType::param_iterator I = NestFTy->param_begin(),
11119          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
11120       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
11121         // Record the parameter type and any other attributes.
11122         NestTy = *I;
11123         NestAttr = NestAttrs.getParamAttributes(NestIdx);
11124         break;
11125       }
11126
11127     if (NestTy) {
11128       Instruction *Caller = CS.getInstruction();
11129       std::vector<Value*> NewArgs;
11130       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
11131
11132       SmallVector<AttributeWithIndex, 8> NewAttrs;
11133       NewAttrs.reserve(Attrs.getNumSlots() + 1);
11134
11135       // Insert the nest argument into the call argument list, which may
11136       // mean appending it.  Likewise for attributes.
11137
11138       // Add any result attributes.
11139       if (Attributes Attr = Attrs.getRetAttributes())
11140         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
11141
11142       {
11143         unsigned Idx = 1;
11144         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11145         do {
11146           if (Idx == NestIdx) {
11147             // Add the chain argument and attributes.
11148             Value *NestVal = Tramp->getOperand(3);
11149             if (NestVal->getType() != NestTy)
11150               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11151             NewArgs.push_back(NestVal);
11152             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
11153           }
11154
11155           if (I == E)
11156             break;
11157
11158           // Add the original argument and attributes.
11159           NewArgs.push_back(*I);
11160           if (Attributes Attr = Attrs.getParamAttributes(Idx))
11161             NewAttrs.push_back
11162               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
11163
11164           ++Idx, ++I;
11165         } while (1);
11166       }
11167
11168       // Add any function attributes.
11169       if (Attributes Attr = Attrs.getFnAttributes())
11170         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11171
11172       // The trampoline may have been bitcast to a bogus type (FTy).
11173       // Handle this by synthesizing a new function type, equal to FTy
11174       // with the chain parameter inserted.
11175
11176       std::vector<const Type*> NewTypes;
11177       NewTypes.reserve(FTy->getNumParams()+1);
11178
11179       // Insert the chain's type into the list of parameter types, which may
11180       // mean appending it.
11181       {
11182         unsigned Idx = 1;
11183         FunctionType::param_iterator I = FTy->param_begin(),
11184           E = FTy->param_end();
11185
11186         do {
11187           if (Idx == NestIdx)
11188             // Add the chain's type.
11189             NewTypes.push_back(NestTy);
11190
11191           if (I == E)
11192             break;
11193
11194           // Add the original type.
11195           NewTypes.push_back(*I);
11196
11197           ++Idx, ++I;
11198         } while (1);
11199       }
11200
11201       // Replace the trampoline call with a direct call.  Let the generic
11202       // code sort out any function type mismatches.
11203       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
11204                                                 FTy->isVarArg());
11205       Constant *NewCallee =
11206         NestF->getType() == PointerType::getUnqual(NewFTy) ?
11207         NestF : ConstantExpr::getBitCast(NestF, 
11208                                          PointerType::getUnqual(NewFTy));
11209       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11210                                                    NewAttrs.end());
11211
11212       Instruction *NewCaller;
11213       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
11214         NewCaller = InvokeInst::Create(NewCallee,
11215                                        II->getNormalDest(), II->getUnwindDest(),
11216                                        NewArgs.begin(), NewArgs.end(),
11217                                        Caller->getName(), Caller);
11218         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
11219         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
11220       } else {
11221         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11222                                      Caller->getName(), Caller);
11223         if (cast<CallInst>(Caller)->isTailCall())
11224           cast<CallInst>(NewCaller)->setTailCall();
11225         cast<CallInst>(NewCaller)->
11226           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
11227         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
11228       }
11229       if (!Caller->getType()->isVoidTy())
11230         Caller->replaceAllUsesWith(NewCaller);
11231       Caller->eraseFromParent();
11232       Worklist.Remove(Caller);
11233       return 0;
11234     }
11235   }
11236
11237   // Replace the trampoline call with a direct call.  Since there is no 'nest'
11238   // parameter, there is no need to adjust the argument list.  Let the generic
11239   // code sort out any function type mismatches.
11240   Constant *NewCallee =
11241     NestF->getType() == PTy ? NestF : 
11242                               ConstantExpr::getBitCast(NestF, PTy);
11243   CS.setCalledFunction(NewCallee);
11244   return CS.getInstruction();
11245 }
11246
11247 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11248 /// and if a/b/c and the add's all have a single use, turn this into a phi
11249 /// and a single binop.
11250 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11251   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11252   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
11253   unsigned Opc = FirstInst->getOpcode();
11254   Value *LHSVal = FirstInst->getOperand(0);
11255   Value *RHSVal = FirstInst->getOperand(1);
11256     
11257   const Type *LHSType = LHSVal->getType();
11258   const Type *RHSType = RHSVal->getType();
11259   
11260   // Scan to see if all operands are the same opcode, and all have one use.
11261   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11262     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11263     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
11264         // Verify type of the LHS matches so we don't fold cmp's of different
11265         // types or GEP's with different index types.
11266         I->getOperand(0)->getType() != LHSType ||
11267         I->getOperand(1)->getType() != RHSType)
11268       return 0;
11269
11270     // If they are CmpInst instructions, check their predicates
11271     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11272       if (cast<CmpInst>(I)->getPredicate() !=
11273           cast<CmpInst>(FirstInst)->getPredicate())
11274         return 0;
11275     
11276     // Keep track of which operand needs a phi node.
11277     if (I->getOperand(0) != LHSVal) LHSVal = 0;
11278     if (I->getOperand(1) != RHSVal) RHSVal = 0;
11279   }
11280
11281   // If both LHS and RHS would need a PHI, don't do this transformation,
11282   // because it would increase the number of PHIs entering the block,
11283   // which leads to higher register pressure. This is especially
11284   // bad when the PHIs are in the header of a loop.
11285   if (!LHSVal && !RHSVal)
11286     return 0;
11287   
11288   // Otherwise, this is safe to transform!
11289   
11290   Value *InLHS = FirstInst->getOperand(0);
11291   Value *InRHS = FirstInst->getOperand(1);
11292   PHINode *NewLHS = 0, *NewRHS = 0;
11293   if (LHSVal == 0) {
11294     NewLHS = PHINode::Create(LHSType,
11295                              FirstInst->getOperand(0)->getName() + ".pn");
11296     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11297     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
11298     InsertNewInstBefore(NewLHS, PN);
11299     LHSVal = NewLHS;
11300   }
11301   
11302   if (RHSVal == 0) {
11303     NewRHS = PHINode::Create(RHSType,
11304                              FirstInst->getOperand(1)->getName() + ".pn");
11305     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11306     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
11307     InsertNewInstBefore(NewRHS, PN);
11308     RHSVal = NewRHS;
11309   }
11310   
11311   // Add all operands to the new PHIs.
11312   if (NewLHS || NewRHS) {
11313     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11314       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11315       if (NewLHS) {
11316         Value *NewInLHS = InInst->getOperand(0);
11317         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11318       }
11319       if (NewRHS) {
11320         Value *NewInRHS = InInst->getOperand(1);
11321         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11322       }
11323     }
11324   }
11325     
11326   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11327     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
11328   CmpInst *CIOp = cast<CmpInst>(FirstInst);
11329   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11330                          LHSVal, RHSVal);
11331 }
11332
11333 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11334   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11335   
11336   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
11337                                         FirstInst->op_end());
11338   // This is true if all GEP bases are allocas and if all indices into them are
11339   // constants.
11340   bool AllBasePointersAreAllocas = true;
11341
11342   // We don't want to replace this phi if the replacement would require
11343   // more than one phi, which leads to higher register pressure. This is
11344   // especially bad when the PHIs are in the header of a loop.
11345   bool NeededPhi = false;
11346   
11347   // Scan to see if all operands are the same opcode, and all have one use.
11348   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11349     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11350     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11351       GEP->getNumOperands() != FirstInst->getNumOperands())
11352       return 0;
11353
11354     // Keep track of whether or not all GEPs are of alloca pointers.
11355     if (AllBasePointersAreAllocas &&
11356         (!isa<AllocaInst>(GEP->getOperand(0)) ||
11357          !GEP->hasAllConstantIndices()))
11358       AllBasePointersAreAllocas = false;
11359     
11360     // Compare the operand lists.
11361     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11362       if (FirstInst->getOperand(op) == GEP->getOperand(op))
11363         continue;
11364       
11365       // Don't merge two GEPs when two operands differ (introducing phi nodes)
11366       // if one of the PHIs has a constant for the index.  The index may be
11367       // substantially cheaper to compute for the constants, so making it a
11368       // variable index could pessimize the path.  This also handles the case
11369       // for struct indices, which must always be constant.
11370       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11371           isa<ConstantInt>(GEP->getOperand(op)))
11372         return 0;
11373       
11374       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11375         return 0;
11376
11377       // If we already needed a PHI for an earlier operand, and another operand
11378       // also requires a PHI, we'd be introducing more PHIs than we're
11379       // eliminating, which increases register pressure on entry to the PHI's
11380       // block.
11381       if (NeededPhi)
11382         return 0;
11383
11384       FixedOperands[op] = 0;  // Needs a PHI.
11385       NeededPhi = true;
11386     }
11387   }
11388   
11389   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
11390   // bother doing this transformation.  At best, this will just save a bit of
11391   // offset calculation, but all the predecessors will have to materialize the
11392   // stack address into a register anyway.  We'd actually rather *clone* the
11393   // load up into the predecessors so that we have a load of a gep of an alloca,
11394   // which can usually all be folded into the load.
11395   if (AllBasePointersAreAllocas)
11396     return 0;
11397   
11398   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
11399   // that is variable.
11400   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11401   
11402   bool HasAnyPHIs = false;
11403   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11404     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
11405     Value *FirstOp = FirstInst->getOperand(i);
11406     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11407                                      FirstOp->getName()+".pn");
11408     InsertNewInstBefore(NewPN, PN);
11409     
11410     NewPN->reserveOperandSpace(e);
11411     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11412     OperandPhis[i] = NewPN;
11413     FixedOperands[i] = NewPN;
11414     HasAnyPHIs = true;
11415   }
11416
11417   
11418   // Add all operands to the new PHIs.
11419   if (HasAnyPHIs) {
11420     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11421       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11422       BasicBlock *InBB = PN.getIncomingBlock(i);
11423       
11424       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11425         if (PHINode *OpPhi = OperandPhis[op])
11426           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11427     }
11428   }
11429   
11430   Value *Base = FixedOperands[0];
11431   return cast<GEPOperator>(FirstInst)->isInBounds() ?
11432     GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11433                                       FixedOperands.end()) :
11434     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11435                               FixedOperands.end());
11436 }
11437
11438
11439 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11440 /// sink the load out of the block that defines it.  This means that it must be
11441 /// obvious the value of the load is not changed from the point of the load to
11442 /// the end of the block it is in.
11443 ///
11444 /// Finally, it is safe, but not profitable, to sink a load targetting a
11445 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
11446 /// to a register.
11447 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
11448   BasicBlock::iterator BBI = L, E = L->getParent()->end();
11449   
11450   for (++BBI; BBI != E; ++BBI)
11451     if (BBI->mayWriteToMemory())
11452       return false;
11453   
11454   // Check for non-address taken alloca.  If not address-taken already, it isn't
11455   // profitable to do this xform.
11456   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11457     bool isAddressTaken = false;
11458     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11459          UI != E; ++UI) {
11460       if (isa<LoadInst>(UI)) continue;
11461       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11462         // If storing TO the alloca, then the address isn't taken.
11463         if (SI->getOperand(1) == AI) continue;
11464       }
11465       isAddressTaken = true;
11466       break;
11467     }
11468     
11469     if (!isAddressTaken && AI->isStaticAlloca())
11470       return false;
11471   }
11472   
11473   // If this load is a load from a GEP with a constant offset from an alloca,
11474   // then we don't want to sink it.  In its present form, it will be
11475   // load [constant stack offset].  Sinking it will cause us to have to
11476   // materialize the stack addresses in each predecessor in a register only to
11477   // do a shared load from register in the successor.
11478   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11479     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11480       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11481         return false;
11482   
11483   return true;
11484 }
11485
11486 Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11487   LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11488   
11489   // When processing loads, we need to propagate two bits of information to the
11490   // sunk load: whether it is volatile, and what its alignment is.  We currently
11491   // don't sink loads when some have their alignment specified and some don't.
11492   // visitLoadInst will propagate an alignment onto the load when TD is around,
11493   // and if TD isn't around, we can't handle the mixed case.
11494   bool isVolatile = FirstLI->isVolatile();
11495   unsigned LoadAlignment = FirstLI->getAlignment();
11496   
11497   // We can't sink the load if the loaded value could be modified between the
11498   // load and the PHI.
11499   if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11500       !isSafeAndProfitableToSinkLoad(FirstLI))
11501     return 0;
11502   
11503   // If the PHI is of volatile loads and the load block has multiple
11504   // successors, sinking it would remove a load of the volatile value from
11505   // the path through the other successor.
11506   if (isVolatile && 
11507       FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11508     return 0;
11509   
11510   // Check to see if all arguments are the same operation.
11511   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11512     LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11513     if (!LI || !LI->hasOneUse())
11514       return 0;
11515     
11516     // We can't sink the load if the loaded value could be modified between 
11517     // the load and the PHI.
11518     if (LI->isVolatile() != isVolatile ||
11519         LI->getParent() != PN.getIncomingBlock(i) ||
11520         !isSafeAndProfitableToSinkLoad(LI))
11521       return 0;
11522       
11523     // If some of the loads have an alignment specified but not all of them,
11524     // we can't do the transformation.
11525     if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11526       return 0;
11527     
11528     LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
11529     
11530     // If the PHI is of volatile loads and the load block has multiple
11531     // successors, sinking it would remove a load of the volatile value from
11532     // the path through the other successor.
11533     if (isVolatile &&
11534         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11535       return 0;
11536   }
11537   
11538   // Okay, they are all the same operation.  Create a new PHI node of the
11539   // correct type, and PHI together all of the LHS's of the instructions.
11540   PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11541                                    PN.getName()+".in");
11542   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11543   
11544   Value *InVal = FirstLI->getOperand(0);
11545   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11546   
11547   // Add all operands to the new PHI.
11548   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11549     Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11550     if (NewInVal != InVal)
11551       InVal = 0;
11552     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11553   }
11554   
11555   Value *PhiVal;
11556   if (InVal) {
11557     // The new PHI unions all of the same values together.  This is really
11558     // common, so we handle it intelligently here for compile-time speed.
11559     PhiVal = InVal;
11560     delete NewPN;
11561   } else {
11562     InsertNewInstBefore(NewPN, PN);
11563     PhiVal = NewPN;
11564   }
11565   
11566   // If this was a volatile load that we are merging, make sure to loop through
11567   // and mark all the input loads as non-volatile.  If we don't do this, we will
11568   // insert a new volatile load and the old ones will not be deletable.
11569   if (isVolatile)
11570     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11571       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11572   
11573   return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11574 }
11575
11576
11577
11578 /// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11579 /// operator and they all are only used by the PHI, PHI together their
11580 /// inputs, and do the operation once, to the result of the PHI.
11581 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11582   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11583
11584   if (isa<GetElementPtrInst>(FirstInst))
11585     return FoldPHIArgGEPIntoPHI(PN);
11586   if (isa<LoadInst>(FirstInst))
11587     return FoldPHIArgLoadIntoPHI(PN);
11588   
11589   // Scan the instruction, looking for input operations that can be folded away.
11590   // If all input operands to the phi are the same instruction (e.g. a cast from
11591   // the same type or "+42") we can pull the operation through the PHI, reducing
11592   // code size and simplifying code.
11593   Constant *ConstantOp = 0;
11594   const Type *CastSrcTy = 0;
11595   
11596   if (isa<CastInst>(FirstInst)) {
11597     CastSrcTy = FirstInst->getOperand(0)->getType();
11598
11599     // Be careful about transforming integer PHIs.  We don't want to pessimize
11600     // the code by turning an i32 into an i1293.
11601     if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
11602       if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
11603         return 0;
11604     }
11605   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
11606     // Can fold binop, compare or shift here if the RHS is a constant, 
11607     // otherwise call FoldPHIArgBinOpIntoPHI.
11608     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
11609     if (ConstantOp == 0)
11610       return FoldPHIArgBinOpIntoPHI(PN);
11611   } else {
11612     return 0;  // Cannot fold this operation.
11613   }
11614
11615   // Check to see if all arguments are the same operation.
11616   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11617     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11618     if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
11619       return 0;
11620     if (CastSrcTy) {
11621       if (I->getOperand(0)->getType() != CastSrcTy)
11622         return 0;  // Cast operation must match.
11623     } else if (I->getOperand(1) != ConstantOp) {
11624       return 0;
11625     }
11626   }
11627
11628   // Okay, they are all the same operation.  Create a new PHI node of the
11629   // correct type, and PHI together all of the LHS's of the instructions.
11630   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11631                                    PN.getName()+".in");
11632   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11633
11634   Value *InVal = FirstInst->getOperand(0);
11635   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11636
11637   // Add all operands to the new PHI.
11638   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11639     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11640     if (NewInVal != InVal)
11641       InVal = 0;
11642     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11643   }
11644
11645   Value *PhiVal;
11646   if (InVal) {
11647     // The new PHI unions all of the same values together.  This is really
11648     // common, so we handle it intelligently here for compile-time speed.
11649     PhiVal = InVal;
11650     delete NewPN;
11651   } else {
11652     InsertNewInstBefore(NewPN, PN);
11653     PhiVal = NewPN;
11654   }
11655
11656   // Insert and return the new operation.
11657   if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
11658     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
11659   
11660   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
11661     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
11662   
11663   CmpInst *CIOp = cast<CmpInst>(FirstInst);
11664   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11665                          PhiVal, ConstantOp);
11666 }
11667
11668 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11669 /// that is dead.
11670 static bool DeadPHICycle(PHINode *PN,
11671                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
11672   if (PN->use_empty()) return true;
11673   if (!PN->hasOneUse()) return false;
11674
11675   // Remember this node, and if we find the cycle, return.
11676   if (!PotentiallyDeadPHIs.insert(PN))
11677     return true;
11678   
11679   // Don't scan crazily complex things.
11680   if (PotentiallyDeadPHIs.size() == 16)
11681     return false;
11682
11683   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11684     return DeadPHICycle(PU, PotentiallyDeadPHIs);
11685
11686   return false;
11687 }
11688
11689 /// PHIsEqualValue - Return true if this phi node is always equal to
11690 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
11691 ///   z = some value; x = phi (y, z); y = phi (x, z)
11692 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
11693                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11694   // See if we already saw this PHI node.
11695   if (!ValueEqualPHIs.insert(PN))
11696     return true;
11697   
11698   // Don't scan crazily complex things.
11699   if (ValueEqualPHIs.size() == 16)
11700     return false;
11701  
11702   // Scan the operands to see if they are either phi nodes or are equal to
11703   // the value.
11704   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11705     Value *Op = PN->getIncomingValue(i);
11706     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11707       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11708         return false;
11709     } else if (Op != NonPhiInVal)
11710       return false;
11711   }
11712   
11713   return true;
11714 }
11715
11716
11717 namespace {
11718 struct PHIUsageRecord {
11719   unsigned PHIId;     // The ID # of the PHI (something determinstic to sort on)
11720   unsigned Shift;     // The amount shifted.
11721   Instruction *Inst;  // The trunc instruction.
11722   
11723   PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11724     : PHIId(pn), Shift(Sh), Inst(User) {}
11725   
11726   bool operator<(const PHIUsageRecord &RHS) const {
11727     if (PHIId < RHS.PHIId) return true;
11728     if (PHIId > RHS.PHIId) return false;
11729     if (Shift < RHS.Shift) return true;
11730     if (Shift > RHS.Shift) return false;
11731     return Inst->getType()->getPrimitiveSizeInBits() <
11732            RHS.Inst->getType()->getPrimitiveSizeInBits();
11733   }
11734 };
11735   
11736 struct LoweredPHIRecord {
11737   PHINode *PN;        // The PHI that was lowered.
11738   unsigned Shift;     // The amount shifted.
11739   unsigned Width;     // The width extracted.
11740   
11741   LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11742     : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11743   
11744   // Ctor form used by DenseMap.
11745   LoweredPHIRecord(PHINode *pn, unsigned Sh)
11746     : PN(pn), Shift(Sh), Width(0) {}
11747 };
11748 }
11749
11750 namespace llvm {
11751   template<>
11752   struct DenseMapInfo<LoweredPHIRecord> {
11753     static inline LoweredPHIRecord getEmptyKey() {
11754       return LoweredPHIRecord(0, 0);
11755     }
11756     static inline LoweredPHIRecord getTombstoneKey() {
11757       return LoweredPHIRecord(0, 1);
11758     }
11759     static unsigned getHashValue(const LoweredPHIRecord &Val) {
11760       return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11761              (Val.Width>>3);
11762     }
11763     static bool isEqual(const LoweredPHIRecord &LHS,
11764                         const LoweredPHIRecord &RHS) {
11765       return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11766              LHS.Width == RHS.Width;
11767     }
11768   };
11769   template <>
11770   struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
11771 }
11772
11773
11774 /// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11775 /// illegal type: see if it is only used by trunc or trunc(lshr) operations.  If
11776 /// so, we split the PHI into the various pieces being extracted.  This sort of
11777 /// thing is introduced when SROA promotes an aggregate to large integer values.
11778 ///
11779 /// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11780 /// inttoptr.  We should produce new PHIs in the right type.
11781 ///
11782 Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11783   // PHIUsers - Keep track of all of the truncated values extracted from a set
11784   // of PHIs, along with their offset.  These are the things we want to rewrite.
11785   SmallVector<PHIUsageRecord, 16> PHIUsers;
11786   
11787   // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11788   // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11789   // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11790   // check the uses of (to ensure they are all extracts).
11791   SmallVector<PHINode*, 8> PHIsToSlice;
11792   SmallPtrSet<PHINode*, 8> PHIsInspected;
11793   
11794   PHIsToSlice.push_back(&FirstPhi);
11795   PHIsInspected.insert(&FirstPhi);
11796   
11797   for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11798     PHINode *PN = PHIsToSlice[PHIId];
11799     
11800     // Scan the input list of the PHI.  If any input is an invoke, and if the
11801     // input is defined in the predecessor, then we won't be split the critical
11802     // edge which is required to insert a truncate.  Because of this, we have to
11803     // bail out.
11804     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11805       InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11806       if (II == 0) continue;
11807       if (II->getParent() != PN->getIncomingBlock(i))
11808         continue;
11809      
11810       // If we have a phi, and if it's directly in the predecessor, then we have
11811       // a critical edge where we need to put the truncate.  Since we can't
11812       // split the edge in instcombine, we have to bail out.
11813       return 0;
11814     }
11815       
11816     
11817     for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11818          UI != E; ++UI) {
11819       Instruction *User = cast<Instruction>(*UI);
11820       
11821       // If the user is a PHI, inspect its uses recursively.
11822       if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11823         if (PHIsInspected.insert(UserPN))
11824           PHIsToSlice.push_back(UserPN);
11825         continue;
11826       }
11827       
11828       // Truncates are always ok.
11829       if (isa<TruncInst>(User)) {
11830         PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11831         continue;
11832       }
11833       
11834       // Otherwise it must be a lshr which can only be used by one trunc.
11835       if (User->getOpcode() != Instruction::LShr ||
11836           !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11837           !isa<ConstantInt>(User->getOperand(1)))
11838         return 0;
11839       
11840       unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11841       PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
11842     }
11843   }
11844   
11845   // If we have no users, they must be all self uses, just nuke the PHI.
11846   if (PHIUsers.empty())
11847     return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
11848   
11849   // If this phi node is transformable, create new PHIs for all the pieces
11850   // extracted out of it.  First, sort the users by their offset and size.
11851   array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11852   
11853   DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11854             for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11855               errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11856         );
11857   
11858   // PredValues - This is a temporary used when rewriting PHI nodes.  It is
11859   // hoisted out here to avoid construction/destruction thrashing.
11860   DenseMap<BasicBlock*, Value*> PredValues;
11861   
11862   // ExtractedVals - Each new PHI we introduce is saved here so we don't
11863   // introduce redundant PHIs.
11864   DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11865   
11866   for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11867     unsigned PHIId = PHIUsers[UserI].PHIId;
11868     PHINode *PN = PHIsToSlice[PHIId];
11869     unsigned Offset = PHIUsers[UserI].Shift;
11870     const Type *Ty = PHIUsers[UserI].Inst->getType();
11871     
11872     PHINode *EltPHI;
11873     
11874     // If we've already lowered a user like this, reuse the previously lowered
11875     // value.
11876     if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
11877       
11878       // Otherwise, Create the new PHI node for this user.
11879       EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11880       assert(EltPHI->getType() != PN->getType() &&
11881              "Truncate didn't shrink phi?");
11882     
11883       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11884         BasicBlock *Pred = PN->getIncomingBlock(i);
11885         Value *&PredVal = PredValues[Pred];
11886         
11887         // If we already have a value for this predecessor, reuse it.
11888         if (PredVal) {
11889           EltPHI->addIncoming(PredVal, Pred);
11890           continue;
11891         }
11892
11893         // Handle the PHI self-reuse case.
11894         Value *InVal = PN->getIncomingValue(i);
11895         if (InVal == PN) {
11896           PredVal = EltPHI;
11897           EltPHI->addIncoming(PredVal, Pred);
11898           continue;
11899         }
11900         
11901         if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
11902           // If the incoming value was a PHI, and if it was one of the PHIs we
11903           // already rewrote it, just use the lowered value.
11904           if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11905             PredVal = Res;
11906             EltPHI->addIncoming(PredVal, Pred);
11907             continue;
11908           }
11909         }
11910         
11911         // Otherwise, do an extract in the predecessor.
11912         Builder->SetInsertPoint(Pred, Pred->getTerminator());
11913         Value *Res = InVal;
11914         if (Offset)
11915           Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11916                                                           Offset), "extract");
11917         Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11918         PredVal = Res;
11919         EltPHI->addIncoming(Res, Pred);
11920         
11921         // If the incoming value was a PHI, and if it was one of the PHIs we are
11922         // rewriting, we will ultimately delete the code we inserted.  This
11923         // means we need to revisit that PHI to make sure we extract out the
11924         // needed piece.
11925         if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11926           if (PHIsInspected.count(OldInVal)) {
11927             unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11928                                           OldInVal)-PHIsToSlice.begin();
11929             PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset, 
11930                                               cast<Instruction>(Res)));
11931             ++UserE;
11932           }
11933       }
11934       PredValues.clear();
11935       
11936       DEBUG(errs() << "  Made element PHI for offset " << Offset << ": "
11937                    << *EltPHI << '\n');
11938       ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
11939     }
11940     
11941     // Replace the use of this piece with the PHI node.
11942     ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
11943   }
11944   
11945   // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11946   // with undefs.
11947   Value *Undef = UndefValue::get(FirstPhi.getType());
11948   for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11949     ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11950   return ReplaceInstUsesWith(FirstPhi, Undef);
11951 }
11952
11953 // PHINode simplification
11954 //
11955 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
11956   // If LCSSA is around, don't mess with Phi nodes
11957   if (MustPreserveLCSSA) return 0;
11958   
11959   if (Value *V = PN.hasConstantValue())
11960     return ReplaceInstUsesWith(PN, V);
11961
11962   // If all PHI operands are the same operation, pull them through the PHI,
11963   // reducing code size.
11964   if (isa<Instruction>(PN.getIncomingValue(0)) &&
11965       isa<Instruction>(PN.getIncomingValue(1)) &&
11966       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11967       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11968       // FIXME: The hasOneUse check will fail for PHIs that use the value more
11969       // than themselves more than once.
11970       PN.getIncomingValue(0)->hasOneUse())
11971     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11972       return Result;
11973
11974   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
11975   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11976   // PHI)... break the cycle.
11977   if (PN.hasOneUse()) {
11978     Instruction *PHIUser = cast<Instruction>(PN.use_back());
11979     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
11980       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
11981       PotentiallyDeadPHIs.insert(&PN);
11982       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
11983         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11984     }
11985    
11986     // If this phi has a single use, and if that use just computes a value for
11987     // the next iteration of a loop, delete the phi.  This occurs with unused
11988     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
11989     // common case here is good because the only other things that catch this
11990     // are induction variable analysis (sometimes) and ADCE, which is only run
11991     // late.
11992     if (PHIUser->hasOneUse() &&
11993         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11994         PHIUser->use_back() == &PN) {
11995       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
11996     }
11997   }
11998
11999   // We sometimes end up with phi cycles that non-obviously end up being the
12000   // same value, for example:
12001   //   z = some value; x = phi (y, z); y = phi (x, z)
12002   // where the phi nodes don't necessarily need to be in the same block.  Do a
12003   // quick check to see if the PHI node only contains a single non-phi value, if
12004   // so, scan to see if the phi cycle is actually equal to that value.
12005   {
12006     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
12007     // Scan for the first non-phi operand.
12008     while (InValNo != NumOperandVals && 
12009            isa<PHINode>(PN.getIncomingValue(InValNo)))
12010       ++InValNo;
12011
12012     if (InValNo != NumOperandVals) {
12013       Value *NonPhiInVal = PN.getOperand(InValNo);
12014       
12015       // Scan the rest of the operands to see if there are any conflicts, if so
12016       // there is no need to recursively scan other phis.
12017       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
12018         Value *OpVal = PN.getIncomingValue(InValNo);
12019         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
12020           break;
12021       }
12022       
12023       // If we scanned over all operands, then we have one unique value plus
12024       // phi values.  Scan PHI nodes to see if they all merge in each other or
12025       // the value.
12026       if (InValNo == NumOperandVals) {
12027         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
12028         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
12029           return ReplaceInstUsesWith(PN, NonPhiInVal);
12030       }
12031     }
12032   }
12033
12034   // If there are multiple PHIs, sort their operands so that they all list
12035   // the blocks in the same order. This will help identical PHIs be eliminated
12036   // by other passes. Other passes shouldn't depend on this for correctness
12037   // however.
12038   PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
12039   if (&PN != FirstPN)
12040     for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
12041       BasicBlock *BBA = PN.getIncomingBlock(i);
12042       BasicBlock *BBB = FirstPN->getIncomingBlock(i);
12043       if (BBA != BBB) {
12044         Value *VA = PN.getIncomingValue(i);
12045         unsigned j = PN.getBasicBlockIndex(BBB);
12046         Value *VB = PN.getIncomingValue(j);
12047         PN.setIncomingBlock(i, BBB);
12048         PN.setIncomingValue(i, VB);
12049         PN.setIncomingBlock(j, BBA);
12050         PN.setIncomingValue(j, VA);
12051         // NOTE: Instcombine normally would want us to "return &PN" if we
12052         // modified any of the operands of an instruction.  However, since we
12053         // aren't adding or removing uses (just rearranging them) we don't do
12054         // this in this case.
12055       }
12056     }
12057
12058   // If this is an integer PHI and we know that it has an illegal type, see if
12059   // it is only used by trunc or trunc(lshr) operations.  If so, we split the
12060   // PHI into the various pieces being extracted.  This sort of thing is
12061   // introduced when SROA promotes an aggregate to a single large integer type.
12062   if (isa<IntegerType>(PN.getType()) && TD &&
12063       !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
12064     if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
12065       return Res;
12066   
12067   return 0;
12068 }
12069
12070 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
12071   SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
12072
12073   if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
12074     return ReplaceInstUsesWith(GEP, V);
12075
12076   Value *PtrOp = GEP.getOperand(0);
12077
12078   if (isa<UndefValue>(GEP.getOperand(0)))
12079     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
12080
12081   // Eliminate unneeded casts for indices.
12082   if (TD) {
12083     bool MadeChange = false;
12084     unsigned PtrSize = TD->getPointerSizeInBits();
12085     
12086     gep_type_iterator GTI = gep_type_begin(GEP);
12087     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
12088          I != E; ++I, ++GTI) {
12089       if (!isa<SequentialType>(*GTI)) continue;
12090       
12091       // If we are using a wider index than needed for this platform, shrink it
12092       // to what we need.  If narrower, sign-extend it to what we need.  This
12093       // explicit cast can make subsequent optimizations more obvious.
12094       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
12095       if (OpBits == PtrSize)
12096         continue;
12097       
12098       *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
12099       MadeChange = true;
12100     }
12101     if (MadeChange) return &GEP;
12102   }
12103
12104   // Combine Indices - If the source pointer to this getelementptr instruction
12105   // is a getelementptr instruction, combine the indices of the two
12106   // getelementptr instructions into a single instruction.
12107   //
12108   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
12109     // Note that if our source is a gep chain itself that we wait for that
12110     // chain to be resolved before we perform this transformation.  This
12111     // avoids us creating a TON of code in some cases.
12112     //
12113     if (GetElementPtrInst *SrcGEP =
12114           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
12115       if (SrcGEP->getNumOperands() == 2)
12116         return 0;   // Wait until our source is folded to completion.
12117
12118     SmallVector<Value*, 8> Indices;
12119
12120     // Find out whether the last index in the source GEP is a sequential idx.
12121     bool EndsWithSequential = false;
12122     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
12123          I != E; ++I)
12124       EndsWithSequential = !isa<StructType>(*I);
12125
12126     // Can we combine the two pointer arithmetics offsets?
12127     if (EndsWithSequential) {
12128       // Replace: gep (gep %P, long B), long A, ...
12129       // With:    T = long A+B; gep %P, T, ...
12130       //
12131       Value *Sum;
12132       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
12133       Value *GO1 = GEP.getOperand(1);
12134       if (SO1 == Constant::getNullValue(SO1->getType())) {
12135         Sum = GO1;
12136       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
12137         Sum = SO1;
12138       } else {
12139         // If they aren't the same type, then the input hasn't been processed
12140         // by the loop above yet (which canonicalizes sequential index types to
12141         // intptr_t).  Just avoid transforming this until the input has been
12142         // normalized.
12143         if (SO1->getType() != GO1->getType())
12144           return 0;
12145         Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
12146       }
12147
12148       // Update the GEP in place if possible.
12149       if (Src->getNumOperands() == 2) {
12150         GEP.setOperand(0, Src->getOperand(0));
12151         GEP.setOperand(1, Sum);
12152         return &GEP;
12153       }
12154       Indices.append(Src->op_begin()+1, Src->op_end()-1);
12155       Indices.push_back(Sum);
12156       Indices.append(GEP.op_begin()+2, GEP.op_end());
12157     } else if (isa<Constant>(*GEP.idx_begin()) &&
12158                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
12159                Src->getNumOperands() != 1) {
12160       // Otherwise we can do the fold if the first index of the GEP is a zero
12161       Indices.append(Src->op_begin()+1, Src->op_end());
12162       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
12163     }
12164
12165     if (!Indices.empty())
12166       return (cast<GEPOperator>(&GEP)->isInBounds() &&
12167               Src->isInBounds()) ?
12168         GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12169                                           Indices.end(), GEP.getName()) :
12170         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
12171                                   Indices.end(), GEP.getName());
12172   }
12173   
12174   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12175   if (Value *X = getBitCastOperand(PtrOp)) {
12176     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
12177
12178     // If the input bitcast is actually "bitcast(bitcast(x))", then we don't 
12179     // want to change the gep until the bitcasts are eliminated.
12180     if (getBitCastOperand(X)) {
12181       Worklist.AddValue(PtrOp);
12182       return 0;
12183     }
12184     
12185     bool HasZeroPointerIndex = false;
12186     if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12187       HasZeroPointerIndex = C->isZero();
12188     
12189     // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12190     // into     : GEP [10 x i8]* X, i32 0, ...
12191     //
12192     // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12193     //           into     : GEP i8* X, ...
12194     // 
12195     // This occurs when the program declares an array extern like "int X[];"
12196     if (HasZeroPointerIndex) {
12197       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12198       const PointerType *XTy = cast<PointerType>(X->getType());
12199       if (const ArrayType *CATy =
12200           dyn_cast<ArrayType>(CPTy->getElementType())) {
12201         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12202         if (CATy->getElementType() == XTy->getElementType()) {
12203           // -> GEP i8* X, ...
12204           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
12205           return cast<GEPOperator>(&GEP)->isInBounds() ?
12206             GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12207                                               GEP.getName()) :
12208             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12209                                       GEP.getName());
12210         }
12211         
12212         if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
12213           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
12214           if (CATy->getElementType() == XATy->getElementType()) {
12215             // -> GEP [10 x i8]* X, i32 0, ...
12216             // At this point, we know that the cast source type is a pointer
12217             // to an array of the same type as the destination pointer
12218             // array.  Because the array type is never stepped over (there
12219             // is a leading zero) we can fold the cast into this GEP.
12220             GEP.setOperand(0, X);
12221             return &GEP;
12222           }
12223         }
12224       }
12225     } else if (GEP.getNumOperands() == 2) {
12226       // Transform things like:
12227       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12228       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
12229       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12230       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
12231       if (TD && isa<ArrayType>(SrcElTy) &&
12232           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12233           TD->getTypeAllocSize(ResElTy)) {
12234         Value *Idx[2];
12235         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12236         Idx[1] = GEP.getOperand(1);
12237         Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12238           Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12239           Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
12240         // V and GEP are both pointer types --> BitCast
12241         return new BitCastInst(NewGEP, GEP.getType());
12242       }
12243       
12244       // Transform things like:
12245       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
12246       //   (where tmp = 8*tmp2) into:
12247       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
12248       
12249       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
12250         uint64_t ArrayEltSize =
12251             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
12252         
12253         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
12254         // allow either a mul, shift, or constant here.
12255         Value *NewIdx = 0;
12256         ConstantInt *Scale = 0;
12257         if (ArrayEltSize == 1) {
12258           NewIdx = GEP.getOperand(1);
12259           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
12260         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
12261           NewIdx = ConstantInt::get(CI->getType(), 1);
12262           Scale = CI;
12263         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12264           if (Inst->getOpcode() == Instruction::Shl &&
12265               isa<ConstantInt>(Inst->getOperand(1))) {
12266             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12267             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
12268             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
12269                                      1ULL << ShAmtVal);
12270             NewIdx = Inst->getOperand(0);
12271           } else if (Inst->getOpcode() == Instruction::Mul &&
12272                      isa<ConstantInt>(Inst->getOperand(1))) {
12273             Scale = cast<ConstantInt>(Inst->getOperand(1));
12274             NewIdx = Inst->getOperand(0);
12275           }
12276         }
12277         
12278         // If the index will be to exactly the right offset with the scale taken
12279         // out, perform the transformation. Note, we don't know whether Scale is
12280         // signed or not. We'll use unsigned version of division/modulo
12281         // operation after making sure Scale doesn't have the sign bit set.
12282         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
12283             Scale->getZExtValue() % ArrayEltSize == 0) {
12284           Scale = ConstantInt::get(Scale->getType(),
12285                                    Scale->getZExtValue() / ArrayEltSize);
12286           if (Scale->getZExtValue() != 1) {
12287             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12288                                                        false /*ZExt*/);
12289             NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
12290           }
12291
12292           // Insert the new GEP instruction.
12293           Value *Idx[2];
12294           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12295           Idx[1] = NewIdx;
12296           Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12297             Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12298             Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
12299           // The NewGEP must be pointer typed, so must the old one -> BitCast
12300           return new BitCastInst(NewGEP, GEP.getType());
12301         }
12302       }
12303     }
12304   }
12305   
12306   /// See if we can simplify:
12307   ///   X = bitcast A* to B*
12308   ///   Y = gep X, <...constant indices...>
12309   /// into a gep of the original struct.  This is important for SROA and alias
12310   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
12311   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
12312     if (TD &&
12313         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
12314       // Determine how much the GEP moves the pointer.  We are guaranteed to get
12315       // a constant back from EmitGEPOffset.
12316       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
12317       int64_t Offset = OffsetV->getSExtValue();
12318       
12319       // If this GEP instruction doesn't move the pointer, just replace the GEP
12320       // with a bitcast of the real input to the dest type.
12321       if (Offset == 0) {
12322         // If the bitcast is of an allocation, and the allocation will be
12323         // converted to match the type of the cast, don't touch this.
12324         if (isa<AllocaInst>(BCI->getOperand(0)) ||
12325             isMalloc(BCI->getOperand(0))) {
12326           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12327           if (Instruction *I = visitBitCast(*BCI)) {
12328             if (I != BCI) {
12329               I->takeName(BCI);
12330               BCI->getParent()->getInstList().insert(BCI, I);
12331               ReplaceInstUsesWith(*BCI, I);
12332             }
12333             return &GEP;
12334           }
12335         }
12336         return new BitCastInst(BCI->getOperand(0), GEP.getType());
12337       }
12338       
12339       // Otherwise, if the offset is non-zero, we need to find out if there is a
12340       // field at Offset in 'A's type.  If so, we can pull the cast through the
12341       // GEP.
12342       SmallVector<Value*, 8> NewIndices;
12343       const Type *InTy =
12344         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
12345       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
12346         Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12347           Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12348                                      NewIndices.end()) :
12349           Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12350                              NewIndices.end());
12351         
12352         if (NGEP->getType() == GEP.getType())
12353           return ReplaceInstUsesWith(GEP, NGEP);
12354         NGEP->takeName(&GEP);
12355         return new BitCastInst(NGEP, GEP.getType());
12356       }
12357     }
12358   }    
12359     
12360   return 0;
12361 }
12362
12363 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
12364   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
12365   if (AI.isArrayAllocation()) {  // Check C != 1
12366     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12367       const Type *NewTy = 
12368         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
12369       assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
12370       AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
12371       New->setAlignment(AI.getAlignment());
12372
12373       // Scan to the end of the allocation instructions, to skip over a block of
12374       // allocas if possible...also skip interleaved debug info
12375       //
12376       BasicBlock::iterator It = New;
12377       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
12378
12379       // Now that I is pointing to the first non-allocation-inst in the block,
12380       // insert our getelementptr instruction...
12381       //
12382       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
12383       Value *Idx[2];
12384       Idx[0] = NullIdx;
12385       Idx[1] = NullIdx;
12386       Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12387                                                    New->getName()+".sub", It);
12388
12389       // Now make everything use the getelementptr instead of the original
12390       // allocation.
12391       return ReplaceInstUsesWith(AI, V);
12392     } else if (isa<UndefValue>(AI.getArraySize())) {
12393       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
12394     }
12395   }
12396
12397   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
12398     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
12399     // Note that we only do this for alloca's, because malloc should allocate
12400     // and return a unique pointer, even for a zero byte allocation.
12401     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
12402       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
12403
12404     // If the alignment is 0 (unspecified), assign it the preferred alignment.
12405     if (AI.getAlignment() == 0)
12406       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12407   }
12408
12409   return 0;
12410 }
12411
12412 Instruction *InstCombiner::visitFree(Instruction &FI) {
12413   Value *Op = FI.getOperand(1);
12414
12415   // free undef -> unreachable.
12416   if (isa<UndefValue>(Op)) {
12417     // Insert a new store to null because we cannot modify the CFG here.
12418     new StoreInst(ConstantInt::getTrue(*Context),
12419            UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12420     return EraseInstFromFunction(FI);
12421   }
12422   
12423   // If we have 'free null' delete the instruction.  This can happen in stl code
12424   // when lots of inlining happens.
12425   if (isa<ConstantPointerNull>(Op))
12426     return EraseInstFromFunction(FI);
12427
12428   // If we have a malloc call whose only use is a free call, delete both.
12429   if (isMalloc(Op)) {
12430     if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12431       if (Op->hasOneUse() && CI->hasOneUse()) {
12432         EraseInstFromFunction(FI);
12433         EraseInstFromFunction(*CI);
12434         return EraseInstFromFunction(*cast<Instruction>(Op));
12435       }
12436     } else {
12437       // Op is a call to malloc
12438       if (Op->hasOneUse()) {
12439         EraseInstFromFunction(FI);
12440         return EraseInstFromFunction(*cast<Instruction>(Op));
12441       }
12442     }
12443   }
12444
12445   return 0;
12446 }
12447
12448 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
12449 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
12450                                         const TargetData *TD) {
12451   User *CI = cast<User>(LI.getOperand(0));
12452   Value *CastOp = CI->getOperand(0);
12453   LLVMContext *Context = IC.getContext();
12454
12455   const PointerType *DestTy = cast<PointerType>(CI->getType());
12456   const Type *DestPTy = DestTy->getElementType();
12457   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
12458
12459     // If the address spaces don't match, don't eliminate the cast.
12460     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12461       return 0;
12462
12463     const Type *SrcPTy = SrcTy->getElementType();
12464
12465     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
12466          isa<VectorType>(DestPTy)) {
12467       // If the source is an array, the code below will not succeed.  Check to
12468       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12469       // constants.
12470       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12471         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12472           if (ASrcTy->getNumElements() != 0) {
12473             Value *Idxs[2];
12474             Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12475             Idxs[1] = Idxs[0];
12476             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
12477             SrcTy = cast<PointerType>(CastOp->getType());
12478             SrcPTy = SrcTy->getElementType();
12479           }
12480
12481       if (IC.getTargetData() &&
12482           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
12483             isa<VectorType>(SrcPTy)) &&
12484           // Do not allow turning this into a load of an integer, which is then
12485           // casted to a pointer, this pessimizes pointer analysis a lot.
12486           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
12487           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12488                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
12489
12490         // Okay, we are casting from one integer or pointer type to another of
12491         // the same size.  Instead of casting the pointer before the load, cast
12492         // the result of the loaded value.
12493         Value *NewLoad = 
12494           IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
12495         // Now cast the result of the load.
12496         return new BitCastInst(NewLoad, LI.getType());
12497       }
12498     }
12499   }
12500   return 0;
12501 }
12502
12503 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12504   Value *Op = LI.getOperand(0);
12505
12506   // Attempt to improve the alignment.
12507   if (TD) {
12508     unsigned KnownAlign =
12509       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12510     if (KnownAlign >
12511         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12512                                   LI.getAlignment()))
12513       LI.setAlignment(KnownAlign);
12514   }
12515
12516   // load (cast X) --> cast (load X) iff safe.
12517   if (isa<CastInst>(Op))
12518     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12519       return Res;
12520
12521   // None of the following transforms are legal for volatile loads.
12522   if (LI.isVolatile()) return 0;
12523   
12524   // Do really simple store-to-load forwarding and load CSE, to catch cases
12525   // where there are several consequtive memory accesses to the same location,
12526   // separated by a few arithmetic operations.
12527   BasicBlock::iterator BBI = &LI;
12528   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12529     return ReplaceInstUsesWith(LI, AvailableVal);
12530
12531   // load(gep null, ...) -> unreachable
12532   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12533     const Value *GEPI0 = GEPI->getOperand(0);
12534     // TODO: Consider a target hook for valid address spaces for this xform.
12535     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
12536       // Insert a new store to null instruction before the load to indicate
12537       // that this code is not reachable.  We do this instead of inserting
12538       // an unreachable instruction directly because we cannot modify the
12539       // CFG.
12540       new StoreInst(UndefValue::get(LI.getType()),
12541                     Constant::getNullValue(Op->getType()), &LI);
12542       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12543     }
12544   } 
12545
12546   // load null/undef -> unreachable
12547   // TODO: Consider a target hook for valid address spaces for this xform.
12548   if (isa<UndefValue>(Op) ||
12549       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12550     // Insert a new store to null instruction before the load to indicate that
12551     // this code is not reachable.  We do this instead of inserting an
12552     // unreachable instruction directly because we cannot modify the CFG.
12553     new StoreInst(UndefValue::get(LI.getType()),
12554                   Constant::getNullValue(Op->getType()), &LI);
12555     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
12556   }
12557
12558   // Instcombine load (constantexpr_cast global) -> cast (load global)
12559   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12560     if (CE->isCast())
12561       if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12562         return Res;
12563   
12564   if (Op->hasOneUse()) {
12565     // Change select and PHI nodes to select values instead of addresses: this
12566     // helps alias analysis out a lot, allows many others simplifications, and
12567     // exposes redundancy in the code.
12568     //
12569     // Note that we cannot do the transformation unless we know that the
12570     // introduced loads cannot trap!  Something like this is valid as long as
12571     // the condition is always false: load (select bool %C, int* null, int* %G),
12572     // but it would not be valid if we transformed it to load from null
12573     // unconditionally.
12574     //
12575     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12576       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
12577       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12578           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
12579         Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12580                                         SI->getOperand(1)->getName()+".val");
12581         Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12582                                         SI->getOperand(2)->getName()+".val");
12583         return SelectInst::Create(SI->getCondition(), V1, V2);
12584       }
12585
12586       // load (select (cond, null, P)) -> load P
12587       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12588         if (C->isNullValue()) {
12589           LI.setOperand(0, SI->getOperand(2));
12590           return &LI;
12591         }
12592
12593       // load (select (cond, P, null)) -> load P
12594       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12595         if (C->isNullValue()) {
12596           LI.setOperand(0, SI->getOperand(1));
12597           return &LI;
12598         }
12599     }
12600   }
12601   return 0;
12602 }
12603
12604 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
12605 /// when possible.  This makes it generally easy to do alias analysis and/or
12606 /// SROA/mem2reg of the memory object.
12607 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12608   User *CI = cast<User>(SI.getOperand(1));
12609   Value *CastOp = CI->getOperand(0);
12610
12611   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
12612   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12613   if (SrcTy == 0) return 0;
12614   
12615   const Type *SrcPTy = SrcTy->getElementType();
12616
12617   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12618     return 0;
12619   
12620   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12621   /// to its first element.  This allows us to handle things like:
12622   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12623   /// on 32-bit hosts.
12624   SmallVector<Value*, 4> NewGEPIndices;
12625   
12626   // If the source is an array, the code below will not succeed.  Check to
12627   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
12628   // constants.
12629   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12630     // Index through pointer.
12631     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
12632     NewGEPIndices.push_back(Zero);
12633     
12634     while (1) {
12635       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
12636         if (!STy->getNumElements()) /* Struct can be empty {} */
12637           break;
12638         NewGEPIndices.push_back(Zero);
12639         SrcPTy = STy->getElementType(0);
12640       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12641         NewGEPIndices.push_back(Zero);
12642         SrcPTy = ATy->getElementType();
12643       } else {
12644         break;
12645       }
12646     }
12647     
12648     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
12649   }
12650
12651   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12652     return 0;
12653   
12654   // If the pointers point into different address spaces or if they point to
12655   // values with different sizes, we can't do the transformation.
12656   if (!IC.getTargetData() ||
12657       SrcTy->getAddressSpace() != 
12658         cast<PointerType>(CI->getType())->getAddressSpace() ||
12659       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12660       IC.getTargetData()->getTypeSizeInBits(DestPTy))
12661     return 0;
12662
12663   // Okay, we are casting from one integer or pointer type to another of
12664   // the same size.  Instead of casting the pointer before 
12665   // the store, cast the value to be stored.
12666   Value *NewCast;
12667   Value *SIOp0 = SI.getOperand(0);
12668   Instruction::CastOps opcode = Instruction::BitCast;
12669   const Type* CastSrcTy = SIOp0->getType();
12670   const Type* CastDstTy = SrcPTy;
12671   if (isa<PointerType>(CastDstTy)) {
12672     if (CastSrcTy->isInteger())
12673       opcode = Instruction::IntToPtr;
12674   } else if (isa<IntegerType>(CastDstTy)) {
12675     if (isa<PointerType>(SIOp0->getType()))
12676       opcode = Instruction::PtrToInt;
12677   }
12678   
12679   // SIOp0 is a pointer to aggregate and this is a store to the first field,
12680   // emit a GEP to index into its first field.
12681   if (!NewGEPIndices.empty())
12682     CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12683                                            NewGEPIndices.end());
12684   
12685   NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12686                                    SIOp0->getName()+".c");
12687   return new StoreInst(NewCast, CastOp);
12688 }
12689
12690 /// equivalentAddressValues - Test if A and B will obviously have the same
12691 /// value. This includes recognizing that %t0 and %t1 will have the same
12692 /// value in code like this:
12693 ///   %t0 = getelementptr \@a, 0, 3
12694 ///   store i32 0, i32* %t0
12695 ///   %t1 = getelementptr \@a, 0, 3
12696 ///   %t2 = load i32* %t1
12697 ///
12698 static bool equivalentAddressValues(Value *A, Value *B) {
12699   // Test if the values are trivially equivalent.
12700   if (A == B) return true;
12701   
12702   // Test if the values come form identical arithmetic instructions.
12703   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12704   // its only used to compare two uses within the same basic block, which
12705   // means that they'll always either have the same value or one of them
12706   // will have an undefined value.
12707   if (isa<BinaryOperator>(A) ||
12708       isa<CastInst>(A) ||
12709       isa<PHINode>(A) ||
12710       isa<GetElementPtrInst>(A))
12711     if (Instruction *BI = dyn_cast<Instruction>(B))
12712       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
12713         return true;
12714   
12715   // Otherwise they may not be equivalent.
12716   return false;
12717 }
12718
12719 // If this instruction has two uses, one of which is a llvm.dbg.declare,
12720 // return the llvm.dbg.declare.
12721 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12722   if (!V->hasNUses(2))
12723     return 0;
12724   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12725        UI != E; ++UI) {
12726     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12727       return DI;
12728     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12729       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12730         return DI;
12731       }
12732   }
12733   return 0;
12734 }
12735
12736 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12737   Value *Val = SI.getOperand(0);
12738   Value *Ptr = SI.getOperand(1);
12739
12740   // If the RHS is an alloca with a single use, zapify the store, making the
12741   // alloca dead.
12742   // If the RHS is an alloca with a two uses, the other one being a 
12743   // llvm.dbg.declare, zapify the store and the declare, making the
12744   // alloca dead.  We must do this to prevent declare's from affecting
12745   // codegen.
12746   if (!SI.isVolatile()) {
12747     if (Ptr->hasOneUse()) {
12748       if (isa<AllocaInst>(Ptr)) {
12749         EraseInstFromFunction(SI);
12750         ++NumCombined;
12751         return 0;
12752       }
12753       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12754         if (isa<AllocaInst>(GEP->getOperand(0))) {
12755           if (GEP->getOperand(0)->hasOneUse()) {
12756             EraseInstFromFunction(SI);
12757             ++NumCombined;
12758             return 0;
12759           }
12760           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12761             EraseInstFromFunction(*DI);
12762             EraseInstFromFunction(SI);
12763             ++NumCombined;
12764             return 0;
12765           }
12766         }
12767       }
12768     }
12769     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12770       EraseInstFromFunction(*DI);
12771       EraseInstFromFunction(SI);
12772       ++NumCombined;
12773       return 0;
12774     }
12775   }
12776
12777   // Attempt to improve the alignment.
12778   if (TD) {
12779     unsigned KnownAlign =
12780       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12781     if (KnownAlign >
12782         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12783                                   SI.getAlignment()))
12784       SI.setAlignment(KnownAlign);
12785   }
12786
12787   // Do really simple DSE, to catch cases where there are several consecutive
12788   // stores to the same location, separated by a few arithmetic operations. This
12789   // situation often occurs with bitfield accesses.
12790   BasicBlock::iterator BBI = &SI;
12791   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12792        --ScanInsts) {
12793     --BBI;
12794     // Don't count debug info directives, lest they affect codegen,
12795     // and we skip pointer-to-pointer bitcasts, which are NOPs.
12796     // It is necessary for correctness to skip those that feed into a
12797     // llvm.dbg.declare, as these are not present when debugging is off.
12798     if (isa<DbgInfoIntrinsic>(BBI) ||
12799         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12800       ScanInsts++;
12801       continue;
12802     }    
12803     
12804     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12805       // Prev store isn't volatile, and stores to the same location?
12806       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12807                                                           SI.getOperand(1))) {
12808         ++NumDeadStore;
12809         ++BBI;
12810         EraseInstFromFunction(*PrevSI);
12811         continue;
12812       }
12813       break;
12814     }
12815     
12816     // If this is a load, we have to stop.  However, if the loaded value is from
12817     // the pointer we're loading and is producing the pointer we're storing,
12818     // then *this* store is dead (X = load P; store X -> P).
12819     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
12820       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12821           !SI.isVolatile()) {
12822         EraseInstFromFunction(SI);
12823         ++NumCombined;
12824         return 0;
12825       }
12826       // Otherwise, this is a load from some other location.  Stores before it
12827       // may not be dead.
12828       break;
12829     }
12830     
12831     // Don't skip over loads or things that can modify memory.
12832     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
12833       break;
12834   }
12835   
12836   
12837   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
12838
12839   // store X, null    -> turns into 'unreachable' in SimplifyCFG
12840   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
12841     if (!isa<UndefValue>(Val)) {
12842       SI.setOperand(0, UndefValue::get(Val->getType()));
12843       if (Instruction *U = dyn_cast<Instruction>(Val))
12844         Worklist.Add(U);  // Dropped a use.
12845       ++NumCombined;
12846     }
12847     return 0;  // Do not modify these!
12848   }
12849
12850   // store undef, Ptr -> noop
12851   if (isa<UndefValue>(Val)) {
12852     EraseInstFromFunction(SI);
12853     ++NumCombined;
12854     return 0;
12855   }
12856
12857   // If the pointer destination is a cast, see if we can fold the cast into the
12858   // source instead.
12859   if (isa<CastInst>(Ptr))
12860     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12861       return Res;
12862   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
12863     if (CE->isCast())
12864       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12865         return Res;
12866
12867   
12868   // If this store is the last instruction in the basic block (possibly
12869   // excepting debug info instructions and the pointer bitcasts that feed
12870   // into them), and if the block ends with an unconditional branch, try
12871   // to move it to the successor block.
12872   BBI = &SI; 
12873   do {
12874     ++BBI;
12875   } while (isa<DbgInfoIntrinsic>(BBI) ||
12876            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
12877   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
12878     if (BI->isUnconditional())
12879       if (SimplifyStoreAtEndOfBlock(SI))
12880         return 0;  // xform done!
12881   
12882   return 0;
12883 }
12884
12885 /// SimplifyStoreAtEndOfBlock - Turn things like:
12886 ///   if () { *P = v1; } else { *P = v2 }
12887 /// into a phi node with a store in the successor.
12888 ///
12889 /// Simplify things like:
12890 ///   *P = v1; if () { *P = v2; }
12891 /// into a phi node with a store in the successor.
12892 ///
12893 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12894   BasicBlock *StoreBB = SI.getParent();
12895   
12896   // Check to see if the successor block has exactly two incoming edges.  If
12897   // so, see if the other predecessor contains a store to the same location.
12898   // if so, insert a PHI node (if needed) and move the stores down.
12899   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12900   
12901   // Determine whether Dest has exactly two predecessors and, if so, compute
12902   // the other predecessor.
12903   pred_iterator PI = pred_begin(DestBB);
12904   BasicBlock *OtherBB = 0;
12905   if (*PI != StoreBB)
12906     OtherBB = *PI;
12907   ++PI;
12908   if (PI == pred_end(DestBB))
12909     return false;
12910   
12911   if (*PI != StoreBB) {
12912     if (OtherBB)
12913       return false;
12914     OtherBB = *PI;
12915   }
12916   if (++PI != pred_end(DestBB))
12917     return false;
12918
12919   // Bail out if all the relevant blocks aren't distinct (this can happen,
12920   // for example, if SI is in an infinite loop)
12921   if (StoreBB == DestBB || OtherBB == DestBB)
12922     return false;
12923
12924   // Verify that the other block ends in a branch and is not otherwise empty.
12925   BasicBlock::iterator BBI = OtherBB->getTerminator();
12926   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12927   if (!OtherBr || BBI == OtherBB->begin())
12928     return false;
12929   
12930   // If the other block ends in an unconditional branch, check for the 'if then
12931   // else' case.  there is an instruction before the branch.
12932   StoreInst *OtherStore = 0;
12933   if (OtherBr->isUnconditional()) {
12934     --BBI;
12935     // Skip over debugging info.
12936     while (isa<DbgInfoIntrinsic>(BBI) ||
12937            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12938       if (BBI==OtherBB->begin())
12939         return false;
12940       --BBI;
12941     }
12942     // If this isn't a store, isn't a store to the same location, or if the
12943     // alignments differ, bail out.
12944     OtherStore = dyn_cast<StoreInst>(BBI);
12945     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12946         OtherStore->getAlignment() != SI.getAlignment())
12947       return false;
12948   } else {
12949     // Otherwise, the other block ended with a conditional branch. If one of the
12950     // destinations is StoreBB, then we have the if/then case.
12951     if (OtherBr->getSuccessor(0) != StoreBB && 
12952         OtherBr->getSuccessor(1) != StoreBB)
12953       return false;
12954     
12955     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12956     // if/then triangle.  See if there is a store to the same ptr as SI that
12957     // lives in OtherBB.
12958     for (;; --BBI) {
12959       // Check to see if we find the matching store.
12960       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12961         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12962             OtherStore->getAlignment() != SI.getAlignment())
12963           return false;
12964         break;
12965       }
12966       // If we find something that may be using or overwriting the stored
12967       // value, or if we run out of instructions, we can't do the xform.
12968       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12969           BBI == OtherBB->begin())
12970         return false;
12971     }
12972     
12973     // In order to eliminate the store in OtherBr, we have to
12974     // make sure nothing reads or overwrites the stored value in
12975     // StoreBB.
12976     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12977       // FIXME: This should really be AA driven.
12978       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12979         return false;
12980     }
12981   }
12982   
12983   // Insert a PHI node now if we need it.
12984   Value *MergedVal = OtherStore->getOperand(0);
12985   if (MergedVal != SI.getOperand(0)) {
12986     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12987     PN->reserveOperandSpace(2);
12988     PN->addIncoming(SI.getOperand(0), SI.getParent());
12989     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12990     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12991   }
12992   
12993   // Advance to a place where it is safe to insert the new store and
12994   // insert it.
12995   BBI = DestBB->getFirstNonPHI();
12996   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12997                                     OtherStore->isVolatile(),
12998                                     SI.getAlignment()), *BBI);
12999   
13000   // Nuke the old stores.
13001   EraseInstFromFunction(SI);
13002   EraseInstFromFunction(*OtherStore);
13003   ++NumCombined;
13004   return true;
13005 }
13006
13007
13008 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
13009   // Change br (not X), label True, label False to: br X, label False, True
13010   Value *X = 0;
13011   BasicBlock *TrueDest;
13012   BasicBlock *FalseDest;
13013   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
13014       !isa<Constant>(X)) {
13015     // Swap Destinations and condition...
13016     BI.setCondition(X);
13017     BI.setSuccessor(0, FalseDest);
13018     BI.setSuccessor(1, TrueDest);
13019     return &BI;
13020   }
13021
13022   // Cannonicalize fcmp_one -> fcmp_oeq
13023   FCmpInst::Predicate FPred; Value *Y;
13024   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
13025                              TrueDest, FalseDest)) &&
13026       BI.getCondition()->hasOneUse())
13027     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
13028         FPred == FCmpInst::FCMP_OGE) {
13029       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
13030       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
13031       
13032       // Swap Destinations and condition.
13033       BI.setSuccessor(0, FalseDest);
13034       BI.setSuccessor(1, TrueDest);
13035       Worklist.Add(Cond);
13036       return &BI;
13037     }
13038
13039   // Cannonicalize icmp_ne -> icmp_eq
13040   ICmpInst::Predicate IPred;
13041   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
13042                       TrueDest, FalseDest)) &&
13043       BI.getCondition()->hasOneUse())
13044     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
13045         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
13046         IPred == ICmpInst::ICMP_SGE) {
13047       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
13048       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
13049       // Swap Destinations and condition.
13050       BI.setSuccessor(0, FalseDest);
13051       BI.setSuccessor(1, TrueDest);
13052       Worklist.Add(Cond);
13053       return &BI;
13054     }
13055
13056   return 0;
13057 }
13058
13059 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
13060   Value *Cond = SI.getCondition();
13061   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
13062     if (I->getOpcode() == Instruction::Add)
13063       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
13064         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
13065         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
13066           SI.setOperand(i,
13067                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
13068                                                 AddRHS));
13069         SI.setOperand(0, I->getOperand(0));
13070         Worklist.Add(I);
13071         return &SI;
13072       }
13073   }
13074   return 0;
13075 }
13076
13077 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
13078   Value *Agg = EV.getAggregateOperand();
13079
13080   if (!EV.hasIndices())
13081     return ReplaceInstUsesWith(EV, Agg);
13082
13083   if (Constant *C = dyn_cast<Constant>(Agg)) {
13084     if (isa<UndefValue>(C))
13085       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
13086       
13087     if (isa<ConstantAggregateZero>(C))
13088       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
13089
13090     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
13091       // Extract the element indexed by the first index out of the constant
13092       Value *V = C->getOperand(*EV.idx_begin());
13093       if (EV.getNumIndices() > 1)
13094         // Extract the remaining indices out of the constant indexed by the
13095         // first index
13096         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
13097       else
13098         return ReplaceInstUsesWith(EV, V);
13099     }
13100     return 0; // Can't handle other constants
13101   } 
13102   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
13103     // We're extracting from an insertvalue instruction, compare the indices
13104     const unsigned *exti, *exte, *insi, *inse;
13105     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
13106          exte = EV.idx_end(), inse = IV->idx_end();
13107          exti != exte && insi != inse;
13108          ++exti, ++insi) {
13109       if (*insi != *exti)
13110         // The insert and extract both reference distinctly different elements.
13111         // This means the extract is not influenced by the insert, and we can
13112         // replace the aggregate operand of the extract with the aggregate
13113         // operand of the insert. i.e., replace
13114         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13115         // %E = extractvalue { i32, { i32 } } %I, 0
13116         // with
13117         // %E = extractvalue { i32, { i32 } } %A, 0
13118         return ExtractValueInst::Create(IV->getAggregateOperand(),
13119                                         EV.idx_begin(), EV.idx_end());
13120     }
13121     if (exti == exte && insi == inse)
13122       // Both iterators are at the end: Index lists are identical. Replace
13123       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13124       // %C = extractvalue { i32, { i32 } } %B, 1, 0
13125       // with "i32 42"
13126       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
13127     if (exti == exte) {
13128       // The extract list is a prefix of the insert list. i.e. replace
13129       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13130       // %E = extractvalue { i32, { i32 } } %I, 1
13131       // with
13132       // %X = extractvalue { i32, { i32 } } %A, 1
13133       // %E = insertvalue { i32 } %X, i32 42, 0
13134       // by switching the order of the insert and extract (though the
13135       // insertvalue should be left in, since it may have other uses).
13136       Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13137                                                  EV.idx_begin(), EV.idx_end());
13138       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13139                                      insi, inse);
13140     }
13141     if (insi == inse)
13142       // The insert list is a prefix of the extract list
13143       // We can simply remove the common indices from the extract and make it
13144       // operate on the inserted value instead of the insertvalue result.
13145       // i.e., replace
13146       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13147       // %E = extractvalue { i32, { i32 } } %I, 1, 0
13148       // with
13149       // %E extractvalue { i32 } { i32 42 }, 0
13150       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
13151                                       exti, exte);
13152   }
13153   if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13154     // We're extracting from an intrinsic, see if we're the only user, which
13155     // allows us to simplify multiple result intrinsics to simpler things that
13156     // just get one value..
13157     if (II->hasOneUse()) {
13158       // Check if we're grabbing the overflow bit or the result of a 'with
13159       // overflow' intrinsic.  If it's the latter we can remove the intrinsic
13160       // and replace it with a traditional binary instruction.
13161       switch (II->getIntrinsicID()) {
13162       case Intrinsic::uadd_with_overflow:
13163       case Intrinsic::sadd_with_overflow:
13164         if (*EV.idx_begin() == 0) {  // Normal result.
13165           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13166           II->replaceAllUsesWith(UndefValue::get(II->getType()));
13167           EraseInstFromFunction(*II);
13168           return BinaryOperator::CreateAdd(LHS, RHS);
13169         }
13170         break;
13171       case Intrinsic::usub_with_overflow:
13172       case Intrinsic::ssub_with_overflow:
13173         if (*EV.idx_begin() == 0) {  // Normal result.
13174           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13175           II->replaceAllUsesWith(UndefValue::get(II->getType()));
13176           EraseInstFromFunction(*II);
13177           return BinaryOperator::CreateSub(LHS, RHS);
13178         }
13179         break;
13180       case Intrinsic::umul_with_overflow:
13181       case Intrinsic::smul_with_overflow:
13182         if (*EV.idx_begin() == 0) {  // Normal result.
13183           Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13184           II->replaceAllUsesWith(UndefValue::get(II->getType()));
13185           EraseInstFromFunction(*II);
13186           return BinaryOperator::CreateMul(LHS, RHS);
13187         }
13188         break;
13189       default:
13190         break;
13191       }
13192     }
13193   }
13194   // Can't simplify extracts from other values. Note that nested extracts are
13195   // already simplified implicitely by the above (extract ( extract (insert) )
13196   // will be translated into extract ( insert ( extract ) ) first and then just
13197   // the value inserted, if appropriate).
13198   return 0;
13199 }
13200
13201 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13202 /// is to leave as a vector operation.
13203 static bool CheapToScalarize(Value *V, bool isConstant) {
13204   if (isa<ConstantAggregateZero>(V)) 
13205     return true;
13206   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
13207     if (isConstant) return true;
13208     // If all elts are the same, we can extract.
13209     Constant *Op0 = C->getOperand(0);
13210     for (unsigned i = 1; i < C->getNumOperands(); ++i)
13211       if (C->getOperand(i) != Op0)
13212         return false;
13213     return true;
13214   }
13215   Instruction *I = dyn_cast<Instruction>(V);
13216   if (!I) return false;
13217   
13218   // Insert element gets simplified to the inserted element or is deleted if
13219   // this is constant idx extract element and its a constant idx insertelt.
13220   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13221       isa<ConstantInt>(I->getOperand(2)))
13222     return true;
13223   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13224     return true;
13225   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13226     if (BO->hasOneUse() &&
13227         (CheapToScalarize(BO->getOperand(0), isConstant) ||
13228          CheapToScalarize(BO->getOperand(1), isConstant)))
13229       return true;
13230   if (CmpInst *CI = dyn_cast<CmpInst>(I))
13231     if (CI->hasOneUse() &&
13232         (CheapToScalarize(CI->getOperand(0), isConstant) ||
13233          CheapToScalarize(CI->getOperand(1), isConstant)))
13234       return true;
13235   
13236   return false;
13237 }
13238
13239 /// Read and decode a shufflevector mask.
13240 ///
13241 /// It turns undef elements into values that are larger than the number of
13242 /// elements in the input.
13243 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13244   unsigned NElts = SVI->getType()->getNumElements();
13245   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13246     return std::vector<unsigned>(NElts, 0);
13247   if (isa<UndefValue>(SVI->getOperand(2)))
13248     return std::vector<unsigned>(NElts, 2*NElts);
13249
13250   std::vector<unsigned> Result;
13251   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
13252   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13253     if (isa<UndefValue>(*i))
13254       Result.push_back(NElts*2);  // undef -> 8
13255     else
13256       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
13257   return Result;
13258 }
13259
13260 /// FindScalarElement - Given a vector and an element number, see if the scalar
13261 /// value is already around as a register, for example if it were inserted then
13262 /// extracted from the vector.
13263 static Value *FindScalarElement(Value *V, unsigned EltNo,
13264                                 LLVMContext *Context) {
13265   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13266   const VectorType *PTy = cast<VectorType>(V->getType());
13267   unsigned Width = PTy->getNumElements();
13268   if (EltNo >= Width)  // Out of range access.
13269     return UndefValue::get(PTy->getElementType());
13270   
13271   if (isa<UndefValue>(V))
13272     return UndefValue::get(PTy->getElementType());
13273   else if (isa<ConstantAggregateZero>(V))
13274     return Constant::getNullValue(PTy->getElementType());
13275   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
13276     return CP->getOperand(EltNo);
13277   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13278     // If this is an insert to a variable element, we don't know what it is.
13279     if (!isa<ConstantInt>(III->getOperand(2))) 
13280       return 0;
13281     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
13282     
13283     // If this is an insert to the element we are looking for, return the
13284     // inserted value.
13285     if (EltNo == IIElt) 
13286       return III->getOperand(1);
13287     
13288     // Otherwise, the insertelement doesn't modify the value, recurse on its
13289     // vector input.
13290     return FindScalarElement(III->getOperand(0), EltNo, Context);
13291   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
13292     unsigned LHSWidth =
13293       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13294     unsigned InEl = getShuffleMask(SVI)[EltNo];
13295     if (InEl < LHSWidth)
13296       return FindScalarElement(SVI->getOperand(0), InEl, Context);
13297     else if (InEl < LHSWidth*2)
13298       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
13299     else
13300       return UndefValue::get(PTy->getElementType());
13301   }
13302   
13303   // Otherwise, we don't know.
13304   return 0;
13305 }
13306
13307 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
13308   // If vector val is undef, replace extract with scalar undef.
13309   if (isa<UndefValue>(EI.getOperand(0)))
13310     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
13311
13312   // If vector val is constant 0, replace extract with scalar 0.
13313   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
13314     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
13315   
13316   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
13317     // If vector val is constant with all elements the same, replace EI with
13318     // that element. When the elements are not identical, we cannot replace yet
13319     // (we do that below, but only when the index is constant).
13320     Constant *op0 = C->getOperand(0);
13321     for (unsigned i = 1; i != C->getNumOperands(); ++i)
13322       if (C->getOperand(i) != op0) {
13323         op0 = 0; 
13324         break;
13325       }
13326     if (op0)
13327       return ReplaceInstUsesWith(EI, op0);
13328   }
13329   
13330   // If extracting a specified index from the vector, see if we can recursively
13331   // find a previously computed scalar that was inserted into the vector.
13332   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13333     unsigned IndexVal = IdxC->getZExtValue();
13334     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
13335       
13336     // If this is extracting an invalid index, turn this into undef, to avoid
13337     // crashing the code below.
13338     if (IndexVal >= VectorWidth)
13339       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
13340     
13341     // This instruction only demands the single element from the input vector.
13342     // If the input vector has a single use, simplify it based on this use
13343     // property.
13344     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
13345       APInt UndefElts(VectorWidth, 0);
13346       APInt DemandedMask(VectorWidth, 1 << IndexVal);
13347       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
13348                                                 DemandedMask, UndefElts)) {
13349         EI.setOperand(0, V);
13350         return &EI;
13351       }
13352     }
13353     
13354     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
13355       return ReplaceInstUsesWith(EI, Elt);
13356     
13357     // If the this extractelement is directly using a bitcast from a vector of
13358     // the same number of elements, see if we can find the source element from
13359     // it.  In this case, we will end up needing to bitcast the scalars.
13360     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13361       if (const VectorType *VT = 
13362               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13363         if (VT->getNumElements() == VectorWidth)
13364           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13365                                              IndexVal, Context))
13366             return new BitCastInst(Elt, EI.getType());
13367     }
13368   }
13369   
13370   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
13371     // Push extractelement into predecessor operation if legal and
13372     // profitable to do so
13373     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13374       if (I->hasOneUse() &&
13375           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13376         Value *newEI0 =
13377           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13378                                         EI.getName()+".lhs");
13379         Value *newEI1 =
13380           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13381                                         EI.getName()+".rhs");
13382         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
13383       }
13384     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
13385       // Extracting the inserted element?
13386       if (IE->getOperand(2) == EI.getOperand(1))
13387         return ReplaceInstUsesWith(EI, IE->getOperand(1));
13388       // If the inserted and extracted elements are constants, they must not
13389       // be the same value, extract from the pre-inserted value instead.
13390       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
13391         Worklist.AddValue(EI.getOperand(0));
13392         EI.setOperand(0, IE->getOperand(0));
13393         return &EI;
13394       }
13395     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13396       // If this is extracting an element from a shufflevector, figure out where
13397       // it came from and extract from the appropriate input element instead.
13398       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13399         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
13400         Value *Src;
13401         unsigned LHSWidth =
13402           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13403
13404         if (SrcIdx < LHSWidth)
13405           Src = SVI->getOperand(0);
13406         else if (SrcIdx < LHSWidth*2) {
13407           SrcIdx -= LHSWidth;
13408           Src = SVI->getOperand(1);
13409         } else {
13410           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
13411         }
13412         return ExtractElementInst::Create(Src,
13413                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13414                                           false));
13415       }
13416     }
13417     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
13418   }
13419   return 0;
13420 }
13421
13422 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13423 /// elements from either LHS or RHS, return the shuffle mask and true. 
13424 /// Otherwise, return false.
13425 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
13426                                          std::vector<Constant*> &Mask,
13427                                          LLVMContext *Context) {
13428   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13429          "Invalid CollectSingleShuffleElements");
13430   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13431
13432   if (isa<UndefValue>(V)) {
13433     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
13434     return true;
13435   } else if (V == LHS) {
13436     for (unsigned i = 0; i != NumElts; ++i)
13437       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
13438     return true;
13439   } else if (V == RHS) {
13440     for (unsigned i = 0; i != NumElts; ++i)
13441       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
13442     return true;
13443   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13444     // If this is an insert of an extract from some other vector, include it.
13445     Value *VecOp    = IEI->getOperand(0);
13446     Value *ScalarOp = IEI->getOperand(1);
13447     Value *IdxOp    = IEI->getOperand(2);
13448     
13449     if (!isa<ConstantInt>(IdxOp))
13450       return false;
13451     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13452     
13453     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
13454       // Okay, we can handle this if the vector we are insertinting into is
13455       // transitively ok.
13456       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
13457         // If so, update the mask to reflect the inserted undef.
13458         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
13459         return true;
13460       }      
13461     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13462       if (isa<ConstantInt>(EI->getOperand(1)) &&
13463           EI->getOperand(0)->getType() == V->getType()) {
13464         unsigned ExtractedIdx =
13465           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13466         
13467         // This must be extracting from either LHS or RHS.
13468         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13469           // Okay, we can handle this if the vector we are insertinting into is
13470           // transitively ok.
13471           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
13472             // If so, update the mask to reflect the inserted value.
13473             if (EI->getOperand(0) == LHS) {
13474               Mask[InsertedIdx % NumElts] = 
13475                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
13476             } else {
13477               assert(EI->getOperand(0) == RHS);
13478               Mask[InsertedIdx % NumElts] = 
13479                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
13480               
13481             }
13482             return true;
13483           }
13484         }
13485       }
13486     }
13487   }
13488   // TODO: Handle shufflevector here!
13489   
13490   return false;
13491 }
13492
13493 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13494 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
13495 /// that computes V and the LHS value of the shuffle.
13496 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
13497                                      Value *&RHS, LLVMContext *Context) {
13498   assert(isa<VectorType>(V->getType()) && 
13499          (RHS == 0 || V->getType() == RHS->getType()) &&
13500          "Invalid shuffle!");
13501   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
13502
13503   if (isa<UndefValue>(V)) {
13504     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
13505     return V;
13506   } else if (isa<ConstantAggregateZero>(V)) {
13507     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
13508     return V;
13509   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13510     // If this is an insert of an extract from some other vector, include it.
13511     Value *VecOp    = IEI->getOperand(0);
13512     Value *ScalarOp = IEI->getOperand(1);
13513     Value *IdxOp    = IEI->getOperand(2);
13514     
13515     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13516       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13517           EI->getOperand(0)->getType() == V->getType()) {
13518         unsigned ExtractedIdx =
13519           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13520         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13521         
13522         // Either the extracted from or inserted into vector must be RHSVec,
13523         // otherwise we'd end up with a shuffle of three inputs.
13524         if (EI->getOperand(0) == RHS || RHS == 0) {
13525           RHS = EI->getOperand(0);
13526           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
13527           Mask[InsertedIdx % NumElts] = 
13528             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
13529           return V;
13530         }
13531         
13532         if (VecOp == RHS) {
13533           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13534                                             RHS, Context);
13535           // Everything but the extracted element is replaced with the RHS.
13536           for (unsigned i = 0; i != NumElts; ++i) {
13537             if (i != InsertedIdx)
13538               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
13539           }
13540           return V;
13541         }
13542         
13543         // If this insertelement is a chain that comes from exactly these two
13544         // vectors, return the vector and the effective shuffle.
13545         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13546                                          Context))
13547           return EI->getOperand(0);
13548         
13549       }
13550     }
13551   }
13552   // TODO: Handle shufflevector here!
13553   
13554   // Otherwise, can't do anything fancy.  Return an identity vector.
13555   for (unsigned i = 0; i != NumElts; ++i)
13556     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
13557   return V;
13558 }
13559
13560 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13561   Value *VecOp    = IE.getOperand(0);
13562   Value *ScalarOp = IE.getOperand(1);
13563   Value *IdxOp    = IE.getOperand(2);
13564   
13565   // Inserting an undef or into an undefined place, remove this.
13566   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13567     ReplaceInstUsesWith(IE, VecOp);
13568   
13569   // If the inserted element was extracted from some other vector, and if the 
13570   // indexes are constant, try to turn this into a shufflevector operation.
13571   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13572     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13573         EI->getOperand(0)->getType() == IE.getType()) {
13574       unsigned NumVectorElts = IE.getType()->getNumElements();
13575       unsigned ExtractedIdx =
13576         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13577       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
13578       
13579       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13580         return ReplaceInstUsesWith(IE, VecOp);
13581       
13582       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
13583         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
13584       
13585       // If we are extracting a value from a vector, then inserting it right
13586       // back into the same place, just use the input vector.
13587       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13588         return ReplaceInstUsesWith(IE, VecOp);      
13589       
13590       // If this insertelement isn't used by some other insertelement, turn it
13591       // (and any insertelements it points to), into one big shuffle.
13592       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13593         std::vector<Constant*> Mask;
13594         Value *RHS = 0;
13595         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
13596         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
13597         // We now have a shuffle of LHS, RHS, Mask.
13598         return new ShuffleVectorInst(LHS, RHS,
13599                                      ConstantVector::get(Mask));
13600       }
13601     }
13602   }
13603
13604   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13605   APInt UndefElts(VWidth, 0);
13606   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13607   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13608     return &IE;
13609
13610   return 0;
13611 }
13612
13613
13614 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13615   Value *LHS = SVI.getOperand(0);
13616   Value *RHS = SVI.getOperand(1);
13617   std::vector<unsigned> Mask = getShuffleMask(&SVI);
13618
13619   bool MadeChange = false;
13620
13621   // Undefined shuffle mask -> undefined value.
13622   if (isa<UndefValue>(SVI.getOperand(2)))
13623     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
13624
13625   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
13626
13627   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13628     return 0;
13629
13630   APInt UndefElts(VWidth, 0);
13631   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13632   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
13633     LHS = SVI.getOperand(0);
13634     RHS = SVI.getOperand(1);
13635     MadeChange = true;
13636   }
13637   
13638   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
13639   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13640   if (LHS == RHS || isa<UndefValue>(LHS)) {
13641     if (isa<UndefValue>(LHS) && LHS == RHS) {
13642       // shuffle(undef,undef,mask) -> undef.
13643       return ReplaceInstUsesWith(SVI, LHS);
13644     }
13645     
13646     // Remap any references to RHS to use LHS.
13647     std::vector<Constant*> Elts;
13648     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13649       if (Mask[i] >= 2*e)
13650         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13651       else {
13652         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
13653             (Mask[i] <  e && isa<UndefValue>(LHS))) {
13654           Mask[i] = 2*e;     // Turn into undef.
13655           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13656         } else {
13657           Mask[i] = Mask[i] % e;  // Force to LHS.
13658           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
13659         }
13660       }
13661     }
13662     SVI.setOperand(0, SVI.getOperand(1));
13663     SVI.setOperand(1, UndefValue::get(RHS->getType()));
13664     SVI.setOperand(2, ConstantVector::get(Elts));
13665     LHS = SVI.getOperand(0);
13666     RHS = SVI.getOperand(1);
13667     MadeChange = true;
13668   }
13669   
13670   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
13671   bool isLHSID = true, isRHSID = true;
13672     
13673   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13674     if (Mask[i] >= e*2) continue;  // Ignore undef values.
13675     // Is this an identity shuffle of the LHS value?
13676     isLHSID &= (Mask[i] == i);
13677       
13678     // Is this an identity shuffle of the RHS value?
13679     isRHSID &= (Mask[i]-e == i);
13680   }
13681
13682   // Eliminate identity shuffles.
13683   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13684   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
13685   
13686   // If the LHS is a shufflevector itself, see if we can combine it with this
13687   // one without producing an unusual shuffle.  Here we are really conservative:
13688   // we are absolutely afraid of producing a shuffle mask not in the input
13689   // program, because the code gen may not be smart enough to turn a merged
13690   // shuffle into two specific shuffles: it may produce worse code.  As such,
13691   // we only merge two shuffles if the result is one of the two input shuffle
13692   // masks.  In this case, merging the shuffles just removes one instruction,
13693   // which we know is safe.  This is good for things like turning:
13694   // (splat(splat)) -> splat.
13695   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13696     if (isa<UndefValue>(RHS)) {
13697       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13698
13699       if (LHSMask.size() == Mask.size()) {
13700         std::vector<unsigned> NewMask;
13701         for (unsigned i = 0, e = Mask.size(); i != e; ++i)
13702           if (Mask[i] >= e)
13703             NewMask.push_back(2*e);
13704           else
13705             NewMask.push_back(LHSMask[Mask[i]]);
13706       
13707         // If the result mask is equal to the src shuffle or this
13708         // shuffle mask, do the replacement.
13709         if (NewMask == LHSMask || NewMask == Mask) {
13710           unsigned LHSInNElts =
13711             cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13712             getNumElements();
13713           std::vector<Constant*> Elts;
13714           for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13715             if (NewMask[i] >= LHSInNElts*2) {
13716               Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13717             } else {
13718               Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13719                                               NewMask[i]));
13720             }
13721           }
13722           return new ShuffleVectorInst(LHSSVI->getOperand(0),
13723                                        LHSSVI->getOperand(1),
13724                                        ConstantVector::get(Elts));
13725         }
13726       }
13727     }
13728   }
13729
13730   return MadeChange ? &SVI : 0;
13731 }
13732
13733
13734
13735
13736 /// TryToSinkInstruction - Try to move the specified instruction from its
13737 /// current block into the beginning of DestBlock, which can only happen if it's
13738 /// safe to move the instruction past all of the instructions between it and the
13739 /// end of its block.
13740 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13741   assert(I->hasOneUse() && "Invariants didn't hold!");
13742
13743   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
13744   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
13745     return false;
13746
13747   // Do not sink alloca instructions out of the entry block.
13748   if (isa<AllocaInst>(I) && I->getParent() ==
13749         &DestBlock->getParent()->getEntryBlock())
13750     return false;
13751
13752   // We can only sink load instructions if there is nothing between the load and
13753   // the end of block that could change the value.
13754   if (I->mayReadFromMemory()) {
13755     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
13756          Scan != E; ++Scan)
13757       if (Scan->mayWriteToMemory())
13758         return false;
13759   }
13760
13761   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
13762
13763   CopyPrecedingStopPoint(I, InsertPos);
13764   I->moveBefore(InsertPos);
13765   ++NumSunkInst;
13766   return true;
13767 }
13768
13769
13770 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13771 /// all reachable code to the worklist.
13772 ///
13773 /// This has a couple of tricks to make the code faster and more powerful.  In
13774 /// particular, we constant fold and DCE instructions as we go, to avoid adding
13775 /// them to the worklist (this significantly speeds up instcombine on code where
13776 /// many instructions are dead or constant).  Additionally, if we find a branch
13777 /// whose condition is a known constant, we only visit the reachable successors.
13778 ///
13779 static bool AddReachableCodeToWorklist(BasicBlock *BB, 
13780                                        SmallPtrSet<BasicBlock*, 64> &Visited,
13781                                        InstCombiner &IC,
13782                                        const TargetData *TD) {
13783   bool MadeIRChange = false;
13784   SmallVector<BasicBlock*, 256> Worklist;
13785   Worklist.push_back(BB);
13786   
13787   std::vector<Instruction*> InstrsForInstCombineWorklist;
13788   InstrsForInstCombineWorklist.reserve(128);
13789
13790   SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13791   
13792   while (!Worklist.empty()) {
13793     BB = Worklist.back();
13794     Worklist.pop_back();
13795     
13796     // We have now visited this block!  If we've already been here, ignore it.
13797     if (!Visited.insert(BB)) continue;
13798
13799     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13800       Instruction *Inst = BBI++;
13801       
13802       // DCE instruction if trivially dead.
13803       if (isInstructionTriviallyDead(Inst)) {
13804         ++NumDeadInst;
13805         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
13806         Inst->eraseFromParent();
13807         continue;
13808       }
13809       
13810       // ConstantProp instruction if trivially constant.
13811       if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
13812         if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
13813           DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13814                        << *Inst << '\n');
13815           Inst->replaceAllUsesWith(C);
13816           ++NumConstProp;
13817           Inst->eraseFromParent();
13818           continue;
13819         }
13820       
13821       
13822       
13823       if (TD) {
13824         // See if we can constant fold its operands.
13825         for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13826              i != e; ++i) {
13827           ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13828           if (CE == 0) continue;
13829           
13830           // If we already folded this constant, don't try again.
13831           if (!FoldedConstants.insert(CE))
13832             continue;
13833           
13834           Constant *NewC = ConstantFoldConstantExpression(CE, TD);
13835           if (NewC && NewC != CE) {
13836             *i = NewC;
13837             MadeIRChange = true;
13838           }
13839         }
13840       }
13841       
13842
13843       InstrsForInstCombineWorklist.push_back(Inst);
13844     }
13845
13846     // Recursively visit successors.  If this is a branch or switch on a
13847     // constant, only visit the reachable successor.
13848     TerminatorInst *TI = BB->getTerminator();
13849     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13850       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13851         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
13852         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
13853         Worklist.push_back(ReachableBB);
13854         continue;
13855       }
13856     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13857       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13858         // See if this is an explicit destination.
13859         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13860           if (SI->getCaseValue(i) == Cond) {
13861             BasicBlock *ReachableBB = SI->getSuccessor(i);
13862             Worklist.push_back(ReachableBB);
13863             continue;
13864           }
13865         
13866         // Otherwise it is the default destination.
13867         Worklist.push_back(SI->getSuccessor(0));
13868         continue;
13869       }
13870     }
13871     
13872     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13873       Worklist.push_back(TI->getSuccessor(i));
13874   }
13875   
13876   // Once we've found all of the instructions to add to instcombine's worklist,
13877   // add them in reverse order.  This way instcombine will visit from the top
13878   // of the function down.  This jives well with the way that it adds all uses
13879   // of instructions to the worklist after doing a transformation, thus avoiding
13880   // some N^2 behavior in pathological cases.
13881   IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13882                               InstrsForInstCombineWorklist.size());
13883   
13884   return MadeIRChange;
13885 }
13886
13887 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
13888   MadeIRChange = false;
13889   
13890   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13891         << F.getNameStr() << "\n");
13892
13893   {
13894     // Do a depth-first traversal of the function, populate the worklist with
13895     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
13896     // track of which blocks we visit.
13897     SmallPtrSet<BasicBlock*, 64> Visited;
13898     MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
13899
13900     // Do a quick scan over the function.  If we find any blocks that are
13901     // unreachable, remove any instructions inside of them.  This prevents
13902     // the instcombine code from having to deal with some bad special cases.
13903     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13904       if (!Visited.count(BB)) {
13905         Instruction *Term = BB->getTerminator();
13906         while (Term != BB->begin()) {   // Remove instrs bottom-up
13907           BasicBlock::iterator I = Term; --I;
13908
13909           DEBUG(errs() << "IC: DCE: " << *I << '\n');
13910           // A debug intrinsic shouldn't force another iteration if we weren't
13911           // going to do one without it.
13912           if (!isa<DbgInfoIntrinsic>(I)) {
13913             ++NumDeadInst;
13914             MadeIRChange = true;
13915           }
13916
13917           // If I is not void type then replaceAllUsesWith undef.
13918           // This allows ValueHandlers and custom metadata to adjust itself.
13919           if (!I->getType()->isVoidTy())
13920             I->replaceAllUsesWith(UndefValue::get(I->getType()));
13921           I->eraseFromParent();
13922         }
13923       }
13924   }
13925
13926   while (!Worklist.isEmpty()) {
13927     Instruction *I = Worklist.RemoveOne();
13928     if (I == 0) continue;  // skip null values.
13929
13930     // Check to see if we can DCE the instruction.
13931     if (isInstructionTriviallyDead(I)) {
13932       DEBUG(errs() << "IC: DCE: " << *I << '\n');
13933       EraseInstFromFunction(*I);
13934       ++NumDeadInst;
13935       MadeIRChange = true;
13936       continue;
13937     }
13938
13939     // Instruction isn't dead, see if we can constant propagate it.
13940     if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
13941       if (Constant *C = ConstantFoldInstruction(I, TD)) {
13942         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
13943
13944         // Add operands to the worklist.
13945         ReplaceInstUsesWith(*I, C);
13946         ++NumConstProp;
13947         EraseInstFromFunction(*I);
13948         MadeIRChange = true;
13949         continue;
13950       }
13951
13952     // See if we can trivially sink this instruction to a successor basic block.
13953     if (I->hasOneUse()) {
13954       BasicBlock *BB = I->getParent();
13955       Instruction *UserInst = cast<Instruction>(I->use_back());
13956       BasicBlock *UserParent;
13957       
13958       // Get the block the use occurs in.
13959       if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13960         UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13961       else
13962         UserParent = UserInst->getParent();
13963       
13964       if (UserParent != BB) {
13965         bool UserIsSuccessor = false;
13966         // See if the user is one of our successors.
13967         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13968           if (*SI == UserParent) {
13969             UserIsSuccessor = true;
13970             break;
13971           }
13972
13973         // If the user is one of our immediate successors, and if that successor
13974         // only has us as a predecessors (we'd have to split the critical edge
13975         // otherwise), we can keep going.
13976         if (UserIsSuccessor && UserParent->getSinglePredecessor())
13977           // Okay, the CFG is simple enough, try to sink this instruction.
13978           MadeIRChange |= TryToSinkInstruction(I, UserParent);
13979       }
13980     }
13981
13982     // Now that we have an instruction, try combining it to simplify it.
13983     Builder->SetInsertPoint(I->getParent(), I);
13984     
13985 #ifndef NDEBUG
13986     std::string OrigI;
13987 #endif
13988     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13989     DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13990
13991     if (Instruction *Result = visit(*I)) {
13992       ++NumCombined;
13993       // Should we replace the old instruction with a new one?
13994       if (Result != I) {
13995         DEBUG(errs() << "IC: Old = " << *I << '\n'
13996                      << "    New = " << *Result << '\n');
13997
13998         // Everything uses the new instruction now.
13999         I->replaceAllUsesWith(Result);
14000
14001         // Push the new instruction and any users onto the worklist.
14002         Worklist.Add(Result);
14003         Worklist.AddUsersToWorkList(*Result);
14004
14005         // Move the name to the new instruction first.
14006         Result->takeName(I);
14007
14008         // Insert the new instruction into the basic block...
14009         BasicBlock *InstParent = I->getParent();
14010         BasicBlock::iterator InsertPos = I;
14011
14012         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
14013           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
14014             ++InsertPos;
14015
14016         InstParent->getInstList().insert(InsertPos, Result);
14017
14018         EraseInstFromFunction(*I);
14019       } else {
14020 #ifndef NDEBUG
14021         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
14022                      << "    New = " << *I << '\n');
14023 #endif
14024
14025         // If the instruction was modified, it's possible that it is now dead.
14026         // if so, remove it.
14027         if (isInstructionTriviallyDead(I)) {
14028           EraseInstFromFunction(*I);
14029         } else {
14030           Worklist.Add(I);
14031           Worklist.AddUsersToWorkList(*I);
14032         }
14033       }
14034       MadeIRChange = true;
14035     }
14036   }
14037
14038   Worklist.Zap();
14039   return MadeIRChange;
14040 }
14041
14042
14043 bool InstCombiner::runOnFunction(Function &F) {
14044   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
14045   Context = &F.getContext();
14046   TD = getAnalysisIfAvailable<TargetData>();
14047
14048   
14049   /// Builder - This is an IRBuilder that automatically inserts new
14050   /// instructions into the worklist when they are created.
14051   IRBuilder<true, TargetFolder, InstCombineIRInserter> 
14052     TheBuilder(F.getContext(), TargetFolder(TD),
14053                InstCombineIRInserter(Worklist));
14054   Builder = &TheBuilder;
14055   
14056   bool EverMadeChange = false;
14057
14058   // Iterate while there is work to do.
14059   unsigned Iteration = 0;
14060   while (DoOneIteration(F, Iteration++))
14061     EverMadeChange = true;
14062   
14063   Builder = 0;
14064   return EverMadeChange;
14065 }
14066
14067 FunctionPass *llvm::createInstructionCombiningPass() {
14068   return new InstCombiner();
14069 }