add a new InstCombineWorklist::AddValue method that works even
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG.  This pass is where
12 // algebraic simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %X, 2
19 //
20 // This is a simple worklist driven algorithm.
21 //
22 // This pass guarantees that the following canonicalizations are performed on
23 // the program:
24 //    1. If a binary operator has a constant operand, it is moved to the RHS
25 //    2. Bitwise operators with constant operands are always grouped so that
26 //       shifts are performed first, then or's, then and's, then xor's.
27 //    3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/Statistic.h"
63 #include "llvm/ADT/STLExtras.h"
64 #include <algorithm>
65 #include <climits>
66 #include <sstream>
67 using namespace llvm;
68 using namespace llvm::PatternMatch;
69
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
75
76 namespace {
77   /// InstCombineWorklist - This is the worklist management logic for
78   /// InstCombine.
79   class InstCombineWorklist {
80     SmallVector<Instruction*, 256> Worklist;
81     DenseMap<Instruction*, unsigned> WorklistMap;
82     
83     void operator=(const InstCombineWorklist&RHS);   // DO NOT IMPLEMENT
84     InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85   public:
86     InstCombineWorklist() {}
87     
88     bool isEmpty() const { return Worklist.empty(); }
89     
90     /// Add - Add the specified instruction to the worklist if it isn't already
91     /// in it.
92     void Add(Instruction *I) {
93       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94         Worklist.push_back(I);
95     }
96     
97     void AddValue(Value *V) {
98       if (Instruction *I = dyn_cast<Instruction>(V))
99         Add(I);
100     }
101     
102     // Remove - remove I from the worklist if it exists.
103     void Remove(Instruction *I) {
104       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105       if (It == WorklistMap.end()) return; // Not in worklist.
106       
107       // Don't bother moving everything down, just null out the slot.
108       Worklist[It->second] = 0;
109       
110       WorklistMap.erase(It);
111     }
112     
113     Instruction *RemoveOne() {
114       Instruction *I = Worklist.back();
115       Worklist.pop_back();
116       WorklistMap.erase(I);
117       return I;
118     }
119
120     /// AddUsersToWorkList - When an instruction is simplified, add all users of
121     /// the instruction to the work lists because they might get more simplified
122     /// now.
123     ///
124     void AddUsersToWorkList(Instruction &I) {
125       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126            UI != UE; ++UI)
127         Add(cast<Instruction>(*UI));
128     }
129     
130     
131     /// Zap - check that the worklist is empty and nuke the backing store for
132     /// the map if it is large.
133     void Zap() {
134       assert(WorklistMap.empty() && "Worklist empty, but map not?");
135       
136       // Do an explicit clear, this shrinks the map if needed.
137       WorklistMap.clear();
138     }
139   };
140 } // end anonymous namespace.
141
142
143 namespace {
144   class VISIBILITY_HIDDEN InstCombiner
145     : public FunctionPass,
146       public InstVisitor<InstCombiner, Instruction*> {
147     TargetData *TD;
148     bool MustPreserveLCSSA;
149   public:
150     // Worklist of all of the instructions that need to be simplified.
151     InstCombineWorklist Worklist;
152
153     static char ID; // Pass identification, replacement for typeid
154     InstCombiner() : FunctionPass(&ID) {}
155
156     LLVMContext *Context;
157     LLVMContext *getContext() const { return Context; }
158
159   public:
160     virtual bool runOnFunction(Function &F);
161     
162     bool DoOneIteration(Function &F, unsigned ItNum);
163
164     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
165       AU.addPreservedID(LCSSAID);
166       AU.setPreservesCFG();
167     }
168
169     TargetData *getTargetData() const { return TD; }
170
171     // Visitation implementation - Implement instruction combining for different
172     // instruction types.  The semantics are as follows:
173     // Return Value:
174     //    null        - No change was made
175     //     I          - Change was made, I is still valid, I may be dead though
176     //   otherwise    - Change was made, replace I with returned instruction
177     //
178     Instruction *visitAdd(BinaryOperator &I);
179     Instruction *visitFAdd(BinaryOperator &I);
180     Instruction *visitSub(BinaryOperator &I);
181     Instruction *visitFSub(BinaryOperator &I);
182     Instruction *visitMul(BinaryOperator &I);
183     Instruction *visitFMul(BinaryOperator &I);
184     Instruction *visitURem(BinaryOperator &I);
185     Instruction *visitSRem(BinaryOperator &I);
186     Instruction *visitFRem(BinaryOperator &I);
187     bool SimplifyDivRemOfSelect(BinaryOperator &I);
188     Instruction *commonRemTransforms(BinaryOperator &I);
189     Instruction *commonIRemTransforms(BinaryOperator &I);
190     Instruction *commonDivTransforms(BinaryOperator &I);
191     Instruction *commonIDivTransforms(BinaryOperator &I);
192     Instruction *visitUDiv(BinaryOperator &I);
193     Instruction *visitSDiv(BinaryOperator &I);
194     Instruction *visitFDiv(BinaryOperator &I);
195     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
196     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
197     Instruction *visitAnd(BinaryOperator &I);
198     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
199     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
200     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
201                                      Value *A, Value *B, Value *C);
202     Instruction *visitOr (BinaryOperator &I);
203     Instruction *visitXor(BinaryOperator &I);
204     Instruction *visitShl(BinaryOperator &I);
205     Instruction *visitAShr(BinaryOperator &I);
206     Instruction *visitLShr(BinaryOperator &I);
207     Instruction *commonShiftTransforms(BinaryOperator &I);
208     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
209                                       Constant *RHSC);
210     Instruction *visitFCmpInst(FCmpInst &I);
211     Instruction *visitICmpInst(ICmpInst &I);
212     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
213     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
214                                                 Instruction *LHS,
215                                                 ConstantInt *RHS);
216     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
217                                 ConstantInt *DivRHS);
218
219     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
220                              ICmpInst::Predicate Cond, Instruction &I);
221     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
222                                      BinaryOperator &I);
223     Instruction *commonCastTransforms(CastInst &CI);
224     Instruction *commonIntCastTransforms(CastInst &CI);
225     Instruction *commonPointerCastTransforms(CastInst &CI);
226     Instruction *visitTrunc(TruncInst &CI);
227     Instruction *visitZExt(ZExtInst &CI);
228     Instruction *visitSExt(SExtInst &CI);
229     Instruction *visitFPTrunc(FPTruncInst &CI);
230     Instruction *visitFPExt(CastInst &CI);
231     Instruction *visitFPToUI(FPToUIInst &FI);
232     Instruction *visitFPToSI(FPToSIInst &FI);
233     Instruction *visitUIToFP(CastInst &CI);
234     Instruction *visitSIToFP(CastInst &CI);
235     Instruction *visitPtrToInt(PtrToIntInst &CI);
236     Instruction *visitIntToPtr(IntToPtrInst &CI);
237     Instruction *visitBitCast(BitCastInst &CI);
238     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
239                                 Instruction *FI);
240     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
241     Instruction *visitSelectInst(SelectInst &SI);
242     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
243     Instruction *visitCallInst(CallInst &CI);
244     Instruction *visitInvokeInst(InvokeInst &II);
245     Instruction *visitPHINode(PHINode &PN);
246     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
247     Instruction *visitAllocationInst(AllocationInst &AI);
248     Instruction *visitFreeInst(FreeInst &FI);
249     Instruction *visitLoadInst(LoadInst &LI);
250     Instruction *visitStoreInst(StoreInst &SI);
251     Instruction *visitBranchInst(BranchInst &BI);
252     Instruction *visitSwitchInst(SwitchInst &SI);
253     Instruction *visitInsertElementInst(InsertElementInst &IE);
254     Instruction *visitExtractElementInst(ExtractElementInst &EI);
255     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
256     Instruction *visitExtractValueInst(ExtractValueInst &EV);
257
258     // visitInstruction - Specify what to return for unhandled instructions...
259     Instruction *visitInstruction(Instruction &I) { return 0; }
260
261   private:
262     Instruction *visitCallSite(CallSite CS);
263     bool transformConstExprCastCall(CallSite CS);
264     Instruction *transformCallThroughTrampoline(CallSite CS);
265     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
266                                    bool DoXform = true);
267     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
268     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
269
270
271   public:
272     // InsertNewInstBefore - insert an instruction New before instruction Old
273     // in the program.  Add the new instruction to the worklist.
274     //
275     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
276       assert(New && New->getParent() == 0 &&
277              "New instruction already inserted into a basic block!");
278       BasicBlock *BB = Old.getParent();
279       BB->getInstList().insert(&Old, New);  // Insert inst
280       Worklist.Add(New);
281       return New;
282     }
283
284     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
285     /// This also adds the cast to the worklist.  Finally, this returns the
286     /// cast.
287     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
288                             Instruction &Pos) {
289       if (V->getType() == Ty) return V;
290
291       if (Constant *CV = dyn_cast<Constant>(V))
292         return ConstantExpr::getCast(opc, CV, Ty);
293       
294       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
295       Worklist.Add(C);
296       return C;
297     }
298         
299     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
300       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
301     }
302
303
304     // ReplaceInstUsesWith - This method is to be used when an instruction is
305     // found to be dead, replacable with another preexisting expression.  Here
306     // we add all uses of I to the worklist, replace all uses of I with the new
307     // value, then return I, so that the inst combiner will know that I was
308     // modified.
309     //
310     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
311       Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
312       
313       // If we are replacing the instruction with itself, this must be in a
314       // segment of unreachable code, so just clobber the instruction.
315       if (&I == V) 
316         V = UndefValue::get(I.getType());
317         
318       I.replaceAllUsesWith(V);
319       return &I;
320     }
321
322     // EraseInstFromFunction - When dealing with an instruction that has side
323     // effects or produces a void value, we can't rely on DCE to delete the
324     // instruction.  Instead, visit methods should return the value returned by
325     // this function.
326     Instruction *EraseInstFromFunction(Instruction &I) {
327       assert(I.use_empty() && "Cannot erase instruction that is used!");
328       // Make sure that we reprocess all operands now that we reduced their
329       // use counts.
330       if (I.getNumOperands() < 8) {
331         for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
332           if (Instruction *Op = dyn_cast<Instruction>(*i))
333             Worklist.Add(Op);
334       }
335       Worklist.Remove(&I);
336       I.eraseFromParent();
337       return 0;  // Don't do anything with FI
338     }
339         
340     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
341                            APInt &KnownOne, unsigned Depth = 0) const {
342       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
343     }
344     
345     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
346                            unsigned Depth = 0) const {
347       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
348     }
349     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
350       return llvm::ComputeNumSignBits(Op, TD, Depth);
351     }
352
353   private:
354
355     /// SimplifyCommutative - This performs a few simplifications for 
356     /// commutative operators.
357     bool SimplifyCommutative(BinaryOperator &I);
358
359     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
360     /// most-complex to least-complex order.
361     bool SimplifyCompare(CmpInst &I);
362
363     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
364     /// based on the demanded bits.
365     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
366                                    APInt& KnownZero, APInt& KnownOne,
367                                    unsigned Depth);
368     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
369                               APInt& KnownZero, APInt& KnownOne,
370                               unsigned Depth=0);
371         
372     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
373     /// SimplifyDemandedBits knows about.  See if the instruction has any
374     /// properties that allow us to simplify its operands.
375     bool SimplifyDemandedInstructionBits(Instruction &Inst);
376         
377     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
378                                       APInt& UndefElts, unsigned Depth = 0);
379       
380     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
381     // PHI node as operand #0, see if we can fold the instruction into the PHI
382     // (which is only possible if all operands to the PHI are constants).
383     Instruction *FoldOpIntoPhi(Instruction &I);
384
385     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
386     // operator and they all are only used by the PHI, PHI together their
387     // inputs, and do the operation once, to the result of the PHI.
388     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
389     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
390     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
391
392     
393     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
394                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
395     
396     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
397                               bool isSub, Instruction &I);
398     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
399                                  bool isSigned, bool Inside, Instruction &IB);
400     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
401     Instruction *MatchBSwap(BinaryOperator &I);
402     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
403     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
404     Instruction *SimplifyMemSet(MemSetInst *MI);
405
406
407     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
408
409     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
410                                     unsigned CastOpc, int &NumCastsRemoved);
411     unsigned GetOrEnforceKnownAlignment(Value *V,
412                                         unsigned PrefAlign = 0);
413
414   };
415 } // end anonymous namespace
416
417 char InstCombiner::ID = 0;
418 static RegisterPass<InstCombiner>
419 X("instcombine", "Combine redundant instructions");
420
421 // getComplexity:  Assign a complexity or rank value to LLVM Values...
422 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
423 static unsigned getComplexity(Value *V) {
424   if (isa<Instruction>(V)) {
425     if (BinaryOperator::isNeg(V) ||
426         BinaryOperator::isFNeg(V) ||
427         BinaryOperator::isNot(V))
428       return 3;
429     return 4;
430   }
431   if (isa<Argument>(V)) return 3;
432   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
433 }
434
435 // isOnlyUse - Return true if this instruction will be deleted if we stop using
436 // it.
437 static bool isOnlyUse(Value *V) {
438   return V->hasOneUse() || isa<Constant>(V);
439 }
440
441 // getPromotedType - Return the specified type promoted as it would be to pass
442 // though a va_arg area...
443 static const Type *getPromotedType(const Type *Ty) {
444   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
445     if (ITy->getBitWidth() < 32)
446       return Type::getInt32Ty(Ty->getContext());
447   }
448   return Ty;
449 }
450
451 /// getBitCastOperand - If the specified operand is a CastInst, a constant
452 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
453 /// operand value, otherwise return null.
454 static Value *getBitCastOperand(Value *V) {
455   if (Operator *O = dyn_cast<Operator>(V)) {
456     if (O->getOpcode() == Instruction::BitCast)
457       return O->getOperand(0);
458     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
459       if (GEP->hasAllZeroIndices())
460         return GEP->getPointerOperand();
461   }
462   return 0;
463 }
464
465 /// This function is a wrapper around CastInst::isEliminableCastPair. It
466 /// simply extracts arguments and returns what that function returns.
467 static Instruction::CastOps 
468 isEliminableCastPair(
469   const CastInst *CI, ///< The first cast instruction
470   unsigned opcode,       ///< The opcode of the second cast instruction
471   const Type *DstTy,     ///< The target type for the second cast instruction
472   TargetData *TD         ///< The target data for pointer size
473 ) {
474
475   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
476   const Type *MidTy = CI->getType();                  // B from above
477
478   // Get the opcodes of the two Cast instructions
479   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
481
482   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483                                                 DstTy,
484                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
485   
486   // We don't want to form an inttoptr or ptrtoint that converts to an integer
487   // type that differs from the pointer size.
488   if ((Res == Instruction::IntToPtr &&
489           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
490       (Res == Instruction::PtrToInt &&
491           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
492     Res = 0;
493   
494   return Instruction::CastOps(Res);
495 }
496
497 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
498 /// in any code being generated.  It does not require codegen if V is simple
499 /// enough or if the cast can be folded into other casts.
500 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
501                               const Type *Ty, TargetData *TD) {
502   if (V->getType() == Ty || isa<Constant>(V)) return false;
503   
504   // If this is another cast that can be eliminated, it isn't codegen either.
505   if (const CastInst *CI = dyn_cast<CastInst>(V))
506     if (isEliminableCastPair(CI, opcode, Ty, TD))
507       return false;
508   return true;
509 }
510
511 // SimplifyCommutative - This performs a few simplifications for commutative
512 // operators:
513 //
514 //  1. Order operands such that they are listed from right (least complex) to
515 //     left (most complex).  This puts constants before unary operators before
516 //     binary operators.
517 //
518 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
519 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
520 //
521 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
522   bool Changed = false;
523   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
524     Changed = !I.swapOperands();
525
526   if (!I.isAssociative()) return Changed;
527   Instruction::BinaryOps Opcode = I.getOpcode();
528   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
529     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
530       if (isa<Constant>(I.getOperand(1))) {
531         Constant *Folded = ConstantExpr::get(I.getOpcode(),
532                                              cast<Constant>(I.getOperand(1)),
533                                              cast<Constant>(Op->getOperand(1)));
534         I.setOperand(0, Op->getOperand(0));
535         I.setOperand(1, Folded);
536         return true;
537       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
538         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
539             isOnlyUse(Op) && isOnlyUse(Op1)) {
540           Constant *C1 = cast<Constant>(Op->getOperand(1));
541           Constant *C2 = cast<Constant>(Op1->getOperand(1));
542
543           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
544           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
545           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
546                                                     Op1->getOperand(0),
547                                                     Op1->getName(), &I);
548           Worklist.Add(New);
549           I.setOperand(0, New);
550           I.setOperand(1, Folded);
551           return true;
552         }
553     }
554   return Changed;
555 }
556
557 /// SimplifyCompare - For a CmpInst this function just orders the operands
558 /// so that theyare listed from right (least complex) to left (most complex).
559 /// This puts constants before unary operators before binary operators.
560 bool InstCombiner::SimplifyCompare(CmpInst &I) {
561   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
562     return false;
563   I.swapOperands();
564   // Compare instructions are not associative so there's nothing else we can do.
565   return true;
566 }
567
568 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
569 // if the LHS is a constant zero (which is the 'negate' form).
570 //
571 static inline Value *dyn_castNegVal(Value *V) {
572   if (BinaryOperator::isNeg(V))
573     return BinaryOperator::getNegArgument(V);
574
575   // Constants can be considered to be negated values if they can be folded.
576   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
577     return ConstantExpr::getNeg(C);
578
579   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
580     if (C->getType()->getElementType()->isInteger())
581       return ConstantExpr::getNeg(C);
582
583   return 0;
584 }
585
586 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
587 // instruction if the LHS is a constant negative zero (which is the 'negate'
588 // form).
589 //
590 static inline Value *dyn_castFNegVal(Value *V) {
591   if (BinaryOperator::isFNeg(V))
592     return BinaryOperator::getFNegArgument(V);
593
594   // Constants can be considered to be negated values if they can be folded.
595   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
596     return ConstantExpr::getFNeg(C);
597
598   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
599     if (C->getType()->getElementType()->isFloatingPoint())
600       return ConstantExpr::getFNeg(C);
601
602   return 0;
603 }
604
605 static inline Value *dyn_castNotVal(Value *V) {
606   if (BinaryOperator::isNot(V))
607     return BinaryOperator::getNotArgument(V);
608
609   // Constants can be considered to be not'ed values...
610   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
611     return ConstantInt::get(C->getType(), ~C->getValue());
612   return 0;
613 }
614
615 // dyn_castFoldableMul - If this value is a multiply that can be folded into
616 // other computations (because it has a constant operand), return the
617 // non-constant operand of the multiply, and set CST to point to the multiplier.
618 // Otherwise, return null.
619 //
620 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
621   if (V->hasOneUse() && V->getType()->isInteger())
622     if (Instruction *I = dyn_cast<Instruction>(V)) {
623       if (I->getOpcode() == Instruction::Mul)
624         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
625           return I->getOperand(0);
626       if (I->getOpcode() == Instruction::Shl)
627         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
628           // The multiplier is really 1 << CST.
629           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
630           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
631           CST = ConstantInt::get(V->getType()->getContext(),
632                                  APInt(BitWidth, 1).shl(CSTVal));
633           return I->getOperand(0);
634         }
635     }
636   return 0;
637 }
638
639 /// AddOne - Add one to a ConstantInt
640 static Constant *AddOne(Constant *C) {
641   return ConstantExpr::getAdd(C, 
642     ConstantInt::get(C->getType(), 1));
643 }
644 /// SubOne - Subtract one from a ConstantInt
645 static Constant *SubOne(ConstantInt *C) {
646   return ConstantExpr::getSub(C, 
647     ConstantInt::get(C->getType(), 1));
648 }
649 /// MultiplyOverflows - True if the multiply can not be expressed in an int
650 /// this size.
651 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
652   uint32_t W = C1->getBitWidth();
653   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
654   if (sign) {
655     LHSExt.sext(W * 2);
656     RHSExt.sext(W * 2);
657   } else {
658     LHSExt.zext(W * 2);
659     RHSExt.zext(W * 2);
660   }
661
662   APInt MulExt = LHSExt * RHSExt;
663
664   if (sign) {
665     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
666     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
667     return MulExt.slt(Min) || MulExt.sgt(Max);
668   } else 
669     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
670 }
671
672
673 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
674 /// specified instruction is a constant integer.  If so, check to see if there
675 /// are any bits set in the constant that are not demanded.  If so, shrink the
676 /// constant and return true.
677 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
678                                    APInt Demanded) {
679   assert(I && "No instruction?");
680   assert(OpNo < I->getNumOperands() && "Operand index too large");
681
682   // If the operand is not a constant integer, nothing to do.
683   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
684   if (!OpC) return false;
685
686   // If there are no bits set that aren't demanded, nothing to do.
687   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
688   if ((~Demanded & OpC->getValue()) == 0)
689     return false;
690
691   // This instruction is producing bits that are not demanded. Shrink the RHS.
692   Demanded &= OpC->getValue();
693   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
694   return true;
695 }
696
697 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
698 // set of known zero and one bits, compute the maximum and minimum values that
699 // could have the specified known zero and known one bits, returning them in
700 // min/max.
701 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
702                                                    const APInt& KnownOne,
703                                                    APInt& Min, APInt& Max) {
704   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
705          KnownZero.getBitWidth() == Min.getBitWidth() &&
706          KnownZero.getBitWidth() == Max.getBitWidth() &&
707          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
708   APInt UnknownBits = ~(KnownZero|KnownOne);
709
710   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
711   // bit if it is unknown.
712   Min = KnownOne;
713   Max = KnownOne|UnknownBits;
714   
715   if (UnknownBits.isNegative()) { // Sign bit is unknown
716     Min.set(Min.getBitWidth()-1);
717     Max.clear(Max.getBitWidth()-1);
718   }
719 }
720
721 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
722 // a set of known zero and one bits, compute the maximum and minimum values that
723 // could have the specified known zero and known one bits, returning them in
724 // min/max.
725 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
726                                                      const APInt &KnownOne,
727                                                      APInt &Min, APInt &Max) {
728   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
729          KnownZero.getBitWidth() == Min.getBitWidth() &&
730          KnownZero.getBitWidth() == Max.getBitWidth() &&
731          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
732   APInt UnknownBits = ~(KnownZero|KnownOne);
733   
734   // The minimum value is when the unknown bits are all zeros.
735   Min = KnownOne;
736   // The maximum value is when the unknown bits are all ones.
737   Max = KnownOne|UnknownBits;
738 }
739
740 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
741 /// SimplifyDemandedBits knows about.  See if the instruction has any
742 /// properties that allow us to simplify its operands.
743 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
744   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
745   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
746   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
747   
748   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
749                                      KnownZero, KnownOne, 0);
750   if (V == 0) return false;
751   if (V == &Inst) return true;
752   ReplaceInstUsesWith(Inst, V);
753   return true;
754 }
755
756 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
757 /// specified instruction operand if possible, updating it in place.  It returns
758 /// true if it made any change and false otherwise.
759 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
760                                         APInt &KnownZero, APInt &KnownOne,
761                                         unsigned Depth) {
762   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
763                                           KnownZero, KnownOne, Depth);
764   if (NewVal == 0) return false;
765   U.set(NewVal);
766   return true;
767 }
768
769
770 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
771 /// value based on the demanded bits.  When this function is called, it is known
772 /// that only the bits set in DemandedMask of the result of V are ever used
773 /// downstream. Consequently, depending on the mask and V, it may be possible
774 /// to replace V with a constant or one of its operands. In such cases, this
775 /// function does the replacement and returns true. In all other cases, it
776 /// returns false after analyzing the expression and setting KnownOne and known
777 /// to be one in the expression.  KnownZero contains all the bits that are known
778 /// to be zero in the expression. These are provided to potentially allow the
779 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
780 /// the expression. KnownOne and KnownZero always follow the invariant that 
781 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
782 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
783 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
784 /// and KnownOne must all be the same.
785 ///
786 /// This returns null if it did not change anything and it permits no
787 /// simplification.  This returns V itself if it did some simplification of V's
788 /// operands based on the information about what bits are demanded. This returns
789 /// some other non-null value if it found out that V is equal to another value
790 /// in the context where the specified bits are demanded, but not for all users.
791 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
792                                              APInt &KnownZero, APInt &KnownOne,
793                                              unsigned Depth) {
794   assert(V != 0 && "Null pointer of Value???");
795   assert(Depth <= 6 && "Limit Search Depth");
796   uint32_t BitWidth = DemandedMask.getBitWidth();
797   const Type *VTy = V->getType();
798   assert((TD || !isa<PointerType>(VTy)) &&
799          "SimplifyDemandedBits needs to know bit widths!");
800   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
801          (!VTy->isIntOrIntVector() ||
802           VTy->getScalarSizeInBits() == BitWidth) &&
803          KnownZero.getBitWidth() == BitWidth &&
804          KnownOne.getBitWidth() == BitWidth &&
805          "Value *V, DemandedMask, KnownZero and KnownOne "
806          "must have same BitWidth");
807   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
808     // We know all of the bits for a constant!
809     KnownOne = CI->getValue() & DemandedMask;
810     KnownZero = ~KnownOne & DemandedMask;
811     return 0;
812   }
813   if (isa<ConstantPointerNull>(V)) {
814     // We know all of the bits for a constant!
815     KnownOne.clear();
816     KnownZero = DemandedMask;
817     return 0;
818   }
819
820   KnownZero.clear();
821   KnownOne.clear();
822   if (DemandedMask == 0) {   // Not demanding any bits from V.
823     if (isa<UndefValue>(V))
824       return 0;
825     return UndefValue::get(VTy);
826   }
827   
828   if (Depth == 6)        // Limit search depth.
829     return 0;
830   
831   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
832   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
833
834   Instruction *I = dyn_cast<Instruction>(V);
835   if (!I) {
836     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
837     return 0;        // Only analyze instructions.
838   }
839
840   // If there are multiple uses of this value and we aren't at the root, then
841   // we can't do any simplifications of the operands, because DemandedMask
842   // only reflects the bits demanded by *one* of the users.
843   if (Depth != 0 && !I->hasOneUse()) {
844     // Despite the fact that we can't simplify this instruction in all User's
845     // context, we can at least compute the knownzero/knownone bits, and we can
846     // do simplifications that apply to *just* the one user if we know that
847     // this instruction has a simpler value in that context.
848     if (I->getOpcode() == Instruction::And) {
849       // If either the LHS or the RHS are Zero, the result is zero.
850       ComputeMaskedBits(I->getOperand(1), DemandedMask,
851                         RHSKnownZero, RHSKnownOne, Depth+1);
852       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
853                         LHSKnownZero, LHSKnownOne, Depth+1);
854       
855       // If all of the demanded bits are known 1 on one side, return the other.
856       // These bits cannot contribute to the result of the 'and' in this
857       // context.
858       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
859           (DemandedMask & ~LHSKnownZero))
860         return I->getOperand(0);
861       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
862           (DemandedMask & ~RHSKnownZero))
863         return I->getOperand(1);
864       
865       // If all of the demanded bits in the inputs are known zeros, return zero.
866       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
867         return Constant::getNullValue(VTy);
868       
869     } else if (I->getOpcode() == Instruction::Or) {
870       // We can simplify (X|Y) -> X or Y in the user's context if we know that
871       // only bits from X or Y are demanded.
872       
873       // If either the LHS or the RHS are One, the result is One.
874       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
875                         RHSKnownZero, RHSKnownOne, Depth+1);
876       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
877                         LHSKnownZero, LHSKnownOne, Depth+1);
878       
879       // If all of the demanded bits are known zero on one side, return the
880       // other.  These bits cannot contribute to the result of the 'or' in this
881       // context.
882       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
883           (DemandedMask & ~LHSKnownOne))
884         return I->getOperand(0);
885       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
886           (DemandedMask & ~RHSKnownOne))
887         return I->getOperand(1);
888       
889       // If all of the potentially set bits on one side are known to be set on
890       // the other side, just use the 'other' side.
891       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
892           (DemandedMask & (~RHSKnownZero)))
893         return I->getOperand(0);
894       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
895           (DemandedMask & (~LHSKnownZero)))
896         return I->getOperand(1);
897     }
898     
899     // Compute the KnownZero/KnownOne bits to simplify things downstream.
900     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
901     return 0;
902   }
903   
904   // If this is the root being simplified, allow it to have multiple uses,
905   // just set the DemandedMask to all bits so that we can try to simplify the
906   // operands.  This allows visitTruncInst (for example) to simplify the
907   // operand of a trunc without duplicating all the logic below.
908   if (Depth == 0 && !V->hasOneUse())
909     DemandedMask = APInt::getAllOnesValue(BitWidth);
910   
911   switch (I->getOpcode()) {
912   default:
913     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
914     break;
915   case Instruction::And:
916     // If either the LHS or the RHS are Zero, the result is zero.
917     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
918                              RHSKnownZero, RHSKnownOne, Depth+1) ||
919         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
920                              LHSKnownZero, LHSKnownOne, Depth+1))
921       return I;
922     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
923     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
924
925     // If all of the demanded bits are known 1 on one side, return the other.
926     // These bits cannot contribute to the result of the 'and'.
927     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
928         (DemandedMask & ~LHSKnownZero))
929       return I->getOperand(0);
930     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
931         (DemandedMask & ~RHSKnownZero))
932       return I->getOperand(1);
933     
934     // If all of the demanded bits in the inputs are known zeros, return zero.
935     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
936       return Constant::getNullValue(VTy);
937       
938     // If the RHS is a constant, see if we can simplify it.
939     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
940       return I;
941       
942     // Output known-1 bits are only known if set in both the LHS & RHS.
943     RHSKnownOne &= LHSKnownOne;
944     // Output known-0 are known to be clear if zero in either the LHS | RHS.
945     RHSKnownZero |= LHSKnownZero;
946     break;
947   case Instruction::Or:
948     // If either the LHS or the RHS are One, the result is One.
949     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
950                              RHSKnownZero, RHSKnownOne, Depth+1) ||
951         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
952                              LHSKnownZero, LHSKnownOne, Depth+1))
953       return I;
954     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
955     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
956     
957     // If all of the demanded bits are known zero on one side, return the other.
958     // These bits cannot contribute to the result of the 'or'.
959     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
960         (DemandedMask & ~LHSKnownOne))
961       return I->getOperand(0);
962     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
963         (DemandedMask & ~RHSKnownOne))
964       return I->getOperand(1);
965
966     // If all of the potentially set bits on one side are known to be set on
967     // the other side, just use the 'other' side.
968     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
969         (DemandedMask & (~RHSKnownZero)))
970       return I->getOperand(0);
971     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
972         (DemandedMask & (~LHSKnownZero)))
973       return I->getOperand(1);
974         
975     // If the RHS is a constant, see if we can simplify it.
976     if (ShrinkDemandedConstant(I, 1, DemandedMask))
977       return I;
978           
979     // Output known-0 bits are only known if clear in both the LHS & RHS.
980     RHSKnownZero &= LHSKnownZero;
981     // Output known-1 are known to be set if set in either the LHS | RHS.
982     RHSKnownOne |= LHSKnownOne;
983     break;
984   case Instruction::Xor: {
985     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
986                              RHSKnownZero, RHSKnownOne, Depth+1) ||
987         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
988                              LHSKnownZero, LHSKnownOne, Depth+1))
989       return I;
990     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
991     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
992     
993     // If all of the demanded bits are known zero on one side, return the other.
994     // These bits cannot contribute to the result of the 'xor'.
995     if ((DemandedMask & RHSKnownZero) == DemandedMask)
996       return I->getOperand(0);
997     if ((DemandedMask & LHSKnownZero) == DemandedMask)
998       return I->getOperand(1);
999     
1000     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1001     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1002                          (RHSKnownOne & LHSKnownOne);
1003     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1004     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1005                         (RHSKnownOne & LHSKnownZero);
1006     
1007     // If all of the demanded bits are known to be zero on one side or the
1008     // other, turn this into an *inclusive* or.
1009     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1010     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1011       Instruction *Or =
1012         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1013                                  I->getName());
1014       return InsertNewInstBefore(Or, *I);
1015     }
1016     
1017     // If all of the demanded bits on one side are known, and all of the set
1018     // bits on that side are also known to be set on the other side, turn this
1019     // into an AND, as we know the bits will be cleared.
1020     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1021     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1022       // all known
1023       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1024         Constant *AndC = Constant::getIntegerValue(VTy,
1025                                                    ~RHSKnownOne & DemandedMask);
1026         Instruction *And = 
1027           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1028         return InsertNewInstBefore(And, *I);
1029       }
1030     }
1031     
1032     // If the RHS is a constant, see if we can simplify it.
1033     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1034     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1035       return I;
1036     
1037     RHSKnownZero = KnownZeroOut;
1038     RHSKnownOne  = KnownOneOut;
1039     break;
1040   }
1041   case Instruction::Select:
1042     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1043                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1044         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1045                              LHSKnownZero, LHSKnownOne, Depth+1))
1046       return I;
1047     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1048     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1049     
1050     // If the operands are constants, see if we can simplify them.
1051     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1052         ShrinkDemandedConstant(I, 2, DemandedMask))
1053       return I;
1054     
1055     // Only known if known in both the LHS and RHS.
1056     RHSKnownOne &= LHSKnownOne;
1057     RHSKnownZero &= LHSKnownZero;
1058     break;
1059   case Instruction::Trunc: {
1060     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1061     DemandedMask.zext(truncBf);
1062     RHSKnownZero.zext(truncBf);
1063     RHSKnownOne.zext(truncBf);
1064     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1065                              RHSKnownZero, RHSKnownOne, Depth+1))
1066       return I;
1067     DemandedMask.trunc(BitWidth);
1068     RHSKnownZero.trunc(BitWidth);
1069     RHSKnownOne.trunc(BitWidth);
1070     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1071     break;
1072   }
1073   case Instruction::BitCast:
1074     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1075       return false;  // vector->int or fp->int?
1076
1077     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1078       if (const VectorType *SrcVTy =
1079             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1080         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1081           // Don't touch a bitcast between vectors of different element counts.
1082           return false;
1083       } else
1084         // Don't touch a scalar-to-vector bitcast.
1085         return false;
1086     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1087       // Don't touch a vector-to-scalar bitcast.
1088       return false;
1089
1090     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1091                              RHSKnownZero, RHSKnownOne, Depth+1))
1092       return I;
1093     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1094     break;
1095   case Instruction::ZExt: {
1096     // Compute the bits in the result that are not present in the input.
1097     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1098     
1099     DemandedMask.trunc(SrcBitWidth);
1100     RHSKnownZero.trunc(SrcBitWidth);
1101     RHSKnownOne.trunc(SrcBitWidth);
1102     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103                              RHSKnownZero, RHSKnownOne, Depth+1))
1104       return I;
1105     DemandedMask.zext(BitWidth);
1106     RHSKnownZero.zext(BitWidth);
1107     RHSKnownOne.zext(BitWidth);
1108     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1109     // The top bits are known to be zero.
1110     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1111     break;
1112   }
1113   case Instruction::SExt: {
1114     // Compute the bits in the result that are not present in the input.
1115     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1116     
1117     APInt InputDemandedBits = DemandedMask & 
1118                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1119
1120     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1121     // If any of the sign extended bits are demanded, we know that the sign
1122     // bit is demanded.
1123     if ((NewBits & DemandedMask) != 0)
1124       InputDemandedBits.set(SrcBitWidth-1);
1125       
1126     InputDemandedBits.trunc(SrcBitWidth);
1127     RHSKnownZero.trunc(SrcBitWidth);
1128     RHSKnownOne.trunc(SrcBitWidth);
1129     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1130                              RHSKnownZero, RHSKnownOne, Depth+1))
1131       return I;
1132     InputDemandedBits.zext(BitWidth);
1133     RHSKnownZero.zext(BitWidth);
1134     RHSKnownOne.zext(BitWidth);
1135     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1136       
1137     // If the sign bit of the input is known set or clear, then we know the
1138     // top bits of the result.
1139
1140     // If the input sign bit is known zero, or if the NewBits are not demanded
1141     // convert this into a zero extension.
1142     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1143       // Convert to ZExt cast
1144       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1145       return InsertNewInstBefore(NewCast, *I);
1146     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1147       RHSKnownOne |= NewBits;
1148     }
1149     break;
1150   }
1151   case Instruction::Add: {
1152     // Figure out what the input bits are.  If the top bits of the and result
1153     // are not demanded, then the add doesn't demand them from its input
1154     // either.
1155     unsigned NLZ = DemandedMask.countLeadingZeros();
1156       
1157     // If there is a constant on the RHS, there are a variety of xformations
1158     // we can do.
1159     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1160       // If null, this should be simplified elsewhere.  Some of the xforms here
1161       // won't work if the RHS is zero.
1162       if (RHS->isZero())
1163         break;
1164       
1165       // If the top bit of the output is demanded, demand everything from the
1166       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1167       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1168
1169       // Find information about known zero/one bits in the input.
1170       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1171                                LHSKnownZero, LHSKnownOne, Depth+1))
1172         return I;
1173
1174       // If the RHS of the add has bits set that can't affect the input, reduce
1175       // the constant.
1176       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1177         return I;
1178       
1179       // Avoid excess work.
1180       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1181         break;
1182       
1183       // Turn it into OR if input bits are zero.
1184       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1185         Instruction *Or =
1186           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1187                                    I->getName());
1188         return InsertNewInstBefore(Or, *I);
1189       }
1190       
1191       // We can say something about the output known-zero and known-one bits,
1192       // depending on potential carries from the input constant and the
1193       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1194       // bits set and the RHS constant is 0x01001, then we know we have a known
1195       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1196       
1197       // To compute this, we first compute the potential carry bits.  These are
1198       // the bits which may be modified.  I'm not aware of a better way to do
1199       // this scan.
1200       const APInt &RHSVal = RHS->getValue();
1201       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1202       
1203       // Now that we know which bits have carries, compute the known-1/0 sets.
1204       
1205       // Bits are known one if they are known zero in one operand and one in the
1206       // other, and there is no input carry.
1207       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1208                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1209       
1210       // Bits are known zero if they are known zero in both operands and there
1211       // is no input carry.
1212       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1213     } else {
1214       // If the high-bits of this ADD are not demanded, then it does not demand
1215       // the high bits of its LHS or RHS.
1216       if (DemandedMask[BitWidth-1] == 0) {
1217         // Right fill the mask of bits for this ADD to demand the most
1218         // significant bit and all those below it.
1219         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1220         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1221                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1222             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1223                                  LHSKnownZero, LHSKnownOne, Depth+1))
1224           return I;
1225       }
1226     }
1227     break;
1228   }
1229   case Instruction::Sub:
1230     // If the high-bits of this SUB are not demanded, then it does not demand
1231     // the high bits of its LHS or RHS.
1232     if (DemandedMask[BitWidth-1] == 0) {
1233       // Right fill the mask of bits for this SUB to demand the most
1234       // significant bit and all those below it.
1235       uint32_t NLZ = DemandedMask.countLeadingZeros();
1236       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1237       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1238                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1239           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1240                                LHSKnownZero, LHSKnownOne, Depth+1))
1241         return I;
1242     }
1243     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1244     // the known zeros and ones.
1245     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1246     break;
1247   case Instruction::Shl:
1248     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1249       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1250       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1251       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1252                                RHSKnownZero, RHSKnownOne, Depth+1))
1253         return I;
1254       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1255       RHSKnownZero <<= ShiftAmt;
1256       RHSKnownOne  <<= ShiftAmt;
1257       // low bits known zero.
1258       if (ShiftAmt)
1259         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1260     }
1261     break;
1262   case Instruction::LShr:
1263     // For a logical shift right
1264     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1265       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1266       
1267       // Unsigned shift right.
1268       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1269       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1270                                RHSKnownZero, RHSKnownOne, Depth+1))
1271         return I;
1272       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1273       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1274       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1275       if (ShiftAmt) {
1276         // Compute the new bits that are at the top now.
1277         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1278         RHSKnownZero |= HighBits;  // high bits known zero.
1279       }
1280     }
1281     break;
1282   case Instruction::AShr:
1283     // If this is an arithmetic shift right and only the low-bit is set, we can
1284     // always convert this into a logical shr, even if the shift amount is
1285     // variable.  The low bit of the shift cannot be an input sign bit unless
1286     // the shift amount is >= the size of the datatype, which is undefined.
1287     if (DemandedMask == 1) {
1288       // Perform the logical shift right.
1289       Instruction *NewVal = BinaryOperator::CreateLShr(
1290                         I->getOperand(0), I->getOperand(1), I->getName());
1291       return InsertNewInstBefore(NewVal, *I);
1292     }    
1293
1294     // If the sign bit is the only bit demanded by this ashr, then there is no
1295     // need to do it, the shift doesn't change the high bit.
1296     if (DemandedMask.isSignBit())
1297       return I->getOperand(0);
1298     
1299     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1300       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1301       
1302       // Signed shift right.
1303       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1304       // If any of the "high bits" are demanded, we should set the sign bit as
1305       // demanded.
1306       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1307         DemandedMaskIn.set(BitWidth-1);
1308       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1309                                RHSKnownZero, RHSKnownOne, Depth+1))
1310         return I;
1311       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1312       // Compute the new bits that are at the top now.
1313       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1314       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1315       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1316         
1317       // Handle the sign bits.
1318       APInt SignBit(APInt::getSignBit(BitWidth));
1319       // Adjust to where it is now in the mask.
1320       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1321         
1322       // If the input sign bit is known to be zero, or if none of the top bits
1323       // are demanded, turn this into an unsigned shift right.
1324       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1325           (HighBits & ~DemandedMask) == HighBits) {
1326         // Perform the logical shift right.
1327         Instruction *NewVal = BinaryOperator::CreateLShr(
1328                           I->getOperand(0), SA, I->getName());
1329         return InsertNewInstBefore(NewVal, *I);
1330       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1331         RHSKnownOne |= HighBits;
1332       }
1333     }
1334     break;
1335   case Instruction::SRem:
1336     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1337       APInt RA = Rem->getValue().abs();
1338       if (RA.isPowerOf2()) {
1339         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1340           return I->getOperand(0);
1341
1342         APInt LowBits = RA - 1;
1343         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1344         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1345                                  LHSKnownZero, LHSKnownOne, Depth+1))
1346           return I;
1347
1348         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1349           LHSKnownZero |= ~LowBits;
1350
1351         KnownZero |= LHSKnownZero & DemandedMask;
1352
1353         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1354       }
1355     }
1356     break;
1357   case Instruction::URem: {
1358     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1359     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1360     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1361                              KnownZero2, KnownOne2, Depth+1) ||
1362         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1363                              KnownZero2, KnownOne2, Depth+1))
1364       return I;
1365
1366     unsigned Leaders = KnownZero2.countLeadingOnes();
1367     Leaders = std::max(Leaders,
1368                        KnownZero2.countLeadingOnes());
1369     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1370     break;
1371   }
1372   case Instruction::Call:
1373     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1374       switch (II->getIntrinsicID()) {
1375       default: break;
1376       case Intrinsic::bswap: {
1377         // If the only bits demanded come from one byte of the bswap result,
1378         // just shift the input byte into position to eliminate the bswap.
1379         unsigned NLZ = DemandedMask.countLeadingZeros();
1380         unsigned NTZ = DemandedMask.countTrailingZeros();
1381           
1382         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1383         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1384         // have 14 leading zeros, round to 8.
1385         NLZ &= ~7;
1386         NTZ &= ~7;
1387         // If we need exactly one byte, we can do this transformation.
1388         if (BitWidth-NLZ-NTZ == 8) {
1389           unsigned ResultBit = NTZ;
1390           unsigned InputBit = BitWidth-NTZ-8;
1391           
1392           // Replace this with either a left or right shift to get the byte into
1393           // the right place.
1394           Instruction *NewVal;
1395           if (InputBit > ResultBit)
1396             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1397                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1398           else
1399             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1400                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1401           NewVal->takeName(I);
1402           return InsertNewInstBefore(NewVal, *I);
1403         }
1404           
1405         // TODO: Could compute known zero/one bits based on the input.
1406         break;
1407       }
1408       }
1409     }
1410     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1411     break;
1412   }
1413   
1414   // If the client is only demanding bits that we know, return the known
1415   // constant.
1416   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1417     return Constant::getIntegerValue(VTy, RHSKnownOne);
1418   return false;
1419 }
1420
1421
1422 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1423 /// any number of elements. DemandedElts contains the set of elements that are
1424 /// actually used by the caller.  This method analyzes which elements of the
1425 /// operand are undef and returns that information in UndefElts.
1426 ///
1427 /// If the information about demanded elements can be used to simplify the
1428 /// operation, the operation is simplified, then the resultant value is
1429 /// returned.  This returns null if no change was made.
1430 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1431                                                 APInt& UndefElts,
1432                                                 unsigned Depth) {
1433   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1434   APInt EltMask(APInt::getAllOnesValue(VWidth));
1435   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1436
1437   if (isa<UndefValue>(V)) {
1438     // If the entire vector is undefined, just return this info.
1439     UndefElts = EltMask;
1440     return 0;
1441   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1442     UndefElts = EltMask;
1443     return UndefValue::get(V->getType());
1444   }
1445
1446   UndefElts = 0;
1447   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1448     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1449     Constant *Undef = UndefValue::get(EltTy);
1450
1451     std::vector<Constant*> Elts;
1452     for (unsigned i = 0; i != VWidth; ++i)
1453       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1454         Elts.push_back(Undef);
1455         UndefElts.set(i);
1456       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1457         Elts.push_back(Undef);
1458         UndefElts.set(i);
1459       } else {                               // Otherwise, defined.
1460         Elts.push_back(CP->getOperand(i));
1461       }
1462
1463     // If we changed the constant, return it.
1464     Constant *NewCP = ConstantVector::get(Elts);
1465     return NewCP != CP ? NewCP : 0;
1466   } else if (isa<ConstantAggregateZero>(V)) {
1467     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1468     // set to undef.
1469     
1470     // Check if this is identity. If so, return 0 since we are not simplifying
1471     // anything.
1472     if (DemandedElts == ((1ULL << VWidth) -1))
1473       return 0;
1474     
1475     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1476     Constant *Zero = Constant::getNullValue(EltTy);
1477     Constant *Undef = UndefValue::get(EltTy);
1478     std::vector<Constant*> Elts;
1479     for (unsigned i = 0; i != VWidth; ++i) {
1480       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1481       Elts.push_back(Elt);
1482     }
1483     UndefElts = DemandedElts ^ EltMask;
1484     return ConstantVector::get(Elts);
1485   }
1486   
1487   // Limit search depth.
1488   if (Depth == 10)
1489     return 0;
1490
1491   // If multiple users are using the root value, procede with
1492   // simplification conservatively assuming that all elements
1493   // are needed.
1494   if (!V->hasOneUse()) {
1495     // Quit if we find multiple users of a non-root value though.
1496     // They'll be handled when it's their turn to be visited by
1497     // the main instcombine process.
1498     if (Depth != 0)
1499       // TODO: Just compute the UndefElts information recursively.
1500       return 0;
1501
1502     // Conservatively assume that all elements are needed.
1503     DemandedElts = EltMask;
1504   }
1505   
1506   Instruction *I = dyn_cast<Instruction>(V);
1507   if (!I) return 0;        // Only analyze instructions.
1508   
1509   bool MadeChange = false;
1510   APInt UndefElts2(VWidth, 0);
1511   Value *TmpV;
1512   switch (I->getOpcode()) {
1513   default: break;
1514     
1515   case Instruction::InsertElement: {
1516     // If this is a variable index, we don't know which element it overwrites.
1517     // demand exactly the same input as we produce.
1518     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1519     if (Idx == 0) {
1520       // Note that we can't propagate undef elt info, because we don't know
1521       // which elt is getting updated.
1522       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1523                                         UndefElts2, Depth+1);
1524       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1525       break;
1526     }
1527     
1528     // If this is inserting an element that isn't demanded, remove this
1529     // insertelement.
1530     unsigned IdxNo = Idx->getZExtValue();
1531     if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1532       Worklist.Add(I);
1533       return I->getOperand(0);
1534     }
1535     
1536     // Otherwise, the element inserted overwrites whatever was there, so the
1537     // input demanded set is simpler than the output set.
1538     APInt DemandedElts2 = DemandedElts;
1539     DemandedElts2.clear(IdxNo);
1540     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1541                                       UndefElts, Depth+1);
1542     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543
1544     // The inserted element is defined.
1545     UndefElts.clear(IdxNo);
1546     break;
1547   }
1548   case Instruction::ShuffleVector: {
1549     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1550     uint64_t LHSVWidth =
1551       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1552     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1553     for (unsigned i = 0; i < VWidth; i++) {
1554       if (DemandedElts[i]) {
1555         unsigned MaskVal = Shuffle->getMaskValue(i);
1556         if (MaskVal != -1u) {
1557           assert(MaskVal < LHSVWidth * 2 &&
1558                  "shufflevector mask index out of range!");
1559           if (MaskVal < LHSVWidth)
1560             LeftDemanded.set(MaskVal);
1561           else
1562             RightDemanded.set(MaskVal - LHSVWidth);
1563         }
1564       }
1565     }
1566
1567     APInt UndefElts4(LHSVWidth, 0);
1568     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1569                                       UndefElts4, Depth+1);
1570     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571
1572     APInt UndefElts3(LHSVWidth, 0);
1573     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1574                                       UndefElts3, Depth+1);
1575     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1576
1577     bool NewUndefElts = false;
1578     for (unsigned i = 0; i < VWidth; i++) {
1579       unsigned MaskVal = Shuffle->getMaskValue(i);
1580       if (MaskVal == -1u) {
1581         UndefElts.set(i);
1582       } else if (MaskVal < LHSVWidth) {
1583         if (UndefElts4[MaskVal]) {
1584           NewUndefElts = true;
1585           UndefElts.set(i);
1586         }
1587       } else {
1588         if (UndefElts3[MaskVal - LHSVWidth]) {
1589           NewUndefElts = true;
1590           UndefElts.set(i);
1591         }
1592       }
1593     }
1594
1595     if (NewUndefElts) {
1596       // Add additional discovered undefs.
1597       std::vector<Constant*> Elts;
1598       for (unsigned i = 0; i < VWidth; ++i) {
1599         if (UndefElts[i])
1600           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1601         else
1602           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1603                                           Shuffle->getMaskValue(i)));
1604       }
1605       I->setOperand(2, ConstantVector::get(Elts));
1606       MadeChange = true;
1607     }
1608     break;
1609   }
1610   case Instruction::BitCast: {
1611     // Vector->vector casts only.
1612     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1613     if (!VTy) break;
1614     unsigned InVWidth = VTy->getNumElements();
1615     APInt InputDemandedElts(InVWidth, 0);
1616     unsigned Ratio;
1617
1618     if (VWidth == InVWidth) {
1619       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1620       // elements as are demanded of us.
1621       Ratio = 1;
1622       InputDemandedElts = DemandedElts;
1623     } else if (VWidth > InVWidth) {
1624       // Untested so far.
1625       break;
1626       
1627       // If there are more elements in the result than there are in the source,
1628       // then an input element is live if any of the corresponding output
1629       // elements are live.
1630       Ratio = VWidth/InVWidth;
1631       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1632         if (DemandedElts[OutIdx])
1633           InputDemandedElts.set(OutIdx/Ratio);
1634       }
1635     } else {
1636       // Untested so far.
1637       break;
1638       
1639       // If there are more elements in the source than there are in the result,
1640       // then an input element is live if the corresponding output element is
1641       // live.
1642       Ratio = InVWidth/VWidth;
1643       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1644         if (DemandedElts[InIdx/Ratio])
1645           InputDemandedElts.set(InIdx);
1646     }
1647     
1648     // div/rem demand all inputs, because they don't want divide by zero.
1649     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1650                                       UndefElts2, Depth+1);
1651     if (TmpV) {
1652       I->setOperand(0, TmpV);
1653       MadeChange = true;
1654     }
1655     
1656     UndefElts = UndefElts2;
1657     if (VWidth > InVWidth) {
1658       llvm_unreachable("Unimp");
1659       // If there are more elements in the result than there are in the source,
1660       // then an output element is undef if the corresponding input element is
1661       // undef.
1662       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1663         if (UndefElts2[OutIdx/Ratio])
1664           UndefElts.set(OutIdx);
1665     } else if (VWidth < InVWidth) {
1666       llvm_unreachable("Unimp");
1667       // If there are more elements in the source than there are in the result,
1668       // then a result element is undef if all of the corresponding input
1669       // elements are undef.
1670       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1671       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1672         if (!UndefElts2[InIdx])            // Not undef?
1673           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1674     }
1675     break;
1676   }
1677   case Instruction::And:
1678   case Instruction::Or:
1679   case Instruction::Xor:
1680   case Instruction::Add:
1681   case Instruction::Sub:
1682   case Instruction::Mul:
1683     // div/rem demand all inputs, because they don't want divide by zero.
1684     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1685                                       UndefElts, Depth+1);
1686     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1687     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1688                                       UndefElts2, Depth+1);
1689     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1690       
1691     // Output elements are undefined if both are undefined.  Consider things
1692     // like undef&0.  The result is known zero, not undef.
1693     UndefElts &= UndefElts2;
1694     break;
1695     
1696   case Instruction::Call: {
1697     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1698     if (!II) break;
1699     switch (II->getIntrinsicID()) {
1700     default: break;
1701       
1702     // Binary vector operations that work column-wise.  A dest element is a
1703     // function of the corresponding input elements from the two inputs.
1704     case Intrinsic::x86_sse_sub_ss:
1705     case Intrinsic::x86_sse_mul_ss:
1706     case Intrinsic::x86_sse_min_ss:
1707     case Intrinsic::x86_sse_max_ss:
1708     case Intrinsic::x86_sse2_sub_sd:
1709     case Intrinsic::x86_sse2_mul_sd:
1710     case Intrinsic::x86_sse2_min_sd:
1711     case Intrinsic::x86_sse2_max_sd:
1712       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1713                                         UndefElts, Depth+1);
1714       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1715       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1716                                         UndefElts2, Depth+1);
1717       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1718
1719       // If only the low elt is demanded and this is a scalarizable intrinsic,
1720       // scalarize it now.
1721       if (DemandedElts == 1) {
1722         switch (II->getIntrinsicID()) {
1723         default: break;
1724         case Intrinsic::x86_sse_sub_ss:
1725         case Intrinsic::x86_sse_mul_ss:
1726         case Intrinsic::x86_sse2_sub_sd:
1727         case Intrinsic::x86_sse2_mul_sd:
1728           // TODO: Lower MIN/MAX/ABS/etc
1729           Value *LHS = II->getOperand(1);
1730           Value *RHS = II->getOperand(2);
1731           // Extract the element as scalars.
1732           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1733             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1734           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1735             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1736           
1737           switch (II->getIntrinsicID()) {
1738           default: llvm_unreachable("Case stmts out of sync!");
1739           case Intrinsic::x86_sse_sub_ss:
1740           case Intrinsic::x86_sse2_sub_sd:
1741             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1742                                                         II->getName()), *II);
1743             break;
1744           case Intrinsic::x86_sse_mul_ss:
1745           case Intrinsic::x86_sse2_mul_sd:
1746             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1747                                                          II->getName()), *II);
1748             break;
1749           }
1750           
1751           Instruction *New =
1752             InsertElementInst::Create(
1753               UndefValue::get(II->getType()), TmpV,
1754               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1755           InsertNewInstBefore(New, *II);
1756           return New;
1757         }            
1758       }
1759         
1760       // Output elements are undefined if both are undefined.  Consider things
1761       // like undef&0.  The result is known zero, not undef.
1762       UndefElts &= UndefElts2;
1763       break;
1764     }
1765     break;
1766   }
1767   }
1768   return MadeChange ? I : 0;
1769 }
1770
1771
1772 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1773 /// function is designed to check a chain of associative operators for a
1774 /// potential to apply a certain optimization.  Since the optimization may be
1775 /// applicable if the expression was reassociated, this checks the chain, then
1776 /// reassociates the expression as necessary to expose the optimization
1777 /// opportunity.  This makes use of a special Functor, which must define
1778 /// 'shouldApply' and 'apply' methods.
1779 ///
1780 template<typename Functor>
1781 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1782   unsigned Opcode = Root.getOpcode();
1783   Value *LHS = Root.getOperand(0);
1784
1785   // Quick check, see if the immediate LHS matches...
1786   if (F.shouldApply(LHS))
1787     return F.apply(Root);
1788
1789   // Otherwise, if the LHS is not of the same opcode as the root, return.
1790   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1791   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1792     // Should we apply this transform to the RHS?
1793     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1794
1795     // If not to the RHS, check to see if we should apply to the LHS...
1796     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1797       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1798       ShouldApply = true;
1799     }
1800
1801     // If the functor wants to apply the optimization to the RHS of LHSI,
1802     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1803     if (ShouldApply) {
1804       // Now all of the instructions are in the current basic block, go ahead
1805       // and perform the reassociation.
1806       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1807
1808       // First move the selected RHS to the LHS of the root...
1809       Root.setOperand(0, LHSI->getOperand(1));
1810
1811       // Make what used to be the LHS of the root be the user of the root...
1812       Value *ExtraOperand = TmpLHSI->getOperand(1);
1813       if (&Root == TmpLHSI) {
1814         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1815         return 0;
1816       }
1817       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1818       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1819       BasicBlock::iterator ARI = &Root; ++ARI;
1820       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1821       ARI = Root;
1822
1823       // Now propagate the ExtraOperand down the chain of instructions until we
1824       // get to LHSI.
1825       while (TmpLHSI != LHSI) {
1826         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1827         // Move the instruction to immediately before the chain we are
1828         // constructing to avoid breaking dominance properties.
1829         NextLHSI->moveBefore(ARI);
1830         ARI = NextLHSI;
1831
1832         Value *NextOp = NextLHSI->getOperand(1);
1833         NextLHSI->setOperand(1, ExtraOperand);
1834         TmpLHSI = NextLHSI;
1835         ExtraOperand = NextOp;
1836       }
1837
1838       // Now that the instructions are reassociated, have the functor perform
1839       // the transformation...
1840       return F.apply(Root);
1841     }
1842
1843     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1844   }
1845   return 0;
1846 }
1847
1848 namespace {
1849
1850 // AddRHS - Implements: X + X --> X << 1
1851 struct AddRHS {
1852   Value *RHS;
1853   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1854   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1855   Instruction *apply(BinaryOperator &Add) const {
1856     return BinaryOperator::CreateShl(Add.getOperand(0),
1857                                      ConstantInt::get(Add.getType(), 1));
1858   }
1859 };
1860
1861 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1862 //                 iff C1&C2 == 0
1863 struct AddMaskingAnd {
1864   Constant *C2;
1865   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1866   bool shouldApply(Value *LHS) const {
1867     ConstantInt *C1;
1868     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1869            ConstantExpr::getAnd(C1, C2)->isNullValue();
1870   }
1871   Instruction *apply(BinaryOperator &Add) const {
1872     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1873   }
1874 };
1875
1876 }
1877
1878 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1879                                              InstCombiner *IC) {
1880   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1881     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1882   }
1883
1884   // Figure out if the constant is the left or the right argument.
1885   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1886   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1887
1888   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1889     if (ConstIsRHS)
1890       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1891     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1892   }
1893
1894   Value *Op0 = SO, *Op1 = ConstOperand;
1895   if (!ConstIsRHS)
1896     std::swap(Op0, Op1);
1897   Instruction *New;
1898   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1899     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1900   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1901     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1902                           Op0, Op1, SO->getName()+".cmp");
1903   else {
1904     llvm_unreachable("Unknown binary instruction type!");
1905   }
1906   return IC->InsertNewInstBefore(New, I);
1907 }
1908
1909 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1910 // constant as the other operand, try to fold the binary operator into the
1911 // select arguments.  This also works for Cast instructions, which obviously do
1912 // not have a second operand.
1913 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1914                                      InstCombiner *IC) {
1915   // Don't modify shared select instructions
1916   if (!SI->hasOneUse()) return 0;
1917   Value *TV = SI->getOperand(1);
1918   Value *FV = SI->getOperand(2);
1919
1920   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1921     // Bool selects with constant operands can be folded to logical ops.
1922     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1923
1924     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1925     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1926
1927     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1928                               SelectFalseVal);
1929   }
1930   return 0;
1931 }
1932
1933
1934 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1935 /// node as operand #0, see if we can fold the instruction into the PHI (which
1936 /// is only possible if all operands to the PHI are constants).
1937 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1938   PHINode *PN = cast<PHINode>(I.getOperand(0));
1939   unsigned NumPHIValues = PN->getNumIncomingValues();
1940   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1941
1942   // Check to see if all of the operands of the PHI are constants.  If there is
1943   // one non-constant value, remember the BB it is.  If there is more than one
1944   // or if *it* is a PHI, bail out.
1945   BasicBlock *NonConstBB = 0;
1946   for (unsigned i = 0; i != NumPHIValues; ++i)
1947     if (!isa<Constant>(PN->getIncomingValue(i))) {
1948       if (NonConstBB) return 0;  // More than one non-const value.
1949       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1950       NonConstBB = PN->getIncomingBlock(i);
1951       
1952       // If the incoming non-constant value is in I's block, we have an infinite
1953       // loop.
1954       if (NonConstBB == I.getParent())
1955         return 0;
1956     }
1957   
1958   // If there is exactly one non-constant value, we can insert a copy of the
1959   // operation in that block.  However, if this is a critical edge, we would be
1960   // inserting the computation one some other paths (e.g. inside a loop).  Only
1961   // do this if the pred block is unconditionally branching into the phi block.
1962   if (NonConstBB) {
1963     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1964     if (!BI || !BI->isUnconditional()) return 0;
1965   }
1966
1967   // Okay, we can do the transformation: create the new PHI node.
1968   PHINode *NewPN = PHINode::Create(I.getType(), "");
1969   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1970   InsertNewInstBefore(NewPN, *PN);
1971   NewPN->takeName(PN);
1972
1973   // Next, add all of the operands to the PHI.
1974   if (I.getNumOperands() == 2) {
1975     Constant *C = cast<Constant>(I.getOperand(1));
1976     for (unsigned i = 0; i != NumPHIValues; ++i) {
1977       Value *InV = 0;
1978       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1979         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1980           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1981         else
1982           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1983       } else {
1984         assert(PN->getIncomingBlock(i) == NonConstBB);
1985         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1986           InV = BinaryOperator::Create(BO->getOpcode(),
1987                                        PN->getIncomingValue(i), C, "phitmp",
1988                                        NonConstBB->getTerminator());
1989         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1990           InV = CmpInst::Create(CI->getOpcode(),
1991                                 CI->getPredicate(),
1992                                 PN->getIncomingValue(i), C, "phitmp",
1993                                 NonConstBB->getTerminator());
1994         else
1995           llvm_unreachable("Unknown binop!");
1996         
1997         Worklist.Add(cast<Instruction>(InV));
1998       }
1999       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2000     }
2001   } else { 
2002     CastInst *CI = cast<CastInst>(&I);
2003     const Type *RetTy = CI->getType();
2004     for (unsigned i = 0; i != NumPHIValues; ++i) {
2005       Value *InV;
2006       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2007         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2008       } else {
2009         assert(PN->getIncomingBlock(i) == NonConstBB);
2010         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2011                                I.getType(), "phitmp", 
2012                                NonConstBB->getTerminator());
2013         Worklist.Add(cast<Instruction>(InV));
2014       }
2015       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2016     }
2017   }
2018   return ReplaceInstUsesWith(I, NewPN);
2019 }
2020
2021
2022 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2023 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2024 /// This basically requires proving that the add in the original type would not
2025 /// overflow to change the sign bit or have a carry out.
2026 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2027   // There are different heuristics we can use for this.  Here are some simple
2028   // ones.
2029   
2030   // Add has the property that adding any two 2's complement numbers can only 
2031   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2032   // have at least two sign bits, we know that the addition of the two values will
2033   // sign extend fine.
2034   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2035     return true;
2036   
2037   
2038   // If one of the operands only has one non-zero bit, and if the other operand
2039   // has a known-zero bit in a more significant place than it (not including the
2040   // sign bit) the ripple may go up to and fill the zero, but won't change the
2041   // sign.  For example, (X & ~4) + 1.
2042   
2043   // TODO: Implement.
2044   
2045   return false;
2046 }
2047
2048
2049 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2050   bool Changed = SimplifyCommutative(I);
2051   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2052
2053   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2054     // X + undef -> undef
2055     if (isa<UndefValue>(RHS))
2056       return ReplaceInstUsesWith(I, RHS);
2057
2058     // X + 0 --> X
2059     if (RHSC->isNullValue())
2060       return ReplaceInstUsesWith(I, LHS);
2061
2062     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2063       // X + (signbit) --> X ^ signbit
2064       const APInt& Val = CI->getValue();
2065       uint32_t BitWidth = Val.getBitWidth();
2066       if (Val == APInt::getSignBit(BitWidth))
2067         return BinaryOperator::CreateXor(LHS, RHS);
2068       
2069       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2070       // (X & 254)+1 -> (X&254)|1
2071       if (SimplifyDemandedInstructionBits(I))
2072         return &I;
2073
2074       // zext(bool) + C -> bool ? C + 1 : C
2075       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2076         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2077           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2078     }
2079
2080     if (isa<PHINode>(LHS))
2081       if (Instruction *NV = FoldOpIntoPhi(I))
2082         return NV;
2083     
2084     ConstantInt *XorRHS = 0;
2085     Value *XorLHS = 0;
2086     if (isa<ConstantInt>(RHSC) &&
2087         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2088       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2089       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2090       
2091       uint32_t Size = TySizeBits / 2;
2092       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2093       APInt CFF80Val(-C0080Val);
2094       do {
2095         if (TySizeBits > Size) {
2096           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2097           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2098           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2099               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2100             // This is a sign extend if the top bits are known zero.
2101             if (!MaskedValueIsZero(XorLHS, 
2102                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2103               Size = 0;  // Not a sign ext, but can't be any others either.
2104             break;
2105           }
2106         }
2107         Size >>= 1;
2108         C0080Val = APIntOps::lshr(C0080Val, Size);
2109         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2110       } while (Size >= 1);
2111       
2112       // FIXME: This shouldn't be necessary. When the backends can handle types
2113       // with funny bit widths then this switch statement should be removed. It
2114       // is just here to get the size of the "middle" type back up to something
2115       // that the back ends can handle.
2116       const Type *MiddleType = 0;
2117       switch (Size) {
2118         default: break;
2119         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2120         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2121         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2122       }
2123       if (MiddleType) {
2124         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2125         InsertNewInstBefore(NewTrunc, I);
2126         return new SExtInst(NewTrunc, I.getType(), I.getName());
2127       }
2128     }
2129   }
2130
2131   if (I.getType() == Type::getInt1Ty(*Context))
2132     return BinaryOperator::CreateXor(LHS, RHS);
2133
2134   // X + X --> X << 1
2135   if (I.getType()->isInteger()) {
2136     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2137       return Result;
2138
2139     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2140       if (RHSI->getOpcode() == Instruction::Sub)
2141         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2142           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2143     }
2144     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2145       if (LHSI->getOpcode() == Instruction::Sub)
2146         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2147           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2148     }
2149   }
2150
2151   // -A + B  -->  B - A
2152   // -A + -B  -->  -(A + B)
2153   if (Value *LHSV = dyn_castNegVal(LHS)) {
2154     if (LHS->getType()->isIntOrIntVector()) {
2155       if (Value *RHSV = dyn_castNegVal(RHS)) {
2156         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2157         InsertNewInstBefore(NewAdd, I);
2158         return BinaryOperator::CreateNeg(NewAdd);
2159       }
2160     }
2161     
2162     return BinaryOperator::CreateSub(RHS, LHSV);
2163   }
2164
2165   // A + -B  -->  A - B
2166   if (!isa<Constant>(RHS))
2167     if (Value *V = dyn_castNegVal(RHS))
2168       return BinaryOperator::CreateSub(LHS, V);
2169
2170
2171   ConstantInt *C2;
2172   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2173     if (X == RHS)   // X*C + X --> X * (C+1)
2174       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2175
2176     // X*C1 + X*C2 --> X * (C1+C2)
2177     ConstantInt *C1;
2178     if (X == dyn_castFoldableMul(RHS, C1))
2179       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2180   }
2181
2182   // X + X*C --> X * (C+1)
2183   if (dyn_castFoldableMul(RHS, C2) == LHS)
2184     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2185
2186   // X + ~X --> -1   since   ~X = -X-1
2187   if (dyn_castNotVal(LHS) == RHS ||
2188       dyn_castNotVal(RHS) == LHS)
2189     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2190   
2191
2192   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2193   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2194     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2195       return R;
2196   
2197   // A+B --> A|B iff A and B have no bits set in common.
2198   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2199     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2200     APInt LHSKnownOne(IT->getBitWidth(), 0);
2201     APInt LHSKnownZero(IT->getBitWidth(), 0);
2202     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2203     if (LHSKnownZero != 0) {
2204       APInt RHSKnownOne(IT->getBitWidth(), 0);
2205       APInt RHSKnownZero(IT->getBitWidth(), 0);
2206       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2207       
2208       // No bits in common -> bitwise or.
2209       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2210         return BinaryOperator::CreateOr(LHS, RHS);
2211     }
2212   }
2213
2214   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2215   if (I.getType()->isIntOrIntVector()) {
2216     Value *W, *X, *Y, *Z;
2217     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2218         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2219       if (W != Y) {
2220         if (W == Z) {
2221           std::swap(Y, Z);
2222         } else if (Y == X) {
2223           std::swap(W, X);
2224         } else if (X == Z) {
2225           std::swap(Y, Z);
2226           std::swap(W, X);
2227         }
2228       }
2229
2230       if (W == Y) {
2231         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2232                                                             LHS->getName()), I);
2233         return BinaryOperator::CreateMul(W, NewAdd);
2234       }
2235     }
2236   }
2237
2238   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2239     Value *X = 0;
2240     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2241       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2242
2243     // (X & FF00) + xx00  -> (X+xx00) & FF00
2244     if (LHS->hasOneUse() &&
2245         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2246       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2247       if (Anded == CRHS) {
2248         // See if all bits from the first bit set in the Add RHS up are included
2249         // in the mask.  First, get the rightmost bit.
2250         const APInt& AddRHSV = CRHS->getValue();
2251
2252         // Form a mask of all bits from the lowest bit added through the top.
2253         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2254
2255         // See if the and mask includes all of these bits.
2256         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2257
2258         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2259           // Okay, the xform is safe.  Insert the new add pronto.
2260           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2261                                                             LHS->getName()), I);
2262           return BinaryOperator::CreateAnd(NewAdd, C2);
2263         }
2264       }
2265     }
2266
2267     // Try to fold constant add into select arguments.
2268     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2269       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2270         return R;
2271   }
2272
2273   // add (select X 0 (sub n A)) A  -->  select X A n
2274   {
2275     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2276     Value *A = RHS;
2277     if (!SI) {
2278       SI = dyn_cast<SelectInst>(RHS);
2279       A = LHS;
2280     }
2281     if (SI && SI->hasOneUse()) {
2282       Value *TV = SI->getTrueValue();
2283       Value *FV = SI->getFalseValue();
2284       Value *N;
2285
2286       // Can we fold the add into the argument of the select?
2287       // We check both true and false select arguments for a matching subtract.
2288       if (match(FV, m_Zero()) &&
2289           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2290         // Fold the add into the true select value.
2291         return SelectInst::Create(SI->getCondition(), N, A);
2292       if (match(TV, m_Zero()) &&
2293           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2294         // Fold the add into the false select value.
2295         return SelectInst::Create(SI->getCondition(), A, N);
2296     }
2297   }
2298
2299   // Check for (add (sext x), y), see if we can merge this into an
2300   // integer add followed by a sext.
2301   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2302     // (add (sext x), cst) --> (sext (add x, cst'))
2303     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2304       Constant *CI = 
2305         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2306       if (LHSConv->hasOneUse() &&
2307           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2308           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2309         // Insert the new, smaller add.
2310         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2311                                                         CI, "addconv");
2312         InsertNewInstBefore(NewAdd, I);
2313         return new SExtInst(NewAdd, I.getType());
2314       }
2315     }
2316     
2317     // (add (sext x), (sext y)) --> (sext (add int x, y))
2318     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2319       // Only do this if x/y have the same type, if at last one of them has a
2320       // single use (so we don't increase the number of sexts), and if the
2321       // integer add will not overflow.
2322       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2323           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2324           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2325                                    RHSConv->getOperand(0))) {
2326         // Insert the new integer add.
2327         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2328                                                         RHSConv->getOperand(0),
2329                                                         "addconv");
2330         InsertNewInstBefore(NewAdd, I);
2331         return new SExtInst(NewAdd, I.getType());
2332       }
2333     }
2334   }
2335
2336   return Changed ? &I : 0;
2337 }
2338
2339 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2340   bool Changed = SimplifyCommutative(I);
2341   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2342
2343   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2344     // X + 0 --> X
2345     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2346       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2347                               (I.getType())->getValueAPF()))
2348         return ReplaceInstUsesWith(I, LHS);
2349     }
2350
2351     if (isa<PHINode>(LHS))
2352       if (Instruction *NV = FoldOpIntoPhi(I))
2353         return NV;
2354   }
2355
2356   // -A + B  -->  B - A
2357   // -A + -B  -->  -(A + B)
2358   if (Value *LHSV = dyn_castFNegVal(LHS))
2359     return BinaryOperator::CreateFSub(RHS, LHSV);
2360
2361   // A + -B  -->  A - B
2362   if (!isa<Constant>(RHS))
2363     if (Value *V = dyn_castFNegVal(RHS))
2364       return BinaryOperator::CreateFSub(LHS, V);
2365
2366   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2367   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2368     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2369       return ReplaceInstUsesWith(I, LHS);
2370
2371   // Check for (add double (sitofp x), y), see if we can merge this into an
2372   // integer add followed by a promotion.
2373   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2374     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2375     // ... if the constant fits in the integer value.  This is useful for things
2376     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2377     // requires a constant pool load, and generally allows the add to be better
2378     // instcombined.
2379     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2380       Constant *CI = 
2381       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2382       if (LHSConv->hasOneUse() &&
2383           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2384           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2385         // Insert the new integer add.
2386         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2387                                                         CI, "addconv");
2388         InsertNewInstBefore(NewAdd, I);
2389         return new SIToFPInst(NewAdd, I.getType());
2390       }
2391     }
2392     
2393     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2394     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2395       // Only do this if x/y have the same type, if at last one of them has a
2396       // single use (so we don't increase the number of int->fp conversions),
2397       // and if the integer add will not overflow.
2398       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2399           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2400           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2401                                    RHSConv->getOperand(0))) {
2402         // Insert the new integer add.
2403         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2404                                                         RHSConv->getOperand(0),
2405                                                         "addconv");
2406         InsertNewInstBefore(NewAdd, I);
2407         return new SIToFPInst(NewAdd, I.getType());
2408       }
2409     }
2410   }
2411   
2412   return Changed ? &I : 0;
2413 }
2414
2415 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2416   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2417
2418   if (Op0 == Op1)                        // sub X, X  -> 0
2419     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2420
2421   // If this is a 'B = x-(-A)', change to B = x+A...
2422   if (Value *V = dyn_castNegVal(Op1))
2423     return BinaryOperator::CreateAdd(Op0, V);
2424
2425   if (isa<UndefValue>(Op0))
2426     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2427   if (isa<UndefValue>(Op1))
2428     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2429
2430   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2431     // Replace (-1 - A) with (~A)...
2432     if (C->isAllOnesValue())
2433       return BinaryOperator::CreateNot(Op1);
2434
2435     // C - ~X == X + (1+C)
2436     Value *X = 0;
2437     if (match(Op1, m_Not(m_Value(X))))
2438       return BinaryOperator::CreateAdd(X, AddOne(C));
2439
2440     // -(X >>u 31) -> (X >>s 31)
2441     // -(X >>s 31) -> (X >>u 31)
2442     if (C->isZero()) {
2443       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2444         if (SI->getOpcode() == Instruction::LShr) {
2445           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2446             // Check to see if we are shifting out everything but the sign bit.
2447             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2448                 SI->getType()->getPrimitiveSizeInBits()-1) {
2449               // Ok, the transformation is safe.  Insert AShr.
2450               return BinaryOperator::Create(Instruction::AShr, 
2451                                           SI->getOperand(0), CU, SI->getName());
2452             }
2453           }
2454         }
2455         else if (SI->getOpcode() == Instruction::AShr) {
2456           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2457             // Check to see if we are shifting out everything but the sign bit.
2458             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2459                 SI->getType()->getPrimitiveSizeInBits()-1) {
2460               // Ok, the transformation is safe.  Insert LShr. 
2461               return BinaryOperator::CreateLShr(
2462                                           SI->getOperand(0), CU, SI->getName());
2463             }
2464           }
2465         }
2466       }
2467     }
2468
2469     // Try to fold constant sub into select arguments.
2470     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2471       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2472         return R;
2473
2474     // C - zext(bool) -> bool ? C - 1 : C
2475     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2476       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2477         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2478   }
2479
2480   if (I.getType() == Type::getInt1Ty(*Context))
2481     return BinaryOperator::CreateXor(Op0, Op1);
2482
2483   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2484     if (Op1I->getOpcode() == Instruction::Add) {
2485       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2486         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2487                                          I.getName());
2488       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2489         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2490                                          I.getName());
2491       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2492         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2493           // C1-(X+C2) --> (C1-C2)-X
2494           return BinaryOperator::CreateSub(
2495             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2496       }
2497     }
2498
2499     if (Op1I->hasOneUse()) {
2500       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2501       // is not used by anyone else...
2502       //
2503       if (Op1I->getOpcode() == Instruction::Sub) {
2504         // Swap the two operands of the subexpr...
2505         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2506         Op1I->setOperand(0, IIOp1);
2507         Op1I->setOperand(1, IIOp0);
2508
2509         // Create the new top level add instruction...
2510         return BinaryOperator::CreateAdd(Op0, Op1);
2511       }
2512
2513       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2514       //
2515       if (Op1I->getOpcode() == Instruction::And &&
2516           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2517         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2518
2519         Value *NewNot =
2520           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2521         return BinaryOperator::CreateAnd(Op0, NewNot);
2522       }
2523
2524       // 0 - (X sdiv C)  -> (X sdiv -C)
2525       if (Op1I->getOpcode() == Instruction::SDiv)
2526         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2527           if (CSI->isZero())
2528             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2529               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2530                                           ConstantExpr::getNeg(DivRHS));
2531
2532       // X - X*C --> X * (1-C)
2533       ConstantInt *C2 = 0;
2534       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2535         Constant *CP1 = 
2536           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2537                                              C2);
2538         return BinaryOperator::CreateMul(Op0, CP1);
2539       }
2540     }
2541   }
2542
2543   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2544     if (Op0I->getOpcode() == Instruction::Add) {
2545       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2546         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2547       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2548         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2549     } else if (Op0I->getOpcode() == Instruction::Sub) {
2550       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2551         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2552                                          I.getName());
2553     }
2554   }
2555
2556   ConstantInt *C1;
2557   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2558     if (X == Op1)  // X*C - X --> X * (C-1)
2559       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2560
2561     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2562     if (X == dyn_castFoldableMul(Op1, C2))
2563       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2564   }
2565   return 0;
2566 }
2567
2568 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2569   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2570
2571   // If this is a 'B = x-(-A)', change to B = x+A...
2572   if (Value *V = dyn_castFNegVal(Op1))
2573     return BinaryOperator::CreateFAdd(Op0, V);
2574
2575   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2576     if (Op1I->getOpcode() == Instruction::FAdd) {
2577       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2578         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2579                                           I.getName());
2580       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2581         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2582                                           I.getName());
2583     }
2584   }
2585
2586   return 0;
2587 }
2588
2589 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2590 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2591 /// TrueIfSigned if the result of the comparison is true when the input value is
2592 /// signed.
2593 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2594                            bool &TrueIfSigned) {
2595   switch (pred) {
2596   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2597     TrueIfSigned = true;
2598     return RHS->isZero();
2599   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2600     TrueIfSigned = true;
2601     return RHS->isAllOnesValue();
2602   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2603     TrueIfSigned = false;
2604     return RHS->isAllOnesValue();
2605   case ICmpInst::ICMP_UGT:
2606     // True if LHS u> RHS and RHS == high-bit-mask - 1
2607     TrueIfSigned = true;
2608     return RHS->getValue() ==
2609       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2610   case ICmpInst::ICMP_UGE: 
2611     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2612     TrueIfSigned = true;
2613     return RHS->getValue().isSignBit();
2614   default:
2615     return false;
2616   }
2617 }
2618
2619 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2620   bool Changed = SimplifyCommutative(I);
2621   Value *Op0 = I.getOperand(0);
2622
2623   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2624     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2625
2626   // Simplify mul instructions with a constant RHS...
2627   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2628     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2629
2630       // ((X << C1)*C2) == (X * (C2 << C1))
2631       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2632         if (SI->getOpcode() == Instruction::Shl)
2633           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2634             return BinaryOperator::CreateMul(SI->getOperand(0),
2635                                         ConstantExpr::getShl(CI, ShOp));
2636
2637       if (CI->isZero())
2638         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2639       if (CI->equalsInt(1))                  // X * 1  == X
2640         return ReplaceInstUsesWith(I, Op0);
2641       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2642         return BinaryOperator::CreateNeg(Op0, I.getName());
2643
2644       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2645       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2646         return BinaryOperator::CreateShl(Op0,
2647                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2648       }
2649     } else if (isa<VectorType>(Op1->getType())) {
2650       if (Op1->isNullValue())
2651         return ReplaceInstUsesWith(I, Op1);
2652
2653       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2654         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2655           return BinaryOperator::CreateNeg(Op0, I.getName());
2656
2657         // As above, vector X*splat(1.0) -> X in all defined cases.
2658         if (Constant *Splat = Op1V->getSplatValue()) {
2659           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2660             if (CI->equalsInt(1))
2661               return ReplaceInstUsesWith(I, Op0);
2662         }
2663       }
2664     }
2665     
2666     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2667       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2668           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2669         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2670         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2671                                                      Op1, "tmp");
2672         InsertNewInstBefore(Add, I);
2673         Value *C1C2 = ConstantExpr::getMul(Op1, 
2674                                            cast<Constant>(Op0I->getOperand(1)));
2675         return BinaryOperator::CreateAdd(Add, C1C2);
2676         
2677       }
2678
2679     // Try to fold constant mul into select arguments.
2680     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2681       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2682         return R;
2683
2684     if (isa<PHINode>(Op0))
2685       if (Instruction *NV = FoldOpIntoPhi(I))
2686         return NV;
2687   }
2688
2689   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2690     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2691       return BinaryOperator::CreateMul(Op0v, Op1v);
2692
2693   // (X / Y) *  Y = X - (X % Y)
2694   // (X / Y) * -Y = (X % Y) - X
2695   {
2696     Value *Op1 = I.getOperand(1);
2697     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2698     if (!BO ||
2699         (BO->getOpcode() != Instruction::UDiv && 
2700          BO->getOpcode() != Instruction::SDiv)) {
2701       Op1 = Op0;
2702       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2703     }
2704     Value *Neg = dyn_castNegVal(Op1);
2705     if (BO && BO->hasOneUse() &&
2706         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2707         (BO->getOpcode() == Instruction::UDiv ||
2708          BO->getOpcode() == Instruction::SDiv)) {
2709       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2710
2711       // If the division is exact, X % Y is zero.
2712       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2713         if (SDiv->isExact()) {
2714           if (Op1BO == Op1)
2715             return ReplaceInstUsesWith(I, Op0BO);
2716           else
2717             return BinaryOperator::CreateNeg(Op0BO);
2718         }
2719
2720       Instruction *Rem;
2721       if (BO->getOpcode() == Instruction::UDiv)
2722         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2723       else
2724         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2725
2726       InsertNewInstBefore(Rem, I);
2727       Rem->takeName(BO);
2728
2729       if (Op1BO == Op1)
2730         return BinaryOperator::CreateSub(Op0BO, Rem);
2731       else
2732         return BinaryOperator::CreateSub(Rem, Op0BO);
2733     }
2734   }
2735
2736   if (I.getType() == Type::getInt1Ty(*Context))
2737     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2738
2739   // If one of the operands of the multiply is a cast from a boolean value, then
2740   // we know the bool is either zero or one, so this is a 'masking' multiply.
2741   // See if we can simplify things based on how the boolean was originally
2742   // formed.
2743   CastInst *BoolCast = 0;
2744   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2745     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2746       BoolCast = CI;
2747   if (!BoolCast)
2748     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2749       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2750         BoolCast = CI;
2751   if (BoolCast) {
2752     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2753       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2754       const Type *SCOpTy = SCIOp0->getType();
2755       bool TIS = false;
2756       
2757       // If the icmp is true iff the sign bit of X is set, then convert this
2758       // multiply into a shift/and combination.
2759       if (isa<ConstantInt>(SCIOp1) &&
2760           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2761           TIS) {
2762         // Shift the X value right to turn it into "all signbits".
2763         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2764                                           SCOpTy->getPrimitiveSizeInBits()-1);
2765         Value *V =
2766           InsertNewInstBefore(
2767             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2768                                             BoolCast->getOperand(0)->getName()+
2769                                             ".mask"), I);
2770
2771         // If the multiply type is not the same as the source type, sign extend
2772         // or truncate to the multiply type.
2773         if (I.getType() != V->getType()) {
2774           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2775           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2776           Instruction::CastOps opcode = 
2777             (SrcBits == DstBits ? Instruction::BitCast : 
2778              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2779           V = InsertCastBefore(opcode, V, I.getType(), I);
2780         }
2781
2782         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2783         return BinaryOperator::CreateAnd(V, OtherOp);
2784       }
2785     }
2786   }
2787
2788   return Changed ? &I : 0;
2789 }
2790
2791 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2792   bool Changed = SimplifyCommutative(I);
2793   Value *Op0 = I.getOperand(0);
2794
2795   // Simplify mul instructions with a constant RHS...
2796   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2797     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2798       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2799       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2800       if (Op1F->isExactlyValue(1.0))
2801         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2802     } else if (isa<VectorType>(Op1->getType())) {
2803       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2804         // As above, vector X*splat(1.0) -> X in all defined cases.
2805         if (Constant *Splat = Op1V->getSplatValue()) {
2806           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2807             if (F->isExactlyValue(1.0))
2808               return ReplaceInstUsesWith(I, Op0);
2809         }
2810       }
2811     }
2812
2813     // Try to fold constant mul into select arguments.
2814     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2815       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2816         return R;
2817
2818     if (isa<PHINode>(Op0))
2819       if (Instruction *NV = FoldOpIntoPhi(I))
2820         return NV;
2821   }
2822
2823   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2824     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2825       return BinaryOperator::CreateFMul(Op0v, Op1v);
2826
2827   return Changed ? &I : 0;
2828 }
2829
2830 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2831 /// instruction.
2832 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2833   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2834   
2835   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2836   int NonNullOperand = -1;
2837   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2838     if (ST->isNullValue())
2839       NonNullOperand = 2;
2840   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2841   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2842     if (ST->isNullValue())
2843       NonNullOperand = 1;
2844   
2845   if (NonNullOperand == -1)
2846     return false;
2847   
2848   Value *SelectCond = SI->getOperand(0);
2849   
2850   // Change the div/rem to use 'Y' instead of the select.
2851   I.setOperand(1, SI->getOperand(NonNullOperand));
2852   
2853   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2854   // problem.  However, the select, or the condition of the select may have
2855   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2856   // propagate the known value for the select into other uses of it, and
2857   // propagate a known value of the condition into its other users.
2858   
2859   // If the select and condition only have a single use, don't bother with this,
2860   // early exit.
2861   if (SI->use_empty() && SelectCond->hasOneUse())
2862     return true;
2863   
2864   // Scan the current block backward, looking for other uses of SI.
2865   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2866   
2867   while (BBI != BBFront) {
2868     --BBI;
2869     // If we found a call to a function, we can't assume it will return, so
2870     // information from below it cannot be propagated above it.
2871     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2872       break;
2873     
2874     // Replace uses of the select or its condition with the known values.
2875     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2876          I != E; ++I) {
2877       if (*I == SI) {
2878         *I = SI->getOperand(NonNullOperand);
2879         Worklist.Add(BBI);
2880       } else if (*I == SelectCond) {
2881         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2882                                    ConstantInt::getFalse(*Context);
2883         Worklist.Add(BBI);
2884       }
2885     }
2886     
2887     // If we past the instruction, quit looking for it.
2888     if (&*BBI == SI)
2889       SI = 0;
2890     if (&*BBI == SelectCond)
2891       SelectCond = 0;
2892     
2893     // If we ran out of things to eliminate, break out of the loop.
2894     if (SelectCond == 0 && SI == 0)
2895       break;
2896     
2897   }
2898   return true;
2899 }
2900
2901
2902 /// This function implements the transforms on div instructions that work
2903 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2904 /// used by the visitors to those instructions.
2905 /// @brief Transforms common to all three div instructions
2906 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2907   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2908
2909   // undef / X -> 0        for integer.
2910   // undef / X -> undef    for FP (the undef could be a snan).
2911   if (isa<UndefValue>(Op0)) {
2912     if (Op0->getType()->isFPOrFPVector())
2913       return ReplaceInstUsesWith(I, Op0);
2914     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2915   }
2916
2917   // X / undef -> undef
2918   if (isa<UndefValue>(Op1))
2919     return ReplaceInstUsesWith(I, Op1);
2920
2921   return 0;
2922 }
2923
2924 /// This function implements the transforms common to both integer division
2925 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2926 /// division instructions.
2927 /// @brief Common integer divide transforms
2928 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2929   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2930
2931   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2932   if (Op0 == Op1) {
2933     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2934       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2935       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2936       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2937     }
2938
2939     Constant *CI = ConstantInt::get(I.getType(), 1);
2940     return ReplaceInstUsesWith(I, CI);
2941   }
2942   
2943   if (Instruction *Common = commonDivTransforms(I))
2944     return Common;
2945   
2946   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2947   // This does not apply for fdiv.
2948   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2949     return &I;
2950
2951   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2952     // div X, 1 == X
2953     if (RHS->equalsInt(1))
2954       return ReplaceInstUsesWith(I, Op0);
2955
2956     // (X / C1) / C2  -> X / (C1*C2)
2957     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2958       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2959         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2960           if (MultiplyOverflows(RHS, LHSRHS,
2961                                 I.getOpcode()==Instruction::SDiv))
2962             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2963           else 
2964             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2965                                       ConstantExpr::getMul(RHS, LHSRHS));
2966         }
2967
2968     if (!RHS->isZero()) { // avoid X udiv 0
2969       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2970         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2971           return R;
2972       if (isa<PHINode>(Op0))
2973         if (Instruction *NV = FoldOpIntoPhi(I))
2974           return NV;
2975     }
2976   }
2977
2978   // 0 / X == 0, we don't need to preserve faults!
2979   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2980     if (LHS->equalsInt(0))
2981       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2982
2983   // It can't be division by zero, hence it must be division by one.
2984   if (I.getType() == Type::getInt1Ty(*Context))
2985     return ReplaceInstUsesWith(I, Op0);
2986
2987   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2988     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2989       // div X, 1 == X
2990       if (X->isOne())
2991         return ReplaceInstUsesWith(I, Op0);
2992   }
2993
2994   return 0;
2995 }
2996
2997 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2998   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2999
3000   // Handle the integer div common cases
3001   if (Instruction *Common = commonIDivTransforms(I))
3002     return Common;
3003
3004   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3005     // X udiv C^2 -> X >> C
3006     // Check to see if this is an unsigned division with an exact power of 2,
3007     // if so, convert to a right shift.
3008     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3009       return BinaryOperator::CreateLShr(Op0, 
3010             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3011
3012     // X udiv C, where C >= signbit
3013     if (C->getValue().isNegative()) {
3014       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3015                                       I);
3016       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3017                                 ConstantInt::get(I.getType(), 1));
3018     }
3019   }
3020
3021   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3022   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3023     if (RHSI->getOpcode() == Instruction::Shl &&
3024         isa<ConstantInt>(RHSI->getOperand(0))) {
3025       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3026       if (C1.isPowerOf2()) {
3027         Value *N = RHSI->getOperand(1);
3028         const Type *NTy = N->getType();
3029         if (uint32_t C2 = C1.logBase2()) {
3030           Constant *C2V = ConstantInt::get(NTy, C2);
3031           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3032         }
3033         return BinaryOperator::CreateLShr(Op0, N);
3034       }
3035     }
3036   }
3037   
3038   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3039   // where C1&C2 are powers of two.
3040   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3041     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3042       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3043         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3044         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3045           // Compute the shift amounts
3046           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3047           // Construct the "on true" case of the select
3048           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3049           Instruction *TSI = BinaryOperator::CreateLShr(
3050                                                  Op0, TC, SI->getName()+".t");
3051           TSI = InsertNewInstBefore(TSI, I);
3052   
3053           // Construct the "on false" case of the select
3054           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3055           Instruction *FSI = BinaryOperator::CreateLShr(
3056                                                  Op0, FC, SI->getName()+".f");
3057           FSI = InsertNewInstBefore(FSI, I);
3058
3059           // construct the select instruction and return it.
3060           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3061         }
3062       }
3063   return 0;
3064 }
3065
3066 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3067   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3068
3069   // Handle the integer div common cases
3070   if (Instruction *Common = commonIDivTransforms(I))
3071     return Common;
3072
3073   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3074     // sdiv X, -1 == -X
3075     if (RHS->isAllOnesValue())
3076       return BinaryOperator::CreateNeg(Op0);
3077
3078     // sdiv X, C  -->  ashr X, log2(C)
3079     if (cast<SDivOperator>(&I)->isExact() &&
3080         RHS->getValue().isNonNegative() &&
3081         RHS->getValue().isPowerOf2()) {
3082       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3083                                             RHS->getValue().exactLogBase2());
3084       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3085     }
3086
3087     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3088     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3089       if (isa<Constant>(Sub->getOperand(0)) &&
3090           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3091           Sub->hasNoSignedWrap())
3092         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3093                                           ConstantExpr::getNeg(RHS));
3094   }
3095
3096   // If the sign bits of both operands are zero (i.e. we can prove they are
3097   // unsigned inputs), turn this into a udiv.
3098   if (I.getType()->isInteger()) {
3099     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3100     if (MaskedValueIsZero(Op0, Mask)) {
3101       if (MaskedValueIsZero(Op1, Mask)) {
3102         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3103         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3104       }
3105       ConstantInt *ShiftedInt;
3106       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3107           ShiftedInt->getValue().isPowerOf2()) {
3108         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3109         // Safe because the only negative value (1 << Y) can take on is
3110         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3111         // the sign bit set.
3112         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3113       }
3114     }
3115   }
3116   
3117   return 0;
3118 }
3119
3120 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3121   return commonDivTransforms(I);
3122 }
3123
3124 /// This function implements the transforms on rem instructions that work
3125 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3126 /// is used by the visitors to those instructions.
3127 /// @brief Transforms common to all three rem instructions
3128 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3129   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3130
3131   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3132     if (I.getType()->isFPOrFPVector())
3133       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3134     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3135   }
3136   if (isa<UndefValue>(Op1))
3137     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3138
3139   // Handle cases involving: rem X, (select Cond, Y, Z)
3140   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3141     return &I;
3142
3143   return 0;
3144 }
3145
3146 /// This function implements the transforms common to both integer remainder
3147 /// instructions (urem and srem). It is called by the visitors to those integer
3148 /// remainder instructions.
3149 /// @brief Common integer remainder transforms
3150 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3151   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3152
3153   if (Instruction *common = commonRemTransforms(I))
3154     return common;
3155
3156   // 0 % X == 0 for integer, we don't need to preserve faults!
3157   if (Constant *LHS = dyn_cast<Constant>(Op0))
3158     if (LHS->isNullValue())
3159       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3160
3161   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3162     // X % 0 == undef, we don't need to preserve faults!
3163     if (RHS->equalsInt(0))
3164       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3165     
3166     if (RHS->equalsInt(1))  // X % 1 == 0
3167       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3168
3169     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3170       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3171         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3172           return R;
3173       } else if (isa<PHINode>(Op0I)) {
3174         if (Instruction *NV = FoldOpIntoPhi(I))
3175           return NV;
3176       }
3177
3178       // See if we can fold away this rem instruction.
3179       if (SimplifyDemandedInstructionBits(I))
3180         return &I;
3181     }
3182   }
3183
3184   return 0;
3185 }
3186
3187 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3188   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3189
3190   if (Instruction *common = commonIRemTransforms(I))
3191     return common;
3192   
3193   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3194     // X urem C^2 -> X and C
3195     // Check to see if this is an unsigned remainder with an exact power of 2,
3196     // if so, convert to a bitwise and.
3197     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3198       if (C->getValue().isPowerOf2())
3199         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3200   }
3201
3202   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3203     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3204     if (RHSI->getOpcode() == Instruction::Shl &&
3205         isa<ConstantInt>(RHSI->getOperand(0))) {
3206       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3207         Constant *N1 = Constant::getAllOnesValue(I.getType());
3208         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3209                                                                    "tmp"), I);
3210         return BinaryOperator::CreateAnd(Op0, Add);
3211       }
3212     }
3213   }
3214
3215   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3216   // where C1&C2 are powers of two.
3217   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3218     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3219       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3220         // STO == 0 and SFO == 0 handled above.
3221         if ((STO->getValue().isPowerOf2()) && 
3222             (SFO->getValue().isPowerOf2())) {
3223           Value *TrueAnd = InsertNewInstBefore(
3224             BinaryOperator::CreateAnd(Op0, SubOne(STO),
3225                                       SI->getName()+".t"), I);
3226           Value *FalseAnd = InsertNewInstBefore(
3227             BinaryOperator::CreateAnd(Op0, SubOne(SFO),
3228                                       SI->getName()+".f"), I);
3229           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3230         }
3231       }
3232   }
3233   
3234   return 0;
3235 }
3236
3237 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3238   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3239
3240   // Handle the integer rem common cases
3241   if (Instruction *Common = commonIRemTransforms(I))
3242     return Common;
3243   
3244   if (Value *RHSNeg = dyn_castNegVal(Op1))
3245     if (!isa<Constant>(RHSNeg) ||
3246         (isa<ConstantInt>(RHSNeg) &&
3247          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3248       // X % -Y -> X % Y
3249       Worklist.AddValue(I.getOperand(1));
3250       I.setOperand(1, RHSNeg);
3251       return &I;
3252     }
3253
3254   // If the sign bits of both operands are zero (i.e. we can prove they are
3255   // unsigned inputs), turn this into a urem.
3256   if (I.getType()->isInteger()) {
3257     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3258     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3259       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3260       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3261     }
3262   }
3263
3264   // If it's a constant vector, flip any negative values positive.
3265   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3266     unsigned VWidth = RHSV->getNumOperands();
3267
3268     bool hasNegative = false;
3269     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3270       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3271         if (RHS->getValue().isNegative())
3272           hasNegative = true;
3273
3274     if (hasNegative) {
3275       std::vector<Constant *> Elts(VWidth);
3276       for (unsigned i = 0; i != VWidth; ++i) {
3277         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3278           if (RHS->getValue().isNegative())
3279             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3280           else
3281             Elts[i] = RHS;
3282         }
3283       }
3284
3285       Constant *NewRHSV = ConstantVector::get(Elts);
3286       if (NewRHSV != RHSV) {
3287         Worklist.AddValue(I.getOperand(1));
3288         I.setOperand(1, NewRHSV);
3289         return &I;
3290       }
3291     }
3292   }
3293
3294   return 0;
3295 }
3296
3297 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3298   return commonRemTransforms(I);
3299 }
3300
3301 // isOneBitSet - Return true if there is exactly one bit set in the specified
3302 // constant.
3303 static bool isOneBitSet(const ConstantInt *CI) {
3304   return CI->getValue().isPowerOf2();
3305 }
3306
3307 // isHighOnes - Return true if the constant is of the form 1+0+.
3308 // This is the same as lowones(~X).
3309 static bool isHighOnes(const ConstantInt *CI) {
3310   return (~CI->getValue() + 1).isPowerOf2();
3311 }
3312
3313 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3314 /// are carefully arranged to allow folding of expressions such as:
3315 ///
3316 ///      (A < B) | (A > B) --> (A != B)
3317 ///
3318 /// Note that this is only valid if the first and second predicates have the
3319 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3320 ///
3321 /// Three bits are used to represent the condition, as follows:
3322 ///   0  A > B
3323 ///   1  A == B
3324 ///   2  A < B
3325 ///
3326 /// <=>  Value  Definition
3327 /// 000     0   Always false
3328 /// 001     1   A >  B
3329 /// 010     2   A == B
3330 /// 011     3   A >= B
3331 /// 100     4   A <  B
3332 /// 101     5   A != B
3333 /// 110     6   A <= B
3334 /// 111     7   Always true
3335 ///  
3336 static unsigned getICmpCode(const ICmpInst *ICI) {
3337   switch (ICI->getPredicate()) {
3338     // False -> 0
3339   case ICmpInst::ICMP_UGT: return 1;  // 001
3340   case ICmpInst::ICMP_SGT: return 1;  // 001
3341   case ICmpInst::ICMP_EQ:  return 2;  // 010
3342   case ICmpInst::ICMP_UGE: return 3;  // 011
3343   case ICmpInst::ICMP_SGE: return 3;  // 011
3344   case ICmpInst::ICMP_ULT: return 4;  // 100
3345   case ICmpInst::ICMP_SLT: return 4;  // 100
3346   case ICmpInst::ICMP_NE:  return 5;  // 101
3347   case ICmpInst::ICMP_ULE: return 6;  // 110
3348   case ICmpInst::ICMP_SLE: return 6;  // 110
3349     // True -> 7
3350   default:
3351     llvm_unreachable("Invalid ICmp predicate!");
3352     return 0;
3353   }
3354 }
3355
3356 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3357 /// predicate into a three bit mask. It also returns whether it is an ordered
3358 /// predicate by reference.
3359 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3360   isOrdered = false;
3361   switch (CC) {
3362   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3363   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3364   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3365   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3366   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3367   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3368   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3369   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3370   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3371   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3372   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3373   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3374   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3375   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3376     // True -> 7
3377   default:
3378     // Not expecting FCMP_FALSE and FCMP_TRUE;
3379     llvm_unreachable("Unexpected FCmp predicate!");
3380     return 0;
3381   }
3382 }
3383
3384 /// getICmpValue - This is the complement of getICmpCode, which turns an
3385 /// opcode and two operands into either a constant true or false, or a brand 
3386 /// new ICmp instruction. The sign is passed in to determine which kind
3387 /// of predicate to use in the new icmp instruction.
3388 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3389                            LLVMContext *Context) {
3390   switch (code) {
3391   default: llvm_unreachable("Illegal ICmp code!");
3392   case  0: return ConstantInt::getFalse(*Context);
3393   case  1: 
3394     if (sign)
3395       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3396     else
3397       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3398   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3399   case  3: 
3400     if (sign)
3401       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3402     else
3403       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3404   case  4: 
3405     if (sign)
3406       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3407     else
3408       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3409   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3410   case  6: 
3411     if (sign)
3412       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3413     else
3414       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3415   case  7: return ConstantInt::getTrue(*Context);
3416   }
3417 }
3418
3419 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3420 /// opcode and two operands into either a FCmp instruction. isordered is passed
3421 /// in to determine which kind of predicate to use in the new fcmp instruction.
3422 static Value *getFCmpValue(bool isordered, unsigned code,
3423                            Value *LHS, Value *RHS, LLVMContext *Context) {
3424   switch (code) {
3425   default: llvm_unreachable("Illegal FCmp code!");
3426   case  0:
3427     if (isordered)
3428       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3429     else
3430       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3431   case  1: 
3432     if (isordered)
3433       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3434     else
3435       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3436   case  2: 
3437     if (isordered)
3438       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3439     else
3440       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3441   case  3: 
3442     if (isordered)
3443       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3444     else
3445       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3446   case  4: 
3447     if (isordered)
3448       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3449     else
3450       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3451   case  5: 
3452     if (isordered)
3453       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3454     else
3455       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3456   case  6: 
3457     if (isordered)
3458       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3459     else
3460       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3461   case  7: return ConstantInt::getTrue(*Context);
3462   }
3463 }
3464
3465 /// PredicatesFoldable - Return true if both predicates match sign or if at
3466 /// least one of them is an equality comparison (which is signless).
3467 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3468   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3469          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3470          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3471 }
3472
3473 namespace { 
3474 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3475 struct FoldICmpLogical {
3476   InstCombiner &IC;
3477   Value *LHS, *RHS;
3478   ICmpInst::Predicate pred;
3479   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3480     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3481       pred(ICI->getPredicate()) {}
3482   bool shouldApply(Value *V) const {
3483     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3484       if (PredicatesFoldable(pred, ICI->getPredicate()))
3485         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3486                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3487     return false;
3488   }
3489   Instruction *apply(Instruction &Log) const {
3490     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3491     if (ICI->getOperand(0) != LHS) {
3492       assert(ICI->getOperand(1) == LHS);
3493       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3494     }
3495
3496     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3497     unsigned LHSCode = getICmpCode(ICI);
3498     unsigned RHSCode = getICmpCode(RHSICI);
3499     unsigned Code;
3500     switch (Log.getOpcode()) {
3501     case Instruction::And: Code = LHSCode & RHSCode; break;
3502     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3503     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3504     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3505     }
3506
3507     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3508                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3509       
3510     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3511     if (Instruction *I = dyn_cast<Instruction>(RV))
3512       return I;
3513     // Otherwise, it's a constant boolean value...
3514     return IC.ReplaceInstUsesWith(Log, RV);
3515   }
3516 };
3517 } // end anonymous namespace
3518
3519 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3520 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3521 // guaranteed to be a binary operator.
3522 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3523                                     ConstantInt *OpRHS,
3524                                     ConstantInt *AndRHS,
3525                                     BinaryOperator &TheAnd) {
3526   Value *X = Op->getOperand(0);
3527   Constant *Together = 0;
3528   if (!Op->isShift())
3529     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3530
3531   switch (Op->getOpcode()) {
3532   case Instruction::Xor:
3533     if (Op->hasOneUse()) {
3534       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3535       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3536       InsertNewInstBefore(And, TheAnd);
3537       And->takeName(Op);
3538       return BinaryOperator::CreateXor(And, Together);
3539     }
3540     break;
3541   case Instruction::Or:
3542     if (Together == AndRHS) // (X | C) & C --> C
3543       return ReplaceInstUsesWith(TheAnd, AndRHS);
3544
3545     if (Op->hasOneUse() && Together != OpRHS) {
3546       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3547       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3548       InsertNewInstBefore(Or, TheAnd);
3549       Or->takeName(Op);
3550       return BinaryOperator::CreateAnd(Or, AndRHS);
3551     }
3552     break;
3553   case Instruction::Add:
3554     if (Op->hasOneUse()) {
3555       // Adding a one to a single bit bit-field should be turned into an XOR
3556       // of the bit.  First thing to check is to see if this AND is with a
3557       // single bit constant.
3558       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3559
3560       // If there is only one bit set...
3561       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3562         // Ok, at this point, we know that we are masking the result of the
3563         // ADD down to exactly one bit.  If the constant we are adding has
3564         // no bits set below this bit, then we can eliminate the ADD.
3565         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3566
3567         // Check to see if any bits below the one bit set in AndRHSV are set.
3568         if ((AddRHS & (AndRHSV-1)) == 0) {
3569           // If not, the only thing that can effect the output of the AND is
3570           // the bit specified by AndRHSV.  If that bit is set, the effect of
3571           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3572           // no effect.
3573           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3574             TheAnd.setOperand(0, X);
3575             return &TheAnd;
3576           } else {
3577             // Pull the XOR out of the AND.
3578             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3579             InsertNewInstBefore(NewAnd, TheAnd);
3580             NewAnd->takeName(Op);
3581             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3582           }
3583         }
3584       }
3585     }
3586     break;
3587
3588   case Instruction::Shl: {
3589     // We know that the AND will not produce any of the bits shifted in, so if
3590     // the anded constant includes them, clear them now!
3591     //
3592     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3593     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3594     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3595     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3596
3597     if (CI->getValue() == ShlMask) { 
3598     // Masking out bits that the shift already masks
3599       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3600     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3601       TheAnd.setOperand(1, CI);
3602       return &TheAnd;
3603     }
3604     break;
3605   }
3606   case Instruction::LShr:
3607   {
3608     // We know that the AND will not produce any of the bits shifted in, so if
3609     // the anded constant includes them, clear them now!  This only applies to
3610     // unsigned shifts, because a signed shr may bring in set bits!
3611     //
3612     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3613     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3614     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3615     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3616
3617     if (CI->getValue() == ShrMask) {   
3618     // Masking out bits that the shift already masks.
3619       return ReplaceInstUsesWith(TheAnd, Op);
3620     } else if (CI != AndRHS) {
3621       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3622       return &TheAnd;
3623     }
3624     break;
3625   }
3626   case Instruction::AShr:
3627     // Signed shr.
3628     // See if this is shifting in some sign extension, then masking it out
3629     // with an and.
3630     if (Op->hasOneUse()) {
3631       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3632       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3633       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3634       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3635       if (C == AndRHS) {          // Masking out bits shifted in.
3636         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3637         // Make the argument unsigned.
3638         Value *ShVal = Op->getOperand(0);
3639         ShVal = InsertNewInstBefore(
3640             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3641                                    Op->getName()), TheAnd);
3642         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3643       }
3644     }
3645     break;
3646   }
3647   return 0;
3648 }
3649
3650
3651 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3652 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3653 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3654 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3655 /// insert new instructions.
3656 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3657                                            bool isSigned, bool Inside, 
3658                                            Instruction &IB) {
3659   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3660             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3661          "Lo is not <= Hi in range emission code!");
3662     
3663   if (Inside) {
3664     if (Lo == Hi)  // Trivially false.
3665       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3666
3667     // V >= Min && V < Hi --> V < Hi
3668     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3669       ICmpInst::Predicate pred = (isSigned ? 
3670         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3671       return new ICmpInst(pred, V, Hi);
3672     }
3673
3674     // Emit V-Lo <u Hi-Lo
3675     Constant *NegLo = ConstantExpr::getNeg(Lo);
3676     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3677     InsertNewInstBefore(Add, IB);
3678     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3679     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3680   }
3681
3682   if (Lo == Hi)  // Trivially true.
3683     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3684
3685   // V < Min || V >= Hi -> V > Hi-1
3686   Hi = SubOne(cast<ConstantInt>(Hi));
3687   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3688     ICmpInst::Predicate pred = (isSigned ? 
3689         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3690     return new ICmpInst(pred, V, Hi);
3691   }
3692
3693   // Emit V-Lo >u Hi-1-Lo
3694   // Note that Hi has already had one subtracted from it, above.
3695   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3696   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3697   InsertNewInstBefore(Add, IB);
3698   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3699   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3700 }
3701
3702 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3703 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3704 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3705 // not, since all 1s are not contiguous.
3706 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3707   const APInt& V = Val->getValue();
3708   uint32_t BitWidth = Val->getType()->getBitWidth();
3709   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3710
3711   // look for the first zero bit after the run of ones
3712   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3713   // look for the first non-zero bit
3714   ME = V.getActiveBits(); 
3715   return true;
3716 }
3717
3718 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3719 /// where isSub determines whether the operator is a sub.  If we can fold one of
3720 /// the following xforms:
3721 /// 
3722 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3723 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3724 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3725 ///
3726 /// return (A +/- B).
3727 ///
3728 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3729                                         ConstantInt *Mask, bool isSub,
3730                                         Instruction &I) {
3731   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3732   if (!LHSI || LHSI->getNumOperands() != 2 ||
3733       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3734
3735   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3736
3737   switch (LHSI->getOpcode()) {
3738   default: return 0;
3739   case Instruction::And:
3740     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3741       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3742       if ((Mask->getValue().countLeadingZeros() + 
3743            Mask->getValue().countPopulation()) == 
3744           Mask->getValue().getBitWidth())
3745         break;
3746
3747       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3748       // part, we don't need any explicit masks to take them out of A.  If that
3749       // is all N is, ignore it.
3750       uint32_t MB = 0, ME = 0;
3751       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3752         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3753         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3754         if (MaskedValueIsZero(RHS, Mask))
3755           break;
3756       }
3757     }
3758     return 0;
3759   case Instruction::Or:
3760   case Instruction::Xor:
3761     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3762     if ((Mask->getValue().countLeadingZeros() + 
3763          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3764         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3765       break;
3766     return 0;
3767   }
3768   
3769   Instruction *New;
3770   if (isSub)
3771     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3772   else
3773     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3774   return InsertNewInstBefore(New, I);
3775 }
3776
3777 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3778 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3779                                           ICmpInst *LHS, ICmpInst *RHS) {
3780   Value *Val, *Val2;
3781   ConstantInt *LHSCst, *RHSCst;
3782   ICmpInst::Predicate LHSCC, RHSCC;
3783   
3784   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3785   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3786                          m_ConstantInt(LHSCst))) ||
3787       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3788                          m_ConstantInt(RHSCst))))
3789     return 0;
3790   
3791   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3792   // where C is a power of 2
3793   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3794       LHSCst->getValue().isPowerOf2()) {
3795     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3796     InsertNewInstBefore(NewOr, I);
3797     return new ICmpInst(LHSCC, NewOr, LHSCst);
3798   }
3799   
3800   // From here on, we only handle:
3801   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3802   if (Val != Val2) return 0;
3803   
3804   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3805   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3806       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3807       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3808       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3809     return 0;
3810   
3811   // We can't fold (ugt x, C) & (sgt x, C2).
3812   if (!PredicatesFoldable(LHSCC, RHSCC))
3813     return 0;
3814     
3815   // Ensure that the larger constant is on the RHS.
3816   bool ShouldSwap;
3817   if (ICmpInst::isSignedPredicate(LHSCC) ||
3818       (ICmpInst::isEquality(LHSCC) && 
3819        ICmpInst::isSignedPredicate(RHSCC)))
3820     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3821   else
3822     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3823     
3824   if (ShouldSwap) {
3825     std::swap(LHS, RHS);
3826     std::swap(LHSCst, RHSCst);
3827     std::swap(LHSCC, RHSCC);
3828   }
3829
3830   // At this point, we know we have have two icmp instructions
3831   // comparing a value against two constants and and'ing the result
3832   // together.  Because of the above check, we know that we only have
3833   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3834   // (from the FoldICmpLogical check above), that the two constants 
3835   // are not equal and that the larger constant is on the RHS
3836   assert(LHSCst != RHSCst && "Compares not folded above?");
3837
3838   switch (LHSCC) {
3839   default: llvm_unreachable("Unknown integer condition code!");
3840   case ICmpInst::ICMP_EQ:
3841     switch (RHSCC) {
3842     default: llvm_unreachable("Unknown integer condition code!");
3843     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3844     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3845     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3846       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3847     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3848     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3849     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3850       return ReplaceInstUsesWith(I, LHS);
3851     }
3852   case ICmpInst::ICMP_NE:
3853     switch (RHSCC) {
3854     default: llvm_unreachable("Unknown integer condition code!");
3855     case ICmpInst::ICMP_ULT:
3856       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3857         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3858       break;                        // (X != 13 & X u< 15) -> no change
3859     case ICmpInst::ICMP_SLT:
3860       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3861         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3862       break;                        // (X != 13 & X s< 15) -> no change
3863     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3864     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3865     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3866       return ReplaceInstUsesWith(I, RHS);
3867     case ICmpInst::ICMP_NE:
3868       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3869         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3870         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3871                                                      Val->getName()+".off");
3872         InsertNewInstBefore(Add, I);
3873         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3874                             ConstantInt::get(Add->getType(), 1));
3875       }
3876       break;                        // (X != 13 & X != 15) -> no change
3877     }
3878     break;
3879   case ICmpInst::ICMP_ULT:
3880     switch (RHSCC) {
3881     default: llvm_unreachable("Unknown integer condition code!");
3882     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3883     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3884       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3885     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3886       break;
3887     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3888     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3889       return ReplaceInstUsesWith(I, LHS);
3890     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3891       break;
3892     }
3893     break;
3894   case ICmpInst::ICMP_SLT:
3895     switch (RHSCC) {
3896     default: llvm_unreachable("Unknown integer condition code!");
3897     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3898     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3899       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3900     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3901       break;
3902     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3903     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3904       return ReplaceInstUsesWith(I, LHS);
3905     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3906       break;
3907     }
3908     break;
3909   case ICmpInst::ICMP_UGT:
3910     switch (RHSCC) {
3911     default: llvm_unreachable("Unknown integer condition code!");
3912     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3913     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3914       return ReplaceInstUsesWith(I, RHS);
3915     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3916       break;
3917     case ICmpInst::ICMP_NE:
3918       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3919         return new ICmpInst(LHSCC, Val, RHSCst);
3920       break;                        // (X u> 13 & X != 15) -> no change
3921     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3922       return InsertRangeTest(Val, AddOne(LHSCst),
3923                              RHSCst, false, true, I);
3924     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3925       break;
3926     }
3927     break;
3928   case ICmpInst::ICMP_SGT:
3929     switch (RHSCC) {
3930     default: llvm_unreachable("Unknown integer condition code!");
3931     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3932     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3933       return ReplaceInstUsesWith(I, RHS);
3934     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3935       break;
3936     case ICmpInst::ICMP_NE:
3937       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3938         return new ICmpInst(LHSCC, Val, RHSCst);
3939       break;                        // (X s> 13 & X != 15) -> no change
3940     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3941       return InsertRangeTest(Val, AddOne(LHSCst),
3942                              RHSCst, true, true, I);
3943     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3944       break;
3945     }
3946     break;
3947   }
3948  
3949   return 0;
3950 }
3951
3952 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3953                                           FCmpInst *RHS) {
3954   
3955   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3956       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3957     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3958     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3959       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3960         // If either of the constants are nans, then the whole thing returns
3961         // false.
3962         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3963           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3964         return new FCmpInst(FCmpInst::FCMP_ORD,
3965                             LHS->getOperand(0), RHS->getOperand(0));
3966       }
3967     
3968     // Handle vector zeros.  This occurs because the canonical form of
3969     // "fcmp ord x,x" is "fcmp ord x, 0".
3970     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3971         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3972       return new FCmpInst(FCmpInst::FCMP_ORD,
3973                           LHS->getOperand(0), RHS->getOperand(0));
3974     return 0;
3975   }
3976   
3977   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3978   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3979   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3980   
3981   
3982   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3983     // Swap RHS operands to match LHS.
3984     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3985     std::swap(Op1LHS, Op1RHS);
3986   }
3987   
3988   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3989     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3990     if (Op0CC == Op1CC)
3991       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3992     
3993     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3994       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3995     if (Op0CC == FCmpInst::FCMP_TRUE)
3996       return ReplaceInstUsesWith(I, RHS);
3997     if (Op1CC == FCmpInst::FCMP_TRUE)
3998       return ReplaceInstUsesWith(I, LHS);
3999     
4000     bool Op0Ordered;
4001     bool Op1Ordered;
4002     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4003     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4004     if (Op1Pred == 0) {
4005       std::swap(LHS, RHS);
4006       std::swap(Op0Pred, Op1Pred);
4007       std::swap(Op0Ordered, Op1Ordered);
4008     }
4009     if (Op0Pred == 0) {
4010       // uno && ueq -> uno && (uno || eq) -> ueq
4011       // ord && olt -> ord && (ord && lt) -> olt
4012       if (Op0Ordered == Op1Ordered)
4013         return ReplaceInstUsesWith(I, RHS);
4014       
4015       // uno && oeq -> uno && (ord && eq) -> false
4016       // uno && ord -> false
4017       if (!Op0Ordered)
4018         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4019       // ord && ueq -> ord && (uno || eq) -> oeq
4020       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4021                                             Op0LHS, Op0RHS, Context));
4022     }
4023   }
4024
4025   return 0;
4026 }
4027
4028
4029 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4030   bool Changed = SimplifyCommutative(I);
4031   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4032
4033   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4034     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4035
4036   // and X, X = X
4037   if (Op0 == Op1)
4038     return ReplaceInstUsesWith(I, Op1);
4039
4040   // See if we can simplify any instructions used by the instruction whose sole 
4041   // purpose is to compute bits we don't care about.
4042   if (SimplifyDemandedInstructionBits(I))
4043     return &I;
4044   if (isa<VectorType>(I.getType())) {
4045     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4046       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4047         return ReplaceInstUsesWith(I, I.getOperand(0));
4048     } else if (isa<ConstantAggregateZero>(Op1)) {
4049       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4050     }
4051   }
4052
4053   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4054     const APInt& AndRHSMask = AndRHS->getValue();
4055     APInt NotAndRHS(~AndRHSMask);
4056
4057     // Optimize a variety of ((val OP C1) & C2) combinations...
4058     if (isa<BinaryOperator>(Op0)) {
4059       Instruction *Op0I = cast<Instruction>(Op0);
4060       Value *Op0LHS = Op0I->getOperand(0);
4061       Value *Op0RHS = Op0I->getOperand(1);
4062       switch (Op0I->getOpcode()) {
4063       case Instruction::Xor:
4064       case Instruction::Or:
4065         // If the mask is only needed on one incoming arm, push it up.
4066         if (Op0I->hasOneUse()) {
4067           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4068             // Not masking anything out for the LHS, move to RHS.
4069             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4070                                                    Op0RHS->getName()+".masked");
4071             InsertNewInstBefore(NewRHS, I);
4072             return BinaryOperator::Create(
4073                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4074           }
4075           if (!isa<Constant>(Op0RHS) &&
4076               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4077             // Not masking anything out for the RHS, move to LHS.
4078             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4079                                                    Op0LHS->getName()+".masked");
4080             InsertNewInstBefore(NewLHS, I);
4081             return BinaryOperator::Create(
4082                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4083           }
4084         }
4085
4086         break;
4087       case Instruction::Add:
4088         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4089         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4090         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4091         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4092           return BinaryOperator::CreateAnd(V, AndRHS);
4093         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4094           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4095         break;
4096
4097       case Instruction::Sub:
4098         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4099         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4100         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4101         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4102           return BinaryOperator::CreateAnd(V, AndRHS);
4103
4104         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4105         // has 1's for all bits that the subtraction with A might affect.
4106         if (Op0I->hasOneUse()) {
4107           uint32_t BitWidth = AndRHSMask.getBitWidth();
4108           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4109           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4110
4111           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4112           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4113               MaskedValueIsZero(Op0LHS, Mask)) {
4114             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4115             InsertNewInstBefore(NewNeg, I);
4116             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4117           }
4118         }
4119         break;
4120
4121       case Instruction::Shl:
4122       case Instruction::LShr:
4123         // (1 << x) & 1 --> zext(x == 0)
4124         // (1 >> x) & 1 --> zext(x == 0)
4125         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4126           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
4127                                     Op0RHS, Constant::getNullValue(I.getType()));
4128           InsertNewInstBefore(NewICmp, I);
4129           return new ZExtInst(NewICmp, I.getType());
4130         }
4131         break;
4132       }
4133
4134       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4135         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4136           return Res;
4137     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4138       // If this is an integer truncation or change from signed-to-unsigned, and
4139       // if the source is an and/or with immediate, transform it.  This
4140       // frequently occurs for bitfield accesses.
4141       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4142         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4143             CastOp->getNumOperands() == 2)
4144           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4145             if (CastOp->getOpcode() == Instruction::And) {
4146               // Change: and (cast (and X, C1) to T), C2
4147               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4148               // This will fold the two constants together, which may allow 
4149               // other simplifications.
4150               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4151                 CastOp->getOperand(0), I.getType(), 
4152                 CastOp->getName()+".shrunk");
4153               NewCast = InsertNewInstBefore(NewCast, I);
4154               // trunc_or_bitcast(C1)&C2
4155               Constant *C3 =
4156                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4157               C3 = ConstantExpr::getAnd(C3, AndRHS);
4158               return BinaryOperator::CreateAnd(NewCast, C3);
4159             } else if (CastOp->getOpcode() == Instruction::Or) {
4160               // Change: and (cast (or X, C1) to T), C2
4161               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4162               Constant *C3 =
4163                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4164               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4165                 // trunc(C1)&C2
4166                 return ReplaceInstUsesWith(I, AndRHS);
4167             }
4168           }
4169       }
4170     }
4171
4172     // Try to fold constant and into select arguments.
4173     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4174       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4175         return R;
4176     if (isa<PHINode>(Op0))
4177       if (Instruction *NV = FoldOpIntoPhi(I))
4178         return NV;
4179   }
4180
4181   Value *Op0NotVal = dyn_castNotVal(Op0);
4182   Value *Op1NotVal = dyn_castNotVal(Op1);
4183
4184   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4185     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4186
4187   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4188   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4189     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4190                                                I.getName()+".demorgan");
4191     InsertNewInstBefore(Or, I);
4192     return BinaryOperator::CreateNot(Or);
4193   }
4194   
4195   {
4196     Value *A = 0, *B = 0, *C = 0, *D = 0;
4197     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4198       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4199         return ReplaceInstUsesWith(I, Op1);
4200     
4201       // (A|B) & ~(A&B) -> A^B
4202       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4203         if ((A == C && B == D) || (A == D && B == C))
4204           return BinaryOperator::CreateXor(A, B);
4205       }
4206     }
4207     
4208     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4209       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4210         return ReplaceInstUsesWith(I, Op0);
4211
4212       // ~(A&B) & (A|B) -> A^B
4213       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4214         if ((A == C && B == D) || (A == D && B == C))
4215           return BinaryOperator::CreateXor(A, B);
4216       }
4217     }
4218     
4219     if (Op0->hasOneUse() &&
4220         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4221       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4222         I.swapOperands();     // Simplify below
4223         std::swap(Op0, Op1);
4224       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4225         cast<BinaryOperator>(Op0)->swapOperands();
4226         I.swapOperands();     // Simplify below
4227         std::swap(Op0, Op1);
4228       }
4229     }
4230
4231     if (Op1->hasOneUse() &&
4232         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4233       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4234         cast<BinaryOperator>(Op1)->swapOperands();
4235         std::swap(A, B);
4236       }
4237       if (A == Op0) {                                // A&(A^B) -> A & ~B
4238         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4239         InsertNewInstBefore(NotB, I);
4240         return BinaryOperator::CreateAnd(A, NotB);
4241       }
4242     }
4243
4244     // (A&((~A)|B)) -> A&B
4245     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4246         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4247       return BinaryOperator::CreateAnd(A, Op1);
4248     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4249         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4250       return BinaryOperator::CreateAnd(A, Op0);
4251   }
4252   
4253   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4254     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4255     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4256       return R;
4257
4258     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4259       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4260         return Res;
4261   }
4262
4263   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4264   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4265     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4266       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4267         const Type *SrcTy = Op0C->getOperand(0)->getType();
4268         if (SrcTy == Op1C->getOperand(0)->getType() &&
4269             SrcTy->isIntOrIntVector() &&
4270             // Only do this if the casts both really cause code to be generated.
4271             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4272                               I.getType(), TD) &&
4273             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4274                               I.getType(), TD)) {
4275           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4276                                                          Op1C->getOperand(0),
4277                                                          I.getName());
4278           InsertNewInstBefore(NewOp, I);
4279           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4280         }
4281       }
4282     
4283   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4284   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4285     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4286       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4287           SI0->getOperand(1) == SI1->getOperand(1) &&
4288           (SI0->hasOneUse() || SI1->hasOneUse())) {
4289         Instruction *NewOp =
4290           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4291                                                         SI1->getOperand(0),
4292                                                         SI0->getName()), I);
4293         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4294                                       SI1->getOperand(1));
4295       }
4296   }
4297
4298   // If and'ing two fcmp, try combine them into one.
4299   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4300     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4301       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4302         return Res;
4303   }
4304
4305   return Changed ? &I : 0;
4306 }
4307
4308 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4309 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4310 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4311 /// the expression came from the corresponding "byte swapped" byte in some other
4312 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4313 /// we know that the expression deposits the low byte of %X into the high byte
4314 /// of the bswap result and that all other bytes are zero.  This expression is
4315 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4316 /// match.
4317 ///
4318 /// This function returns true if the match was unsuccessful and false if so.
4319 /// On entry to the function the "OverallLeftShift" is a signed integer value
4320 /// indicating the number of bytes that the subexpression is later shifted.  For
4321 /// example, if the expression is later right shifted by 16 bits, the
4322 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4323 /// byte of ByteValues is actually being set.
4324 ///
4325 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4326 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4327 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4328 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4329 /// always in the local (OverallLeftShift) coordinate space.
4330 ///
4331 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4332                               SmallVector<Value*, 8> &ByteValues) {
4333   if (Instruction *I = dyn_cast<Instruction>(V)) {
4334     // If this is an or instruction, it may be an inner node of the bswap.
4335     if (I->getOpcode() == Instruction::Or) {
4336       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4337                                ByteValues) ||
4338              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4339                                ByteValues);
4340     }
4341   
4342     // If this is a logical shift by a constant multiple of 8, recurse with
4343     // OverallLeftShift and ByteMask adjusted.
4344     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4345       unsigned ShAmt = 
4346         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4347       // Ensure the shift amount is defined and of a byte value.
4348       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4349         return true;
4350
4351       unsigned ByteShift = ShAmt >> 3;
4352       if (I->getOpcode() == Instruction::Shl) {
4353         // X << 2 -> collect(X, +2)
4354         OverallLeftShift += ByteShift;
4355         ByteMask >>= ByteShift;
4356       } else {
4357         // X >>u 2 -> collect(X, -2)
4358         OverallLeftShift -= ByteShift;
4359         ByteMask <<= ByteShift;
4360         ByteMask &= (~0U >> (32-ByteValues.size()));
4361       }
4362
4363       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4364       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4365
4366       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4367                                ByteValues);
4368     }
4369
4370     // If this is a logical 'and' with a mask that clears bytes, clear the
4371     // corresponding bytes in ByteMask.
4372     if (I->getOpcode() == Instruction::And &&
4373         isa<ConstantInt>(I->getOperand(1))) {
4374       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4375       unsigned NumBytes = ByteValues.size();
4376       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4377       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4378       
4379       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4380         // If this byte is masked out by a later operation, we don't care what
4381         // the and mask is.
4382         if ((ByteMask & (1 << i)) == 0)
4383           continue;
4384         
4385         // If the AndMask is all zeros for this byte, clear the bit.
4386         APInt MaskB = AndMask & Byte;
4387         if (MaskB == 0) {
4388           ByteMask &= ~(1U << i);
4389           continue;
4390         }
4391         
4392         // If the AndMask is not all ones for this byte, it's not a bytezap.
4393         if (MaskB != Byte)
4394           return true;
4395
4396         // Otherwise, this byte is kept.
4397       }
4398
4399       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4400                                ByteValues);
4401     }
4402   }
4403   
4404   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4405   // the input value to the bswap.  Some observations: 1) if more than one byte
4406   // is demanded from this input, then it could not be successfully assembled
4407   // into a byteswap.  At least one of the two bytes would not be aligned with
4408   // their ultimate destination.
4409   if (!isPowerOf2_32(ByteMask)) return true;
4410   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4411   
4412   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4413   // is demanded, it needs to go into byte 0 of the result.  This means that the
4414   // byte needs to be shifted until it lands in the right byte bucket.  The
4415   // shift amount depends on the position: if the byte is coming from the high
4416   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4417   // low part, it must be shifted left.
4418   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4419   if (InputByteNo < ByteValues.size()/2) {
4420     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4421       return true;
4422   } else {
4423     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4424       return true;
4425   }
4426   
4427   // If the destination byte value is already defined, the values are or'd
4428   // together, which isn't a bswap (unless it's an or of the same bits).
4429   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4430     return true;
4431   ByteValues[DestByteNo] = V;
4432   return false;
4433 }
4434
4435 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4436 /// If so, insert the new bswap intrinsic and return it.
4437 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4438   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4439   if (!ITy || ITy->getBitWidth() % 16 || 
4440       // ByteMask only allows up to 32-byte values.
4441       ITy->getBitWidth() > 32*8) 
4442     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4443   
4444   /// ByteValues - For each byte of the result, we keep track of which value
4445   /// defines each byte.
4446   SmallVector<Value*, 8> ByteValues;
4447   ByteValues.resize(ITy->getBitWidth()/8);
4448     
4449   // Try to find all the pieces corresponding to the bswap.
4450   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4451   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4452     return 0;
4453   
4454   // Check to see if all of the bytes come from the same value.
4455   Value *V = ByteValues[0];
4456   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4457   
4458   // Check to make sure that all of the bytes come from the same value.
4459   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4460     if (ByteValues[i] != V)
4461       return 0;
4462   const Type *Tys[] = { ITy };
4463   Module *M = I.getParent()->getParent()->getParent();
4464   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4465   return CallInst::Create(F, V);
4466 }
4467
4468 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4469 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4470 /// we can simplify this expression to "cond ? C : D or B".
4471 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4472                                          Value *C, Value *D,
4473                                          LLVMContext *Context) {
4474   // If A is not a select of -1/0, this cannot match.
4475   Value *Cond = 0;
4476   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4477     return 0;
4478
4479   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4480   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4481     return SelectInst::Create(Cond, C, B);
4482   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4483     return SelectInst::Create(Cond, C, B);
4484   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4485   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4486     return SelectInst::Create(Cond, C, D);
4487   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4488     return SelectInst::Create(Cond, C, D);
4489   return 0;
4490 }
4491
4492 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4493 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4494                                          ICmpInst *LHS, ICmpInst *RHS) {
4495   Value *Val, *Val2;
4496   ConstantInt *LHSCst, *RHSCst;
4497   ICmpInst::Predicate LHSCC, RHSCC;
4498   
4499   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4500   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4501              m_ConstantInt(LHSCst))) ||
4502       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4503              m_ConstantInt(RHSCst))))
4504     return 0;
4505   
4506   // From here on, we only handle:
4507   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4508   if (Val != Val2) return 0;
4509   
4510   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4511   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4512       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4513       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4514       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4515     return 0;
4516   
4517   // We can't fold (ugt x, C) | (sgt x, C2).
4518   if (!PredicatesFoldable(LHSCC, RHSCC))
4519     return 0;
4520   
4521   // Ensure that the larger constant is on the RHS.
4522   bool ShouldSwap;
4523   if (ICmpInst::isSignedPredicate(LHSCC) ||
4524       (ICmpInst::isEquality(LHSCC) && 
4525        ICmpInst::isSignedPredicate(RHSCC)))
4526     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4527   else
4528     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4529   
4530   if (ShouldSwap) {
4531     std::swap(LHS, RHS);
4532     std::swap(LHSCst, RHSCst);
4533     std::swap(LHSCC, RHSCC);
4534   }
4535   
4536   // At this point, we know we have have two icmp instructions
4537   // comparing a value against two constants and or'ing the result
4538   // together.  Because of the above check, we know that we only have
4539   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4540   // FoldICmpLogical check above), that the two constants are not
4541   // equal.
4542   assert(LHSCst != RHSCst && "Compares not folded above?");
4543
4544   switch (LHSCC) {
4545   default: llvm_unreachable("Unknown integer condition code!");
4546   case ICmpInst::ICMP_EQ:
4547     switch (RHSCC) {
4548     default: llvm_unreachable("Unknown integer condition code!");
4549     case ICmpInst::ICMP_EQ:
4550       if (LHSCst == SubOne(RHSCst)) {
4551         // (X == 13 | X == 14) -> X-13 <u 2
4552         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4553         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4554                                                      Val->getName()+".off");
4555         InsertNewInstBefore(Add, I);
4556         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4557         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4558       }
4559       break;                         // (X == 13 | X == 15) -> no change
4560     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4561     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4562       break;
4563     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4564     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4565     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4566       return ReplaceInstUsesWith(I, RHS);
4567     }
4568     break;
4569   case ICmpInst::ICMP_NE:
4570     switch (RHSCC) {
4571     default: llvm_unreachable("Unknown integer condition code!");
4572     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4573     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4574     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4575       return ReplaceInstUsesWith(I, LHS);
4576     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4577     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4578     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4579       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4580     }
4581     break;
4582   case ICmpInst::ICMP_ULT:
4583     switch (RHSCC) {
4584     default: llvm_unreachable("Unknown integer condition code!");
4585     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4586       break;
4587     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4588       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4589       // this can cause overflow.
4590       if (RHSCst->isMaxValue(false))
4591         return ReplaceInstUsesWith(I, LHS);
4592       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4593                              false, false, I);
4594     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4595       break;
4596     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4597     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4598       return ReplaceInstUsesWith(I, RHS);
4599     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4600       break;
4601     }
4602     break;
4603   case ICmpInst::ICMP_SLT:
4604     switch (RHSCC) {
4605     default: llvm_unreachable("Unknown integer condition code!");
4606     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4607       break;
4608     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4609       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4610       // this can cause overflow.
4611       if (RHSCst->isMaxValue(true))
4612         return ReplaceInstUsesWith(I, LHS);
4613       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4614                              true, false, I);
4615     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4616       break;
4617     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4618     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4619       return ReplaceInstUsesWith(I, RHS);
4620     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4621       break;
4622     }
4623     break;
4624   case ICmpInst::ICMP_UGT:
4625     switch (RHSCC) {
4626     default: llvm_unreachable("Unknown integer condition code!");
4627     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4628     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4629       return ReplaceInstUsesWith(I, LHS);
4630     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4631       break;
4632     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4633     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4634       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4635     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4636       break;
4637     }
4638     break;
4639   case ICmpInst::ICMP_SGT:
4640     switch (RHSCC) {
4641     default: llvm_unreachable("Unknown integer condition code!");
4642     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4643     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4644       return ReplaceInstUsesWith(I, LHS);
4645     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4646       break;
4647     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4648     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4649       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4650     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4651       break;
4652     }
4653     break;
4654   }
4655   return 0;
4656 }
4657
4658 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4659                                          FCmpInst *RHS) {
4660   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4661       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4662       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4663     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4664       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4665         // If either of the constants are nans, then the whole thing returns
4666         // true.
4667         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4668           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4669         
4670         // Otherwise, no need to compare the two constants, compare the
4671         // rest.
4672         return new FCmpInst(FCmpInst::FCMP_UNO,
4673                             LHS->getOperand(0), RHS->getOperand(0));
4674       }
4675     
4676     // Handle vector zeros.  This occurs because the canonical form of
4677     // "fcmp uno x,x" is "fcmp uno x, 0".
4678     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4679         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4680       return new FCmpInst(FCmpInst::FCMP_UNO,
4681                           LHS->getOperand(0), RHS->getOperand(0));
4682     
4683     return 0;
4684   }
4685   
4686   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4687   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4688   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4689   
4690   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4691     // Swap RHS operands to match LHS.
4692     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4693     std::swap(Op1LHS, Op1RHS);
4694   }
4695   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4696     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4697     if (Op0CC == Op1CC)
4698       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4699                           Op0LHS, Op0RHS);
4700     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4701       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4702     if (Op0CC == FCmpInst::FCMP_FALSE)
4703       return ReplaceInstUsesWith(I, RHS);
4704     if (Op1CC == FCmpInst::FCMP_FALSE)
4705       return ReplaceInstUsesWith(I, LHS);
4706     bool Op0Ordered;
4707     bool Op1Ordered;
4708     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4709     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4710     if (Op0Ordered == Op1Ordered) {
4711       // If both are ordered or unordered, return a new fcmp with
4712       // or'ed predicates.
4713       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4714                                Op0LHS, Op0RHS, Context);
4715       if (Instruction *I = dyn_cast<Instruction>(RV))
4716         return I;
4717       // Otherwise, it's a constant boolean value...
4718       return ReplaceInstUsesWith(I, RV);
4719     }
4720   }
4721   return 0;
4722 }
4723
4724 /// FoldOrWithConstants - This helper function folds:
4725 ///
4726 ///     ((A | B) & C1) | (B & C2)
4727 ///
4728 /// into:
4729 /// 
4730 ///     (A & C1) | B
4731 ///
4732 /// when the XOR of the two constants is "all ones" (-1).
4733 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4734                                                Value *A, Value *B, Value *C) {
4735   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4736   if (!CI1) return 0;
4737
4738   Value *V1 = 0;
4739   ConstantInt *CI2 = 0;
4740   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4741
4742   APInt Xor = CI1->getValue() ^ CI2->getValue();
4743   if (!Xor.isAllOnesValue()) return 0;
4744
4745   if (V1 == A || V1 == B) {
4746     Instruction *NewOp =
4747       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4748     return BinaryOperator::CreateOr(NewOp, V1);
4749   }
4750
4751   return 0;
4752 }
4753
4754 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4755   bool Changed = SimplifyCommutative(I);
4756   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4757
4758   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4759     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4760
4761   // or X, X = X
4762   if (Op0 == Op1)
4763     return ReplaceInstUsesWith(I, Op0);
4764
4765   // See if we can simplify any instructions used by the instruction whose sole 
4766   // purpose is to compute bits we don't care about.
4767   if (SimplifyDemandedInstructionBits(I))
4768     return &I;
4769   if (isa<VectorType>(I.getType())) {
4770     if (isa<ConstantAggregateZero>(Op1)) {
4771       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4772     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4773       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4774         return ReplaceInstUsesWith(I, I.getOperand(1));
4775     }
4776   }
4777
4778   // or X, -1 == -1
4779   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4780     ConstantInt *C1 = 0; Value *X = 0;
4781     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4782     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4783         isOnlyUse(Op0)) {
4784       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4785       InsertNewInstBefore(Or, I);
4786       Or->takeName(Op0);
4787       return BinaryOperator::CreateAnd(Or, 
4788                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4789     }
4790
4791     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4792     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4793         isOnlyUse(Op0)) {
4794       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4795       InsertNewInstBefore(Or, I);
4796       Or->takeName(Op0);
4797       return BinaryOperator::CreateXor(Or,
4798                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4799     }
4800
4801     // Try to fold constant and into select arguments.
4802     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4803       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4804         return R;
4805     if (isa<PHINode>(Op0))
4806       if (Instruction *NV = FoldOpIntoPhi(I))
4807         return NV;
4808   }
4809
4810   Value *A = 0, *B = 0;
4811   ConstantInt *C1 = 0, *C2 = 0;
4812
4813   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4814     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4815       return ReplaceInstUsesWith(I, Op1);
4816   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4817     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4818       return ReplaceInstUsesWith(I, Op0);
4819
4820   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4821   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4822   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4823       match(Op1, m_Or(m_Value(), m_Value())) ||
4824       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4825        match(Op1, m_Shift(m_Value(), m_Value())))) {
4826     if (Instruction *BSwap = MatchBSwap(I))
4827       return BSwap;
4828   }
4829   
4830   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4831   if (Op0->hasOneUse() &&
4832       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4833       MaskedValueIsZero(Op1, C1->getValue())) {
4834     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4835     InsertNewInstBefore(NOr, I);
4836     NOr->takeName(Op0);
4837     return BinaryOperator::CreateXor(NOr, C1);
4838   }
4839
4840   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4841   if (Op1->hasOneUse() &&
4842       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4843       MaskedValueIsZero(Op0, C1->getValue())) {
4844     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4845     InsertNewInstBefore(NOr, I);
4846     NOr->takeName(Op0);
4847     return BinaryOperator::CreateXor(NOr, C1);
4848   }
4849
4850   // (A & C)|(B & D)
4851   Value *C = 0, *D = 0;
4852   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4853       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4854     Value *V1 = 0, *V2 = 0, *V3 = 0;
4855     C1 = dyn_cast<ConstantInt>(C);
4856     C2 = dyn_cast<ConstantInt>(D);
4857     if (C1 && C2) {  // (A & C1)|(B & C2)
4858       // If we have: ((V + N) & C1) | (V & C2)
4859       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4860       // replace with V+N.
4861       if (C1->getValue() == ~C2->getValue()) {
4862         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4863             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4864           // Add commutes, try both ways.
4865           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4866             return ReplaceInstUsesWith(I, A);
4867           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4868             return ReplaceInstUsesWith(I, A);
4869         }
4870         // Or commutes, try both ways.
4871         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4872             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4873           // Add commutes, try both ways.
4874           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4875             return ReplaceInstUsesWith(I, B);
4876           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4877             return ReplaceInstUsesWith(I, B);
4878         }
4879       }
4880       V1 = 0; V2 = 0; V3 = 0;
4881     }
4882     
4883     // Check to see if we have any common things being and'ed.  If so, find the
4884     // terms for V1 & (V2|V3).
4885     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4886       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4887         V1 = A, V2 = C, V3 = D;
4888       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4889         V1 = A, V2 = B, V3 = C;
4890       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4891         V1 = C, V2 = A, V3 = D;
4892       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4893         V1 = C, V2 = A, V3 = B;
4894       
4895       if (V1) {
4896         Value *Or =
4897           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4898         return BinaryOperator::CreateAnd(V1, Or);
4899       }
4900     }
4901
4902     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4903     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4904       return Match;
4905     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4906       return Match;
4907     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4908       return Match;
4909     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4910       return Match;
4911
4912     // ((A&~B)|(~A&B)) -> A^B
4913     if ((match(C, m_Not(m_Specific(D))) &&
4914          match(B, m_Not(m_Specific(A)))))
4915       return BinaryOperator::CreateXor(A, D);
4916     // ((~B&A)|(~A&B)) -> A^B
4917     if ((match(A, m_Not(m_Specific(D))) &&
4918          match(B, m_Not(m_Specific(C)))))
4919       return BinaryOperator::CreateXor(C, D);
4920     // ((A&~B)|(B&~A)) -> A^B
4921     if ((match(C, m_Not(m_Specific(B))) &&
4922          match(D, m_Not(m_Specific(A)))))
4923       return BinaryOperator::CreateXor(A, B);
4924     // ((~B&A)|(B&~A)) -> A^B
4925     if ((match(A, m_Not(m_Specific(B))) &&
4926          match(D, m_Not(m_Specific(C)))))
4927       return BinaryOperator::CreateXor(C, B);
4928   }
4929   
4930   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4931   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4932     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4933       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4934           SI0->getOperand(1) == SI1->getOperand(1) &&
4935           (SI0->hasOneUse() || SI1->hasOneUse())) {
4936         Instruction *NewOp =
4937         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4938                                                      SI1->getOperand(0),
4939                                                      SI0->getName()), I);
4940         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4941                                       SI1->getOperand(1));
4942       }
4943   }
4944
4945   // ((A|B)&1)|(B&-2) -> (A&1) | B
4946   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4947       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4948     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4949     if (Ret) return Ret;
4950   }
4951   // (B&-2)|((A|B)&1) -> (A&1) | B
4952   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4953       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4954     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4955     if (Ret) return Ret;
4956   }
4957
4958   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4959     if (A == Op1)   // ~A | A == -1
4960       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4961   } else {
4962     A = 0;
4963   }
4964   // Note, A is still live here!
4965   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4966     if (Op0 == B)
4967       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4968
4969     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4970     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4971       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4972                                               I.getName()+".demorgan"), I);
4973       return BinaryOperator::CreateNot(And);
4974     }
4975   }
4976
4977   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4978   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4979     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4980       return R;
4981
4982     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4983       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4984         return Res;
4985   }
4986     
4987   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4988   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4989     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4990       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4991         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4992             !isa<ICmpInst>(Op1C->getOperand(0))) {
4993           const Type *SrcTy = Op0C->getOperand(0)->getType();
4994           if (SrcTy == Op1C->getOperand(0)->getType() &&
4995               SrcTy->isIntOrIntVector() &&
4996               // Only do this if the casts both really cause code to be
4997               // generated.
4998               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4999                                 I.getType(), TD) &&
5000               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5001                                 I.getType(), TD)) {
5002             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
5003                                                           Op1C->getOperand(0),
5004                                                           I.getName());
5005             InsertNewInstBefore(NewOp, I);
5006             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5007           }
5008         }
5009       }
5010   }
5011   
5012     
5013   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5014   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5015     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5016       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5017         return Res;
5018   }
5019
5020   return Changed ? &I : 0;
5021 }
5022
5023 namespace {
5024
5025 // XorSelf - Implements: X ^ X --> 0
5026 struct XorSelf {
5027   Value *RHS;
5028   XorSelf(Value *rhs) : RHS(rhs) {}
5029   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5030   Instruction *apply(BinaryOperator &Xor) const {
5031     return &Xor;
5032   }
5033 };
5034
5035 }
5036
5037 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5038   bool Changed = SimplifyCommutative(I);
5039   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5040
5041   if (isa<UndefValue>(Op1)) {
5042     if (isa<UndefValue>(Op0))
5043       // Handle undef ^ undef -> 0 special case. This is a common
5044       // idiom (misuse).
5045       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5046     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5047   }
5048
5049   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5050   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5051     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5052     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5053   }
5054   
5055   // See if we can simplify any instructions used by the instruction whose sole 
5056   // purpose is to compute bits we don't care about.
5057   if (SimplifyDemandedInstructionBits(I))
5058     return &I;
5059   if (isa<VectorType>(I.getType()))
5060     if (isa<ConstantAggregateZero>(Op1))
5061       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5062
5063   // Is this a ~ operation?
5064   if (Value *NotOp = dyn_castNotVal(&I)) {
5065     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5066     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5067     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5068       if (Op0I->getOpcode() == Instruction::And || 
5069           Op0I->getOpcode() == Instruction::Or) {
5070         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5071         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5072           Instruction *NotY =
5073             BinaryOperator::CreateNot(Op0I->getOperand(1),
5074                                       Op0I->getOperand(1)->getName()+".not");
5075           InsertNewInstBefore(NotY, I);
5076           if (Op0I->getOpcode() == Instruction::And)
5077             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5078           else
5079             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5080         }
5081       }
5082     }
5083   }
5084   
5085   
5086   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5087     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5088       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5089       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5090         return new ICmpInst(ICI->getInversePredicate(),
5091                             ICI->getOperand(0), ICI->getOperand(1));
5092
5093       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5094         return new FCmpInst(FCI->getInversePredicate(),
5095                             FCI->getOperand(0), FCI->getOperand(1));
5096     }
5097
5098     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5099     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5100       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5101         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5102           Instruction::CastOps Opcode = Op0C->getOpcode();
5103           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5104             if (RHS == ConstantExpr::getCast(Opcode, 
5105                                              ConstantInt::getTrue(*Context),
5106                                              Op0C->getDestTy())) {
5107               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5108                                      CI->getOpcode(), CI->getInversePredicate(),
5109                                      CI->getOperand(0), CI->getOperand(1)), I);
5110               NewCI->takeName(CI);
5111               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5112             }
5113           }
5114         }
5115       }
5116     }
5117
5118     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5119       // ~(c-X) == X-c-1 == X+(-c-1)
5120       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5121         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5122           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5123           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5124                                       ConstantInt::get(I.getType(), 1));
5125           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5126         }
5127           
5128       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5129         if (Op0I->getOpcode() == Instruction::Add) {
5130           // ~(X-c) --> (-c-1)-X
5131           if (RHS->isAllOnesValue()) {
5132             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5133             return BinaryOperator::CreateSub(
5134                            ConstantExpr::getSub(NegOp0CI,
5135                                       ConstantInt::get(I.getType(), 1)),
5136                                       Op0I->getOperand(0));
5137           } else if (RHS->getValue().isSignBit()) {
5138             // (X + C) ^ signbit -> (X + C + signbit)
5139             Constant *C = ConstantInt::get(*Context,
5140                                            RHS->getValue() + Op0CI->getValue());
5141             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5142
5143           }
5144         } else if (Op0I->getOpcode() == Instruction::Or) {
5145           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5146           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5147             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5148             // Anything in both C1 and C2 is known to be zero, remove it from
5149             // NewRHS.
5150             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5151             NewRHS = ConstantExpr::getAnd(NewRHS, 
5152                                        ConstantExpr::getNot(CommonBits));
5153             Worklist.Add(Op0I);
5154             I.setOperand(0, Op0I->getOperand(0));
5155             I.setOperand(1, NewRHS);
5156             return &I;
5157           }
5158         }
5159       }
5160     }
5161
5162     // Try to fold constant and into select arguments.
5163     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5164       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5165         return R;
5166     if (isa<PHINode>(Op0))
5167       if (Instruction *NV = FoldOpIntoPhi(I))
5168         return NV;
5169   }
5170
5171   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5172     if (X == Op1)
5173       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5174
5175   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5176     if (X == Op0)
5177       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5178
5179   
5180   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5181   if (Op1I) {
5182     Value *A, *B;
5183     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5184       if (A == Op0) {              // B^(B|A) == (A|B)^B
5185         Op1I->swapOperands();
5186         I.swapOperands();
5187         std::swap(Op0, Op1);
5188       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5189         I.swapOperands();     // Simplified below.
5190         std::swap(Op0, Op1);
5191       }
5192     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5193       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5194     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5195       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5196     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5197                Op1I->hasOneUse()){
5198       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5199         Op1I->swapOperands();
5200         std::swap(A, B);
5201       }
5202       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5203         I.swapOperands();     // Simplified below.
5204         std::swap(Op0, Op1);
5205       }
5206     }
5207   }
5208   
5209   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5210   if (Op0I) {
5211     Value *A, *B;
5212     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5213         Op0I->hasOneUse()) {
5214       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5215         std::swap(A, B);
5216       if (B == Op1) {                                // (A|B)^B == A & ~B
5217         Instruction *NotB =
5218           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5219         return BinaryOperator::CreateAnd(A, NotB);
5220       }
5221     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5222       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5223     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5224       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5225     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5226                Op0I->hasOneUse()){
5227       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5228         std::swap(A, B);
5229       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5230           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5231         Instruction *N =
5232           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5233         return BinaryOperator::CreateAnd(N, Op1);
5234       }
5235     }
5236   }
5237   
5238   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5239   if (Op0I && Op1I && Op0I->isShift() && 
5240       Op0I->getOpcode() == Op1I->getOpcode() && 
5241       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5242       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5243     Instruction *NewOp =
5244       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5245                                                     Op1I->getOperand(0),
5246                                                     Op0I->getName()), I);
5247     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5248                                   Op1I->getOperand(1));
5249   }
5250     
5251   if (Op0I && Op1I) {
5252     Value *A, *B, *C, *D;
5253     // (A & B)^(A | B) -> A ^ B
5254     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5255         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5256       if ((A == C && B == D) || (A == D && B == C)) 
5257         return BinaryOperator::CreateXor(A, B);
5258     }
5259     // (A | B)^(A & B) -> A ^ B
5260     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5261         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5262       if ((A == C && B == D) || (A == D && B == C)) 
5263         return BinaryOperator::CreateXor(A, B);
5264     }
5265     
5266     // (A & B)^(C & D)
5267     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5268         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5269         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5270       // (X & Y)^(X & Y) -> (Y^Z) & X
5271       Value *X = 0, *Y = 0, *Z = 0;
5272       if (A == C)
5273         X = A, Y = B, Z = D;
5274       else if (A == D)
5275         X = A, Y = B, Z = C;
5276       else if (B == C)
5277         X = B, Y = A, Z = D;
5278       else if (B == D)
5279         X = B, Y = A, Z = C;
5280       
5281       if (X) {
5282         Instruction *NewOp =
5283         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5284         return BinaryOperator::CreateAnd(NewOp, X);
5285       }
5286     }
5287   }
5288     
5289   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5290   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5291     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5292       return R;
5293
5294   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5295   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5296     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5297       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5298         const Type *SrcTy = Op0C->getOperand(0)->getType();
5299         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5300             // Only do this if the casts both really cause code to be generated.
5301             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5302                               I.getType(), TD) &&
5303             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5304                               I.getType(), TD)) {
5305           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5306                                                          Op1C->getOperand(0),
5307                                                          I.getName());
5308           InsertNewInstBefore(NewOp, I);
5309           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5310         }
5311       }
5312   }
5313
5314   return Changed ? &I : 0;
5315 }
5316
5317 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5318                                    LLVMContext *Context) {
5319   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5320 }
5321
5322 static bool HasAddOverflow(ConstantInt *Result,
5323                            ConstantInt *In1, ConstantInt *In2,
5324                            bool IsSigned) {
5325   if (IsSigned)
5326     if (In2->getValue().isNegative())
5327       return Result->getValue().sgt(In1->getValue());
5328     else
5329       return Result->getValue().slt(In1->getValue());
5330   else
5331     return Result->getValue().ult(In1->getValue());
5332 }
5333
5334 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5335 /// overflowed for this type.
5336 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5337                             Constant *In2, LLVMContext *Context,
5338                             bool IsSigned = false) {
5339   Result = ConstantExpr::getAdd(In1, In2);
5340
5341   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5342     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5343       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5344       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5345                          ExtractElement(In1, Idx, Context),
5346                          ExtractElement(In2, Idx, Context),
5347                          IsSigned))
5348         return true;
5349     }
5350     return false;
5351   }
5352
5353   return HasAddOverflow(cast<ConstantInt>(Result),
5354                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5355                         IsSigned);
5356 }
5357
5358 static bool HasSubOverflow(ConstantInt *Result,
5359                            ConstantInt *In1, ConstantInt *In2,
5360                            bool IsSigned) {
5361   if (IsSigned)
5362     if (In2->getValue().isNegative())
5363       return Result->getValue().slt(In1->getValue());
5364     else
5365       return Result->getValue().sgt(In1->getValue());
5366   else
5367     return Result->getValue().ugt(In1->getValue());
5368 }
5369
5370 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5371 /// overflowed for this type.
5372 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5373                             Constant *In2, LLVMContext *Context,
5374                             bool IsSigned = false) {
5375   Result = ConstantExpr::getSub(In1, In2);
5376
5377   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5378     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5379       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5380       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5381                          ExtractElement(In1, Idx, Context),
5382                          ExtractElement(In2, Idx, Context),
5383                          IsSigned))
5384         return true;
5385     }
5386     return false;
5387   }
5388
5389   return HasSubOverflow(cast<ConstantInt>(Result),
5390                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5391                         IsSigned);
5392 }
5393
5394 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5395 /// code necessary to compute the offset from the base pointer (without adding
5396 /// in the base pointer).  Return the result as a signed integer of intptr size.
5397 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5398   TargetData &TD = *IC.getTargetData();
5399   gep_type_iterator GTI = gep_type_begin(GEP);
5400   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5401   LLVMContext *Context = IC.getContext();
5402   Value *Result = Constant::getNullValue(IntPtrTy);
5403
5404   // Build a mask for high order bits.
5405   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5406   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5407
5408   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5409        ++i, ++GTI) {
5410     Value *Op = *i;
5411     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5412     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5413       if (OpC->isZero()) continue;
5414       
5415       // Handle a struct index, which adds its field offset to the pointer.
5416       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5417         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5418         
5419         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5420           Result = 
5421              ConstantInt::get(*Context, 
5422                               RC->getValue() + APInt(IntPtrWidth, Size));
5423         else
5424           Result = IC.InsertNewInstBefore(
5425                    BinaryOperator::CreateAdd(Result,
5426                                         ConstantInt::get(IntPtrTy, Size),
5427                                              GEP->getName()+".offs"), I);
5428         continue;
5429       }
5430       
5431       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5432       Constant *OC =
5433               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5434       Scale = ConstantExpr::getMul(OC, Scale);
5435       if (Constant *RC = dyn_cast<Constant>(Result))
5436         Result = ConstantExpr::getAdd(RC, Scale);
5437       else {
5438         // Emit an add instruction.
5439         Result = IC.InsertNewInstBefore(
5440            BinaryOperator::CreateAdd(Result, Scale,
5441                                      GEP->getName()+".offs"), I);
5442       }
5443       continue;
5444     }
5445     // Convert to correct type.
5446     if (Op->getType() != IntPtrTy) {
5447       if (Constant *OpC = dyn_cast<Constant>(Op))
5448         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5449       else
5450         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5451                                                                 true,
5452                                                       Op->getName()+".c"), I);
5453     }
5454     if (Size != 1) {
5455       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5456       if (Constant *OpC = dyn_cast<Constant>(Op))
5457         Op = ConstantExpr::getMul(OpC, Scale);
5458       else    // We'll let instcombine(mul) convert this to a shl if possible.
5459         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5460                                                   GEP->getName()+".idx"), I);
5461     }
5462
5463     // Emit an add instruction.
5464     if (isa<Constant>(Op) && isa<Constant>(Result))
5465       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5466                                     cast<Constant>(Result));
5467     else
5468       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5469                                                   GEP->getName()+".offs"), I);
5470   }
5471   return Result;
5472 }
5473
5474
5475 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5476 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5477 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5478 /// be complex, and scales are involved.  The above expression would also be
5479 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5480 /// This later form is less amenable to optimization though, and we are allowed
5481 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5482 ///
5483 /// If we can't emit an optimized form for this expression, this returns null.
5484 /// 
5485 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5486                                           InstCombiner &IC) {
5487   TargetData &TD = *IC.getTargetData();
5488   gep_type_iterator GTI = gep_type_begin(GEP);
5489
5490   // Check to see if this gep only has a single variable index.  If so, and if
5491   // any constant indices are a multiple of its scale, then we can compute this
5492   // in terms of the scale of the variable index.  For example, if the GEP
5493   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5494   // because the expression will cross zero at the same point.
5495   unsigned i, e = GEP->getNumOperands();
5496   int64_t Offset = 0;
5497   for (i = 1; i != e; ++i, ++GTI) {
5498     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5499       // Compute the aggregate offset of constant indices.
5500       if (CI->isZero()) continue;
5501
5502       // Handle a struct index, which adds its field offset to the pointer.
5503       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5504         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5505       } else {
5506         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5507         Offset += Size*CI->getSExtValue();
5508       }
5509     } else {
5510       // Found our variable index.
5511       break;
5512     }
5513   }
5514   
5515   // If there are no variable indices, we must have a constant offset, just
5516   // evaluate it the general way.
5517   if (i == e) return 0;
5518   
5519   Value *VariableIdx = GEP->getOperand(i);
5520   // Determine the scale factor of the variable element.  For example, this is
5521   // 4 if the variable index is into an array of i32.
5522   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5523   
5524   // Verify that there are no other variable indices.  If so, emit the hard way.
5525   for (++i, ++GTI; i != e; ++i, ++GTI) {
5526     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5527     if (!CI) return 0;
5528    
5529     // Compute the aggregate offset of constant indices.
5530     if (CI->isZero()) continue;
5531     
5532     // Handle a struct index, which adds its field offset to the pointer.
5533     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5534       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5535     } else {
5536       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5537       Offset += Size*CI->getSExtValue();
5538     }
5539   }
5540   
5541   // Okay, we know we have a single variable index, which must be a
5542   // pointer/array/vector index.  If there is no offset, life is simple, return
5543   // the index.
5544   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5545   if (Offset == 0) {
5546     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5547     // we don't need to bother extending: the extension won't affect where the
5548     // computation crosses zero.
5549     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5550       VariableIdx = new TruncInst(VariableIdx, 
5551                                   TD.getIntPtrType(VariableIdx->getContext()),
5552                                   VariableIdx->getName(), &I);
5553     return VariableIdx;
5554   }
5555   
5556   // Otherwise, there is an index.  The computation we will do will be modulo
5557   // the pointer size, so get it.
5558   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5559   
5560   Offset &= PtrSizeMask;
5561   VariableScale &= PtrSizeMask;
5562
5563   // To do this transformation, any constant index must be a multiple of the
5564   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5565   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5566   // multiple of the variable scale.
5567   int64_t NewOffs = Offset / (int64_t)VariableScale;
5568   if (Offset != NewOffs*(int64_t)VariableScale)
5569     return 0;
5570
5571   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5572   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5573   if (VariableIdx->getType() != IntPtrTy)
5574     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5575                                               true /*SExt*/, 
5576                                               VariableIdx->getName(), &I);
5577   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5578   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5579 }
5580
5581
5582 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5583 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5584 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5585                                        ICmpInst::Predicate Cond,
5586                                        Instruction &I) {
5587   // Look through bitcasts.
5588   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5589     RHS = BCI->getOperand(0);
5590
5591   Value *PtrBase = GEPLHS->getOperand(0);
5592   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5593     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5594     // This transformation (ignoring the base and scales) is valid because we
5595     // know pointers can't overflow since the gep is inbounds.  See if we can
5596     // output an optimized form.
5597     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5598     
5599     // If not, synthesize the offset the hard way.
5600     if (Offset == 0)
5601       Offset = EmitGEPOffset(GEPLHS, I, *this);
5602     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5603                         Constant::getNullValue(Offset->getType()));
5604   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5605     // If the base pointers are different, but the indices are the same, just
5606     // compare the base pointer.
5607     if (PtrBase != GEPRHS->getOperand(0)) {
5608       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5609       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5610                         GEPRHS->getOperand(0)->getType();
5611       if (IndicesTheSame)
5612         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5613           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5614             IndicesTheSame = false;
5615             break;
5616           }
5617
5618       // If all indices are the same, just compare the base pointers.
5619       if (IndicesTheSame)
5620         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5621                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5622
5623       // Otherwise, the base pointers are different and the indices are
5624       // different, bail out.
5625       return 0;
5626     }
5627
5628     // If one of the GEPs has all zero indices, recurse.
5629     bool AllZeros = true;
5630     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5631       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5632           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5633         AllZeros = false;
5634         break;
5635       }
5636     if (AllZeros)
5637       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5638                           ICmpInst::getSwappedPredicate(Cond), I);
5639
5640     // If the other GEP has all zero indices, recurse.
5641     AllZeros = true;
5642     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5643       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5644           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5645         AllZeros = false;
5646         break;
5647       }
5648     if (AllZeros)
5649       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5650
5651     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5652       // If the GEPs only differ by one index, compare it.
5653       unsigned NumDifferences = 0;  // Keep track of # differences.
5654       unsigned DiffOperand = 0;     // The operand that differs.
5655       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5656         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5657           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5658                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5659             // Irreconcilable differences.
5660             NumDifferences = 2;
5661             break;
5662           } else {
5663             if (NumDifferences++) break;
5664             DiffOperand = i;
5665           }
5666         }
5667
5668       if (NumDifferences == 0)   // SAME GEP?
5669         return ReplaceInstUsesWith(I, // No comparison is needed here.
5670                                    ConstantInt::get(Type::getInt1Ty(*Context),
5671                                              ICmpInst::isTrueWhenEqual(Cond)));
5672
5673       else if (NumDifferences == 1) {
5674         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5675         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5676         // Make sure we do a signed comparison here.
5677         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5678       }
5679     }
5680
5681     // Only lower this if the icmp is the only user of the GEP or if we expect
5682     // the result to fold to a constant!
5683     if (TD &&
5684         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5685         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5686       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5687       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5688       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5689       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5690     }
5691   }
5692   return 0;
5693 }
5694
5695 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5696 ///
5697 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5698                                                 Instruction *LHSI,
5699                                                 Constant *RHSC) {
5700   if (!isa<ConstantFP>(RHSC)) return 0;
5701   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5702   
5703   // Get the width of the mantissa.  We don't want to hack on conversions that
5704   // might lose information from the integer, e.g. "i64 -> float"
5705   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5706   if (MantissaWidth == -1) return 0;  // Unknown.
5707   
5708   // Check to see that the input is converted from an integer type that is small
5709   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5710   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5711   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5712   
5713   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5714   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5715   if (LHSUnsigned)
5716     ++InputSize;
5717   
5718   // If the conversion would lose info, don't hack on this.
5719   if ((int)InputSize > MantissaWidth)
5720     return 0;
5721   
5722   // Otherwise, we can potentially simplify the comparison.  We know that it
5723   // will always come through as an integer value and we know the constant is
5724   // not a NAN (it would have been previously simplified).
5725   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5726   
5727   ICmpInst::Predicate Pred;
5728   switch (I.getPredicate()) {
5729   default: llvm_unreachable("Unexpected predicate!");
5730   case FCmpInst::FCMP_UEQ:
5731   case FCmpInst::FCMP_OEQ:
5732     Pred = ICmpInst::ICMP_EQ;
5733     break;
5734   case FCmpInst::FCMP_UGT:
5735   case FCmpInst::FCMP_OGT:
5736     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5737     break;
5738   case FCmpInst::FCMP_UGE:
5739   case FCmpInst::FCMP_OGE:
5740     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5741     break;
5742   case FCmpInst::FCMP_ULT:
5743   case FCmpInst::FCMP_OLT:
5744     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5745     break;
5746   case FCmpInst::FCMP_ULE:
5747   case FCmpInst::FCMP_OLE:
5748     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5749     break;
5750   case FCmpInst::FCMP_UNE:
5751   case FCmpInst::FCMP_ONE:
5752     Pred = ICmpInst::ICMP_NE;
5753     break;
5754   case FCmpInst::FCMP_ORD:
5755     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5756   case FCmpInst::FCMP_UNO:
5757     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5758   }
5759   
5760   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5761   
5762   // Now we know that the APFloat is a normal number, zero or inf.
5763   
5764   // See if the FP constant is too large for the integer.  For example,
5765   // comparing an i8 to 300.0.
5766   unsigned IntWidth = IntTy->getScalarSizeInBits();
5767   
5768   if (!LHSUnsigned) {
5769     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5770     // and large values.
5771     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5772     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5773                           APFloat::rmNearestTiesToEven);
5774     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5775       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5776           Pred == ICmpInst::ICMP_SLE)
5777         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5778       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5779     }
5780   } else {
5781     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5782     // +INF and large values.
5783     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5784     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5785                           APFloat::rmNearestTiesToEven);
5786     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5787       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5788           Pred == ICmpInst::ICMP_ULE)
5789         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5790       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5791     }
5792   }
5793   
5794   if (!LHSUnsigned) {
5795     // See if the RHS value is < SignedMin.
5796     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5797     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5798                           APFloat::rmNearestTiesToEven);
5799     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5800       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5801           Pred == ICmpInst::ICMP_SGE)
5802         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5803       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5804     }
5805   }
5806
5807   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5808   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5809   // casting the FP value to the integer value and back, checking for equality.
5810   // Don't do this for zero, because -0.0 is not fractional.
5811   Constant *RHSInt = LHSUnsigned
5812     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5813     : ConstantExpr::getFPToSI(RHSC, IntTy);
5814   if (!RHS.isZero()) {
5815     bool Equal = LHSUnsigned
5816       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5817       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5818     if (!Equal) {
5819       // If we had a comparison against a fractional value, we have to adjust
5820       // the compare predicate and sometimes the value.  RHSC is rounded towards
5821       // zero at this point.
5822       switch (Pred) {
5823       default: llvm_unreachable("Unexpected integer comparison!");
5824       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5825         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5826       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5827         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5828       case ICmpInst::ICMP_ULE:
5829         // (float)int <= 4.4   --> int <= 4
5830         // (float)int <= -4.4  --> false
5831         if (RHS.isNegative())
5832           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5833         break;
5834       case ICmpInst::ICMP_SLE:
5835         // (float)int <= 4.4   --> int <= 4
5836         // (float)int <= -4.4  --> int < -4
5837         if (RHS.isNegative())
5838           Pred = ICmpInst::ICMP_SLT;
5839         break;
5840       case ICmpInst::ICMP_ULT:
5841         // (float)int < -4.4   --> false
5842         // (float)int < 4.4    --> int <= 4
5843         if (RHS.isNegative())
5844           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5845         Pred = ICmpInst::ICMP_ULE;
5846         break;
5847       case ICmpInst::ICMP_SLT:
5848         // (float)int < -4.4   --> int < -4
5849         // (float)int < 4.4    --> int <= 4
5850         if (!RHS.isNegative())
5851           Pred = ICmpInst::ICMP_SLE;
5852         break;
5853       case ICmpInst::ICMP_UGT:
5854         // (float)int > 4.4    --> int > 4
5855         // (float)int > -4.4   --> true
5856         if (RHS.isNegative())
5857           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5858         break;
5859       case ICmpInst::ICMP_SGT:
5860         // (float)int > 4.4    --> int > 4
5861         // (float)int > -4.4   --> int >= -4
5862         if (RHS.isNegative())
5863           Pred = ICmpInst::ICMP_SGE;
5864         break;
5865       case ICmpInst::ICMP_UGE:
5866         // (float)int >= -4.4   --> true
5867         // (float)int >= 4.4    --> int > 4
5868         if (!RHS.isNegative())
5869           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5870         Pred = ICmpInst::ICMP_UGT;
5871         break;
5872       case ICmpInst::ICMP_SGE:
5873         // (float)int >= -4.4   --> int >= -4
5874         // (float)int >= 4.4    --> int > 4
5875         if (!RHS.isNegative())
5876           Pred = ICmpInst::ICMP_SGT;
5877         break;
5878       }
5879     }
5880   }
5881
5882   // Lower this FP comparison into an appropriate integer version of the
5883   // comparison.
5884   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5885 }
5886
5887 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5888   bool Changed = SimplifyCompare(I);
5889   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5890
5891   // Fold trivial predicates.
5892   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5893     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5894   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5895     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5896   
5897   // Simplify 'fcmp pred X, X'
5898   if (Op0 == Op1) {
5899     switch (I.getPredicate()) {
5900     default: llvm_unreachable("Unknown predicate!");
5901     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5902     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5903     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5904       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5905     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5906     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5907     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5908       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5909       
5910     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5911     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5912     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5913     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5914       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5915       I.setPredicate(FCmpInst::FCMP_UNO);
5916       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5917       return &I;
5918       
5919     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5920     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5921     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5922     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5923       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5924       I.setPredicate(FCmpInst::FCMP_ORD);
5925       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5926       return &I;
5927     }
5928   }
5929     
5930   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5931     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5932
5933   // Handle fcmp with constant RHS
5934   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5935     // If the constant is a nan, see if we can fold the comparison based on it.
5936     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5937       if (CFP->getValueAPF().isNaN()) {
5938         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5939           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5940         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5941                "Comparison must be either ordered or unordered!");
5942         // True if unordered.
5943         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5944       }
5945     }
5946     
5947     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5948       switch (LHSI->getOpcode()) {
5949       case Instruction::PHI:
5950         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5951         // block.  If in the same block, we're encouraging jump threading.  If
5952         // not, we are just pessimizing the code by making an i1 phi.
5953         if (LHSI->getParent() == I.getParent())
5954           if (Instruction *NV = FoldOpIntoPhi(I))
5955             return NV;
5956         break;
5957       case Instruction::SIToFP:
5958       case Instruction::UIToFP:
5959         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5960           return NV;
5961         break;
5962       case Instruction::Select:
5963         // If either operand of the select is a constant, we can fold the
5964         // comparison into the select arms, which will cause one to be
5965         // constant folded and the select turned into a bitwise or.
5966         Value *Op1 = 0, *Op2 = 0;
5967         if (LHSI->hasOneUse()) {
5968           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5969             // Fold the known value into the constant operand.
5970             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5971             // Insert a new FCmp of the other select operand.
5972             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5973                                                       LHSI->getOperand(2), RHSC,
5974                                                       I.getName()), I);
5975           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5976             // Fold the known value into the constant operand.
5977             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5978             // Insert a new FCmp of the other select operand.
5979             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5980                                                       LHSI->getOperand(1), RHSC,
5981                                                       I.getName()), I);
5982           }
5983         }
5984
5985         if (Op1)
5986           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5987         break;
5988       }
5989   }
5990
5991   return Changed ? &I : 0;
5992 }
5993
5994 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5995   bool Changed = SimplifyCompare(I);
5996   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5997   const Type *Ty = Op0->getType();
5998
5999   // icmp X, X
6000   if (Op0 == Op1)
6001     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6002                                                    I.isTrueWhenEqual()));
6003
6004   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
6005     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
6006   
6007   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6008   // addresses never equal each other!  We already know that Op0 != Op1.
6009   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6010        isa<ConstantPointerNull>(Op0)) &&
6011       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6012        isa<ConstantPointerNull>(Op1)))
6013     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6014                                                    !I.isTrueWhenEqual()));
6015
6016   // icmp's with boolean values can always be turned into bitwise operations
6017   if (Ty == Type::getInt1Ty(*Context)) {
6018     switch (I.getPredicate()) {
6019     default: llvm_unreachable("Invalid icmp instruction!");
6020     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6021       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6022       InsertNewInstBefore(Xor, I);
6023       return BinaryOperator::CreateNot(Xor);
6024     }
6025     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6026       return BinaryOperator::CreateXor(Op0, Op1);
6027
6028     case ICmpInst::ICMP_UGT:
6029       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6030       // FALL THROUGH
6031     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6032       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6033       InsertNewInstBefore(Not, I);
6034       return BinaryOperator::CreateAnd(Not, Op1);
6035     }
6036     case ICmpInst::ICMP_SGT:
6037       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6038       // FALL THROUGH
6039     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6040       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6041       InsertNewInstBefore(Not, I);
6042       return BinaryOperator::CreateAnd(Not, Op0);
6043     }
6044     case ICmpInst::ICMP_UGE:
6045       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6046       // FALL THROUGH
6047     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6048       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6049       InsertNewInstBefore(Not, I);
6050       return BinaryOperator::CreateOr(Not, Op1);
6051     }
6052     case ICmpInst::ICMP_SGE:
6053       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6054       // FALL THROUGH
6055     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6056       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6057       InsertNewInstBefore(Not, I);
6058       return BinaryOperator::CreateOr(Not, Op0);
6059     }
6060     }
6061   }
6062
6063   unsigned BitWidth = 0;
6064   if (TD)
6065     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6066   else if (Ty->isIntOrIntVector())
6067     BitWidth = Ty->getScalarSizeInBits();
6068
6069   bool isSignBit = false;
6070
6071   // See if we are doing a comparison with a constant.
6072   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6073     Value *A = 0, *B = 0;
6074     
6075     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6076     if (I.isEquality() && CI->isNullValue() &&
6077         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6078       // (icmp cond A B) if cond is equality
6079       return new ICmpInst(I.getPredicate(), A, B);
6080     }
6081     
6082     // If we have an icmp le or icmp ge instruction, turn it into the
6083     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6084     // them being folded in the code below.
6085     switch (I.getPredicate()) {
6086     default: break;
6087     case ICmpInst::ICMP_ULE:
6088       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6089         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6090       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6091                           AddOne(CI));
6092     case ICmpInst::ICMP_SLE:
6093       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6094         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6095       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6096                           AddOne(CI));
6097     case ICmpInst::ICMP_UGE:
6098       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6099         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6100       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6101                           SubOne(CI));
6102     case ICmpInst::ICMP_SGE:
6103       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6104         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6105       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6106                           SubOne(CI));
6107     }
6108     
6109     // If this comparison is a normal comparison, it demands all
6110     // bits, if it is a sign bit comparison, it only demands the sign bit.
6111     bool UnusedBit;
6112     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6113   }
6114
6115   // See if we can fold the comparison based on range information we can get
6116   // by checking whether bits are known to be zero or one in the input.
6117   if (BitWidth != 0) {
6118     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6119     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6120
6121     if (SimplifyDemandedBits(I.getOperandUse(0),
6122                              isSignBit ? APInt::getSignBit(BitWidth)
6123                                        : APInt::getAllOnesValue(BitWidth),
6124                              Op0KnownZero, Op0KnownOne, 0))
6125       return &I;
6126     if (SimplifyDemandedBits(I.getOperandUse(1),
6127                              APInt::getAllOnesValue(BitWidth),
6128                              Op1KnownZero, Op1KnownOne, 0))
6129       return &I;
6130
6131     // Given the known and unknown bits, compute a range that the LHS could be
6132     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6133     // EQ and NE we use unsigned values.
6134     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6135     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6136     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6137       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6138                                              Op0Min, Op0Max);
6139       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6140                                              Op1Min, Op1Max);
6141     } else {
6142       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6143                                                Op0Min, Op0Max);
6144       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6145                                                Op1Min, Op1Max);
6146     }
6147
6148     // If Min and Max are known to be the same, then SimplifyDemandedBits
6149     // figured out that the LHS is a constant.  Just constant fold this now so
6150     // that code below can assume that Min != Max.
6151     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6152       return new ICmpInst(I.getPredicate(),
6153                           ConstantInt::get(*Context, Op0Min), Op1);
6154     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6155       return new ICmpInst(I.getPredicate(), Op0,
6156                           ConstantInt::get(*Context, Op1Min));
6157
6158     // Based on the range information we know about the LHS, see if we can
6159     // simplify this comparison.  For example, (x&4) < 8  is always true.
6160     switch (I.getPredicate()) {
6161     default: llvm_unreachable("Unknown icmp opcode!");
6162     case ICmpInst::ICMP_EQ:
6163       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6164         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6165       break;
6166     case ICmpInst::ICMP_NE:
6167       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6168         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6169       break;
6170     case ICmpInst::ICMP_ULT:
6171       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6172         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6173       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6174         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6175       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6176         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6177       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6178         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6179           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6180                               SubOne(CI));
6181
6182         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6183         if (CI->isMinValue(true))
6184           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6185                            Constant::getAllOnesValue(Op0->getType()));
6186       }
6187       break;
6188     case ICmpInst::ICMP_UGT:
6189       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6190         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6191       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6192         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6193
6194       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6195         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6196       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6197         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6198           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6199                               AddOne(CI));
6200
6201         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6202         if (CI->isMaxValue(true))
6203           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6204                               Constant::getNullValue(Op0->getType()));
6205       }
6206       break;
6207     case ICmpInst::ICMP_SLT:
6208       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6209         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6210       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6211         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6212       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6213         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6214       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6215         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6216           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6217                               SubOne(CI));
6218       }
6219       break;
6220     case ICmpInst::ICMP_SGT:
6221       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6222         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6223       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6224         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6225
6226       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6227         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6228       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6229         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6230           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6231                               AddOne(CI));
6232       }
6233       break;
6234     case ICmpInst::ICMP_SGE:
6235       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6236       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6237         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6238       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6239         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6240       break;
6241     case ICmpInst::ICMP_SLE:
6242       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6243       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6244         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6245       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6246         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6247       break;
6248     case ICmpInst::ICMP_UGE:
6249       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6250       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6251         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6252       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6253         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6254       break;
6255     case ICmpInst::ICMP_ULE:
6256       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6257       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6258         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6259       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6260         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6261       break;
6262     }
6263
6264     // Turn a signed comparison into an unsigned one if both operands
6265     // are known to have the same sign.
6266     if (I.isSignedPredicate() &&
6267         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6268          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6269       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6270   }
6271
6272   // Test if the ICmpInst instruction is used exclusively by a select as
6273   // part of a minimum or maximum operation. If so, refrain from doing
6274   // any other folding. This helps out other analyses which understand
6275   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6276   // and CodeGen. And in this case, at least one of the comparison
6277   // operands has at least one user besides the compare (the select),
6278   // which would often largely negate the benefit of folding anyway.
6279   if (I.hasOneUse())
6280     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6281       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6282           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6283         return 0;
6284
6285   // See if we are doing a comparison between a constant and an instruction that
6286   // can be folded into the comparison.
6287   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6288     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6289     // instruction, see if that instruction also has constants so that the 
6290     // instruction can be folded into the icmp 
6291     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6292       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6293         return Res;
6294   }
6295
6296   // Handle icmp with constant (but not simple integer constant) RHS
6297   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6298     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6299       switch (LHSI->getOpcode()) {
6300       case Instruction::GetElementPtr:
6301         if (RHSC->isNullValue()) {
6302           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6303           bool isAllZeros = true;
6304           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6305             if (!isa<Constant>(LHSI->getOperand(i)) ||
6306                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6307               isAllZeros = false;
6308               break;
6309             }
6310           if (isAllZeros)
6311             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6312                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6313         }
6314         break;
6315
6316       case Instruction::PHI:
6317         // Only fold icmp into the PHI if the phi and fcmp are in the same
6318         // block.  If in the same block, we're encouraging jump threading.  If
6319         // not, we are just pessimizing the code by making an i1 phi.
6320         if (LHSI->getParent() == I.getParent())
6321           if (Instruction *NV = FoldOpIntoPhi(I))
6322             return NV;
6323         break;
6324       case Instruction::Select: {
6325         // If either operand of the select is a constant, we can fold the
6326         // comparison into the select arms, which will cause one to be
6327         // constant folded and the select turned into a bitwise or.
6328         Value *Op1 = 0, *Op2 = 0;
6329         if (LHSI->hasOneUse()) {
6330           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6331             // Fold the known value into the constant operand.
6332             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6333             // Insert a new ICmp of the other select operand.
6334             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6335                                                    LHSI->getOperand(2), RHSC,
6336                                                    I.getName()), I);
6337           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6338             // Fold the known value into the constant operand.
6339             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6340             // Insert a new ICmp of the other select operand.
6341             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6342                                                    LHSI->getOperand(1), RHSC,
6343                                                    I.getName()), I);
6344           }
6345         }
6346
6347         if (Op1)
6348           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6349         break;
6350       }
6351       case Instruction::Malloc:
6352         // If we have (malloc != null), and if the malloc has a single use, we
6353         // can assume it is successful and remove the malloc.
6354         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6355           Worklist.Add(LHSI);
6356           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6357                                                          !I.isTrueWhenEqual()));
6358         }
6359         break;
6360       }
6361   }
6362
6363   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6364   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6365     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6366       return NI;
6367   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6368     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6369                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6370       return NI;
6371
6372   // Test to see if the operands of the icmp are casted versions of other
6373   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6374   // now.
6375   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6376     if (isa<PointerType>(Op0->getType()) && 
6377         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6378       // We keep moving the cast from the left operand over to the right
6379       // operand, where it can often be eliminated completely.
6380       Op0 = CI->getOperand(0);
6381
6382       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6383       // so eliminate it as well.
6384       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6385         Op1 = CI2->getOperand(0);
6386
6387       // If Op1 is a constant, we can fold the cast into the constant.
6388       if (Op0->getType() != Op1->getType()) {
6389         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6390           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6391         } else {
6392           // Otherwise, cast the RHS right before the icmp
6393           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6394         }
6395       }
6396       return new ICmpInst(I.getPredicate(), Op0, Op1);
6397     }
6398   }
6399   
6400   if (isa<CastInst>(Op0)) {
6401     // Handle the special case of: icmp (cast bool to X), <cst>
6402     // This comes up when you have code like
6403     //   int X = A < B;
6404     //   if (X) ...
6405     // For generality, we handle any zero-extension of any operand comparison
6406     // with a constant or another cast from the same type.
6407     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6408       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6409         return R;
6410   }
6411   
6412   // See if it's the same type of instruction on the left and right.
6413   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6414     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6415       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6416           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6417         switch (Op0I->getOpcode()) {
6418         default: break;
6419         case Instruction::Add:
6420         case Instruction::Sub:
6421         case Instruction::Xor:
6422           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6423             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6424                                 Op1I->getOperand(0));
6425           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6426           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6427             if (CI->getValue().isSignBit()) {
6428               ICmpInst::Predicate Pred = I.isSignedPredicate()
6429                                              ? I.getUnsignedPredicate()
6430                                              : I.getSignedPredicate();
6431               return new ICmpInst(Pred, Op0I->getOperand(0),
6432                                   Op1I->getOperand(0));
6433             }
6434             
6435             if (CI->getValue().isMaxSignedValue()) {
6436               ICmpInst::Predicate Pred = I.isSignedPredicate()
6437                                              ? I.getUnsignedPredicate()
6438                                              : I.getSignedPredicate();
6439               Pred = I.getSwappedPredicate(Pred);
6440               return new ICmpInst(Pred, Op0I->getOperand(0),
6441                                   Op1I->getOperand(0));
6442             }
6443           }
6444           break;
6445         case Instruction::Mul:
6446           if (!I.isEquality())
6447             break;
6448
6449           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6450             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6451             // Mask = -1 >> count-trailing-zeros(Cst).
6452             if (!CI->isZero() && !CI->isOne()) {
6453               const APInt &AP = CI->getValue();
6454               ConstantInt *Mask = ConstantInt::get(*Context, 
6455                                       APInt::getLowBitsSet(AP.getBitWidth(),
6456                                                            AP.getBitWidth() -
6457                                                       AP.countTrailingZeros()));
6458               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6459                                                             Mask);
6460               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6461                                                             Mask);
6462               InsertNewInstBefore(And1, I);
6463               InsertNewInstBefore(And2, I);
6464               return new ICmpInst(I.getPredicate(), And1, And2);
6465             }
6466           }
6467           break;
6468         }
6469       }
6470     }
6471   }
6472   
6473   // ~x < ~y --> y < x
6474   { Value *A, *B;
6475     if (match(Op0, m_Not(m_Value(A))) &&
6476         match(Op1, m_Not(m_Value(B))))
6477       return new ICmpInst(I.getPredicate(), B, A);
6478   }
6479   
6480   if (I.isEquality()) {
6481     Value *A, *B, *C, *D;
6482     
6483     // -x == -y --> x == y
6484     if (match(Op0, m_Neg(m_Value(A))) &&
6485         match(Op1, m_Neg(m_Value(B))))
6486       return new ICmpInst(I.getPredicate(), A, B);
6487     
6488     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6489       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6490         Value *OtherVal = A == Op1 ? B : A;
6491         return new ICmpInst(I.getPredicate(), OtherVal,
6492                             Constant::getNullValue(A->getType()));
6493       }
6494
6495       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6496         // A^c1 == C^c2 --> A == C^(c1^c2)
6497         ConstantInt *C1, *C2;
6498         if (match(B, m_ConstantInt(C1)) &&
6499             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6500           Constant *NC = 
6501                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6502           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6503           return new ICmpInst(I.getPredicate(), A,
6504                               InsertNewInstBefore(Xor, I));
6505         }
6506         
6507         // A^B == A^D -> B == D
6508         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6509         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6510         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6511         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6512       }
6513     }
6514     
6515     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6516         (A == Op0 || B == Op0)) {
6517       // A == (A^B)  ->  B == 0
6518       Value *OtherVal = A == Op0 ? B : A;
6519       return new ICmpInst(I.getPredicate(), OtherVal,
6520                           Constant::getNullValue(A->getType()));
6521     }
6522
6523     // (A-B) == A  ->  B == 0
6524     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6525       return new ICmpInst(I.getPredicate(), B, 
6526                           Constant::getNullValue(B->getType()));
6527
6528     // A == (A-B)  ->  B == 0
6529     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6530       return new ICmpInst(I.getPredicate(), B,
6531                           Constant::getNullValue(B->getType()));
6532     
6533     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6534     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6535         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6536         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6537       Value *X = 0, *Y = 0, *Z = 0;
6538       
6539       if (A == C) {
6540         X = B; Y = D; Z = A;
6541       } else if (A == D) {
6542         X = B; Y = C; Z = A;
6543       } else if (B == C) {
6544         X = A; Y = D; Z = B;
6545       } else if (B == D) {
6546         X = A; Y = C; Z = B;
6547       }
6548       
6549       if (X) {   // Build (X^Y) & Z
6550         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6551         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6552         I.setOperand(0, Op1);
6553         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6554         return &I;
6555       }
6556     }
6557   }
6558   return Changed ? &I : 0;
6559 }
6560
6561
6562 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6563 /// and CmpRHS are both known to be integer constants.
6564 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6565                                           ConstantInt *DivRHS) {
6566   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6567   const APInt &CmpRHSV = CmpRHS->getValue();
6568   
6569   // FIXME: If the operand types don't match the type of the divide 
6570   // then don't attempt this transform. The code below doesn't have the
6571   // logic to deal with a signed divide and an unsigned compare (and
6572   // vice versa). This is because (x /s C1) <s C2  produces different 
6573   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6574   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6575   // work. :(  The if statement below tests that condition and bails 
6576   // if it finds it. 
6577   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6578   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6579     return 0;
6580   if (DivRHS->isZero())
6581     return 0; // The ProdOV computation fails on divide by zero.
6582   if (DivIsSigned && DivRHS->isAllOnesValue())
6583     return 0; // The overflow computation also screws up here
6584   if (DivRHS->isOne())
6585     return 0; // Not worth bothering, and eliminates some funny cases
6586               // with INT_MIN.
6587
6588   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6589   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6590   // C2 (CI). By solving for X we can turn this into a range check 
6591   // instead of computing a divide. 
6592   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6593
6594   // Determine if the product overflows by seeing if the product is
6595   // not equal to the divide. Make sure we do the same kind of divide
6596   // as in the LHS instruction that we're folding. 
6597   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6598                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6599
6600   // Get the ICmp opcode
6601   ICmpInst::Predicate Pred = ICI.getPredicate();
6602
6603   // Figure out the interval that is being checked.  For example, a comparison
6604   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6605   // Compute this interval based on the constants involved and the signedness of
6606   // the compare/divide.  This computes a half-open interval, keeping track of
6607   // whether either value in the interval overflows.  After analysis each
6608   // overflow variable is set to 0 if it's corresponding bound variable is valid
6609   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6610   int LoOverflow = 0, HiOverflow = 0;
6611   Constant *LoBound = 0, *HiBound = 0;
6612   
6613   if (!DivIsSigned) {  // udiv
6614     // e.g. X/5 op 3  --> [15, 20)
6615     LoBound = Prod;
6616     HiOverflow = LoOverflow = ProdOV;
6617     if (!HiOverflow)
6618       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6619   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6620     if (CmpRHSV == 0) {       // (X / pos) op 0
6621       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6622       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6623       HiBound = DivRHS;
6624     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6625       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6626       HiOverflow = LoOverflow = ProdOV;
6627       if (!HiOverflow)
6628         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6629     } else {                       // (X / pos) op neg
6630       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6631       HiBound = AddOne(Prod);
6632       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6633       if (!LoOverflow) {
6634         ConstantInt* DivNeg =
6635                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6636         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6637                                      true) ? -1 : 0;
6638        }
6639     }
6640   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6641     if (CmpRHSV == 0) {       // (X / neg) op 0
6642       // e.g. X/-5 op 0  --> [-4, 5)
6643       LoBound = AddOne(DivRHS);
6644       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6645       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6646         HiOverflow = 1;            // [INTMIN+1, overflow)
6647         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6648       }
6649     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6650       // e.g. X/-5 op 3  --> [-19, -14)
6651       HiBound = AddOne(Prod);
6652       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6653       if (!LoOverflow)
6654         LoOverflow = AddWithOverflow(LoBound, HiBound,
6655                                      DivRHS, Context, true) ? -1 : 0;
6656     } else {                       // (X / neg) op neg
6657       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6658       LoOverflow = HiOverflow = ProdOV;
6659       if (!HiOverflow)
6660         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6661     }
6662     
6663     // Dividing by a negative swaps the condition.  LT <-> GT
6664     Pred = ICmpInst::getSwappedPredicate(Pred);
6665   }
6666
6667   Value *X = DivI->getOperand(0);
6668   switch (Pred) {
6669   default: llvm_unreachable("Unhandled icmp opcode!");
6670   case ICmpInst::ICMP_EQ:
6671     if (LoOverflow && HiOverflow)
6672       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6673     else if (HiOverflow)
6674       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6675                           ICmpInst::ICMP_UGE, X, LoBound);
6676     else if (LoOverflow)
6677       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6678                           ICmpInst::ICMP_ULT, X, HiBound);
6679     else
6680       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6681   case ICmpInst::ICMP_NE:
6682     if (LoOverflow && HiOverflow)
6683       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6684     else if (HiOverflow)
6685       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6686                           ICmpInst::ICMP_ULT, X, LoBound);
6687     else if (LoOverflow)
6688       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6689                           ICmpInst::ICMP_UGE, X, HiBound);
6690     else
6691       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6692   case ICmpInst::ICMP_ULT:
6693   case ICmpInst::ICMP_SLT:
6694     if (LoOverflow == +1)   // Low bound is greater than input range.
6695       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6696     if (LoOverflow == -1)   // Low bound is less than input range.
6697       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6698     return new ICmpInst(Pred, X, LoBound);
6699   case ICmpInst::ICMP_UGT:
6700   case ICmpInst::ICMP_SGT:
6701     if (HiOverflow == +1)       // High bound greater than input range.
6702       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6703     else if (HiOverflow == -1)  // High bound less than input range.
6704       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6705     if (Pred == ICmpInst::ICMP_UGT)
6706       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6707     else
6708       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6709   }
6710 }
6711
6712
6713 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6714 ///
6715 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6716                                                           Instruction *LHSI,
6717                                                           ConstantInt *RHS) {
6718   const APInt &RHSV = RHS->getValue();
6719   
6720   switch (LHSI->getOpcode()) {
6721   case Instruction::Trunc:
6722     if (ICI.isEquality() && LHSI->hasOneUse()) {
6723       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6724       // of the high bits truncated out of x are known.
6725       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6726              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6727       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6728       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6729       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6730       
6731       // If all the high bits are known, we can do this xform.
6732       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6733         // Pull in the high bits from known-ones set.
6734         APInt NewRHS(RHS->getValue());
6735         NewRHS.zext(SrcBits);
6736         NewRHS |= KnownOne;
6737         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6738                             ConstantInt::get(*Context, NewRHS));
6739       }
6740     }
6741     break;
6742       
6743   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6744     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6745       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6746       // fold the xor.
6747       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6748           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6749         Value *CompareVal = LHSI->getOperand(0);
6750         
6751         // If the sign bit of the XorCST is not set, there is no change to
6752         // the operation, just stop using the Xor.
6753         if (!XorCST->getValue().isNegative()) {
6754           ICI.setOperand(0, CompareVal);
6755           Worklist.Add(LHSI);
6756           return &ICI;
6757         }
6758         
6759         // Was the old condition true if the operand is positive?
6760         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6761         
6762         // If so, the new one isn't.
6763         isTrueIfPositive ^= true;
6764         
6765         if (isTrueIfPositive)
6766           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6767                               SubOne(RHS));
6768         else
6769           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6770                               AddOne(RHS));
6771       }
6772
6773       if (LHSI->hasOneUse()) {
6774         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6775         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6776           const APInt &SignBit = XorCST->getValue();
6777           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6778                                          ? ICI.getUnsignedPredicate()
6779                                          : ICI.getSignedPredicate();
6780           return new ICmpInst(Pred, LHSI->getOperand(0),
6781                               ConstantInt::get(*Context, RHSV ^ SignBit));
6782         }
6783
6784         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6785         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6786           const APInt &NotSignBit = XorCST->getValue();
6787           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6788                                          ? ICI.getUnsignedPredicate()
6789                                          : ICI.getSignedPredicate();
6790           Pred = ICI.getSwappedPredicate(Pred);
6791           return new ICmpInst(Pred, LHSI->getOperand(0),
6792                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6793         }
6794       }
6795     }
6796     break;
6797   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6798     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6799         LHSI->getOperand(0)->hasOneUse()) {
6800       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6801       
6802       // If the LHS is an AND of a truncating cast, we can widen the
6803       // and/compare to be the input width without changing the value
6804       // produced, eliminating a cast.
6805       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6806         // We can do this transformation if either the AND constant does not
6807         // have its sign bit set or if it is an equality comparison. 
6808         // Extending a relational comparison when we're checking the sign
6809         // bit would not work.
6810         if (Cast->hasOneUse() &&
6811             (ICI.isEquality() ||
6812              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6813           uint32_t BitWidth = 
6814             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6815           APInt NewCST = AndCST->getValue();
6816           NewCST.zext(BitWidth);
6817           APInt NewCI = RHSV;
6818           NewCI.zext(BitWidth);
6819           Instruction *NewAnd = 
6820             BinaryOperator::CreateAnd(Cast->getOperand(0),
6821                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6822           InsertNewInstBefore(NewAnd, ICI);
6823           return new ICmpInst(ICI.getPredicate(), NewAnd,
6824                               ConstantInt::get(*Context, NewCI));
6825         }
6826       }
6827       
6828       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6829       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6830       // happens a LOT in code produced by the C front-end, for bitfield
6831       // access.
6832       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6833       if (Shift && !Shift->isShift())
6834         Shift = 0;
6835       
6836       ConstantInt *ShAmt;
6837       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6838       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6839       const Type *AndTy = AndCST->getType();          // Type of the and.
6840       
6841       // We can fold this as long as we can't shift unknown bits
6842       // into the mask.  This can only happen with signed shift
6843       // rights, as they sign-extend.
6844       if (ShAmt) {
6845         bool CanFold = Shift->isLogicalShift();
6846         if (!CanFold) {
6847           // To test for the bad case of the signed shr, see if any
6848           // of the bits shifted in could be tested after the mask.
6849           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6850           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6851           
6852           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6853           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6854                AndCST->getValue()) == 0)
6855             CanFold = true;
6856         }
6857         
6858         if (CanFold) {
6859           Constant *NewCst;
6860           if (Shift->getOpcode() == Instruction::Shl)
6861             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6862           else
6863             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6864           
6865           // Check to see if we are shifting out any of the bits being
6866           // compared.
6867           if (ConstantExpr::get(Shift->getOpcode(),
6868                                        NewCst, ShAmt) != RHS) {
6869             // If we shifted bits out, the fold is not going to work out.
6870             // As a special case, check to see if this means that the
6871             // result is always true or false now.
6872             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6873               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6874             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6875               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6876           } else {
6877             ICI.setOperand(1, NewCst);
6878             Constant *NewAndCST;
6879             if (Shift->getOpcode() == Instruction::Shl)
6880               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6881             else
6882               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6883             LHSI->setOperand(1, NewAndCST);
6884             LHSI->setOperand(0, Shift->getOperand(0));
6885             Worklist.Add(Shift); // Shift is dead.
6886             return &ICI;
6887           }
6888         }
6889       }
6890       
6891       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6892       // preferable because it allows the C<<Y expression to be hoisted out
6893       // of a loop if Y is invariant and X is not.
6894       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6895           ICI.isEquality() && !Shift->isArithmeticShift() &&
6896           !isa<Constant>(Shift->getOperand(0))) {
6897         // Compute C << Y.
6898         Value *NS;
6899         if (Shift->getOpcode() == Instruction::LShr) {
6900           NS = BinaryOperator::CreateShl(AndCST, 
6901                                          Shift->getOperand(1), "tmp");
6902         } else {
6903           // Insert a logical shift.
6904           NS = BinaryOperator::CreateLShr(AndCST,
6905                                           Shift->getOperand(1), "tmp");
6906         }
6907         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6908         
6909         // Compute X & (C << Y).
6910         Instruction *NewAnd = 
6911           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6912         InsertNewInstBefore(NewAnd, ICI);
6913         
6914         ICI.setOperand(0, NewAnd);
6915         return &ICI;
6916       }
6917     }
6918     break;
6919     
6920   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6921     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6922     if (!ShAmt) break;
6923     
6924     uint32_t TypeBits = RHSV.getBitWidth();
6925     
6926     // Check that the shift amount is in range.  If not, don't perform
6927     // undefined shifts.  When the shift is visited it will be
6928     // simplified.
6929     if (ShAmt->uge(TypeBits))
6930       break;
6931     
6932     if (ICI.isEquality()) {
6933       // If we are comparing against bits always shifted out, the
6934       // comparison cannot succeed.
6935       Constant *Comp =
6936         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6937                                                                  ShAmt);
6938       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6939         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6940         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6941         return ReplaceInstUsesWith(ICI, Cst);
6942       }
6943       
6944       if (LHSI->hasOneUse()) {
6945         // Otherwise strength reduce the shift into an and.
6946         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6947         Constant *Mask =
6948           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6949                                                        TypeBits-ShAmtVal));
6950         
6951         Instruction *AndI =
6952           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6953                                     Mask, LHSI->getName()+".mask");
6954         Value *And = InsertNewInstBefore(AndI, ICI);
6955         return new ICmpInst(ICI.getPredicate(), And,
6956                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6957       }
6958     }
6959     
6960     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6961     bool TrueIfSigned = false;
6962     if (LHSI->hasOneUse() &&
6963         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6964       // (X << 31) <s 0  --> (X&1) != 0
6965       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6966                                            (TypeBits-ShAmt->getZExtValue()-1));
6967       Instruction *AndI =
6968         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6969                                   Mask, LHSI->getName()+".mask");
6970       Value *And = InsertNewInstBefore(AndI, ICI);
6971       
6972       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6973                           And, Constant::getNullValue(And->getType()));
6974     }
6975     break;
6976   }
6977     
6978   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6979   case Instruction::AShr: {
6980     // Only handle equality comparisons of shift-by-constant.
6981     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6982     if (!ShAmt || !ICI.isEquality()) break;
6983
6984     // Check that the shift amount is in range.  If not, don't perform
6985     // undefined shifts.  When the shift is visited it will be
6986     // simplified.
6987     uint32_t TypeBits = RHSV.getBitWidth();
6988     if (ShAmt->uge(TypeBits))
6989       break;
6990     
6991     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6992       
6993     // If we are comparing against bits always shifted out, the
6994     // comparison cannot succeed.
6995     APInt Comp = RHSV << ShAmtVal;
6996     if (LHSI->getOpcode() == Instruction::LShr)
6997       Comp = Comp.lshr(ShAmtVal);
6998     else
6999       Comp = Comp.ashr(ShAmtVal);
7000     
7001     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7002       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7003       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7004       return ReplaceInstUsesWith(ICI, Cst);
7005     }
7006     
7007     // Otherwise, check to see if the bits shifted out are known to be zero.
7008     // If so, we can compare against the unshifted value:
7009     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7010     if (LHSI->hasOneUse() &&
7011         MaskedValueIsZero(LHSI->getOperand(0), 
7012                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7013       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7014                           ConstantExpr::getShl(RHS, ShAmt));
7015     }
7016       
7017     if (LHSI->hasOneUse()) {
7018       // Otherwise strength reduce the shift into an and.
7019       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7020       Constant *Mask = ConstantInt::get(*Context, Val);
7021       
7022       Instruction *AndI =
7023         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7024                                   Mask, LHSI->getName()+".mask");
7025       Value *And = InsertNewInstBefore(AndI, ICI);
7026       return new ICmpInst(ICI.getPredicate(), And,
7027                           ConstantExpr::getShl(RHS, ShAmt));
7028     }
7029     break;
7030   }
7031     
7032   case Instruction::SDiv:
7033   case Instruction::UDiv:
7034     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7035     // Fold this div into the comparison, producing a range check. 
7036     // Determine, based on the divide type, what the range is being 
7037     // checked.  If there is an overflow on the low or high side, remember 
7038     // it, otherwise compute the range [low, hi) bounding the new value.
7039     // See: InsertRangeTest above for the kinds of replacements possible.
7040     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7041       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7042                                           DivRHS))
7043         return R;
7044     break;
7045
7046   case Instruction::Add:
7047     // Fold: icmp pred (add, X, C1), C2
7048
7049     if (!ICI.isEquality()) {
7050       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7051       if (!LHSC) break;
7052       const APInt &LHSV = LHSC->getValue();
7053
7054       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7055                             .subtract(LHSV);
7056
7057       if (ICI.isSignedPredicate()) {
7058         if (CR.getLower().isSignBit()) {
7059           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7060                               ConstantInt::get(*Context, CR.getUpper()));
7061         } else if (CR.getUpper().isSignBit()) {
7062           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7063                               ConstantInt::get(*Context, CR.getLower()));
7064         }
7065       } else {
7066         if (CR.getLower().isMinValue()) {
7067           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7068                               ConstantInt::get(*Context, CR.getUpper()));
7069         } else if (CR.getUpper().isMinValue()) {
7070           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7071                               ConstantInt::get(*Context, CR.getLower()));
7072         }
7073       }
7074     }
7075     break;
7076   }
7077   
7078   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7079   if (ICI.isEquality()) {
7080     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7081     
7082     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7083     // the second operand is a constant, simplify a bit.
7084     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7085       switch (BO->getOpcode()) {
7086       case Instruction::SRem:
7087         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7088         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7089           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7090           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7091             Instruction *NewRem =
7092               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7093                                          BO->getName());
7094             InsertNewInstBefore(NewRem, ICI);
7095             return new ICmpInst(ICI.getPredicate(), NewRem,
7096                                 Constant::getNullValue(BO->getType()));
7097           }
7098         }
7099         break;
7100       case Instruction::Add:
7101         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7102         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7103           if (BO->hasOneUse())
7104             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7105                                 ConstantExpr::getSub(RHS, BOp1C));
7106         } else if (RHSV == 0) {
7107           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7108           // efficiently invertible, or if the add has just this one use.
7109           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7110           
7111           if (Value *NegVal = dyn_castNegVal(BOp1))
7112             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7113           else if (Value *NegVal = dyn_castNegVal(BOp0))
7114             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7115           else if (BO->hasOneUse()) {
7116             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7117             InsertNewInstBefore(Neg, ICI);
7118             Neg->takeName(BO);
7119             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7120           }
7121         }
7122         break;
7123       case Instruction::Xor:
7124         // For the xor case, we can xor two constants together, eliminating
7125         // the explicit xor.
7126         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7127           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7128                               ConstantExpr::getXor(RHS, BOC));
7129         
7130         // FALLTHROUGH
7131       case Instruction::Sub:
7132         // Replace (([sub|xor] A, B) != 0) with (A != B)
7133         if (RHSV == 0)
7134           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7135                               BO->getOperand(1));
7136         break;
7137         
7138       case Instruction::Or:
7139         // If bits are being or'd in that are not present in the constant we
7140         // are comparing against, then the comparison could never succeed!
7141         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7142           Constant *NotCI = ConstantExpr::getNot(RHS);
7143           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7144             return ReplaceInstUsesWith(ICI,
7145                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7146                                        isICMP_NE));
7147         }
7148         break;
7149         
7150       case Instruction::And:
7151         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7152           // If bits are being compared against that are and'd out, then the
7153           // comparison can never succeed!
7154           if ((RHSV & ~BOC->getValue()) != 0)
7155             return ReplaceInstUsesWith(ICI,
7156                                        ConstantInt::get(Type::getInt1Ty(*Context),
7157                                        isICMP_NE));
7158           
7159           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7160           if (RHS == BOC && RHSV.isPowerOf2())
7161             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7162                                 ICmpInst::ICMP_NE, LHSI,
7163                                 Constant::getNullValue(RHS->getType()));
7164           
7165           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7166           if (BOC->getValue().isSignBit()) {
7167             Value *X = BO->getOperand(0);
7168             Constant *Zero = Constant::getNullValue(X->getType());
7169             ICmpInst::Predicate pred = isICMP_NE ? 
7170               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7171             return new ICmpInst(pred, X, Zero);
7172           }
7173           
7174           // ((X & ~7) == 0) --> X < 8
7175           if (RHSV == 0 && isHighOnes(BOC)) {
7176             Value *X = BO->getOperand(0);
7177             Constant *NegX = ConstantExpr::getNeg(BOC);
7178             ICmpInst::Predicate pred = isICMP_NE ? 
7179               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7180             return new ICmpInst(pred, X, NegX);
7181           }
7182         }
7183       default: break;
7184       }
7185     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7186       // Handle icmp {eq|ne} <intrinsic>, intcst.
7187       if (II->getIntrinsicID() == Intrinsic::bswap) {
7188         Worklist.Add(II);
7189         ICI.setOperand(0, II->getOperand(1));
7190         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7191         return &ICI;
7192       }
7193     }
7194   }
7195   return 0;
7196 }
7197
7198 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7199 /// We only handle extending casts so far.
7200 ///
7201 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7202   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7203   Value *LHSCIOp        = LHSCI->getOperand(0);
7204   const Type *SrcTy     = LHSCIOp->getType();
7205   const Type *DestTy    = LHSCI->getType();
7206   Value *RHSCIOp;
7207
7208   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7209   // integer type is the same size as the pointer type.
7210   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7211       TD->getPointerSizeInBits() ==
7212          cast<IntegerType>(DestTy)->getBitWidth()) {
7213     Value *RHSOp = 0;
7214     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7215       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7216     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7217       RHSOp = RHSC->getOperand(0);
7218       // If the pointer types don't match, insert a bitcast.
7219       if (LHSCIOp->getType() != RHSOp->getType())
7220         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7221     }
7222
7223     if (RHSOp)
7224       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7225   }
7226   
7227   // The code below only handles extension cast instructions, so far.
7228   // Enforce this.
7229   if (LHSCI->getOpcode() != Instruction::ZExt &&
7230       LHSCI->getOpcode() != Instruction::SExt)
7231     return 0;
7232
7233   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7234   bool isSignedCmp = ICI.isSignedPredicate();
7235
7236   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7237     // Not an extension from the same type?
7238     RHSCIOp = CI->getOperand(0);
7239     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7240       return 0;
7241     
7242     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7243     // and the other is a zext), then we can't handle this.
7244     if (CI->getOpcode() != LHSCI->getOpcode())
7245       return 0;
7246
7247     // Deal with equality cases early.
7248     if (ICI.isEquality())
7249       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7250
7251     // A signed comparison of sign extended values simplifies into a
7252     // signed comparison.
7253     if (isSignedCmp && isSignedExt)
7254       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7255
7256     // The other three cases all fold into an unsigned comparison.
7257     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7258   }
7259
7260   // If we aren't dealing with a constant on the RHS, exit early
7261   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7262   if (!CI)
7263     return 0;
7264
7265   // Compute the constant that would happen if we truncated to SrcTy then
7266   // reextended to DestTy.
7267   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7268   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7269                                                 Res1, DestTy);
7270
7271   // If the re-extended constant didn't change...
7272   if (Res2 == CI) {
7273     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7274     // For example, we might have:
7275     //    %A = sext i16 %X to i32
7276     //    %B = icmp ugt i32 %A, 1330
7277     // It is incorrect to transform this into 
7278     //    %B = icmp ugt i16 %X, 1330
7279     // because %A may have negative value. 
7280     //
7281     // However, we allow this when the compare is EQ/NE, because they are
7282     // signless.
7283     if (isSignedExt == isSignedCmp || ICI.isEquality())
7284       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7285     return 0;
7286   }
7287
7288   // The re-extended constant changed so the constant cannot be represented 
7289   // in the shorter type. Consequently, we cannot emit a simple comparison.
7290
7291   // First, handle some easy cases. We know the result cannot be equal at this
7292   // point so handle the ICI.isEquality() cases
7293   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7294     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7295   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7296     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7297
7298   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7299   // should have been folded away previously and not enter in here.
7300   Value *Result;
7301   if (isSignedCmp) {
7302     // We're performing a signed comparison.
7303     if (cast<ConstantInt>(CI)->getValue().isNegative())
7304       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7305     else
7306       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7307   } else {
7308     // We're performing an unsigned comparison.
7309     if (isSignedExt) {
7310       // We're performing an unsigned comp with a sign extended value.
7311       // This is true if the input is >= 0. [aka >s -1]
7312       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7313       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
7314                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7315     } else {
7316       // Unsigned extend & unsigned compare -> always true.
7317       Result = ConstantInt::getTrue(*Context);
7318     }
7319   }
7320
7321   // Finally, return the value computed.
7322   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7323       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7324     return ReplaceInstUsesWith(ICI, Result);
7325
7326   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7327           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7328          "ICmp should be folded!");
7329   if (Constant *CI = dyn_cast<Constant>(Result))
7330     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7331   return BinaryOperator::CreateNot(Result);
7332 }
7333
7334 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7335   return commonShiftTransforms(I);
7336 }
7337
7338 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7339   return commonShiftTransforms(I);
7340 }
7341
7342 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7343   if (Instruction *R = commonShiftTransforms(I))
7344     return R;
7345   
7346   Value *Op0 = I.getOperand(0);
7347   
7348   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7349   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7350     if (CSI->isAllOnesValue())
7351       return ReplaceInstUsesWith(I, CSI);
7352
7353   // See if we can turn a signed shr into an unsigned shr.
7354   if (MaskedValueIsZero(Op0,
7355                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7356     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7357
7358   // Arithmetic shifting an all-sign-bit value is a no-op.
7359   unsigned NumSignBits = ComputeNumSignBits(Op0);
7360   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7361     return ReplaceInstUsesWith(I, Op0);
7362
7363   return 0;
7364 }
7365
7366 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7367   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7368   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7369
7370   // shl X, 0 == X and shr X, 0 == X
7371   // shl 0, X == 0 and shr 0, X == 0
7372   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7373       Op0 == Constant::getNullValue(Op0->getType()))
7374     return ReplaceInstUsesWith(I, Op0);
7375   
7376   if (isa<UndefValue>(Op0)) {            
7377     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7378       return ReplaceInstUsesWith(I, Op0);
7379     else                                    // undef << X -> 0, undef >>u X -> 0
7380       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7381   }
7382   if (isa<UndefValue>(Op1)) {
7383     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7384       return ReplaceInstUsesWith(I, Op0);          
7385     else                                     // X << undef, X >>u undef -> 0
7386       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7387   }
7388
7389   // See if we can fold away this shift.
7390   if (SimplifyDemandedInstructionBits(I))
7391     return &I;
7392
7393   // Try to fold constant and into select arguments.
7394   if (isa<Constant>(Op0))
7395     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7396       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7397         return R;
7398
7399   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7400     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7401       return Res;
7402   return 0;
7403 }
7404
7405 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7406                                                BinaryOperator &I) {
7407   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7408
7409   // See if we can simplify any instructions used by the instruction whose sole 
7410   // purpose is to compute bits we don't care about.
7411   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7412   
7413   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7414   // a signed shift.
7415   //
7416   if (Op1->uge(TypeBits)) {
7417     if (I.getOpcode() != Instruction::AShr)
7418       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7419     else {
7420       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7421       return &I;
7422     }
7423   }
7424   
7425   // ((X*C1) << C2) == (X * (C1 << C2))
7426   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7427     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7428       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7429         return BinaryOperator::CreateMul(BO->getOperand(0),
7430                                         ConstantExpr::getShl(BOOp, Op1));
7431   
7432   // Try to fold constant and into select arguments.
7433   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7434     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7435       return R;
7436   if (isa<PHINode>(Op0))
7437     if (Instruction *NV = FoldOpIntoPhi(I))
7438       return NV;
7439   
7440   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7441   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7442     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7443     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7444     // place.  Don't try to do this transformation in this case.  Also, we
7445     // require that the input operand is a shift-by-constant so that we have
7446     // confidence that the shifts will get folded together.  We could do this
7447     // xform in more cases, but it is unlikely to be profitable.
7448     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7449         isa<ConstantInt>(TrOp->getOperand(1))) {
7450       // Okay, we'll do this xform.  Make the shift of shift.
7451       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7452       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7453                                                 I.getName());
7454       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7455
7456       // For logical shifts, the truncation has the effect of making the high
7457       // part of the register be zeros.  Emulate this by inserting an AND to
7458       // clear the top bits as needed.  This 'and' will usually be zapped by
7459       // other xforms later if dead.
7460       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7461       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7462       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7463       
7464       // The mask we constructed says what the trunc would do if occurring
7465       // between the shifts.  We want to know the effect *after* the second
7466       // shift.  We know that it is a logical shift by a constant, so adjust the
7467       // mask as appropriate.
7468       if (I.getOpcode() == Instruction::Shl)
7469         MaskV <<= Op1->getZExtValue();
7470       else {
7471         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7472         MaskV = MaskV.lshr(Op1->getZExtValue());
7473       }
7474
7475       Instruction *And =
7476         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7477                                   TI->getName());
7478       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7479
7480       // Return the value truncated to the interesting size.
7481       return new TruncInst(And, I.getType());
7482     }
7483   }
7484   
7485   if (Op0->hasOneUse()) {
7486     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7487       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7488       Value *V1, *V2;
7489       ConstantInt *CC;
7490       switch (Op0BO->getOpcode()) {
7491         default: break;
7492         case Instruction::Add:
7493         case Instruction::And:
7494         case Instruction::Or:
7495         case Instruction::Xor: {
7496           // These operators commute.
7497           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7498           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7499               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7500                     m_Specific(Op1)))){
7501             Instruction *YS = BinaryOperator::CreateShl(
7502                                             Op0BO->getOperand(0), Op1,
7503                                             Op0BO->getName());
7504             InsertNewInstBefore(YS, I); // (Y << C)
7505             Instruction *X = 
7506               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7507                                      Op0BO->getOperand(1)->getName());
7508             InsertNewInstBefore(X, I);  // (X + (Y << C))
7509             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7510             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7511                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7512           }
7513           
7514           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7515           Value *Op0BOOp1 = Op0BO->getOperand(1);
7516           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7517               match(Op0BOOp1, 
7518                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7519                           m_ConstantInt(CC))) &&
7520               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7521             Instruction *YS = BinaryOperator::CreateShl(
7522                                                      Op0BO->getOperand(0), Op1,
7523                                                      Op0BO->getName());
7524             InsertNewInstBefore(YS, I); // (Y << C)
7525             Instruction *XM =
7526               BinaryOperator::CreateAnd(V1,
7527                                         ConstantExpr::getShl(CC, Op1),
7528                                         V1->getName()+".mask");
7529             InsertNewInstBefore(XM, I); // X & (CC << C)
7530             
7531             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7532           }
7533         }
7534           
7535         // FALL THROUGH.
7536         case Instruction::Sub: {
7537           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7538           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7539               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7540                     m_Specific(Op1)))) {
7541             Instruction *YS = BinaryOperator::CreateShl(
7542                                                      Op0BO->getOperand(1), Op1,
7543                                                      Op0BO->getName());
7544             InsertNewInstBefore(YS, I); // (Y << C)
7545             Instruction *X =
7546               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7547                                      Op0BO->getOperand(0)->getName());
7548             InsertNewInstBefore(X, I);  // (X + (Y << C))
7549             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7550             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7551                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7552           }
7553           
7554           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7555           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7556               match(Op0BO->getOperand(0),
7557                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7558                           m_ConstantInt(CC))) && V2 == Op1 &&
7559               cast<BinaryOperator>(Op0BO->getOperand(0))
7560                   ->getOperand(0)->hasOneUse()) {
7561             Instruction *YS = BinaryOperator::CreateShl(
7562                                                      Op0BO->getOperand(1), Op1,
7563                                                      Op0BO->getName());
7564             InsertNewInstBefore(YS, I); // (Y << C)
7565             Instruction *XM =
7566               BinaryOperator::CreateAnd(V1, 
7567                                         ConstantExpr::getShl(CC, Op1),
7568                                         V1->getName()+".mask");
7569             InsertNewInstBefore(XM, I); // X & (CC << C)
7570             
7571             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7572           }
7573           
7574           break;
7575         }
7576       }
7577       
7578       
7579       // If the operand is an bitwise operator with a constant RHS, and the
7580       // shift is the only use, we can pull it out of the shift.
7581       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7582         bool isValid = true;     // Valid only for And, Or, Xor
7583         bool highBitSet = false; // Transform if high bit of constant set?
7584         
7585         switch (Op0BO->getOpcode()) {
7586           default: isValid = false; break;   // Do not perform transform!
7587           case Instruction::Add:
7588             isValid = isLeftShift;
7589             break;
7590           case Instruction::Or:
7591           case Instruction::Xor:
7592             highBitSet = false;
7593             break;
7594           case Instruction::And:
7595             highBitSet = true;
7596             break;
7597         }
7598         
7599         // If this is a signed shift right, and the high bit is modified
7600         // by the logical operation, do not perform the transformation.
7601         // The highBitSet boolean indicates the value of the high bit of
7602         // the constant which would cause it to be modified for this
7603         // operation.
7604         //
7605         if (isValid && I.getOpcode() == Instruction::AShr)
7606           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7607         
7608         if (isValid) {
7609           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7610           
7611           Instruction *NewShift =
7612             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7613           InsertNewInstBefore(NewShift, I);
7614           NewShift->takeName(Op0BO);
7615           
7616           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7617                                         NewRHS);
7618         }
7619       }
7620     }
7621   }
7622   
7623   // Find out if this is a shift of a shift by a constant.
7624   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7625   if (ShiftOp && !ShiftOp->isShift())
7626     ShiftOp = 0;
7627   
7628   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7629     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7630     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7631     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7632     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7633     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7634     Value *X = ShiftOp->getOperand(0);
7635     
7636     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7637     
7638     const IntegerType *Ty = cast<IntegerType>(I.getType());
7639     
7640     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7641     if (I.getOpcode() == ShiftOp->getOpcode()) {
7642       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7643       // saturates.
7644       if (AmtSum >= TypeBits) {
7645         if (I.getOpcode() != Instruction::AShr)
7646           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7647         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7648       }
7649       
7650       return BinaryOperator::Create(I.getOpcode(), X,
7651                                     ConstantInt::get(Ty, AmtSum));
7652     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7653                I.getOpcode() == Instruction::AShr) {
7654       if (AmtSum >= TypeBits)
7655         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7656       
7657       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7658       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7659     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7660                I.getOpcode() == Instruction::LShr) {
7661       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7662       if (AmtSum >= TypeBits)
7663         AmtSum = TypeBits-1;
7664       
7665       Instruction *Shift =
7666         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7667       InsertNewInstBefore(Shift, I);
7668
7669       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7670       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7671     }
7672     
7673     // Okay, if we get here, one shift must be left, and the other shift must be
7674     // right.  See if the amounts are equal.
7675     if (ShiftAmt1 == ShiftAmt2) {
7676       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7677       if (I.getOpcode() == Instruction::Shl) {
7678         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7679         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7680       }
7681       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7682       if (I.getOpcode() == Instruction::LShr) {
7683         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7684         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7685       }
7686       // We can simplify ((X << C) >>s C) into a trunc + sext.
7687       // NOTE: we could do this for any C, but that would make 'unusual' integer
7688       // types.  For now, just stick to ones well-supported by the code
7689       // generators.
7690       const Type *SExtType = 0;
7691       switch (Ty->getBitWidth() - ShiftAmt1) {
7692       case 1  :
7693       case 8  :
7694       case 16 :
7695       case 32 :
7696       case 64 :
7697       case 128:
7698         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7699         break;
7700       default: break;
7701       }
7702       if (SExtType) {
7703         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7704         InsertNewInstBefore(NewTrunc, I);
7705         return new SExtInst(NewTrunc, Ty);
7706       }
7707       // Otherwise, we can't handle it yet.
7708     } else if (ShiftAmt1 < ShiftAmt2) {
7709       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7710       
7711       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7712       if (I.getOpcode() == Instruction::Shl) {
7713         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7714                ShiftOp->getOpcode() == Instruction::AShr);
7715         Instruction *Shift =
7716           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7717         InsertNewInstBefore(Shift, I);
7718         
7719         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7720         return BinaryOperator::CreateAnd(Shift,
7721                                          ConstantInt::get(*Context, Mask));
7722       }
7723       
7724       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7725       if (I.getOpcode() == Instruction::LShr) {
7726         assert(ShiftOp->getOpcode() == Instruction::Shl);
7727         Instruction *Shift =
7728           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7729         InsertNewInstBefore(Shift, I);
7730         
7731         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7732         return BinaryOperator::CreateAnd(Shift,
7733                                          ConstantInt::get(*Context, Mask));
7734       }
7735       
7736       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7737     } else {
7738       assert(ShiftAmt2 < ShiftAmt1);
7739       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7740
7741       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7742       if (I.getOpcode() == Instruction::Shl) {
7743         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7744                ShiftOp->getOpcode() == Instruction::AShr);
7745         Instruction *Shift =
7746           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7747                                  ConstantInt::get(Ty, ShiftDiff));
7748         InsertNewInstBefore(Shift, I);
7749         
7750         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7751         return BinaryOperator::CreateAnd(Shift,
7752                                          ConstantInt::get(*Context, Mask));
7753       }
7754       
7755       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7756       if (I.getOpcode() == Instruction::LShr) {
7757         assert(ShiftOp->getOpcode() == Instruction::Shl);
7758         Instruction *Shift =
7759           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7760         InsertNewInstBefore(Shift, I);
7761         
7762         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7763         return BinaryOperator::CreateAnd(Shift,
7764                                          ConstantInt::get(*Context, Mask));
7765       }
7766       
7767       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7768     }
7769   }
7770   return 0;
7771 }
7772
7773
7774 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7775 /// expression.  If so, decompose it, returning some value X, such that Val is
7776 /// X*Scale+Offset.
7777 ///
7778 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7779                                         int &Offset, LLVMContext *Context) {
7780   assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
7781   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7782     Offset = CI->getZExtValue();
7783     Scale  = 0;
7784     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7785   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7786     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7787       if (I->getOpcode() == Instruction::Shl) {
7788         // This is a value scaled by '1 << the shift amt'.
7789         Scale = 1U << RHS->getZExtValue();
7790         Offset = 0;
7791         return I->getOperand(0);
7792       } else if (I->getOpcode() == Instruction::Mul) {
7793         // This value is scaled by 'RHS'.
7794         Scale = RHS->getZExtValue();
7795         Offset = 0;
7796         return I->getOperand(0);
7797       } else if (I->getOpcode() == Instruction::Add) {
7798         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7799         // where C1 is divisible by C2.
7800         unsigned SubScale;
7801         Value *SubVal = 
7802           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7803                                     Offset, Context);
7804         Offset += RHS->getZExtValue();
7805         Scale = SubScale;
7806         return SubVal;
7807       }
7808     }
7809   }
7810
7811   // Otherwise, we can't look past this.
7812   Scale = 1;
7813   Offset = 0;
7814   return Val;
7815 }
7816
7817
7818 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7819 /// try to eliminate the cast by moving the type information into the alloc.
7820 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7821                                                    AllocationInst &AI) {
7822   const PointerType *PTy = cast<PointerType>(CI.getType());
7823   
7824   // Remove any uses of AI that are dead.
7825   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7826   
7827   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7828     Instruction *User = cast<Instruction>(*UI++);
7829     if (isInstructionTriviallyDead(User)) {
7830       while (UI != E && *UI == User)
7831         ++UI; // If this instruction uses AI more than once, don't break UI.
7832       
7833       ++NumDeadInst;
7834       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7835       EraseInstFromFunction(*User);
7836     }
7837   }
7838
7839   // This requires TargetData to get the alloca alignment and size information.
7840   if (!TD) return 0;
7841
7842   // Get the type really allocated and the type casted to.
7843   const Type *AllocElTy = AI.getAllocatedType();
7844   const Type *CastElTy = PTy->getElementType();
7845   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7846
7847   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7848   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7849   if (CastElTyAlign < AllocElTyAlign) return 0;
7850
7851   // If the allocation has multiple uses, only promote it if we are strictly
7852   // increasing the alignment of the resultant allocation.  If we keep it the
7853   // same, we open the door to infinite loops of various kinds.  (A reference
7854   // from a dbg.declare doesn't count as a use for this purpose.)
7855   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7856       CastElTyAlign == AllocElTyAlign) return 0;
7857
7858   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7859   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7860   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7861
7862   // See if we can satisfy the modulus by pulling a scale out of the array
7863   // size argument.
7864   unsigned ArraySizeScale;
7865   int ArrayOffset;
7866   Value *NumElements = // See if the array size is a decomposable linear expr.
7867     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7868                               ArrayOffset, Context);
7869  
7870   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7871   // do the xform.
7872   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7873       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7874
7875   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7876   Value *Amt = 0;
7877   if (Scale == 1) {
7878     Amt = NumElements;
7879   } else {
7880     // If the allocation size is constant, form a constant mul expression
7881     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7882     if (isa<ConstantInt>(NumElements))
7883       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7884                                  cast<ConstantInt>(Amt));
7885     // otherwise multiply the amount and the number of elements
7886     else {
7887       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7888       Amt = InsertNewInstBefore(Tmp, AI);
7889     }
7890   }
7891   
7892   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7893     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7894     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7895     Amt = InsertNewInstBefore(Tmp, AI);
7896   }
7897   
7898   AllocationInst *New;
7899   if (isa<MallocInst>(AI))
7900     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7901   else
7902     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7903   InsertNewInstBefore(New, AI);
7904   New->takeName(&AI);
7905   
7906   // If the allocation has one real use plus a dbg.declare, just remove the
7907   // declare.
7908   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7909     EraseInstFromFunction(*DI);
7910   }
7911   // If the allocation has multiple real uses, insert a cast and change all
7912   // things that used it to use the new cast.  This will also hack on CI, but it
7913   // will die soon.
7914   else if (!AI.hasOneUse()) {
7915     // New is the allocation instruction, pointer typed. AI is the original
7916     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7917     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7918     InsertNewInstBefore(NewCast, AI);
7919     AI.replaceAllUsesWith(NewCast);
7920   }
7921   return ReplaceInstUsesWith(CI, New);
7922 }
7923
7924 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7925 /// and return it as type Ty without inserting any new casts and without
7926 /// changing the computed value.  This is used by code that tries to decide
7927 /// whether promoting or shrinking integer operations to wider or smaller types
7928 /// will allow us to eliminate a truncate or extend.
7929 ///
7930 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7931 /// extension operation if Ty is larger.
7932 ///
7933 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7934 /// should return true if trunc(V) can be computed by computing V in the smaller
7935 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7936 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7937 /// efficiently truncated.
7938 ///
7939 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7940 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7941 /// the final result.
7942 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7943                                               unsigned CastOpc,
7944                                               int &NumCastsRemoved){
7945   // We can always evaluate constants in another type.
7946   if (isa<Constant>(V))
7947     return true;
7948   
7949   Instruction *I = dyn_cast<Instruction>(V);
7950   if (!I) return false;
7951   
7952   const Type *OrigTy = V->getType();
7953   
7954   // If this is an extension or truncate, we can often eliminate it.
7955   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7956     // If this is a cast from the destination type, we can trivially eliminate
7957     // it, and this will remove a cast overall.
7958     if (I->getOperand(0)->getType() == Ty) {
7959       // If the first operand is itself a cast, and is eliminable, do not count
7960       // this as an eliminable cast.  We would prefer to eliminate those two
7961       // casts first.
7962       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7963         ++NumCastsRemoved;
7964       return true;
7965     }
7966   }
7967
7968   // We can't extend or shrink something that has multiple uses: doing so would
7969   // require duplicating the instruction in general, which isn't profitable.
7970   if (!I->hasOneUse()) return false;
7971
7972   unsigned Opc = I->getOpcode();
7973   switch (Opc) {
7974   case Instruction::Add:
7975   case Instruction::Sub:
7976   case Instruction::Mul:
7977   case Instruction::And:
7978   case Instruction::Or:
7979   case Instruction::Xor:
7980     // These operators can all arbitrarily be extended or truncated.
7981     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7982                                       NumCastsRemoved) &&
7983            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7984                                       NumCastsRemoved);
7985
7986   case Instruction::UDiv:
7987   case Instruction::URem: {
7988     // UDiv and URem can be truncated if all the truncated bits are zero.
7989     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7990     uint32_t BitWidth = Ty->getScalarSizeInBits();
7991     if (BitWidth < OrigBitWidth) {
7992       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7993       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7994           MaskedValueIsZero(I->getOperand(1), Mask)) {
7995         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7996                                           NumCastsRemoved) &&
7997                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7998                                           NumCastsRemoved);
7999       }
8000     }
8001     break;
8002   }
8003   case Instruction::Shl:
8004     // If we are truncating the result of this SHL, and if it's a shift of a
8005     // constant amount, we can always perform a SHL in a smaller type.
8006     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8007       uint32_t BitWidth = Ty->getScalarSizeInBits();
8008       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8009           CI->getLimitedValue(BitWidth) < BitWidth)
8010         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8011                                           NumCastsRemoved);
8012     }
8013     break;
8014   case Instruction::LShr:
8015     // If this is a truncate of a logical shr, we can truncate it to a smaller
8016     // lshr iff we know that the bits we would otherwise be shifting in are
8017     // already zeros.
8018     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8019       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8020       uint32_t BitWidth = Ty->getScalarSizeInBits();
8021       if (BitWidth < OrigBitWidth &&
8022           MaskedValueIsZero(I->getOperand(0),
8023             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8024           CI->getLimitedValue(BitWidth) < BitWidth) {
8025         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8026                                           NumCastsRemoved);
8027       }
8028     }
8029     break;
8030   case Instruction::ZExt:
8031   case Instruction::SExt:
8032   case Instruction::Trunc:
8033     // If this is the same kind of case as our original (e.g. zext+zext), we
8034     // can safely replace it.  Note that replacing it does not reduce the number
8035     // of casts in the input.
8036     if (Opc == CastOpc)
8037       return true;
8038
8039     // sext (zext ty1), ty2 -> zext ty2
8040     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8041       return true;
8042     break;
8043   case Instruction::Select: {
8044     SelectInst *SI = cast<SelectInst>(I);
8045     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8046                                       NumCastsRemoved) &&
8047            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8048                                       NumCastsRemoved);
8049   }
8050   case Instruction::PHI: {
8051     // We can change a phi if we can change all operands.
8052     PHINode *PN = cast<PHINode>(I);
8053     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8054       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8055                                       NumCastsRemoved))
8056         return false;
8057     return true;
8058   }
8059   default:
8060     // TODO: Can handle more cases here.
8061     break;
8062   }
8063   
8064   return false;
8065 }
8066
8067 /// EvaluateInDifferentType - Given an expression that 
8068 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8069 /// evaluate the expression.
8070 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8071                                              bool isSigned) {
8072   if (Constant *C = dyn_cast<Constant>(V))
8073     return ConstantExpr::getIntegerCast(C, Ty,
8074                                                isSigned /*Sext or ZExt*/);
8075
8076   // Otherwise, it must be an instruction.
8077   Instruction *I = cast<Instruction>(V);
8078   Instruction *Res = 0;
8079   unsigned Opc = I->getOpcode();
8080   switch (Opc) {
8081   case Instruction::Add:
8082   case Instruction::Sub:
8083   case Instruction::Mul:
8084   case Instruction::And:
8085   case Instruction::Or:
8086   case Instruction::Xor:
8087   case Instruction::AShr:
8088   case Instruction::LShr:
8089   case Instruction::Shl:
8090   case Instruction::UDiv:
8091   case Instruction::URem: {
8092     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8093     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8094     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8095     break;
8096   }    
8097   case Instruction::Trunc:
8098   case Instruction::ZExt:
8099   case Instruction::SExt:
8100     // If the source type of the cast is the type we're trying for then we can
8101     // just return the source.  There's no need to insert it because it is not
8102     // new.
8103     if (I->getOperand(0)->getType() == Ty)
8104       return I->getOperand(0);
8105     
8106     // Otherwise, must be the same type of cast, so just reinsert a new one.
8107     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8108                            Ty);
8109     break;
8110   case Instruction::Select: {
8111     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8112     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8113     Res = SelectInst::Create(I->getOperand(0), True, False);
8114     break;
8115   }
8116   case Instruction::PHI: {
8117     PHINode *OPN = cast<PHINode>(I);
8118     PHINode *NPN = PHINode::Create(Ty);
8119     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8120       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8121       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8122     }
8123     Res = NPN;
8124     break;
8125   }
8126   default: 
8127     // TODO: Can handle more cases here.
8128     llvm_unreachable("Unreachable!");
8129     break;
8130   }
8131   
8132   Res->takeName(I);
8133   return InsertNewInstBefore(Res, *I);
8134 }
8135
8136 /// @brief Implement the transforms common to all CastInst visitors.
8137 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8138   Value *Src = CI.getOperand(0);
8139
8140   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8141   // eliminate it now.
8142   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8143     if (Instruction::CastOps opc = 
8144         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8145       // The first cast (CSrc) is eliminable so we need to fix up or replace
8146       // the second cast (CI). CSrc will then have a good chance of being dead.
8147       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8148     }
8149   }
8150
8151   // If we are casting a select then fold the cast into the select
8152   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8153     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8154       return NV;
8155
8156   // If we are casting a PHI then fold the cast into the PHI
8157   if (isa<PHINode>(Src))
8158     if (Instruction *NV = FoldOpIntoPhi(CI))
8159       return NV;
8160   
8161   return 0;
8162 }
8163
8164 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8165 /// or not there is a sequence of GEP indices into the type that will land us at
8166 /// the specified offset.  If so, fill them into NewIndices and return the
8167 /// resultant element type, otherwise return null.
8168 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8169                                        SmallVectorImpl<Value*> &NewIndices,
8170                                        const TargetData *TD,
8171                                        LLVMContext *Context) {
8172   if (!TD) return 0;
8173   if (!Ty->isSized()) return 0;
8174   
8175   // Start with the index over the outer type.  Note that the type size
8176   // might be zero (even if the offset isn't zero) if the indexed type
8177   // is something like [0 x {int, int}]
8178   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8179   int64_t FirstIdx = 0;
8180   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8181     FirstIdx = Offset/TySize;
8182     Offset -= FirstIdx*TySize;
8183     
8184     // Handle hosts where % returns negative instead of values [0..TySize).
8185     if (Offset < 0) {
8186       --FirstIdx;
8187       Offset += TySize;
8188       assert(Offset >= 0);
8189     }
8190     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8191   }
8192   
8193   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8194     
8195   // Index into the types.  If we fail, set OrigBase to null.
8196   while (Offset) {
8197     // Indexing into tail padding between struct/array elements.
8198     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8199       return 0;
8200     
8201     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8202       const StructLayout *SL = TD->getStructLayout(STy);
8203       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8204              "Offset must stay within the indexed type");
8205       
8206       unsigned Elt = SL->getElementContainingOffset(Offset);
8207       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8208       
8209       Offset -= SL->getElementOffset(Elt);
8210       Ty = STy->getElementType(Elt);
8211     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8212       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8213       assert(EltSize && "Cannot index into a zero-sized array");
8214       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8215       Offset %= EltSize;
8216       Ty = AT->getElementType();
8217     } else {
8218       // Otherwise, we can't index into the middle of this atomic type, bail.
8219       return 0;
8220     }
8221   }
8222   
8223   return Ty;
8224 }
8225
8226 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8227 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8228   Value *Src = CI.getOperand(0);
8229   
8230   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8231     // If casting the result of a getelementptr instruction with no offset, turn
8232     // this into a cast of the original pointer!
8233     if (GEP->hasAllZeroIndices()) {
8234       // Changing the cast operand is usually not a good idea but it is safe
8235       // here because the pointer operand is being replaced with another 
8236       // pointer operand so the opcode doesn't need to change.
8237       Worklist.Add(GEP);
8238       CI.setOperand(0, GEP->getOperand(0));
8239       return &CI;
8240     }
8241     
8242     // If the GEP has a single use, and the base pointer is a bitcast, and the
8243     // GEP computes a constant offset, see if we can convert these three
8244     // instructions into fewer.  This typically happens with unions and other
8245     // non-type-safe code.
8246     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8247       if (GEP->hasAllConstantIndices()) {
8248         // We are guaranteed to get a constant from EmitGEPOffset.
8249         ConstantInt *OffsetV =
8250                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8251         int64_t Offset = OffsetV->getSExtValue();
8252         
8253         // Get the base pointer input of the bitcast, and the type it points to.
8254         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8255         const Type *GEPIdxTy =
8256           cast<PointerType>(OrigBase->getType())->getElementType();
8257         SmallVector<Value*, 8> NewIndices;
8258         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8259           // If we were able to index down into an element, create the GEP
8260           // and bitcast the result.  This eliminates one bitcast, potentially
8261           // two.
8262           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8263                                                         NewIndices.begin(),
8264                                                         NewIndices.end(), "");
8265           InsertNewInstBefore(NGEP, CI);
8266           NGEP->takeName(GEP);
8267           if (cast<GEPOperator>(GEP)->isInBounds())
8268             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8269           
8270           if (isa<BitCastInst>(CI))
8271             return new BitCastInst(NGEP, CI.getType());
8272           assert(isa<PtrToIntInst>(CI));
8273           return new PtrToIntInst(NGEP, CI.getType());
8274         }
8275       }      
8276     }
8277   }
8278     
8279   return commonCastTransforms(CI);
8280 }
8281
8282 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8283 /// type like i42.  We don't want to introduce operations on random non-legal
8284 /// integer types where they don't already exist in the code.  In the future,
8285 /// we should consider making this based off target-data, so that 32-bit targets
8286 /// won't get i64 operations etc.
8287 static bool isSafeIntegerType(const Type *Ty) {
8288   switch (Ty->getPrimitiveSizeInBits()) {
8289   case 8:
8290   case 16:
8291   case 32:
8292   case 64:
8293     return true;
8294   default: 
8295     return false;
8296   }
8297 }
8298
8299 /// commonIntCastTransforms - This function implements the common transforms
8300 /// for trunc, zext, and sext.
8301 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8302   if (Instruction *Result = commonCastTransforms(CI))
8303     return Result;
8304
8305   Value *Src = CI.getOperand(0);
8306   const Type *SrcTy = Src->getType();
8307   const Type *DestTy = CI.getType();
8308   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8309   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8310
8311   // See if we can simplify any instructions used by the LHS whose sole 
8312   // purpose is to compute bits we don't care about.
8313   if (SimplifyDemandedInstructionBits(CI))
8314     return &CI;
8315
8316   // If the source isn't an instruction or has more than one use then we
8317   // can't do anything more. 
8318   Instruction *SrcI = dyn_cast<Instruction>(Src);
8319   if (!SrcI || !Src->hasOneUse())
8320     return 0;
8321
8322   // Attempt to propagate the cast into the instruction for int->int casts.
8323   int NumCastsRemoved = 0;
8324   // Only do this if the dest type is a simple type, don't convert the
8325   // expression tree to something weird like i93 unless the source is also
8326   // strange.
8327   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8328        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8329       CanEvaluateInDifferentType(SrcI, DestTy,
8330                                  CI.getOpcode(), NumCastsRemoved)) {
8331     // If this cast is a truncate, evaluting in a different type always
8332     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8333     // we need to do an AND to maintain the clear top-part of the computation,
8334     // so we require that the input have eliminated at least one cast.  If this
8335     // is a sign extension, we insert two new casts (to do the extension) so we
8336     // require that two casts have been eliminated.
8337     bool DoXForm = false;
8338     bool JustReplace = false;
8339     switch (CI.getOpcode()) {
8340     default:
8341       // All the others use floating point so we shouldn't actually 
8342       // get here because of the check above.
8343       llvm_unreachable("Unknown cast type");
8344     case Instruction::Trunc:
8345       DoXForm = true;
8346       break;
8347     case Instruction::ZExt: {
8348       DoXForm = NumCastsRemoved >= 1;
8349       if (!DoXForm && 0) {
8350         // If it's unnecessary to issue an AND to clear the high bits, it's
8351         // always profitable to do this xform.
8352         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8353         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8354         if (MaskedValueIsZero(TryRes, Mask))
8355           return ReplaceInstUsesWith(CI, TryRes);
8356         
8357         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8358           if (TryI->use_empty())
8359             EraseInstFromFunction(*TryI);
8360       }
8361       break;
8362     }
8363     case Instruction::SExt: {
8364       DoXForm = NumCastsRemoved >= 2;
8365       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8366         // If we do not have to emit the truncate + sext pair, then it's always
8367         // profitable to do this xform.
8368         //
8369         // It's not safe to eliminate the trunc + sext pair if one of the
8370         // eliminated cast is a truncate. e.g.
8371         // t2 = trunc i32 t1 to i16
8372         // t3 = sext i16 t2 to i32
8373         // !=
8374         // i32 t1
8375         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8376         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8377         if (NumSignBits > (DestBitSize - SrcBitSize))
8378           return ReplaceInstUsesWith(CI, TryRes);
8379         
8380         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8381           if (TryI->use_empty())
8382             EraseInstFromFunction(*TryI);
8383       }
8384       break;
8385     }
8386     }
8387     
8388     if (DoXForm) {
8389       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8390             " to avoid cast: " << CI);
8391       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8392                                            CI.getOpcode() == Instruction::SExt);
8393       if (JustReplace)
8394         // Just replace this cast with the result.
8395         return ReplaceInstUsesWith(CI, Res);
8396
8397       assert(Res->getType() == DestTy);
8398       switch (CI.getOpcode()) {
8399       default: llvm_unreachable("Unknown cast type!");
8400       case Instruction::Trunc:
8401         // Just replace this cast with the result.
8402         return ReplaceInstUsesWith(CI, Res);
8403       case Instruction::ZExt: {
8404         assert(SrcBitSize < DestBitSize && "Not a zext?");
8405
8406         // If the high bits are already zero, just replace this cast with the
8407         // result.
8408         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8409         if (MaskedValueIsZero(Res, Mask))
8410           return ReplaceInstUsesWith(CI, Res);
8411
8412         // We need to emit an AND to clear the high bits.
8413         Constant *C = ConstantInt::get(*Context, 
8414                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8415         return BinaryOperator::CreateAnd(Res, C);
8416       }
8417       case Instruction::SExt: {
8418         // If the high bits are already filled with sign bit, just replace this
8419         // cast with the result.
8420         unsigned NumSignBits = ComputeNumSignBits(Res);
8421         if (NumSignBits > (DestBitSize - SrcBitSize))
8422           return ReplaceInstUsesWith(CI, Res);
8423
8424         // We need to emit a cast to truncate, then a cast to sext.
8425         return CastInst::Create(Instruction::SExt,
8426             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8427                              CI), DestTy);
8428       }
8429       }
8430     }
8431   }
8432   
8433   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8434   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8435
8436   switch (SrcI->getOpcode()) {
8437   case Instruction::Add:
8438   case Instruction::Mul:
8439   case Instruction::And:
8440   case Instruction::Or:
8441   case Instruction::Xor:
8442     // If we are discarding information, rewrite.
8443     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8444       // Don't insert two casts unless at least one can be eliminated.
8445       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8446           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8447         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8448         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8449         return BinaryOperator::Create(
8450             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8451       }
8452     }
8453
8454     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8455     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8456         SrcI->getOpcode() == Instruction::Xor &&
8457         Op1 == ConstantInt::getTrue(*Context) &&
8458         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8459       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8460       return BinaryOperator::CreateXor(New,
8461                                       ConstantInt::get(CI.getType(), 1));
8462     }
8463     break;
8464
8465   case Instruction::Shl: {
8466     // Canonicalize trunc inside shl, if we can.
8467     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8468     if (CI && DestBitSize < SrcBitSize &&
8469         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8470       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8471       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8472       return BinaryOperator::CreateShl(Op0c, Op1c);
8473     }
8474     break;
8475   }
8476   }
8477   return 0;
8478 }
8479
8480 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8481   if (Instruction *Result = commonIntCastTransforms(CI))
8482     return Result;
8483   
8484   Value *Src = CI.getOperand(0);
8485   const Type *Ty = CI.getType();
8486   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8487   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8488
8489   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8490   if (DestBitWidth == 1) {
8491     Constant *One = ConstantInt::get(Src->getType(), 1);
8492     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8493     Value *Zero = Constant::getNullValue(Src->getType());
8494     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8495   }
8496
8497   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8498   ConstantInt *ShAmtV = 0;
8499   Value *ShiftOp = 0;
8500   if (Src->hasOneUse() &&
8501       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8502     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8503     
8504     // Get a mask for the bits shifting in.
8505     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8506     if (MaskedValueIsZero(ShiftOp, Mask)) {
8507       if (ShAmt >= DestBitWidth)        // All zeros.
8508         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8509       
8510       // Okay, we can shrink this.  Truncate the input, then return a new
8511       // shift.
8512       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8513       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8514       return BinaryOperator::CreateLShr(V1, V2);
8515     }
8516   }
8517   
8518   return 0;
8519 }
8520
8521 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8522 /// in order to eliminate the icmp.
8523 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8524                                              bool DoXform) {
8525   // If we are just checking for a icmp eq of a single bit and zext'ing it
8526   // to an integer, then shift the bit to the appropriate place and then
8527   // cast to integer to avoid the comparison.
8528   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8529     const APInt &Op1CV = Op1C->getValue();
8530       
8531     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8532     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8533     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8534         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8535       if (!DoXform) return ICI;
8536
8537       Value *In = ICI->getOperand(0);
8538       Value *Sh = ConstantInt::get(In->getType(),
8539                                    In->getType()->getScalarSizeInBits()-1);
8540       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8541                                                         In->getName()+".lobit"),
8542                                CI);
8543       if (In->getType() != CI.getType())
8544         In = CastInst::CreateIntegerCast(In, CI.getType(),
8545                                          false/*ZExt*/, "tmp", &CI);
8546
8547       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8548         Constant *One = ConstantInt::get(In->getType(), 1);
8549         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8550                                                          In->getName()+".not"),
8551                                  CI);
8552       }
8553
8554       return ReplaceInstUsesWith(CI, In);
8555     }
8556       
8557       
8558       
8559     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8560     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8561     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8562     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8563     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8564     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8565     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8566     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8567     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8568         // This only works for EQ and NE
8569         ICI->isEquality()) {
8570       // If Op1C some other power of two, convert:
8571       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8572       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8573       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8574       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8575         
8576       APInt KnownZeroMask(~KnownZero);
8577       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8578         if (!DoXform) return ICI;
8579
8580         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8581         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8582           // (X&4) == 2 --> false
8583           // (X&4) != 2 --> true
8584           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8585           Res = ConstantExpr::getZExt(Res, CI.getType());
8586           return ReplaceInstUsesWith(CI, Res);
8587         }
8588           
8589         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8590         Value *In = ICI->getOperand(0);
8591         if (ShiftAmt) {
8592           // Perform a logical shr by shiftamt.
8593           // Insert the shift to put the result in the low bit.
8594           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8595                               ConstantInt::get(In->getType(), ShiftAmt),
8596                                                    In->getName()+".lobit"), CI);
8597         }
8598           
8599         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8600           Constant *One = ConstantInt::get(In->getType(), 1);
8601           In = BinaryOperator::CreateXor(In, One, "tmp");
8602           InsertNewInstBefore(cast<Instruction>(In), CI);
8603         }
8604           
8605         if (CI.getType() == In->getType())
8606           return ReplaceInstUsesWith(CI, In);
8607         else
8608           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8609       }
8610     }
8611   }
8612
8613   return 0;
8614 }
8615
8616 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8617   // If one of the common conversion will work ..
8618   if (Instruction *Result = commonIntCastTransforms(CI))
8619     return Result;
8620
8621   Value *Src = CI.getOperand(0);
8622
8623   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8624   // types and if the sizes are just right we can convert this into a logical
8625   // 'and' which will be much cheaper than the pair of casts.
8626   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8627     // Get the sizes of the types involved.  We know that the intermediate type
8628     // will be smaller than A or C, but don't know the relation between A and C.
8629     Value *A = CSrc->getOperand(0);
8630     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8631     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8632     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8633     // If we're actually extending zero bits, then if
8634     // SrcSize <  DstSize: zext(a & mask)
8635     // SrcSize == DstSize: a & mask
8636     // SrcSize  > DstSize: trunc(a) & mask
8637     if (SrcSize < DstSize) {
8638       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8639       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8640       Instruction *And =
8641         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8642       InsertNewInstBefore(And, CI);
8643       return new ZExtInst(And, CI.getType());
8644     } else if (SrcSize == DstSize) {
8645       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8646       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8647                                                            AndValue));
8648     } else if (SrcSize > DstSize) {
8649       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8650       InsertNewInstBefore(Trunc, CI);
8651       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8652       return BinaryOperator::CreateAnd(Trunc, 
8653                                        ConstantInt::get(Trunc->getType(),
8654                                                                AndValue));
8655     }
8656   }
8657
8658   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8659     return transformZExtICmp(ICI, CI);
8660
8661   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8662   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8663     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8664     // of the (zext icmp) will be transformed.
8665     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8666     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8667     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8668         (transformZExtICmp(LHS, CI, false) ||
8669          transformZExtICmp(RHS, CI, false))) {
8670       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8671       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8672       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8673     }
8674   }
8675
8676   // zext(trunc(t) & C) -> (t & zext(C)).
8677   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8678     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8679       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8680         Value *TI0 = TI->getOperand(0);
8681         if (TI0->getType() == CI.getType())
8682           return
8683             BinaryOperator::CreateAnd(TI0,
8684                                 ConstantExpr::getZExt(C, CI.getType()));
8685       }
8686
8687   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8688   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8689     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8690       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8691         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8692             And->getOperand(1) == C)
8693           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8694             Value *TI0 = TI->getOperand(0);
8695             if (TI0->getType() == CI.getType()) {
8696               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8697               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8698               InsertNewInstBefore(NewAnd, *And);
8699               return BinaryOperator::CreateXor(NewAnd, ZC);
8700             }
8701           }
8702
8703   return 0;
8704 }
8705
8706 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8707   if (Instruction *I = commonIntCastTransforms(CI))
8708     return I;
8709   
8710   Value *Src = CI.getOperand(0);
8711   
8712   // Canonicalize sign-extend from i1 to a select.
8713   if (Src->getType() == Type::getInt1Ty(*Context))
8714     return SelectInst::Create(Src,
8715                               Constant::getAllOnesValue(CI.getType()),
8716                               Constant::getNullValue(CI.getType()));
8717
8718   // See if the value being truncated is already sign extended.  If so, just
8719   // eliminate the trunc/sext pair.
8720   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8721     Value *Op = cast<User>(Src)->getOperand(0);
8722     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8723     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8724     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8725     unsigned NumSignBits = ComputeNumSignBits(Op);
8726
8727     if (OpBits == DestBits) {
8728       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8729       // bits, it is already ready.
8730       if (NumSignBits > DestBits-MidBits)
8731         return ReplaceInstUsesWith(CI, Op);
8732     } else if (OpBits < DestBits) {
8733       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8734       // bits, just sext from i32.
8735       if (NumSignBits > OpBits-MidBits)
8736         return new SExtInst(Op, CI.getType(), "tmp");
8737     } else {
8738       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8739       // bits, just truncate to i32.
8740       if (NumSignBits > OpBits-MidBits)
8741         return new TruncInst(Op, CI.getType(), "tmp");
8742     }
8743   }
8744
8745   // If the input is a shl/ashr pair of a same constant, then this is a sign
8746   // extension from a smaller value.  If we could trust arbitrary bitwidth
8747   // integers, we could turn this into a truncate to the smaller bit and then
8748   // use a sext for the whole extension.  Since we don't, look deeper and check
8749   // for a truncate.  If the source and dest are the same type, eliminate the
8750   // trunc and extend and just do shifts.  For example, turn:
8751   //   %a = trunc i32 %i to i8
8752   //   %b = shl i8 %a, 6
8753   //   %c = ashr i8 %b, 6
8754   //   %d = sext i8 %c to i32
8755   // into:
8756   //   %a = shl i32 %i, 30
8757   //   %d = ashr i32 %a, 30
8758   Value *A = 0;
8759   ConstantInt *BA = 0, *CA = 0;
8760   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8761                         m_ConstantInt(CA))) &&
8762       BA == CA && isa<TruncInst>(A)) {
8763     Value *I = cast<TruncInst>(A)->getOperand(0);
8764     if (I->getType() == CI.getType()) {
8765       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8766       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8767       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8768       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8769       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8770                                                         CI.getName()), CI);
8771       return BinaryOperator::CreateAShr(I, ShAmtV);
8772     }
8773   }
8774   
8775   return 0;
8776 }
8777
8778 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8779 /// in the specified FP type without changing its value.
8780 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8781                               LLVMContext *Context) {
8782   bool losesInfo;
8783   APFloat F = CFP->getValueAPF();
8784   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8785   if (!losesInfo)
8786     return ConstantFP::get(*Context, F);
8787   return 0;
8788 }
8789
8790 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8791 /// through it until we get the source value.
8792 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8793   if (Instruction *I = dyn_cast<Instruction>(V))
8794     if (I->getOpcode() == Instruction::FPExt)
8795       return LookThroughFPExtensions(I->getOperand(0), Context);
8796   
8797   // If this value is a constant, return the constant in the smallest FP type
8798   // that can accurately represent it.  This allows us to turn
8799   // (float)((double)X+2.0) into x+2.0f.
8800   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8801     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8802       return V;  // No constant folding of this.
8803     // See if the value can be truncated to float and then reextended.
8804     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8805       return V;
8806     if (CFP->getType() == Type::getDoubleTy(*Context))
8807       return V;  // Won't shrink.
8808     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8809       return V;
8810     // Don't try to shrink to various long double types.
8811   }
8812   
8813   return V;
8814 }
8815
8816 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8817   if (Instruction *I = commonCastTransforms(CI))
8818     return I;
8819   
8820   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8821   // smaller than the destination type, we can eliminate the truncate by doing
8822   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8823   // many builtins (sqrt, etc).
8824   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8825   if (OpI && OpI->hasOneUse()) {
8826     switch (OpI->getOpcode()) {
8827     default: break;
8828     case Instruction::FAdd:
8829     case Instruction::FSub:
8830     case Instruction::FMul:
8831     case Instruction::FDiv:
8832     case Instruction::FRem:
8833       const Type *SrcTy = OpI->getType();
8834       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8835       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8836       if (LHSTrunc->getType() != SrcTy && 
8837           RHSTrunc->getType() != SrcTy) {
8838         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8839         // If the source types were both smaller than the destination type of
8840         // the cast, do this xform.
8841         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8842             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8843           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8844                                       CI.getType(), CI);
8845           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8846                                       CI.getType(), CI);
8847           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8848         }
8849       }
8850       break;  
8851     }
8852   }
8853   return 0;
8854 }
8855
8856 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8857   return commonCastTransforms(CI);
8858 }
8859
8860 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8861   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8862   if (OpI == 0)
8863     return commonCastTransforms(FI);
8864
8865   // fptoui(uitofp(X)) --> X
8866   // fptoui(sitofp(X)) --> X
8867   // This is safe if the intermediate type has enough bits in its mantissa to
8868   // accurately represent all values of X.  For example, do not do this with
8869   // i64->float->i64.  This is also safe for sitofp case, because any negative
8870   // 'X' value would cause an undefined result for the fptoui. 
8871   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8872       OpI->getOperand(0)->getType() == FI.getType() &&
8873       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8874                     OpI->getType()->getFPMantissaWidth())
8875     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8876
8877   return commonCastTransforms(FI);
8878 }
8879
8880 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8881   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8882   if (OpI == 0)
8883     return commonCastTransforms(FI);
8884   
8885   // fptosi(sitofp(X)) --> X
8886   // fptosi(uitofp(X)) --> X
8887   // This is safe if the intermediate type has enough bits in its mantissa to
8888   // accurately represent all values of X.  For example, do not do this with
8889   // i64->float->i64.  This is also safe for sitofp case, because any negative
8890   // 'X' value would cause an undefined result for the fptoui. 
8891   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8892       OpI->getOperand(0)->getType() == FI.getType() &&
8893       (int)FI.getType()->getScalarSizeInBits() <=
8894                     OpI->getType()->getFPMantissaWidth())
8895     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8896   
8897   return commonCastTransforms(FI);
8898 }
8899
8900 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8901   return commonCastTransforms(CI);
8902 }
8903
8904 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8905   return commonCastTransforms(CI);
8906 }
8907
8908 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8909   // If the destination integer type is smaller than the intptr_t type for
8910   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8911   // trunc to be exposed to other transforms.  Don't do this for extending
8912   // ptrtoint's, because we don't know if the target sign or zero extends its
8913   // pointers.
8914   if (TD &&
8915       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8916     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8917                                              TD->getIntPtrType(CI.getContext()),
8918                                                     "tmp"), CI);
8919     return new TruncInst(P, CI.getType());
8920   }
8921   
8922   return commonPointerCastTransforms(CI);
8923 }
8924
8925 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8926   // If the source integer type is larger than the intptr_t type for
8927   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8928   // allows the trunc to be exposed to other transforms.  Don't do this for
8929   // extending inttoptr's, because we don't know if the target sign or zero
8930   // extends to pointers.
8931   if (TD &&
8932       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8933       TD->getPointerSizeInBits()) {
8934     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8935                                              TD->getIntPtrType(CI.getContext()),
8936                                                  "tmp"), CI);
8937     return new IntToPtrInst(P, CI.getType());
8938   }
8939   
8940   if (Instruction *I = commonCastTransforms(CI))
8941     return I;
8942
8943   return 0;
8944 }
8945
8946 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8947   // If the operands are integer typed then apply the integer transforms,
8948   // otherwise just apply the common ones.
8949   Value *Src = CI.getOperand(0);
8950   const Type *SrcTy = Src->getType();
8951   const Type *DestTy = CI.getType();
8952
8953   if (isa<PointerType>(SrcTy)) {
8954     if (Instruction *I = commonPointerCastTransforms(CI))
8955       return I;
8956   } else {
8957     if (Instruction *Result = commonCastTransforms(CI))
8958       return Result;
8959   }
8960
8961
8962   // Get rid of casts from one type to the same type. These are useless and can
8963   // be replaced by the operand.
8964   if (DestTy == Src->getType())
8965     return ReplaceInstUsesWith(CI, Src);
8966
8967   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8968     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8969     const Type *DstElTy = DstPTy->getElementType();
8970     const Type *SrcElTy = SrcPTy->getElementType();
8971     
8972     // If the address spaces don't match, don't eliminate the bitcast, which is
8973     // required for changing types.
8974     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8975       return 0;
8976     
8977     // If we are casting a malloc or alloca to a pointer to a type of the same
8978     // size, rewrite the allocation instruction to allocate the "right" type.
8979     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8980       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8981         return V;
8982     
8983     // If the source and destination are pointers, and this cast is equivalent
8984     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8985     // This can enhance SROA and other transforms that want type-safe pointers.
8986     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8987     unsigned NumZeros = 0;
8988     while (SrcElTy != DstElTy && 
8989            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8990            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8991       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8992       ++NumZeros;
8993     }
8994
8995     // If we found a path from the src to dest, create the getelementptr now.
8996     if (SrcElTy == DstElTy) {
8997       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8998       Instruction *GEP = GetElementPtrInst::Create(Src,
8999                                                    Idxs.begin(), Idxs.end(), "",
9000                                                    ((Instruction*) NULL));
9001       cast<GEPOperator>(GEP)->setIsInBounds(true);
9002       return GEP;
9003     }
9004   }
9005
9006   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9007     if (DestVTy->getNumElements() == 1) {
9008       if (!isa<VectorType>(SrcTy)) {
9009         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9010                                        DestVTy->getElementType(), CI);
9011         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9012                                          Constant::getNullValue(Type::getInt32Ty(*Context)));
9013       }
9014       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9015     }
9016   }
9017
9018   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9019     if (SrcVTy->getNumElements() == 1) {
9020       if (!isa<VectorType>(DestTy)) {
9021         Instruction *Elem =
9022           ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
9023         InsertNewInstBefore(Elem, CI);
9024         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9025       }
9026     }
9027   }
9028
9029   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9030     if (SVI->hasOneUse()) {
9031       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9032       // a bitconvert to a vector with the same # elts.
9033       if (isa<VectorType>(DestTy) && 
9034           cast<VectorType>(DestTy)->getNumElements() ==
9035                 SVI->getType()->getNumElements() &&
9036           SVI->getType()->getNumElements() ==
9037             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9038         CastInst *Tmp;
9039         // If either of the operands is a cast from CI.getType(), then
9040         // evaluating the shuffle in the casted destination's type will allow
9041         // us to eliminate at least one cast.
9042         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9043              Tmp->getOperand(0)->getType() == DestTy) ||
9044             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9045              Tmp->getOperand(0)->getType() == DestTy)) {
9046           Value *LHS = InsertCastBefore(Instruction::BitCast,
9047                                         SVI->getOperand(0), DestTy, CI);
9048           Value *RHS = InsertCastBefore(Instruction::BitCast,
9049                                         SVI->getOperand(1), DestTy, CI);
9050           // Return a new shuffle vector.  Use the same element ID's, as we
9051           // know the vector types match #elts.
9052           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9053         }
9054       }
9055     }
9056   }
9057   return 0;
9058 }
9059
9060 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9061 ///   %C = or %A, %B
9062 ///   %D = select %cond, %C, %A
9063 /// into:
9064 ///   %C = select %cond, %B, 0
9065 ///   %D = or %A, %C
9066 ///
9067 /// Assuming that the specified instruction is an operand to the select, return
9068 /// a bitmask indicating which operands of this instruction are foldable if they
9069 /// equal the other incoming value of the select.
9070 ///
9071 static unsigned GetSelectFoldableOperands(Instruction *I) {
9072   switch (I->getOpcode()) {
9073   case Instruction::Add:
9074   case Instruction::Mul:
9075   case Instruction::And:
9076   case Instruction::Or:
9077   case Instruction::Xor:
9078     return 3;              // Can fold through either operand.
9079   case Instruction::Sub:   // Can only fold on the amount subtracted.
9080   case Instruction::Shl:   // Can only fold on the shift amount.
9081   case Instruction::LShr:
9082   case Instruction::AShr:
9083     return 1;
9084   default:
9085     return 0;              // Cannot fold
9086   }
9087 }
9088
9089 /// GetSelectFoldableConstant - For the same transformation as the previous
9090 /// function, return the identity constant that goes into the select.
9091 static Constant *GetSelectFoldableConstant(Instruction *I,
9092                                            LLVMContext *Context) {
9093   switch (I->getOpcode()) {
9094   default: llvm_unreachable("This cannot happen!");
9095   case Instruction::Add:
9096   case Instruction::Sub:
9097   case Instruction::Or:
9098   case Instruction::Xor:
9099   case Instruction::Shl:
9100   case Instruction::LShr:
9101   case Instruction::AShr:
9102     return Constant::getNullValue(I->getType());
9103   case Instruction::And:
9104     return Constant::getAllOnesValue(I->getType());
9105   case Instruction::Mul:
9106     return ConstantInt::get(I->getType(), 1);
9107   }
9108 }
9109
9110 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9111 /// have the same opcode and only one use each.  Try to simplify this.
9112 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9113                                           Instruction *FI) {
9114   if (TI->getNumOperands() == 1) {
9115     // If this is a non-volatile load or a cast from the same type,
9116     // merge.
9117     if (TI->isCast()) {
9118       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9119         return 0;
9120     } else {
9121       return 0;  // unknown unary op.
9122     }
9123
9124     // Fold this by inserting a select from the input values.
9125     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9126                                           FI->getOperand(0), SI.getName()+".v");
9127     InsertNewInstBefore(NewSI, SI);
9128     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9129                             TI->getType());
9130   }
9131
9132   // Only handle binary operators here.
9133   if (!isa<BinaryOperator>(TI))
9134     return 0;
9135
9136   // Figure out if the operations have any operands in common.
9137   Value *MatchOp, *OtherOpT, *OtherOpF;
9138   bool MatchIsOpZero;
9139   if (TI->getOperand(0) == FI->getOperand(0)) {
9140     MatchOp  = TI->getOperand(0);
9141     OtherOpT = TI->getOperand(1);
9142     OtherOpF = FI->getOperand(1);
9143     MatchIsOpZero = true;
9144   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9145     MatchOp  = TI->getOperand(1);
9146     OtherOpT = TI->getOperand(0);
9147     OtherOpF = FI->getOperand(0);
9148     MatchIsOpZero = false;
9149   } else if (!TI->isCommutative()) {
9150     return 0;
9151   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9152     MatchOp  = TI->getOperand(0);
9153     OtherOpT = TI->getOperand(1);
9154     OtherOpF = FI->getOperand(0);
9155     MatchIsOpZero = true;
9156   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9157     MatchOp  = TI->getOperand(1);
9158     OtherOpT = TI->getOperand(0);
9159     OtherOpF = FI->getOperand(1);
9160     MatchIsOpZero = true;
9161   } else {
9162     return 0;
9163   }
9164
9165   // If we reach here, they do have operations in common.
9166   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9167                                          OtherOpF, SI.getName()+".v");
9168   InsertNewInstBefore(NewSI, SI);
9169
9170   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9171     if (MatchIsOpZero)
9172       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9173     else
9174       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9175   }
9176   llvm_unreachable("Shouldn't get here");
9177   return 0;
9178 }
9179
9180 static bool isSelect01(Constant *C1, Constant *C2) {
9181   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9182   if (!C1I)
9183     return false;
9184   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9185   if (!C2I)
9186     return false;
9187   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9188 }
9189
9190 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9191 /// facilitate further optimization.
9192 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9193                                             Value *FalseVal) {
9194   // See the comment above GetSelectFoldableOperands for a description of the
9195   // transformation we are doing here.
9196   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9197     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9198         !isa<Constant>(FalseVal)) {
9199       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9200         unsigned OpToFold = 0;
9201         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9202           OpToFold = 1;
9203         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9204           OpToFold = 2;
9205         }
9206
9207         if (OpToFold) {
9208           Constant *C = GetSelectFoldableConstant(TVI, Context);
9209           Value *OOp = TVI->getOperand(2-OpToFold);
9210           // Avoid creating select between 2 constants unless it's selecting
9211           // between 0 and 1.
9212           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9213             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9214             InsertNewInstBefore(NewSel, SI);
9215             NewSel->takeName(TVI);
9216             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9217               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9218             llvm_unreachable("Unknown instruction!!");
9219           }
9220         }
9221       }
9222     }
9223   }
9224
9225   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9226     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9227         !isa<Constant>(TrueVal)) {
9228       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9229         unsigned OpToFold = 0;
9230         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9231           OpToFold = 1;
9232         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9233           OpToFold = 2;
9234         }
9235
9236         if (OpToFold) {
9237           Constant *C = GetSelectFoldableConstant(FVI, Context);
9238           Value *OOp = FVI->getOperand(2-OpToFold);
9239           // Avoid creating select between 2 constants unless it's selecting
9240           // between 0 and 1.
9241           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9242             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9243             InsertNewInstBefore(NewSel, SI);
9244             NewSel->takeName(FVI);
9245             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9246               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9247             llvm_unreachable("Unknown instruction!!");
9248           }
9249         }
9250       }
9251     }
9252   }
9253
9254   return 0;
9255 }
9256
9257 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9258 /// ICmpInst as its first operand.
9259 ///
9260 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9261                                                    ICmpInst *ICI) {
9262   bool Changed = false;
9263   ICmpInst::Predicate Pred = ICI->getPredicate();
9264   Value *CmpLHS = ICI->getOperand(0);
9265   Value *CmpRHS = ICI->getOperand(1);
9266   Value *TrueVal = SI.getTrueValue();
9267   Value *FalseVal = SI.getFalseValue();
9268
9269   // Check cases where the comparison is with a constant that
9270   // can be adjusted to fit the min/max idiom. We may edit ICI in
9271   // place here, so make sure the select is the only user.
9272   if (ICI->hasOneUse())
9273     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9274       switch (Pred) {
9275       default: break;
9276       case ICmpInst::ICMP_ULT:
9277       case ICmpInst::ICMP_SLT: {
9278         // X < MIN ? T : F  -->  F
9279         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9280           return ReplaceInstUsesWith(SI, FalseVal);
9281         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9282         Constant *AdjustedRHS = SubOne(CI);
9283         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9284             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9285           Pred = ICmpInst::getSwappedPredicate(Pred);
9286           CmpRHS = AdjustedRHS;
9287           std::swap(FalseVal, TrueVal);
9288           ICI->setPredicate(Pred);
9289           ICI->setOperand(1, CmpRHS);
9290           SI.setOperand(1, TrueVal);
9291           SI.setOperand(2, FalseVal);
9292           Changed = true;
9293         }
9294         break;
9295       }
9296       case ICmpInst::ICMP_UGT:
9297       case ICmpInst::ICMP_SGT: {
9298         // X > MAX ? T : F  -->  F
9299         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9300           return ReplaceInstUsesWith(SI, FalseVal);
9301         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9302         Constant *AdjustedRHS = AddOne(CI);
9303         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9304             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9305           Pred = ICmpInst::getSwappedPredicate(Pred);
9306           CmpRHS = AdjustedRHS;
9307           std::swap(FalseVal, TrueVal);
9308           ICI->setPredicate(Pred);
9309           ICI->setOperand(1, CmpRHS);
9310           SI.setOperand(1, TrueVal);
9311           SI.setOperand(2, FalseVal);
9312           Changed = true;
9313         }
9314         break;
9315       }
9316       }
9317
9318       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9319       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9320       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9321       if (match(TrueVal, m_ConstantInt<-1>()) &&
9322           match(FalseVal, m_ConstantInt<0>()))
9323         Pred = ICI->getPredicate();
9324       else if (match(TrueVal, m_ConstantInt<0>()) &&
9325                match(FalseVal, m_ConstantInt<-1>()))
9326         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9327       
9328       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9329         // If we are just checking for a icmp eq of a single bit and zext'ing it
9330         // to an integer, then shift the bit to the appropriate place and then
9331         // cast to integer to avoid the comparison.
9332         const APInt &Op1CV = CI->getValue();
9333     
9334         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9335         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9336         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9337             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9338           Value *In = ICI->getOperand(0);
9339           Value *Sh = ConstantInt::get(In->getType(),
9340                                        In->getType()->getScalarSizeInBits()-1);
9341           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9342                                                         In->getName()+".lobit"),
9343                                    *ICI);
9344           if (In->getType() != SI.getType())
9345             In = CastInst::CreateIntegerCast(In, SI.getType(),
9346                                              true/*SExt*/, "tmp", ICI);
9347     
9348           if (Pred == ICmpInst::ICMP_SGT)
9349             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9350                                        In->getName()+".not"), *ICI);
9351     
9352           return ReplaceInstUsesWith(SI, In);
9353         }
9354       }
9355     }
9356
9357   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9358     // Transform (X == Y) ? X : Y  -> Y
9359     if (Pred == ICmpInst::ICMP_EQ)
9360       return ReplaceInstUsesWith(SI, FalseVal);
9361     // Transform (X != Y) ? X : Y  -> X
9362     if (Pred == ICmpInst::ICMP_NE)
9363       return ReplaceInstUsesWith(SI, TrueVal);
9364     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9365
9366   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9367     // Transform (X == Y) ? Y : X  -> X
9368     if (Pred == ICmpInst::ICMP_EQ)
9369       return ReplaceInstUsesWith(SI, FalseVal);
9370     // Transform (X != Y) ? Y : X  -> Y
9371     if (Pred == ICmpInst::ICMP_NE)
9372       return ReplaceInstUsesWith(SI, TrueVal);
9373     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9374   }
9375
9376   /// NOTE: if we wanted to, this is where to detect integer ABS
9377
9378   return Changed ? &SI : 0;
9379 }
9380
9381 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9382   Value *CondVal = SI.getCondition();
9383   Value *TrueVal = SI.getTrueValue();
9384   Value *FalseVal = SI.getFalseValue();
9385
9386   // select true, X, Y  -> X
9387   // select false, X, Y -> Y
9388   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9389     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9390
9391   // select C, X, X -> X
9392   if (TrueVal == FalseVal)
9393     return ReplaceInstUsesWith(SI, TrueVal);
9394
9395   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9396     return ReplaceInstUsesWith(SI, FalseVal);
9397   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9398     return ReplaceInstUsesWith(SI, TrueVal);
9399   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9400     if (isa<Constant>(TrueVal))
9401       return ReplaceInstUsesWith(SI, TrueVal);
9402     else
9403       return ReplaceInstUsesWith(SI, FalseVal);
9404   }
9405
9406   if (SI.getType() == Type::getInt1Ty(*Context)) {
9407     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9408       if (C->getZExtValue()) {
9409         // Change: A = select B, true, C --> A = or B, C
9410         return BinaryOperator::CreateOr(CondVal, FalseVal);
9411       } else {
9412         // Change: A = select B, false, C --> A = and !B, C
9413         Value *NotCond =
9414           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9415                                              "not."+CondVal->getName()), SI);
9416         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9417       }
9418     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9419       if (C->getZExtValue() == false) {
9420         // Change: A = select B, C, false --> A = and B, C
9421         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9422       } else {
9423         // Change: A = select B, C, true --> A = or !B, C
9424         Value *NotCond =
9425           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9426                                              "not."+CondVal->getName()), SI);
9427         return BinaryOperator::CreateOr(NotCond, TrueVal);
9428       }
9429     }
9430     
9431     // select a, b, a  -> a&b
9432     // select a, a, b  -> a|b
9433     if (CondVal == TrueVal)
9434       return BinaryOperator::CreateOr(CondVal, FalseVal);
9435     else if (CondVal == FalseVal)
9436       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9437   }
9438
9439   // Selecting between two integer constants?
9440   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9441     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9442       // select C, 1, 0 -> zext C to int
9443       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9444         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9445       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9446         // select C, 0, 1 -> zext !C to int
9447         Value *NotCond =
9448           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9449                                                "not."+CondVal->getName()), SI);
9450         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9451       }
9452
9453       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9454         // If one of the constants is zero (we know they can't both be) and we
9455         // have an icmp instruction with zero, and we have an 'and' with the
9456         // non-constant value, eliminate this whole mess.  This corresponds to
9457         // cases like this: ((X & 27) ? 27 : 0)
9458         if (TrueValC->isZero() || FalseValC->isZero())
9459           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9460               cast<Constant>(IC->getOperand(1))->isNullValue())
9461             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9462               if (ICA->getOpcode() == Instruction::And &&
9463                   isa<ConstantInt>(ICA->getOperand(1)) &&
9464                   (ICA->getOperand(1) == TrueValC ||
9465                    ICA->getOperand(1) == FalseValC) &&
9466                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9467                 // Okay, now we know that everything is set up, we just don't
9468                 // know whether we have a icmp_ne or icmp_eq and whether the 
9469                 // true or false val is the zero.
9470                 bool ShouldNotVal = !TrueValC->isZero();
9471                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9472                 Value *V = ICA;
9473                 if (ShouldNotVal)
9474                   V = InsertNewInstBefore(BinaryOperator::Create(
9475                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9476                 return ReplaceInstUsesWith(SI, V);
9477               }
9478       }
9479     }
9480
9481   // See if we are selecting two values based on a comparison of the two values.
9482   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9483     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9484       // Transform (X == Y) ? X : Y  -> Y
9485       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9486         // This is not safe in general for floating point:  
9487         // consider X== -0, Y== +0.
9488         // It becomes safe if either operand is a nonzero constant.
9489         ConstantFP *CFPt, *CFPf;
9490         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9491               !CFPt->getValueAPF().isZero()) ||
9492             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9493              !CFPf->getValueAPF().isZero()))
9494         return ReplaceInstUsesWith(SI, FalseVal);
9495       }
9496       // Transform (X != Y) ? X : Y  -> X
9497       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9498         return ReplaceInstUsesWith(SI, TrueVal);
9499       // NOTE: if we wanted to, this is where to detect MIN/MAX
9500
9501     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9502       // Transform (X == Y) ? Y : X  -> X
9503       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9504         // This is not safe in general for floating point:  
9505         // consider X== -0, Y== +0.
9506         // It becomes safe if either operand is a nonzero constant.
9507         ConstantFP *CFPt, *CFPf;
9508         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9509               !CFPt->getValueAPF().isZero()) ||
9510             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9511              !CFPf->getValueAPF().isZero()))
9512           return ReplaceInstUsesWith(SI, FalseVal);
9513       }
9514       // Transform (X != Y) ? Y : X  -> Y
9515       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9516         return ReplaceInstUsesWith(SI, TrueVal);
9517       // NOTE: if we wanted to, this is where to detect MIN/MAX
9518     }
9519     // NOTE: if we wanted to, this is where to detect ABS
9520   }
9521
9522   // See if we are selecting two values based on a comparison of the two values.
9523   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9524     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9525       return Result;
9526
9527   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9528     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9529       if (TI->hasOneUse() && FI->hasOneUse()) {
9530         Instruction *AddOp = 0, *SubOp = 0;
9531
9532         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9533         if (TI->getOpcode() == FI->getOpcode())
9534           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9535             return IV;
9536
9537         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9538         // even legal for FP.
9539         if ((TI->getOpcode() == Instruction::Sub &&
9540              FI->getOpcode() == Instruction::Add) ||
9541             (TI->getOpcode() == Instruction::FSub &&
9542              FI->getOpcode() == Instruction::FAdd)) {
9543           AddOp = FI; SubOp = TI;
9544         } else if ((FI->getOpcode() == Instruction::Sub &&
9545                     TI->getOpcode() == Instruction::Add) ||
9546                    (FI->getOpcode() == Instruction::FSub &&
9547                     TI->getOpcode() == Instruction::FAdd)) {
9548           AddOp = TI; SubOp = FI;
9549         }
9550
9551         if (AddOp) {
9552           Value *OtherAddOp = 0;
9553           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9554             OtherAddOp = AddOp->getOperand(1);
9555           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9556             OtherAddOp = AddOp->getOperand(0);
9557           }
9558
9559           if (OtherAddOp) {
9560             // So at this point we know we have (Y -> OtherAddOp):
9561             //        select C, (add X, Y), (sub X, Z)
9562             Value *NegVal;  // Compute -Z
9563             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9564               NegVal = ConstantExpr::getNeg(C);
9565             } else {
9566               NegVal = InsertNewInstBefore(
9567                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9568                                               "tmp"), SI);
9569             }
9570
9571             Value *NewTrueOp = OtherAddOp;
9572             Value *NewFalseOp = NegVal;
9573             if (AddOp != TI)
9574               std::swap(NewTrueOp, NewFalseOp);
9575             Instruction *NewSel =
9576               SelectInst::Create(CondVal, NewTrueOp,
9577                                  NewFalseOp, SI.getName() + ".p");
9578
9579             NewSel = InsertNewInstBefore(NewSel, SI);
9580             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9581           }
9582         }
9583       }
9584
9585   // See if we can fold the select into one of our operands.
9586   if (SI.getType()->isInteger()) {
9587     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9588     if (FoldI)
9589       return FoldI;
9590   }
9591
9592   if (BinaryOperator::isNot(CondVal)) {
9593     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9594     SI.setOperand(1, FalseVal);
9595     SI.setOperand(2, TrueVal);
9596     return &SI;
9597   }
9598
9599   return 0;
9600 }
9601
9602 /// EnforceKnownAlignment - If the specified pointer points to an object that
9603 /// we control, modify the object's alignment to PrefAlign. This isn't
9604 /// often possible though. If alignment is important, a more reliable approach
9605 /// is to simply align all global variables and allocation instructions to
9606 /// their preferred alignment from the beginning.
9607 ///
9608 static unsigned EnforceKnownAlignment(Value *V,
9609                                       unsigned Align, unsigned PrefAlign) {
9610
9611   User *U = dyn_cast<User>(V);
9612   if (!U) return Align;
9613
9614   switch (Operator::getOpcode(U)) {
9615   default: break;
9616   case Instruction::BitCast:
9617     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9618   case Instruction::GetElementPtr: {
9619     // If all indexes are zero, it is just the alignment of the base pointer.
9620     bool AllZeroOperands = true;
9621     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9622       if (!isa<Constant>(*i) ||
9623           !cast<Constant>(*i)->isNullValue()) {
9624         AllZeroOperands = false;
9625         break;
9626       }
9627
9628     if (AllZeroOperands) {
9629       // Treat this like a bitcast.
9630       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9631     }
9632     break;
9633   }
9634   }
9635
9636   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9637     // If there is a large requested alignment and we can, bump up the alignment
9638     // of the global.
9639     if (!GV->isDeclaration()) {
9640       if (GV->getAlignment() >= PrefAlign)
9641         Align = GV->getAlignment();
9642       else {
9643         GV->setAlignment(PrefAlign);
9644         Align = PrefAlign;
9645       }
9646     }
9647   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9648     // If there is a requested alignment and if this is an alloca, round up.  We
9649     // don't do this for malloc, because some systems can't respect the request.
9650     if (isa<AllocaInst>(AI)) {
9651       if (AI->getAlignment() >= PrefAlign)
9652         Align = AI->getAlignment();
9653       else {
9654         AI->setAlignment(PrefAlign);
9655         Align = PrefAlign;
9656       }
9657     }
9658   }
9659
9660   return Align;
9661 }
9662
9663 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9664 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9665 /// and it is more than the alignment of the ultimate object, see if we can
9666 /// increase the alignment of the ultimate object, making this check succeed.
9667 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9668                                                   unsigned PrefAlign) {
9669   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9670                       sizeof(PrefAlign) * CHAR_BIT;
9671   APInt Mask = APInt::getAllOnesValue(BitWidth);
9672   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9673   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9674   unsigned TrailZ = KnownZero.countTrailingOnes();
9675   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9676
9677   if (PrefAlign > Align)
9678     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9679   
9680     // We don't need to make any adjustment.
9681   return Align;
9682 }
9683
9684 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9685   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9686   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9687   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9688   unsigned CopyAlign = MI->getAlignment();
9689
9690   if (CopyAlign < MinAlign) {
9691     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9692                                              MinAlign, false));
9693     return MI;
9694   }
9695   
9696   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9697   // load/store.
9698   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9699   if (MemOpLength == 0) return 0;
9700   
9701   // Source and destination pointer types are always "i8*" for intrinsic.  See
9702   // if the size is something we can handle with a single primitive load/store.
9703   // A single load+store correctly handles overlapping memory in the memmove
9704   // case.
9705   unsigned Size = MemOpLength->getZExtValue();
9706   if (Size == 0) return MI;  // Delete this mem transfer.
9707   
9708   if (Size > 8 || (Size&(Size-1)))
9709     return 0;  // If not 1/2/4/8 bytes, exit.
9710   
9711   // Use an integer load+store unless we can find something better.
9712   Type *NewPtrTy =
9713                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9714   
9715   // Memcpy forces the use of i8* for the source and destination.  That means
9716   // that if you're using memcpy to move one double around, you'll get a cast
9717   // from double* to i8*.  We'd much rather use a double load+store rather than
9718   // an i64 load+store, here because this improves the odds that the source or
9719   // dest address will be promotable.  See if we can find a better type than the
9720   // integer datatype.
9721   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9722     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9723     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9724       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9725       // down through these levels if so.
9726       while (!SrcETy->isSingleValueType()) {
9727         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9728           if (STy->getNumElements() == 1)
9729             SrcETy = STy->getElementType(0);
9730           else
9731             break;
9732         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9733           if (ATy->getNumElements() == 1)
9734             SrcETy = ATy->getElementType();
9735           else
9736             break;
9737         } else
9738           break;
9739       }
9740       
9741       if (SrcETy->isSingleValueType())
9742         NewPtrTy = PointerType::getUnqual(SrcETy);
9743     }
9744   }
9745   
9746   
9747   // If the memcpy/memmove provides better alignment info than we can
9748   // infer, use it.
9749   SrcAlign = std::max(SrcAlign, CopyAlign);
9750   DstAlign = std::max(DstAlign, CopyAlign);
9751   
9752   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9753   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9754   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9755   InsertNewInstBefore(L, *MI);
9756   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9757
9758   // Set the size of the copy to 0, it will be deleted on the next iteration.
9759   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9760   return MI;
9761 }
9762
9763 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9764   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9765   if (MI->getAlignment() < Alignment) {
9766     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9767                                              Alignment, false));
9768     return MI;
9769   }
9770   
9771   // Extract the length and alignment and fill if they are constant.
9772   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9773   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9774   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9775     return 0;
9776   uint64_t Len = LenC->getZExtValue();
9777   Alignment = MI->getAlignment();
9778   
9779   // If the length is zero, this is a no-op
9780   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9781   
9782   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9783   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9784     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9785     
9786     Value *Dest = MI->getDest();
9787     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9788
9789     // Alignment 0 is identity for alignment 1 for memset, but not store.
9790     if (Alignment == 0) Alignment = 1;
9791     
9792     // Extract the fill value and store.
9793     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9794     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9795                                       Dest, false, Alignment), *MI);
9796     
9797     // Set the size of the copy to 0, it will be deleted on the next iteration.
9798     MI->setLength(Constant::getNullValue(LenC->getType()));
9799     return MI;
9800   }
9801
9802   return 0;
9803 }
9804
9805
9806 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9807 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9808 /// the heavy lifting.
9809 ///
9810 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9811   // If the caller function is nounwind, mark the call as nounwind, even if the
9812   // callee isn't.
9813   if (CI.getParent()->getParent()->doesNotThrow() &&
9814       !CI.doesNotThrow()) {
9815     CI.setDoesNotThrow();
9816     return &CI;
9817   }
9818   
9819   
9820   
9821   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9822   if (!II) return visitCallSite(&CI);
9823   
9824   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9825   // visitCallSite.
9826   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9827     bool Changed = false;
9828
9829     // memmove/cpy/set of zero bytes is a noop.
9830     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9831       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9832
9833       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9834         if (CI->getZExtValue() == 1) {
9835           // Replace the instruction with just byte operations.  We would
9836           // transform other cases to loads/stores, but we don't know if
9837           // alignment is sufficient.
9838         }
9839     }
9840
9841     // If we have a memmove and the source operation is a constant global,
9842     // then the source and dest pointers can't alias, so we can change this
9843     // into a call to memcpy.
9844     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9845       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9846         if (GVSrc->isConstant()) {
9847           Module *M = CI.getParent()->getParent()->getParent();
9848           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9849           const Type *Tys[1];
9850           Tys[0] = CI.getOperand(3)->getType();
9851           CI.setOperand(0, 
9852                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9853           Changed = true;
9854         }
9855
9856       // memmove(x,x,size) -> noop.
9857       if (MMI->getSource() == MMI->getDest())
9858         return EraseInstFromFunction(CI);
9859     }
9860
9861     // If we can determine a pointer alignment that is bigger than currently
9862     // set, update the alignment.
9863     if (isa<MemTransferInst>(MI)) {
9864       if (Instruction *I = SimplifyMemTransfer(MI))
9865         return I;
9866     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9867       if (Instruction *I = SimplifyMemSet(MSI))
9868         return I;
9869     }
9870           
9871     if (Changed) return II;
9872   }
9873   
9874   switch (II->getIntrinsicID()) {
9875   default: break;
9876   case Intrinsic::bswap:
9877     // bswap(bswap(x)) -> x
9878     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9879       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9880         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9881     break;
9882   case Intrinsic::ppc_altivec_lvx:
9883   case Intrinsic::ppc_altivec_lvxl:
9884   case Intrinsic::x86_sse_loadu_ps:
9885   case Intrinsic::x86_sse2_loadu_pd:
9886   case Intrinsic::x86_sse2_loadu_dq:
9887     // Turn PPC lvx     -> load if the pointer is known aligned.
9888     // Turn X86 loadups -> load if the pointer is known aligned.
9889     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9890       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9891                                    PointerType::getUnqual(II->getType()),
9892                                        CI);
9893       return new LoadInst(Ptr);
9894     }
9895     break;
9896   case Intrinsic::ppc_altivec_stvx:
9897   case Intrinsic::ppc_altivec_stvxl:
9898     // Turn stvx -> store if the pointer is known aligned.
9899     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9900       const Type *OpPtrTy = 
9901         PointerType::getUnqual(II->getOperand(1)->getType());
9902       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9903       return new StoreInst(II->getOperand(1), Ptr);
9904     }
9905     break;
9906   case Intrinsic::x86_sse_storeu_ps:
9907   case Intrinsic::x86_sse2_storeu_pd:
9908   case Intrinsic::x86_sse2_storeu_dq:
9909     // Turn X86 storeu -> store if the pointer is known aligned.
9910     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9911       const Type *OpPtrTy = 
9912         PointerType::getUnqual(II->getOperand(2)->getType());
9913       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9914       return new StoreInst(II->getOperand(2), Ptr);
9915     }
9916     break;
9917     
9918   case Intrinsic::x86_sse_cvttss2si: {
9919     // These intrinsics only demands the 0th element of its input vector.  If
9920     // we can simplify the input based on that, do so now.
9921     unsigned VWidth =
9922       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9923     APInt DemandedElts(VWidth, 1);
9924     APInt UndefElts(VWidth, 0);
9925     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9926                                               UndefElts)) {
9927       II->setOperand(1, V);
9928       return II;
9929     }
9930     break;
9931   }
9932     
9933   case Intrinsic::ppc_altivec_vperm:
9934     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9935     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9936       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9937       
9938       // Check that all of the elements are integer constants or undefs.
9939       bool AllEltsOk = true;
9940       for (unsigned i = 0; i != 16; ++i) {
9941         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9942             !isa<UndefValue>(Mask->getOperand(i))) {
9943           AllEltsOk = false;
9944           break;
9945         }
9946       }
9947       
9948       if (AllEltsOk) {
9949         // Cast the input vectors to byte vectors.
9950         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9951         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9952         Value *Result = UndefValue::get(Op0->getType());
9953         
9954         // Only extract each element once.
9955         Value *ExtractedElts[32];
9956         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9957         
9958         for (unsigned i = 0; i != 16; ++i) {
9959           if (isa<UndefValue>(Mask->getOperand(i)))
9960             continue;
9961           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9962           Idx &= 31;  // Match the hardware behavior.
9963           
9964           if (ExtractedElts[Idx] == 0) {
9965             Instruction *Elt = 
9966               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9967                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
9968             InsertNewInstBefore(Elt, CI);
9969             ExtractedElts[Idx] = Elt;
9970           }
9971         
9972           // Insert this value into the result vector.
9973           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9974                                ConstantInt::get(Type::getInt32Ty(*Context), i, false), 
9975                                "tmp");
9976           InsertNewInstBefore(cast<Instruction>(Result), CI);
9977         }
9978         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9979       }
9980     }
9981     break;
9982
9983   case Intrinsic::stackrestore: {
9984     // If the save is right next to the restore, remove the restore.  This can
9985     // happen when variable allocas are DCE'd.
9986     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9987       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9988         BasicBlock::iterator BI = SS;
9989         if (&*++BI == II)
9990           return EraseInstFromFunction(CI);
9991       }
9992     }
9993     
9994     // Scan down this block to see if there is another stack restore in the
9995     // same block without an intervening call/alloca.
9996     BasicBlock::iterator BI = II;
9997     TerminatorInst *TI = II->getParent()->getTerminator();
9998     bool CannotRemove = false;
9999     for (++BI; &*BI != TI; ++BI) {
10000       if (isa<AllocaInst>(BI)) {
10001         CannotRemove = true;
10002         break;
10003       }
10004       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10005         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10006           // If there is a stackrestore below this one, remove this one.
10007           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10008             return EraseInstFromFunction(CI);
10009           // Otherwise, ignore the intrinsic.
10010         } else {
10011           // If we found a non-intrinsic call, we can't remove the stack
10012           // restore.
10013           CannotRemove = true;
10014           break;
10015         }
10016       }
10017     }
10018     
10019     // If the stack restore is in a return/unwind block and if there are no
10020     // allocas or calls between the restore and the return, nuke the restore.
10021     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10022       return EraseInstFromFunction(CI);
10023     break;
10024   }
10025   }
10026
10027   return visitCallSite(II);
10028 }
10029
10030 // InvokeInst simplification
10031 //
10032 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10033   return visitCallSite(&II);
10034 }
10035
10036 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10037 /// passed through the varargs area, we can eliminate the use of the cast.
10038 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10039                                          const CastInst * const CI,
10040                                          const TargetData * const TD,
10041                                          const int ix) {
10042   if (!CI->isLosslessCast())
10043     return false;
10044
10045   // The size of ByVal arguments is derived from the type, so we
10046   // can't change to a type with a different size.  If the size were
10047   // passed explicitly we could avoid this check.
10048   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10049     return true;
10050
10051   const Type* SrcTy = 
10052             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10053   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10054   if (!SrcTy->isSized() || !DstTy->isSized())
10055     return false;
10056   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10057     return false;
10058   return true;
10059 }
10060
10061 // visitCallSite - Improvements for call and invoke instructions.
10062 //
10063 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10064   bool Changed = false;
10065
10066   // If the callee is a constexpr cast of a function, attempt to move the cast
10067   // to the arguments of the call/invoke.
10068   if (transformConstExprCastCall(CS)) return 0;
10069
10070   Value *Callee = CS.getCalledValue();
10071
10072   if (Function *CalleeF = dyn_cast<Function>(Callee))
10073     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10074       Instruction *OldCall = CS.getInstruction();
10075       // If the call and callee calling conventions don't match, this call must
10076       // be unreachable, as the call is undefined.
10077       new StoreInst(ConstantInt::getTrue(*Context),
10078                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
10079                                   OldCall);
10080       if (!OldCall->use_empty())
10081         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10082       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10083         return EraseInstFromFunction(*OldCall);
10084       return 0;
10085     }
10086
10087   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10088     // This instruction is not reachable, just remove it.  We insert a store to
10089     // undef so that we know that this code is not reachable, despite the fact
10090     // that we can't modify the CFG here.
10091     new StoreInst(ConstantInt::getTrue(*Context),
10092                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10093                   CS.getInstruction());
10094
10095     if (!CS.getInstruction()->use_empty())
10096       CS.getInstruction()->
10097         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10098
10099     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10100       // Don't break the CFG, insert a dummy cond branch.
10101       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10102                          ConstantInt::getTrue(*Context), II);
10103     }
10104     return EraseInstFromFunction(*CS.getInstruction());
10105   }
10106
10107   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10108     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10109       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10110         return transformCallThroughTrampoline(CS);
10111
10112   const PointerType *PTy = cast<PointerType>(Callee->getType());
10113   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10114   if (FTy->isVarArg()) {
10115     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10116     // See if we can optimize any arguments passed through the varargs area of
10117     // the call.
10118     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10119            E = CS.arg_end(); I != E; ++I, ++ix) {
10120       CastInst *CI = dyn_cast<CastInst>(*I);
10121       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10122         *I = CI->getOperand(0);
10123         Changed = true;
10124       }
10125     }
10126   }
10127
10128   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10129     // Inline asm calls cannot throw - mark them 'nounwind'.
10130     CS.setDoesNotThrow();
10131     Changed = true;
10132   }
10133
10134   return Changed ? CS.getInstruction() : 0;
10135 }
10136
10137 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10138 // attempt to move the cast to the arguments of the call/invoke.
10139 //
10140 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10141   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10142   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10143   if (CE->getOpcode() != Instruction::BitCast || 
10144       !isa<Function>(CE->getOperand(0)))
10145     return false;
10146   Function *Callee = cast<Function>(CE->getOperand(0));
10147   Instruction *Caller = CS.getInstruction();
10148   const AttrListPtr &CallerPAL = CS.getAttributes();
10149
10150   // Okay, this is a cast from a function to a different type.  Unless doing so
10151   // would cause a type conversion of one of our arguments, change this call to
10152   // be a direct call with arguments casted to the appropriate types.
10153   //
10154   const FunctionType *FT = Callee->getFunctionType();
10155   const Type *OldRetTy = Caller->getType();
10156   const Type *NewRetTy = FT->getReturnType();
10157
10158   if (isa<StructType>(NewRetTy))
10159     return false; // TODO: Handle multiple return values.
10160
10161   // Check to see if we are changing the return type...
10162   if (OldRetTy != NewRetTy) {
10163     if (Callee->isDeclaration() &&
10164         // Conversion is ok if changing from one pointer type to another or from
10165         // a pointer to an integer of the same size.
10166         !((isa<PointerType>(OldRetTy) || !TD ||
10167            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10168           (isa<PointerType>(NewRetTy) || !TD ||
10169            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10170       return false;   // Cannot transform this return value.
10171
10172     if (!Caller->use_empty() &&
10173         // void -> non-void is handled specially
10174         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10175       return false;   // Cannot transform this return value.
10176
10177     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10178       Attributes RAttrs = CallerPAL.getRetAttributes();
10179       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10180         return false;   // Attribute not compatible with transformed value.
10181     }
10182
10183     // If the callsite is an invoke instruction, and the return value is used by
10184     // a PHI node in a successor, we cannot change the return type of the call
10185     // because there is no place to put the cast instruction (without breaking
10186     // the critical edge).  Bail out in this case.
10187     if (!Caller->use_empty())
10188       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10189         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10190              UI != E; ++UI)
10191           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10192             if (PN->getParent() == II->getNormalDest() ||
10193                 PN->getParent() == II->getUnwindDest())
10194               return false;
10195   }
10196
10197   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10198   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10199
10200   CallSite::arg_iterator AI = CS.arg_begin();
10201   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10202     const Type *ParamTy = FT->getParamType(i);
10203     const Type *ActTy = (*AI)->getType();
10204
10205     if (!CastInst::isCastable(ActTy, ParamTy))
10206       return false;   // Cannot transform this parameter value.
10207
10208     if (CallerPAL.getParamAttributes(i + 1) 
10209         & Attribute::typeIncompatible(ParamTy))
10210       return false;   // Attribute not compatible with transformed value.
10211
10212     // Converting from one pointer type to another or between a pointer and an
10213     // integer of the same size is safe even if we do not have a body.
10214     bool isConvertible = ActTy == ParamTy ||
10215       (TD && ((isa<PointerType>(ParamTy) ||
10216       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10217               (isa<PointerType>(ActTy) ||
10218               ActTy == TD->getIntPtrType(Caller->getContext()))));
10219     if (Callee->isDeclaration() && !isConvertible) return false;
10220   }
10221
10222   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10223       Callee->isDeclaration())
10224     return false;   // Do not delete arguments unless we have a function body.
10225
10226   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10227       !CallerPAL.isEmpty())
10228     // In this case we have more arguments than the new function type, but we
10229     // won't be dropping them.  Check that these extra arguments have attributes
10230     // that are compatible with being a vararg call argument.
10231     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10232       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10233         break;
10234       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10235       if (PAttrs & Attribute::VarArgsIncompatible)
10236         return false;
10237     }
10238
10239   // Okay, we decided that this is a safe thing to do: go ahead and start
10240   // inserting cast instructions as necessary...
10241   std::vector<Value*> Args;
10242   Args.reserve(NumActualArgs);
10243   SmallVector<AttributeWithIndex, 8> attrVec;
10244   attrVec.reserve(NumCommonArgs);
10245
10246   // Get any return attributes.
10247   Attributes RAttrs = CallerPAL.getRetAttributes();
10248
10249   // If the return value is not being used, the type may not be compatible
10250   // with the existing attributes.  Wipe out any problematic attributes.
10251   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10252
10253   // Add the new return attributes.
10254   if (RAttrs)
10255     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10256
10257   AI = CS.arg_begin();
10258   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10259     const Type *ParamTy = FT->getParamType(i);
10260     if ((*AI)->getType() == ParamTy) {
10261       Args.push_back(*AI);
10262     } else {
10263       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10264           false, ParamTy, false);
10265       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10266       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10267     }
10268
10269     // Add any parameter attributes.
10270     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10271       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10272   }
10273
10274   // If the function takes more arguments than the call was taking, add them
10275   // now...
10276   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10277     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10278
10279   // If we are removing arguments to the function, emit an obnoxious warning...
10280   if (FT->getNumParams() < NumActualArgs) {
10281     if (!FT->isVarArg()) {
10282       errs() << "WARNING: While resolving call to function '"
10283              << Callee->getName() << "' arguments were dropped!\n";
10284     } else {
10285       // Add all of the arguments in their promoted form to the arg list...
10286       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10287         const Type *PTy = getPromotedType((*AI)->getType());
10288         if (PTy != (*AI)->getType()) {
10289           // Must promote to pass through va_arg area!
10290           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10291                                                                 PTy, false);
10292           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10293           InsertNewInstBefore(Cast, *Caller);
10294           Args.push_back(Cast);
10295         } else {
10296           Args.push_back(*AI);
10297         }
10298
10299         // Add any parameter attributes.
10300         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10301           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10302       }
10303     }
10304   }
10305
10306   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10307     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10308
10309   if (NewRetTy == Type::getVoidTy(*Context))
10310     Caller->setName("");   // Void type should not have a name.
10311
10312   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10313                                                      attrVec.end());
10314
10315   Instruction *NC;
10316   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10317     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10318                             Args.begin(), Args.end(),
10319                             Caller->getName(), Caller);
10320     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10321     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10322   } else {
10323     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10324                           Caller->getName(), Caller);
10325     CallInst *CI = cast<CallInst>(Caller);
10326     if (CI->isTailCall())
10327       cast<CallInst>(NC)->setTailCall();
10328     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10329     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10330   }
10331
10332   // Insert a cast of the return type as necessary.
10333   Value *NV = NC;
10334   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10335     if (NV->getType() != Type::getVoidTy(*Context)) {
10336       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10337                                                             OldRetTy, false);
10338       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10339
10340       // If this is an invoke instruction, we should insert it after the first
10341       // non-phi, instruction in the normal successor block.
10342       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10343         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10344         InsertNewInstBefore(NC, *I);
10345       } else {
10346         // Otherwise, it's a call, just insert cast right after the call instr
10347         InsertNewInstBefore(NC, *Caller);
10348       }
10349       Worklist.AddUsersToWorkList(*Caller);
10350     } else {
10351       NV = UndefValue::get(Caller->getType());
10352     }
10353   }
10354
10355   if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10356     Caller->replaceAllUsesWith(NV);
10357   Caller->eraseFromParent();
10358   Worklist.Remove(Caller);
10359   return true;
10360 }
10361
10362 // transformCallThroughTrampoline - Turn a call to a function created by the
10363 // init_trampoline intrinsic into a direct call to the underlying function.
10364 //
10365 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10366   Value *Callee = CS.getCalledValue();
10367   const PointerType *PTy = cast<PointerType>(Callee->getType());
10368   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10369   const AttrListPtr &Attrs = CS.getAttributes();
10370
10371   // If the call already has the 'nest' attribute somewhere then give up -
10372   // otherwise 'nest' would occur twice after splicing in the chain.
10373   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10374     return 0;
10375
10376   IntrinsicInst *Tramp =
10377     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10378
10379   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10380   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10381   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10382
10383   const AttrListPtr &NestAttrs = NestF->getAttributes();
10384   if (!NestAttrs.isEmpty()) {
10385     unsigned NestIdx = 1;
10386     const Type *NestTy = 0;
10387     Attributes NestAttr = Attribute::None;
10388
10389     // Look for a parameter marked with the 'nest' attribute.
10390     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10391          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10392       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10393         // Record the parameter type and any other attributes.
10394         NestTy = *I;
10395         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10396         break;
10397       }
10398
10399     if (NestTy) {
10400       Instruction *Caller = CS.getInstruction();
10401       std::vector<Value*> NewArgs;
10402       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10403
10404       SmallVector<AttributeWithIndex, 8> NewAttrs;
10405       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10406
10407       // Insert the nest argument into the call argument list, which may
10408       // mean appending it.  Likewise for attributes.
10409
10410       // Add any result attributes.
10411       if (Attributes Attr = Attrs.getRetAttributes())
10412         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10413
10414       {
10415         unsigned Idx = 1;
10416         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10417         do {
10418           if (Idx == NestIdx) {
10419             // Add the chain argument and attributes.
10420             Value *NestVal = Tramp->getOperand(3);
10421             if (NestVal->getType() != NestTy)
10422               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10423             NewArgs.push_back(NestVal);
10424             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10425           }
10426
10427           if (I == E)
10428             break;
10429
10430           // Add the original argument and attributes.
10431           NewArgs.push_back(*I);
10432           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10433             NewAttrs.push_back
10434               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10435
10436           ++Idx, ++I;
10437         } while (1);
10438       }
10439
10440       // Add any function attributes.
10441       if (Attributes Attr = Attrs.getFnAttributes())
10442         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10443
10444       // The trampoline may have been bitcast to a bogus type (FTy).
10445       // Handle this by synthesizing a new function type, equal to FTy
10446       // with the chain parameter inserted.
10447
10448       std::vector<const Type*> NewTypes;
10449       NewTypes.reserve(FTy->getNumParams()+1);
10450
10451       // Insert the chain's type into the list of parameter types, which may
10452       // mean appending it.
10453       {
10454         unsigned Idx = 1;
10455         FunctionType::param_iterator I = FTy->param_begin(),
10456           E = FTy->param_end();
10457
10458         do {
10459           if (Idx == NestIdx)
10460             // Add the chain's type.
10461             NewTypes.push_back(NestTy);
10462
10463           if (I == E)
10464             break;
10465
10466           // Add the original type.
10467           NewTypes.push_back(*I);
10468
10469           ++Idx, ++I;
10470         } while (1);
10471       }
10472
10473       // Replace the trampoline call with a direct call.  Let the generic
10474       // code sort out any function type mismatches.
10475       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10476                                                 FTy->isVarArg());
10477       Constant *NewCallee =
10478         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10479         NestF : ConstantExpr::getBitCast(NestF, 
10480                                          PointerType::getUnqual(NewFTy));
10481       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10482                                                    NewAttrs.end());
10483
10484       Instruction *NewCaller;
10485       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10486         NewCaller = InvokeInst::Create(NewCallee,
10487                                        II->getNormalDest(), II->getUnwindDest(),
10488                                        NewArgs.begin(), NewArgs.end(),
10489                                        Caller->getName(), Caller);
10490         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10491         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10492       } else {
10493         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10494                                      Caller->getName(), Caller);
10495         if (cast<CallInst>(Caller)->isTailCall())
10496           cast<CallInst>(NewCaller)->setTailCall();
10497         cast<CallInst>(NewCaller)->
10498           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10499         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10500       }
10501       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10502         Caller->replaceAllUsesWith(NewCaller);
10503       Caller->eraseFromParent();
10504       Worklist.Remove(Caller);
10505       return 0;
10506     }
10507   }
10508
10509   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10510   // parameter, there is no need to adjust the argument list.  Let the generic
10511   // code sort out any function type mismatches.
10512   Constant *NewCallee =
10513     NestF->getType() == PTy ? NestF : 
10514                               ConstantExpr::getBitCast(NestF, PTy);
10515   CS.setCalledFunction(NewCallee);
10516   return CS.getInstruction();
10517 }
10518
10519 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10520 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10521 /// and a single binop.
10522 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10523   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10524   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10525   unsigned Opc = FirstInst->getOpcode();
10526   Value *LHSVal = FirstInst->getOperand(0);
10527   Value *RHSVal = FirstInst->getOperand(1);
10528     
10529   const Type *LHSType = LHSVal->getType();
10530   const Type *RHSType = RHSVal->getType();
10531   
10532   // Scan to see if all operands are the same opcode, all have one use, and all
10533   // kill their operands (i.e. the operands have one use).
10534   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10535     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10536     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10537         // Verify type of the LHS matches so we don't fold cmp's of different
10538         // types or GEP's with different index types.
10539         I->getOperand(0)->getType() != LHSType ||
10540         I->getOperand(1)->getType() != RHSType)
10541       return 0;
10542
10543     // If they are CmpInst instructions, check their predicates
10544     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10545       if (cast<CmpInst>(I)->getPredicate() !=
10546           cast<CmpInst>(FirstInst)->getPredicate())
10547         return 0;
10548     
10549     // Keep track of which operand needs a phi node.
10550     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10551     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10552   }
10553   
10554   // Otherwise, this is safe to transform!
10555   
10556   Value *InLHS = FirstInst->getOperand(0);
10557   Value *InRHS = FirstInst->getOperand(1);
10558   PHINode *NewLHS = 0, *NewRHS = 0;
10559   if (LHSVal == 0) {
10560     NewLHS = PHINode::Create(LHSType,
10561                              FirstInst->getOperand(0)->getName() + ".pn");
10562     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10563     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10564     InsertNewInstBefore(NewLHS, PN);
10565     LHSVal = NewLHS;
10566   }
10567   
10568   if (RHSVal == 0) {
10569     NewRHS = PHINode::Create(RHSType,
10570                              FirstInst->getOperand(1)->getName() + ".pn");
10571     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10572     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10573     InsertNewInstBefore(NewRHS, PN);
10574     RHSVal = NewRHS;
10575   }
10576   
10577   // Add all operands to the new PHIs.
10578   if (NewLHS || NewRHS) {
10579     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10580       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10581       if (NewLHS) {
10582         Value *NewInLHS = InInst->getOperand(0);
10583         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10584       }
10585       if (NewRHS) {
10586         Value *NewInRHS = InInst->getOperand(1);
10587         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10588       }
10589     }
10590   }
10591     
10592   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10593     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10594   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10595   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10596                          LHSVal, RHSVal);
10597 }
10598
10599 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10600   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10601   
10602   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10603                                         FirstInst->op_end());
10604   // This is true if all GEP bases are allocas and if all indices into them are
10605   // constants.
10606   bool AllBasePointersAreAllocas = true;
10607   
10608   // Scan to see if all operands are the same opcode, all have one use, and all
10609   // kill their operands (i.e. the operands have one use).
10610   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10611     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10612     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10613       GEP->getNumOperands() != FirstInst->getNumOperands())
10614       return 0;
10615
10616     // Keep track of whether or not all GEPs are of alloca pointers.
10617     if (AllBasePointersAreAllocas &&
10618         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10619          !GEP->hasAllConstantIndices()))
10620       AllBasePointersAreAllocas = false;
10621     
10622     // Compare the operand lists.
10623     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10624       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10625         continue;
10626       
10627       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10628       // if one of the PHIs has a constant for the index.  The index may be
10629       // substantially cheaper to compute for the constants, so making it a
10630       // variable index could pessimize the path.  This also handles the case
10631       // for struct indices, which must always be constant.
10632       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10633           isa<ConstantInt>(GEP->getOperand(op)))
10634         return 0;
10635       
10636       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10637         return 0;
10638       FixedOperands[op] = 0;  // Needs a PHI.
10639     }
10640   }
10641   
10642   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10643   // bother doing this transformation.  At best, this will just save a bit of
10644   // offset calculation, but all the predecessors will have to materialize the
10645   // stack address into a register anyway.  We'd actually rather *clone* the
10646   // load up into the predecessors so that we have a load of a gep of an alloca,
10647   // which can usually all be folded into the load.
10648   if (AllBasePointersAreAllocas)
10649     return 0;
10650   
10651   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10652   // that is variable.
10653   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10654   
10655   bool HasAnyPHIs = false;
10656   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10657     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10658     Value *FirstOp = FirstInst->getOperand(i);
10659     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10660                                      FirstOp->getName()+".pn");
10661     InsertNewInstBefore(NewPN, PN);
10662     
10663     NewPN->reserveOperandSpace(e);
10664     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10665     OperandPhis[i] = NewPN;
10666     FixedOperands[i] = NewPN;
10667     HasAnyPHIs = true;
10668   }
10669
10670   
10671   // Add all operands to the new PHIs.
10672   if (HasAnyPHIs) {
10673     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10674       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10675       BasicBlock *InBB = PN.getIncomingBlock(i);
10676       
10677       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10678         if (PHINode *OpPhi = OperandPhis[op])
10679           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10680     }
10681   }
10682   
10683   Value *Base = FixedOperands[0];
10684   GetElementPtrInst *GEP =
10685     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10686                               FixedOperands.end());
10687   if (cast<GEPOperator>(FirstInst)->isInBounds())
10688     cast<GEPOperator>(GEP)->setIsInBounds(true);
10689   return GEP;
10690 }
10691
10692
10693 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10694 /// sink the load out of the block that defines it.  This means that it must be
10695 /// obvious the value of the load is not changed from the point of the load to
10696 /// the end of the block it is in.
10697 ///
10698 /// Finally, it is safe, but not profitable, to sink a load targetting a
10699 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10700 /// to a register.
10701 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10702   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10703   
10704   for (++BBI; BBI != E; ++BBI)
10705     if (BBI->mayWriteToMemory())
10706       return false;
10707   
10708   // Check for non-address taken alloca.  If not address-taken already, it isn't
10709   // profitable to do this xform.
10710   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10711     bool isAddressTaken = false;
10712     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10713          UI != E; ++UI) {
10714       if (isa<LoadInst>(UI)) continue;
10715       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10716         // If storing TO the alloca, then the address isn't taken.
10717         if (SI->getOperand(1) == AI) continue;
10718       }
10719       isAddressTaken = true;
10720       break;
10721     }
10722     
10723     if (!isAddressTaken && AI->isStaticAlloca())
10724       return false;
10725   }
10726   
10727   // If this load is a load from a GEP with a constant offset from an alloca,
10728   // then we don't want to sink it.  In its present form, it will be
10729   // load [constant stack offset].  Sinking it will cause us to have to
10730   // materialize the stack addresses in each predecessor in a register only to
10731   // do a shared load from register in the successor.
10732   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10733     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10734       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10735         return false;
10736   
10737   return true;
10738 }
10739
10740
10741 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10742 // operator and they all are only used by the PHI, PHI together their
10743 // inputs, and do the operation once, to the result of the PHI.
10744 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10745   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10746
10747   // Scan the instruction, looking for input operations that can be folded away.
10748   // If all input operands to the phi are the same instruction (e.g. a cast from
10749   // the same type or "+42") we can pull the operation through the PHI, reducing
10750   // code size and simplifying code.
10751   Constant *ConstantOp = 0;
10752   const Type *CastSrcTy = 0;
10753   bool isVolatile = false;
10754   if (isa<CastInst>(FirstInst)) {
10755     CastSrcTy = FirstInst->getOperand(0)->getType();
10756   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10757     // Can fold binop, compare or shift here if the RHS is a constant, 
10758     // otherwise call FoldPHIArgBinOpIntoPHI.
10759     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10760     if (ConstantOp == 0)
10761       return FoldPHIArgBinOpIntoPHI(PN);
10762   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10763     isVolatile = LI->isVolatile();
10764     // We can't sink the load if the loaded value could be modified between the
10765     // load and the PHI.
10766     if (LI->getParent() != PN.getIncomingBlock(0) ||
10767         !isSafeAndProfitableToSinkLoad(LI))
10768       return 0;
10769     
10770     // If the PHI is of volatile loads and the load block has multiple
10771     // successors, sinking it would remove a load of the volatile value from
10772     // the path through the other successor.
10773     if (isVolatile &&
10774         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10775       return 0;
10776     
10777   } else if (isa<GetElementPtrInst>(FirstInst)) {
10778     return FoldPHIArgGEPIntoPHI(PN);
10779   } else {
10780     return 0;  // Cannot fold this operation.
10781   }
10782
10783   // Check to see if all arguments are the same operation.
10784   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10785     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10786     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10787     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10788       return 0;
10789     if (CastSrcTy) {
10790       if (I->getOperand(0)->getType() != CastSrcTy)
10791         return 0;  // Cast operation must match.
10792     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10793       // We can't sink the load if the loaded value could be modified between 
10794       // the load and the PHI.
10795       if (LI->isVolatile() != isVolatile ||
10796           LI->getParent() != PN.getIncomingBlock(i) ||
10797           !isSafeAndProfitableToSinkLoad(LI))
10798         return 0;
10799       
10800       // If the PHI is of volatile loads and the load block has multiple
10801       // successors, sinking it would remove a load of the volatile value from
10802       // the path through the other successor.
10803       if (isVolatile &&
10804           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10805         return 0;
10806       
10807     } else if (I->getOperand(1) != ConstantOp) {
10808       return 0;
10809     }
10810   }
10811
10812   // Okay, they are all the same operation.  Create a new PHI node of the
10813   // correct type, and PHI together all of the LHS's of the instructions.
10814   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10815                                    PN.getName()+".in");
10816   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10817
10818   Value *InVal = FirstInst->getOperand(0);
10819   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10820
10821   // Add all operands to the new PHI.
10822   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10823     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10824     if (NewInVal != InVal)
10825       InVal = 0;
10826     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10827   }
10828
10829   Value *PhiVal;
10830   if (InVal) {
10831     // The new PHI unions all of the same values together.  This is really
10832     // common, so we handle it intelligently here for compile-time speed.
10833     PhiVal = InVal;
10834     delete NewPN;
10835   } else {
10836     InsertNewInstBefore(NewPN, PN);
10837     PhiVal = NewPN;
10838   }
10839
10840   // Insert and return the new operation.
10841   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10842     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10843   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10844     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10845   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10846     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10847                            PhiVal, ConstantOp);
10848   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10849   
10850   // If this was a volatile load that we are merging, make sure to loop through
10851   // and mark all the input loads as non-volatile.  If we don't do this, we will
10852   // insert a new volatile load and the old ones will not be deletable.
10853   if (isVolatile)
10854     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10855       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10856   
10857   return new LoadInst(PhiVal, "", isVolatile);
10858 }
10859
10860 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10861 /// that is dead.
10862 static bool DeadPHICycle(PHINode *PN,
10863                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10864   if (PN->use_empty()) return true;
10865   if (!PN->hasOneUse()) return false;
10866
10867   // Remember this node, and if we find the cycle, return.
10868   if (!PotentiallyDeadPHIs.insert(PN))
10869     return true;
10870   
10871   // Don't scan crazily complex things.
10872   if (PotentiallyDeadPHIs.size() == 16)
10873     return false;
10874
10875   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10876     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10877
10878   return false;
10879 }
10880
10881 /// PHIsEqualValue - Return true if this phi node is always equal to
10882 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10883 ///   z = some value; x = phi (y, z); y = phi (x, z)
10884 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10885                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10886   // See if we already saw this PHI node.
10887   if (!ValueEqualPHIs.insert(PN))
10888     return true;
10889   
10890   // Don't scan crazily complex things.
10891   if (ValueEqualPHIs.size() == 16)
10892     return false;
10893  
10894   // Scan the operands to see if they are either phi nodes or are equal to
10895   // the value.
10896   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10897     Value *Op = PN->getIncomingValue(i);
10898     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10899       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10900         return false;
10901     } else if (Op != NonPhiInVal)
10902       return false;
10903   }
10904   
10905   return true;
10906 }
10907
10908
10909 // PHINode simplification
10910 //
10911 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10912   // If LCSSA is around, don't mess with Phi nodes
10913   if (MustPreserveLCSSA) return 0;
10914   
10915   if (Value *V = PN.hasConstantValue())
10916     return ReplaceInstUsesWith(PN, V);
10917
10918   // If all PHI operands are the same operation, pull them through the PHI,
10919   // reducing code size.
10920   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10921       isa<Instruction>(PN.getIncomingValue(1)) &&
10922       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10923       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10924       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10925       // than themselves more than once.
10926       PN.getIncomingValue(0)->hasOneUse())
10927     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10928       return Result;
10929
10930   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10931   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10932   // PHI)... break the cycle.
10933   if (PN.hasOneUse()) {
10934     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10935     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10936       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10937       PotentiallyDeadPHIs.insert(&PN);
10938       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10939         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10940     }
10941    
10942     // If this phi has a single use, and if that use just computes a value for
10943     // the next iteration of a loop, delete the phi.  This occurs with unused
10944     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10945     // common case here is good because the only other things that catch this
10946     // are induction variable analysis (sometimes) and ADCE, which is only run
10947     // late.
10948     if (PHIUser->hasOneUse() &&
10949         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10950         PHIUser->use_back() == &PN) {
10951       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10952     }
10953   }
10954
10955   // We sometimes end up with phi cycles that non-obviously end up being the
10956   // same value, for example:
10957   //   z = some value; x = phi (y, z); y = phi (x, z)
10958   // where the phi nodes don't necessarily need to be in the same block.  Do a
10959   // quick check to see if the PHI node only contains a single non-phi value, if
10960   // so, scan to see if the phi cycle is actually equal to that value.
10961   {
10962     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10963     // Scan for the first non-phi operand.
10964     while (InValNo != NumOperandVals && 
10965            isa<PHINode>(PN.getIncomingValue(InValNo)))
10966       ++InValNo;
10967
10968     if (InValNo != NumOperandVals) {
10969       Value *NonPhiInVal = PN.getOperand(InValNo);
10970       
10971       // Scan the rest of the operands to see if there are any conflicts, if so
10972       // there is no need to recursively scan other phis.
10973       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10974         Value *OpVal = PN.getIncomingValue(InValNo);
10975         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10976           break;
10977       }
10978       
10979       // If we scanned over all operands, then we have one unique value plus
10980       // phi values.  Scan PHI nodes to see if they all merge in each other or
10981       // the value.
10982       if (InValNo == NumOperandVals) {
10983         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10984         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10985           return ReplaceInstUsesWith(PN, NonPhiInVal);
10986       }
10987     }
10988   }
10989   return 0;
10990 }
10991
10992 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10993   Value *PtrOp = GEP.getOperand(0);
10994   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10995   // If so, eliminate the noop.
10996   if (GEP.getNumOperands() == 1)
10997     return ReplaceInstUsesWith(GEP, PtrOp);
10998
10999   if (isa<UndefValue>(GEP.getOperand(0)))
11000     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11001
11002   bool HasZeroPointerIndex = false;
11003   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11004     HasZeroPointerIndex = C->isNullValue();
11005
11006   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11007     return ReplaceInstUsesWith(GEP, PtrOp);
11008
11009   // Eliminate unneeded casts for indices.
11010   if (TD) {
11011     bool MadeChange = false;
11012     unsigned PtrSize = TD->getPointerSizeInBits();
11013     
11014     gep_type_iterator GTI = gep_type_begin(GEP);
11015     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11016          I != E; ++I, ++GTI) {
11017       if (!isa<SequentialType>(*GTI)) continue;
11018       
11019       // If we are using a wider index than needed for this platform, shrink it
11020       // to what we need.  If narrower, sign-extend it to what we need.  This
11021       // explicit cast can make subsequent optimizations more obvious.
11022       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11023       
11024       if (OpBits == PtrSize)
11025         continue;
11026       
11027       Instruction::CastOps Opc =
11028         OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11029       *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11030       MadeChange = true;
11031     }
11032     if (MadeChange) return &GEP;
11033   }
11034
11035   // Combine Indices - If the source pointer to this getelementptr instruction
11036   // is a getelementptr instruction, combine the indices of the two
11037   // getelementptr instructions into a single instruction.
11038   //
11039   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11040     // Note that if our source is a gep chain itself that we wait for that
11041     // chain to be resolved before we perform this transformation.  This
11042     // avoids us creating a TON of code in some cases.
11043     //
11044     if (GetElementPtrInst *SrcGEP =
11045           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11046       if (SrcGEP->getNumOperands() == 2)
11047         return 0;   // Wait until our source is folded to completion.
11048
11049     SmallVector<Value*, 8> Indices;
11050
11051     // Find out whether the last index in the source GEP is a sequential idx.
11052     bool EndsWithSequential = false;
11053     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11054          I != E; ++I)
11055       EndsWithSequential = !isa<StructType>(*I);
11056
11057     // Can we combine the two pointer arithmetics offsets?
11058     if (EndsWithSequential) {
11059       // Replace: gep (gep %P, long B), long A, ...
11060       // With:    T = long A+B; gep %P, T, ...
11061       //
11062       Value *Sum;
11063       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11064       Value *GO1 = GEP.getOperand(1);
11065       if (SO1 == Constant::getNullValue(SO1->getType())) {
11066         Sum = GO1;
11067       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11068         Sum = SO1;
11069       } else {
11070         // If they aren't the same type, then the input hasn't been processed
11071         // by the loop above yet (which canonicalizes sequential index types to
11072         // intptr_t).  Just avoid transforming this until the input has been
11073         // normalized.
11074         if (SO1->getType() != GO1->getType())
11075           return 0;
11076         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11077           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11078         else {
11079           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11080           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11081         }
11082       }
11083
11084       // Update the GEP in place if possible.
11085       if (Src->getNumOperands() == 2) {
11086         GEP.setOperand(0, Src->getOperand(0));
11087         GEP.setOperand(1, Sum);
11088         return &GEP;
11089       }
11090       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11091       Indices.push_back(Sum);
11092       Indices.append(GEP.op_begin()+2, GEP.op_end());
11093     } else if (isa<Constant>(*GEP.idx_begin()) &&
11094                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11095                Src->getNumOperands() != 1) {
11096       // Otherwise we can do the fold if the first index of the GEP is a zero
11097       Indices.append(Src->op_begin()+1, Src->op_end());
11098       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11099     }
11100
11101     if (!Indices.empty()) {
11102       GetElementPtrInst *NewGEP =
11103         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11104                                   Indices.end(), GEP.getName());
11105       if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
11106         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11107       return NewGEP;
11108     }
11109   }
11110   
11111   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11112   if (Value *X = getBitCastOperand(PtrOp)) {
11113     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11114            
11115     if (HasZeroPointerIndex) {
11116       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11117       // into     : GEP [10 x i8]* X, i32 0, ...
11118       //
11119       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11120       //           into     : GEP i8* X, ...
11121       // 
11122       // This occurs when the program declares an array extern like "int X[];"
11123       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11124       const PointerType *XTy = cast<PointerType>(X->getType());
11125       if (const ArrayType *CATy =
11126           dyn_cast<ArrayType>(CPTy->getElementType())) {
11127         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11128         if (CATy->getElementType() == XTy->getElementType()) {
11129           // -> GEP i8* X, ...
11130           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11131           GetElementPtrInst *NewGEP =
11132             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11133                                       GEP.getName());
11134           if (cast<GEPOperator>(&GEP)->isInBounds())
11135             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11136           return NewGEP;
11137         } else if (const ArrayType *XATy =
11138                  dyn_cast<ArrayType>(XTy->getElementType())) {
11139           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11140           if (CATy->getElementType() == XATy->getElementType()) {
11141             // -> GEP [10 x i8]* X, i32 0, ...
11142             // At this point, we know that the cast source type is a pointer
11143             // to an array of the same type as the destination pointer
11144             // array.  Because the array type is never stepped over (there
11145             // is a leading zero) we can fold the cast into this GEP.
11146             GEP.setOperand(0, X);
11147             return &GEP;
11148           }
11149         }
11150       }
11151     } else if (GEP.getNumOperands() == 2) {
11152       // Transform things like:
11153       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11154       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11155       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11156       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11157       if (TD && isa<ArrayType>(SrcElTy) &&
11158           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11159           TD->getTypeAllocSize(ResElTy)) {
11160         Value *Idx[2];
11161         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11162         Idx[1] = GEP.getOperand(1);
11163         GetElementPtrInst *NewGEP =
11164           GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11165         if (cast<GEPOperator>(&GEP)->isInBounds())
11166           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11167         Value *V = InsertNewInstBefore(NewGEP, GEP);
11168         // V and GEP are both pointer types --> BitCast
11169         return new BitCastInst(V, GEP.getType());
11170       }
11171       
11172       // Transform things like:
11173       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11174       //   (where tmp = 8*tmp2) into:
11175       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11176       
11177       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11178         uint64_t ArrayEltSize =
11179             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11180         
11181         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11182         // allow either a mul, shift, or constant here.
11183         Value *NewIdx = 0;
11184         ConstantInt *Scale = 0;
11185         if (ArrayEltSize == 1) {
11186           NewIdx = GEP.getOperand(1);
11187           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11188         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11189           NewIdx = ConstantInt::get(CI->getType(), 1);
11190           Scale = CI;
11191         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11192           if (Inst->getOpcode() == Instruction::Shl &&
11193               isa<ConstantInt>(Inst->getOperand(1))) {
11194             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11195             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11196             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11197                                      1ULL << ShAmtVal);
11198             NewIdx = Inst->getOperand(0);
11199           } else if (Inst->getOpcode() == Instruction::Mul &&
11200                      isa<ConstantInt>(Inst->getOperand(1))) {
11201             Scale = cast<ConstantInt>(Inst->getOperand(1));
11202             NewIdx = Inst->getOperand(0);
11203           }
11204         }
11205         
11206         // If the index will be to exactly the right offset with the scale taken
11207         // out, perform the transformation. Note, we don't know whether Scale is
11208         // signed or not. We'll use unsigned version of division/modulo
11209         // operation after making sure Scale doesn't have the sign bit set.
11210         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11211             Scale->getZExtValue() % ArrayEltSize == 0) {
11212           Scale = ConstantInt::get(Scale->getType(),
11213                                    Scale->getZExtValue() / ArrayEltSize);
11214           if (Scale->getZExtValue() != 1) {
11215             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11216                                                        false /*ZExt*/);
11217             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11218             NewIdx = InsertNewInstBefore(Sc, GEP);
11219           }
11220
11221           // Insert the new GEP instruction.
11222           Value *Idx[2];
11223           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11224           Idx[1] = NewIdx;
11225           Instruction *NewGEP =
11226             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11227           if (cast<GEPOperator>(&GEP)->isInBounds())
11228             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11229           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11230           // The NewGEP must be pointer typed, so must the old one -> BitCast
11231           return new BitCastInst(NewGEP, GEP.getType());
11232         }
11233       }
11234     }
11235   }
11236   
11237   /// See if we can simplify:
11238   ///   X = bitcast A* to B*
11239   ///   Y = gep X, <...constant indices...>
11240   /// into a gep of the original struct.  This is important for SROA and alias
11241   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11242   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11243     if (TD &&
11244         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11245       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11246       // a constant back from EmitGEPOffset.
11247       ConstantInt *OffsetV =
11248                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11249       int64_t Offset = OffsetV->getSExtValue();
11250       
11251       // If this GEP instruction doesn't move the pointer, just replace the GEP
11252       // with a bitcast of the real input to the dest type.
11253       if (Offset == 0) {
11254         // If the bitcast is of an allocation, and the allocation will be
11255         // converted to match the type of the cast, don't touch this.
11256         if (isa<AllocationInst>(BCI->getOperand(0))) {
11257           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11258           if (Instruction *I = visitBitCast(*BCI)) {
11259             if (I != BCI) {
11260               I->takeName(BCI);
11261               BCI->getParent()->getInstList().insert(BCI, I);
11262               ReplaceInstUsesWith(*BCI, I);
11263             }
11264             return &GEP;
11265           }
11266         }
11267         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11268       }
11269       
11270       // Otherwise, if the offset is non-zero, we need to find out if there is a
11271       // field at Offset in 'A's type.  If so, we can pull the cast through the
11272       // GEP.
11273       SmallVector<Value*, 8> NewIndices;
11274       const Type *InTy =
11275         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11276       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11277         Instruction *NGEP =
11278            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11279                                      NewIndices.end());
11280         if (NGEP->getType() == GEP.getType()) return NGEP;
11281         if (cast<GEPOperator>(&GEP)->isInBounds())
11282           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11283         InsertNewInstBefore(NGEP, GEP);
11284         NGEP->takeName(&GEP);
11285         return new BitCastInst(NGEP, GEP.getType());
11286       }
11287     }
11288   }    
11289     
11290   return 0;
11291 }
11292
11293 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11294   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11295   if (AI.isArrayAllocation()) {  // Check C != 1
11296     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11297       const Type *NewTy = 
11298         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11299       AllocationInst *New = 0;
11300
11301       // Create and insert the replacement instruction...
11302       if (isa<MallocInst>(AI))
11303         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11304       else {
11305         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11306         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11307       }
11308
11309       InsertNewInstBefore(New, AI);
11310
11311       // Scan to the end of the allocation instructions, to skip over a block of
11312       // allocas if possible...also skip interleaved debug info
11313       //
11314       BasicBlock::iterator It = New;
11315       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11316
11317       // Now that I is pointing to the first non-allocation-inst in the block,
11318       // insert our getelementptr instruction...
11319       //
11320       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11321       Value *Idx[2];
11322       Idx[0] = NullIdx;
11323       Idx[1] = NullIdx;
11324       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11325                                            New->getName()+".sub", It);
11326       cast<GEPOperator>(V)->setIsInBounds(true);
11327
11328       // Now make everything use the getelementptr instead of the original
11329       // allocation.
11330       return ReplaceInstUsesWith(AI, V);
11331     } else if (isa<UndefValue>(AI.getArraySize())) {
11332       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11333     }
11334   }
11335
11336   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11337     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11338     // Note that we only do this for alloca's, because malloc should allocate
11339     // and return a unique pointer, even for a zero byte allocation.
11340     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11341       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11342
11343     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11344     if (AI.getAlignment() == 0)
11345       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11346   }
11347
11348   return 0;
11349 }
11350
11351 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11352   Value *Op = FI.getOperand(0);
11353
11354   // free undef -> unreachable.
11355   if (isa<UndefValue>(Op)) {
11356     // Insert a new store to null because we cannot modify the CFG here.
11357     new StoreInst(ConstantInt::getTrue(*Context),
11358            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11359     return EraseInstFromFunction(FI);
11360   }
11361   
11362   // If we have 'free null' delete the instruction.  This can happen in stl code
11363   // when lots of inlining happens.
11364   if (isa<ConstantPointerNull>(Op))
11365     return EraseInstFromFunction(FI);
11366   
11367   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11368   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11369     FI.setOperand(0, CI->getOperand(0));
11370     return &FI;
11371   }
11372   
11373   // Change free (gep X, 0,0,0,0) into free(X)
11374   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11375     if (GEPI->hasAllZeroIndices()) {
11376       Worklist.Add(GEPI);
11377       FI.setOperand(0, GEPI->getOperand(0));
11378       return &FI;
11379     }
11380   }
11381   
11382   // Change free(malloc) into nothing, if the malloc has a single use.
11383   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11384     if (MI->hasOneUse()) {
11385       EraseInstFromFunction(FI);
11386       return EraseInstFromFunction(*MI);
11387     }
11388
11389   return 0;
11390 }
11391
11392
11393 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11394 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11395                                         const TargetData *TD) {
11396   User *CI = cast<User>(LI.getOperand(0));
11397   Value *CastOp = CI->getOperand(0);
11398   LLVMContext *Context = IC.getContext();
11399
11400   if (TD) {
11401     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11402       // Instead of loading constant c string, use corresponding integer value
11403       // directly if string length is small enough.
11404       std::string Str;
11405       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11406         unsigned len = Str.length();
11407         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11408         unsigned numBits = Ty->getPrimitiveSizeInBits();
11409         // Replace LI with immediate integer store.
11410         if ((numBits >> 3) == len + 1) {
11411           APInt StrVal(numBits, 0);
11412           APInt SingleChar(numBits, 0);
11413           if (TD->isLittleEndian()) {
11414             for (signed i = len-1; i >= 0; i--) {
11415               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11416               StrVal = (StrVal << 8) | SingleChar;
11417             }
11418           } else {
11419             for (unsigned i = 0; i < len; i++) {
11420               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11421               StrVal = (StrVal << 8) | SingleChar;
11422             }
11423             // Append NULL at the end.
11424             SingleChar = 0;
11425             StrVal = (StrVal << 8) | SingleChar;
11426           }
11427           Value *NL = ConstantInt::get(*Context, StrVal);
11428           return IC.ReplaceInstUsesWith(LI, NL);
11429         }
11430       }
11431     }
11432   }
11433
11434   const PointerType *DestTy = cast<PointerType>(CI->getType());
11435   const Type *DestPTy = DestTy->getElementType();
11436   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11437
11438     // If the address spaces don't match, don't eliminate the cast.
11439     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11440       return 0;
11441
11442     const Type *SrcPTy = SrcTy->getElementType();
11443
11444     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11445          isa<VectorType>(DestPTy)) {
11446       // If the source is an array, the code below will not succeed.  Check to
11447       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11448       // constants.
11449       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11450         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11451           if (ASrcTy->getNumElements() != 0) {
11452             Value *Idxs[2];
11453             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11454             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11455             SrcTy = cast<PointerType>(CastOp->getType());
11456             SrcPTy = SrcTy->getElementType();
11457           }
11458
11459       if (IC.getTargetData() &&
11460           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11461             isa<VectorType>(SrcPTy)) &&
11462           // Do not allow turning this into a load of an integer, which is then
11463           // casted to a pointer, this pessimizes pointer analysis a lot.
11464           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11465           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11466                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11467
11468         // Okay, we are casting from one integer or pointer type to another of
11469         // the same size.  Instead of casting the pointer before the load, cast
11470         // the result of the loaded value.
11471         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11472                                                              CI->getName(),
11473                                                          LI.isVolatile()),LI);
11474         // Now cast the result of the load.
11475         return new BitCastInst(NewLoad, LI.getType());
11476       }
11477     }
11478   }
11479   return 0;
11480 }
11481
11482 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11483   Value *Op = LI.getOperand(0);
11484
11485   // Attempt to improve the alignment.
11486   if (TD) {
11487     unsigned KnownAlign =
11488       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11489     if (KnownAlign >
11490         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11491                                   LI.getAlignment()))
11492       LI.setAlignment(KnownAlign);
11493   }
11494
11495   // load (cast X) --> cast (load X) iff safe
11496   if (isa<CastInst>(Op))
11497     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11498       return Res;
11499
11500   // None of the following transforms are legal for volatile loads.
11501   if (LI.isVolatile()) return 0;
11502   
11503   // Do really simple store-to-load forwarding and load CSE, to catch cases
11504   // where there are several consequtive memory accesses to the same location,
11505   // separated by a few arithmetic operations.
11506   BasicBlock::iterator BBI = &LI;
11507   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11508     return ReplaceInstUsesWith(LI, AvailableVal);
11509
11510   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11511     const Value *GEPI0 = GEPI->getOperand(0);
11512     // TODO: Consider a target hook for valid address spaces for this xform.
11513     if (isa<ConstantPointerNull>(GEPI0) &&
11514         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11515       // Insert a new store to null instruction before the load to indicate
11516       // that this code is not reachable.  We do this instead of inserting
11517       // an unreachable instruction directly because we cannot modify the
11518       // CFG.
11519       new StoreInst(UndefValue::get(LI.getType()),
11520                     Constant::getNullValue(Op->getType()), &LI);
11521       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11522     }
11523   } 
11524
11525   if (Constant *C = dyn_cast<Constant>(Op)) {
11526     // load null/undef -> undef
11527     // TODO: Consider a target hook for valid address spaces for this xform.
11528     if (isa<UndefValue>(C) || (C->isNullValue() && 
11529         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11530       // Insert a new store to null instruction before the load to indicate that
11531       // this code is not reachable.  We do this instead of inserting an
11532       // unreachable instruction directly because we cannot modify the CFG.
11533       new StoreInst(UndefValue::get(LI.getType()),
11534                     Constant::getNullValue(Op->getType()), &LI);
11535       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11536     }
11537
11538     // Instcombine load (constant global) into the value loaded.
11539     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11540       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11541         return ReplaceInstUsesWith(LI, GV->getInitializer());
11542
11543     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11544     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11545       if (CE->getOpcode() == Instruction::GetElementPtr) {
11546         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11547           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11548             if (Constant *V = 
11549                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11550                                                       *Context))
11551               return ReplaceInstUsesWith(LI, V);
11552         if (CE->getOperand(0)->isNullValue()) {
11553           // Insert a new store to null instruction before the load to indicate
11554           // that this code is not reachable.  We do this instead of inserting
11555           // an unreachable instruction directly because we cannot modify the
11556           // CFG.
11557           new StoreInst(UndefValue::get(LI.getType()),
11558                         Constant::getNullValue(Op->getType()), &LI);
11559           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11560         }
11561
11562       } else if (CE->isCast()) {
11563         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11564           return Res;
11565       }
11566     }
11567   }
11568     
11569   // If this load comes from anywhere in a constant global, and if the global
11570   // is all undef or zero, we know what it loads.
11571   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11572     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11573       if (GV->getInitializer()->isNullValue())
11574         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11575       else if (isa<UndefValue>(GV->getInitializer()))
11576         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11577     }
11578   }
11579
11580   if (Op->hasOneUse()) {
11581     // Change select and PHI nodes to select values instead of addresses: this
11582     // helps alias analysis out a lot, allows many others simplifications, and
11583     // exposes redundancy in the code.
11584     //
11585     // Note that we cannot do the transformation unless we know that the
11586     // introduced loads cannot trap!  Something like this is valid as long as
11587     // the condition is always false: load (select bool %C, int* null, int* %G),
11588     // but it would not be valid if we transformed it to load from null
11589     // unconditionally.
11590     //
11591     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11592       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11593       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11594           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11595         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11596                                      SI->getOperand(1)->getName()+".val"), LI);
11597         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11598                                      SI->getOperand(2)->getName()+".val"), LI);
11599         return SelectInst::Create(SI->getCondition(), V1, V2);
11600       }
11601
11602       // load (select (cond, null, P)) -> load P
11603       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11604         if (C->isNullValue()) {
11605           LI.setOperand(0, SI->getOperand(2));
11606           return &LI;
11607         }
11608
11609       // load (select (cond, P, null)) -> load P
11610       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11611         if (C->isNullValue()) {
11612           LI.setOperand(0, SI->getOperand(1));
11613           return &LI;
11614         }
11615     }
11616   }
11617   return 0;
11618 }
11619
11620 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11621 /// when possible.  This makes it generally easy to do alias analysis and/or
11622 /// SROA/mem2reg of the memory object.
11623 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11624   User *CI = cast<User>(SI.getOperand(1));
11625   Value *CastOp = CI->getOperand(0);
11626
11627   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11628   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11629   if (SrcTy == 0) return 0;
11630   
11631   const Type *SrcPTy = SrcTy->getElementType();
11632
11633   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11634     return 0;
11635   
11636   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11637   /// to its first element.  This allows us to handle things like:
11638   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11639   /// on 32-bit hosts.
11640   SmallVector<Value*, 4> NewGEPIndices;
11641   
11642   // If the source is an array, the code below will not succeed.  Check to
11643   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11644   // constants.
11645   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11646     // Index through pointer.
11647     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11648     NewGEPIndices.push_back(Zero);
11649     
11650     while (1) {
11651       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11652         if (!STy->getNumElements()) /* Struct can be empty {} */
11653           break;
11654         NewGEPIndices.push_back(Zero);
11655         SrcPTy = STy->getElementType(0);
11656       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11657         NewGEPIndices.push_back(Zero);
11658         SrcPTy = ATy->getElementType();
11659       } else {
11660         break;
11661       }
11662     }
11663     
11664     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11665   }
11666
11667   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11668     return 0;
11669   
11670   // If the pointers point into different address spaces or if they point to
11671   // values with different sizes, we can't do the transformation.
11672   if (!IC.getTargetData() ||
11673       SrcTy->getAddressSpace() != 
11674         cast<PointerType>(CI->getType())->getAddressSpace() ||
11675       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11676       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11677     return 0;
11678
11679   // Okay, we are casting from one integer or pointer type to another of
11680   // the same size.  Instead of casting the pointer before 
11681   // the store, cast the value to be stored.
11682   Value *NewCast;
11683   Value *SIOp0 = SI.getOperand(0);
11684   Instruction::CastOps opcode = Instruction::BitCast;
11685   const Type* CastSrcTy = SIOp0->getType();
11686   const Type* CastDstTy = SrcPTy;
11687   if (isa<PointerType>(CastDstTy)) {
11688     if (CastSrcTy->isInteger())
11689       opcode = Instruction::IntToPtr;
11690   } else if (isa<IntegerType>(CastDstTy)) {
11691     if (isa<PointerType>(SIOp0->getType()))
11692       opcode = Instruction::PtrToInt;
11693   }
11694   
11695   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11696   // emit a GEP to index into its first field.
11697   if (!NewGEPIndices.empty()) {
11698     if (Constant *C = dyn_cast<Constant>(CastOp))
11699       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11700                                               NewGEPIndices.size());
11701     else
11702       CastOp = IC.InsertNewInstBefore(
11703               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11704                                         NewGEPIndices.end()), SI);
11705     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11706   }
11707   
11708   if (Constant *C = dyn_cast<Constant>(SIOp0))
11709     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11710   else
11711     NewCast = IC.InsertNewInstBefore(
11712       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11713       SI);
11714   return new StoreInst(NewCast, CastOp);
11715 }
11716
11717 /// equivalentAddressValues - Test if A and B will obviously have the same
11718 /// value. This includes recognizing that %t0 and %t1 will have the same
11719 /// value in code like this:
11720 ///   %t0 = getelementptr \@a, 0, 3
11721 ///   store i32 0, i32* %t0
11722 ///   %t1 = getelementptr \@a, 0, 3
11723 ///   %t2 = load i32* %t1
11724 ///
11725 static bool equivalentAddressValues(Value *A, Value *B) {
11726   // Test if the values are trivially equivalent.
11727   if (A == B) return true;
11728   
11729   // Test if the values come form identical arithmetic instructions.
11730   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11731   // its only used to compare two uses within the same basic block, which
11732   // means that they'll always either have the same value or one of them
11733   // will have an undefined value.
11734   if (isa<BinaryOperator>(A) ||
11735       isa<CastInst>(A) ||
11736       isa<PHINode>(A) ||
11737       isa<GetElementPtrInst>(A))
11738     if (Instruction *BI = dyn_cast<Instruction>(B))
11739       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11740         return true;
11741   
11742   // Otherwise they may not be equivalent.
11743   return false;
11744 }
11745
11746 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11747 // return the llvm.dbg.declare.
11748 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11749   if (!V->hasNUses(2))
11750     return 0;
11751   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11752        UI != E; ++UI) {
11753     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11754       return DI;
11755     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11756       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11757         return DI;
11758       }
11759   }
11760   return 0;
11761 }
11762
11763 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11764   Value *Val = SI.getOperand(0);
11765   Value *Ptr = SI.getOperand(1);
11766
11767   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11768     EraseInstFromFunction(SI);
11769     ++NumCombined;
11770     return 0;
11771   }
11772   
11773   // If the RHS is an alloca with a single use, zapify the store, making the
11774   // alloca dead.
11775   // If the RHS is an alloca with a two uses, the other one being a 
11776   // llvm.dbg.declare, zapify the store and the declare, making the
11777   // alloca dead.  We must do this to prevent declare's from affecting
11778   // codegen.
11779   if (!SI.isVolatile()) {
11780     if (Ptr->hasOneUse()) {
11781       if (isa<AllocaInst>(Ptr)) {
11782         EraseInstFromFunction(SI);
11783         ++NumCombined;
11784         return 0;
11785       }
11786       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11787         if (isa<AllocaInst>(GEP->getOperand(0))) {
11788           if (GEP->getOperand(0)->hasOneUse()) {
11789             EraseInstFromFunction(SI);
11790             ++NumCombined;
11791             return 0;
11792           }
11793           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11794             EraseInstFromFunction(*DI);
11795             EraseInstFromFunction(SI);
11796             ++NumCombined;
11797             return 0;
11798           }
11799         }
11800       }
11801     }
11802     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11803       EraseInstFromFunction(*DI);
11804       EraseInstFromFunction(SI);
11805       ++NumCombined;
11806       return 0;
11807     }
11808   }
11809
11810   // Attempt to improve the alignment.
11811   if (TD) {
11812     unsigned KnownAlign =
11813       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11814     if (KnownAlign >
11815         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11816                                   SI.getAlignment()))
11817       SI.setAlignment(KnownAlign);
11818   }
11819
11820   // Do really simple DSE, to catch cases where there are several consecutive
11821   // stores to the same location, separated by a few arithmetic operations. This
11822   // situation often occurs with bitfield accesses.
11823   BasicBlock::iterator BBI = &SI;
11824   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11825        --ScanInsts) {
11826     --BBI;
11827     // Don't count debug info directives, lest they affect codegen,
11828     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11829     // It is necessary for correctness to skip those that feed into a
11830     // llvm.dbg.declare, as these are not present when debugging is off.
11831     if (isa<DbgInfoIntrinsic>(BBI) ||
11832         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11833       ScanInsts++;
11834       continue;
11835     }    
11836     
11837     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11838       // Prev store isn't volatile, and stores to the same location?
11839       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11840                                                           SI.getOperand(1))) {
11841         ++NumDeadStore;
11842         ++BBI;
11843         EraseInstFromFunction(*PrevSI);
11844         continue;
11845       }
11846       break;
11847     }
11848     
11849     // If this is a load, we have to stop.  However, if the loaded value is from
11850     // the pointer we're loading and is producing the pointer we're storing,
11851     // then *this* store is dead (X = load P; store X -> P).
11852     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11853       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11854           !SI.isVolatile()) {
11855         EraseInstFromFunction(SI);
11856         ++NumCombined;
11857         return 0;
11858       }
11859       // Otherwise, this is a load from some other location.  Stores before it
11860       // may not be dead.
11861       break;
11862     }
11863     
11864     // Don't skip over loads or things that can modify memory.
11865     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11866       break;
11867   }
11868   
11869   
11870   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11871
11872   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11873   if (isa<ConstantPointerNull>(Ptr) &&
11874       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11875     if (!isa<UndefValue>(Val)) {
11876       SI.setOperand(0, UndefValue::get(Val->getType()));
11877       if (Instruction *U = dyn_cast<Instruction>(Val))
11878         Worklist.Add(U);  // Dropped a use.
11879       ++NumCombined;
11880     }
11881     return 0;  // Do not modify these!
11882   }
11883
11884   // store undef, Ptr -> noop
11885   if (isa<UndefValue>(Val)) {
11886     EraseInstFromFunction(SI);
11887     ++NumCombined;
11888     return 0;
11889   }
11890
11891   // If the pointer destination is a cast, see if we can fold the cast into the
11892   // source instead.
11893   if (isa<CastInst>(Ptr))
11894     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11895       return Res;
11896   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11897     if (CE->isCast())
11898       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11899         return Res;
11900
11901   
11902   // If this store is the last instruction in the basic block (possibly
11903   // excepting debug info instructions and the pointer bitcasts that feed
11904   // into them), and if the block ends with an unconditional branch, try
11905   // to move it to the successor block.
11906   BBI = &SI; 
11907   do {
11908     ++BBI;
11909   } while (isa<DbgInfoIntrinsic>(BBI) ||
11910            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11911   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11912     if (BI->isUnconditional())
11913       if (SimplifyStoreAtEndOfBlock(SI))
11914         return 0;  // xform done!
11915   
11916   return 0;
11917 }
11918
11919 /// SimplifyStoreAtEndOfBlock - Turn things like:
11920 ///   if () { *P = v1; } else { *P = v2 }
11921 /// into a phi node with a store in the successor.
11922 ///
11923 /// Simplify things like:
11924 ///   *P = v1; if () { *P = v2; }
11925 /// into a phi node with a store in the successor.
11926 ///
11927 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11928   BasicBlock *StoreBB = SI.getParent();
11929   
11930   // Check to see if the successor block has exactly two incoming edges.  If
11931   // so, see if the other predecessor contains a store to the same location.
11932   // if so, insert a PHI node (if needed) and move the stores down.
11933   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11934   
11935   // Determine whether Dest has exactly two predecessors and, if so, compute
11936   // the other predecessor.
11937   pred_iterator PI = pred_begin(DestBB);
11938   BasicBlock *OtherBB = 0;
11939   if (*PI != StoreBB)
11940     OtherBB = *PI;
11941   ++PI;
11942   if (PI == pred_end(DestBB))
11943     return false;
11944   
11945   if (*PI != StoreBB) {
11946     if (OtherBB)
11947       return false;
11948     OtherBB = *PI;
11949   }
11950   if (++PI != pred_end(DestBB))
11951     return false;
11952
11953   // Bail out if all the relevant blocks aren't distinct (this can happen,
11954   // for example, if SI is in an infinite loop)
11955   if (StoreBB == DestBB || OtherBB == DestBB)
11956     return false;
11957
11958   // Verify that the other block ends in a branch and is not otherwise empty.
11959   BasicBlock::iterator BBI = OtherBB->getTerminator();
11960   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11961   if (!OtherBr || BBI == OtherBB->begin())
11962     return false;
11963   
11964   // If the other block ends in an unconditional branch, check for the 'if then
11965   // else' case.  there is an instruction before the branch.
11966   StoreInst *OtherStore = 0;
11967   if (OtherBr->isUnconditional()) {
11968     --BBI;
11969     // Skip over debugging info.
11970     while (isa<DbgInfoIntrinsic>(BBI) ||
11971            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11972       if (BBI==OtherBB->begin())
11973         return false;
11974       --BBI;
11975     }
11976     // If this isn't a store, or isn't a store to the same location, bail out.
11977     OtherStore = dyn_cast<StoreInst>(BBI);
11978     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11979       return false;
11980   } else {
11981     // Otherwise, the other block ended with a conditional branch. If one of the
11982     // destinations is StoreBB, then we have the if/then case.
11983     if (OtherBr->getSuccessor(0) != StoreBB && 
11984         OtherBr->getSuccessor(1) != StoreBB)
11985       return false;
11986     
11987     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11988     // if/then triangle.  See if there is a store to the same ptr as SI that
11989     // lives in OtherBB.
11990     for (;; --BBI) {
11991       // Check to see if we find the matching store.
11992       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11993         if (OtherStore->getOperand(1) != SI.getOperand(1))
11994           return false;
11995         break;
11996       }
11997       // If we find something that may be using or overwriting the stored
11998       // value, or if we run out of instructions, we can't do the xform.
11999       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12000           BBI == OtherBB->begin())
12001         return false;
12002     }
12003     
12004     // In order to eliminate the store in OtherBr, we have to
12005     // make sure nothing reads or overwrites the stored value in
12006     // StoreBB.
12007     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12008       // FIXME: This should really be AA driven.
12009       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12010         return false;
12011     }
12012   }
12013   
12014   // Insert a PHI node now if we need it.
12015   Value *MergedVal = OtherStore->getOperand(0);
12016   if (MergedVal != SI.getOperand(0)) {
12017     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12018     PN->reserveOperandSpace(2);
12019     PN->addIncoming(SI.getOperand(0), SI.getParent());
12020     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12021     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12022   }
12023   
12024   // Advance to a place where it is safe to insert the new store and
12025   // insert it.
12026   BBI = DestBB->getFirstNonPHI();
12027   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12028                                     OtherStore->isVolatile()), *BBI);
12029   
12030   // Nuke the old stores.
12031   EraseInstFromFunction(SI);
12032   EraseInstFromFunction(*OtherStore);
12033   ++NumCombined;
12034   return true;
12035 }
12036
12037
12038 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12039   // Change br (not X), label True, label False to: br X, label False, True
12040   Value *X = 0;
12041   BasicBlock *TrueDest;
12042   BasicBlock *FalseDest;
12043   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12044       !isa<Constant>(X)) {
12045     // Swap Destinations and condition...
12046     BI.setCondition(X);
12047     BI.setSuccessor(0, FalseDest);
12048     BI.setSuccessor(1, TrueDest);
12049     return &BI;
12050   }
12051
12052   // Cannonicalize fcmp_one -> fcmp_oeq
12053   FCmpInst::Predicate FPred; Value *Y;
12054   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12055                              TrueDest, FalseDest)) &&
12056       BI.getCondition()->hasOneUse())
12057     if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12058         FPred == FCmpInst::FCMP_OGE) {
12059       FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12060       Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12061       
12062       // Swap Destinations and condition.
12063       BI.setSuccessor(0, FalseDest);
12064       BI.setSuccessor(1, TrueDest);
12065       Worklist.Add(Cond);
12066       return &BI;
12067     }
12068
12069   // Cannonicalize icmp_ne -> icmp_eq
12070   ICmpInst::Predicate IPred;
12071   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12072                       TrueDest, FalseDest)) &&
12073       BI.getCondition()->hasOneUse())
12074     if (IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12075         IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12076         IPred == ICmpInst::ICMP_SGE) {
12077       ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12078       Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12079       // Swap Destinations and condition.
12080       BI.setSuccessor(0, FalseDest);
12081       BI.setSuccessor(1, TrueDest);
12082       Worklist.Add(Cond);
12083       return &BI;
12084     }
12085
12086   return 0;
12087 }
12088
12089 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12090   Value *Cond = SI.getCondition();
12091   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12092     if (I->getOpcode() == Instruction::Add)
12093       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12094         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12095         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12096           SI.setOperand(i,
12097                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12098                                                 AddRHS));
12099         SI.setOperand(0, I->getOperand(0));
12100         Worklist.Add(I);
12101         return &SI;
12102       }
12103   }
12104   return 0;
12105 }
12106
12107 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12108   Value *Agg = EV.getAggregateOperand();
12109
12110   if (!EV.hasIndices())
12111     return ReplaceInstUsesWith(EV, Agg);
12112
12113   if (Constant *C = dyn_cast<Constant>(Agg)) {
12114     if (isa<UndefValue>(C))
12115       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12116       
12117     if (isa<ConstantAggregateZero>(C))
12118       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12119
12120     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12121       // Extract the element indexed by the first index out of the constant
12122       Value *V = C->getOperand(*EV.idx_begin());
12123       if (EV.getNumIndices() > 1)
12124         // Extract the remaining indices out of the constant indexed by the
12125         // first index
12126         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12127       else
12128         return ReplaceInstUsesWith(EV, V);
12129     }
12130     return 0; // Can't handle other constants
12131   } 
12132   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12133     // We're extracting from an insertvalue instruction, compare the indices
12134     const unsigned *exti, *exte, *insi, *inse;
12135     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12136          exte = EV.idx_end(), inse = IV->idx_end();
12137          exti != exte && insi != inse;
12138          ++exti, ++insi) {
12139       if (*insi != *exti)
12140         // The insert and extract both reference distinctly different elements.
12141         // This means the extract is not influenced by the insert, and we can
12142         // replace the aggregate operand of the extract with the aggregate
12143         // operand of the insert. i.e., replace
12144         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12145         // %E = extractvalue { i32, { i32 } } %I, 0
12146         // with
12147         // %E = extractvalue { i32, { i32 } } %A, 0
12148         return ExtractValueInst::Create(IV->getAggregateOperand(),
12149                                         EV.idx_begin(), EV.idx_end());
12150     }
12151     if (exti == exte && insi == inse)
12152       // Both iterators are at the end: Index lists are identical. Replace
12153       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12154       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12155       // with "i32 42"
12156       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12157     if (exti == exte) {
12158       // The extract list is a prefix of the insert list. i.e. replace
12159       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12160       // %E = extractvalue { i32, { i32 } } %I, 1
12161       // with
12162       // %X = extractvalue { i32, { i32 } } %A, 1
12163       // %E = insertvalue { i32 } %X, i32 42, 0
12164       // by switching the order of the insert and extract (though the
12165       // insertvalue should be left in, since it may have other uses).
12166       Value *NewEV = InsertNewInstBefore(
12167         ExtractValueInst::Create(IV->getAggregateOperand(),
12168                                  EV.idx_begin(), EV.idx_end()),
12169         EV);
12170       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12171                                      insi, inse);
12172     }
12173     if (insi == inse)
12174       // The insert list is a prefix of the extract list
12175       // We can simply remove the common indices from the extract and make it
12176       // operate on the inserted value instead of the insertvalue result.
12177       // i.e., replace
12178       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12179       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12180       // with
12181       // %E extractvalue { i32 } { i32 42 }, 0
12182       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12183                                       exti, exte);
12184   }
12185   // Can't simplify extracts from other values. Note that nested extracts are
12186   // already simplified implicitely by the above (extract ( extract (insert) )
12187   // will be translated into extract ( insert ( extract ) ) first and then just
12188   // the value inserted, if appropriate).
12189   return 0;
12190 }
12191
12192 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12193 /// is to leave as a vector operation.
12194 static bool CheapToScalarize(Value *V, bool isConstant) {
12195   if (isa<ConstantAggregateZero>(V)) 
12196     return true;
12197   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12198     if (isConstant) return true;
12199     // If all elts are the same, we can extract.
12200     Constant *Op0 = C->getOperand(0);
12201     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12202       if (C->getOperand(i) != Op0)
12203         return false;
12204     return true;
12205   }
12206   Instruction *I = dyn_cast<Instruction>(V);
12207   if (!I) return false;
12208   
12209   // Insert element gets simplified to the inserted element or is deleted if
12210   // this is constant idx extract element and its a constant idx insertelt.
12211   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12212       isa<ConstantInt>(I->getOperand(2)))
12213     return true;
12214   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12215     return true;
12216   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12217     if (BO->hasOneUse() &&
12218         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12219          CheapToScalarize(BO->getOperand(1), isConstant)))
12220       return true;
12221   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12222     if (CI->hasOneUse() &&
12223         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12224          CheapToScalarize(CI->getOperand(1), isConstant)))
12225       return true;
12226   
12227   return false;
12228 }
12229
12230 /// Read and decode a shufflevector mask.
12231 ///
12232 /// It turns undef elements into values that are larger than the number of
12233 /// elements in the input.
12234 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12235   unsigned NElts = SVI->getType()->getNumElements();
12236   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12237     return std::vector<unsigned>(NElts, 0);
12238   if (isa<UndefValue>(SVI->getOperand(2)))
12239     return std::vector<unsigned>(NElts, 2*NElts);
12240
12241   std::vector<unsigned> Result;
12242   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12243   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12244     if (isa<UndefValue>(*i))
12245       Result.push_back(NElts*2);  // undef -> 8
12246     else
12247       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12248   return Result;
12249 }
12250
12251 /// FindScalarElement - Given a vector and an element number, see if the scalar
12252 /// value is already around as a register, for example if it were inserted then
12253 /// extracted from the vector.
12254 static Value *FindScalarElement(Value *V, unsigned EltNo,
12255                                 LLVMContext *Context) {
12256   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12257   const VectorType *PTy = cast<VectorType>(V->getType());
12258   unsigned Width = PTy->getNumElements();
12259   if (EltNo >= Width)  // Out of range access.
12260     return UndefValue::get(PTy->getElementType());
12261   
12262   if (isa<UndefValue>(V))
12263     return UndefValue::get(PTy->getElementType());
12264   else if (isa<ConstantAggregateZero>(V))
12265     return Constant::getNullValue(PTy->getElementType());
12266   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12267     return CP->getOperand(EltNo);
12268   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12269     // If this is an insert to a variable element, we don't know what it is.
12270     if (!isa<ConstantInt>(III->getOperand(2))) 
12271       return 0;
12272     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12273     
12274     // If this is an insert to the element we are looking for, return the
12275     // inserted value.
12276     if (EltNo == IIElt) 
12277       return III->getOperand(1);
12278     
12279     // Otherwise, the insertelement doesn't modify the value, recurse on its
12280     // vector input.
12281     return FindScalarElement(III->getOperand(0), EltNo, Context);
12282   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12283     unsigned LHSWidth =
12284       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12285     unsigned InEl = getShuffleMask(SVI)[EltNo];
12286     if (InEl < LHSWidth)
12287       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12288     else if (InEl < LHSWidth*2)
12289       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12290     else
12291       return UndefValue::get(PTy->getElementType());
12292   }
12293   
12294   // Otherwise, we don't know.
12295   return 0;
12296 }
12297
12298 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12299   // If vector val is undef, replace extract with scalar undef.
12300   if (isa<UndefValue>(EI.getOperand(0)))
12301     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12302
12303   // If vector val is constant 0, replace extract with scalar 0.
12304   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12305     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12306   
12307   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12308     // If vector val is constant with all elements the same, replace EI with
12309     // that element. When the elements are not identical, we cannot replace yet
12310     // (we do that below, but only when the index is constant).
12311     Constant *op0 = C->getOperand(0);
12312     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12313       if (C->getOperand(i) != op0) {
12314         op0 = 0; 
12315         break;
12316       }
12317     if (op0)
12318       return ReplaceInstUsesWith(EI, op0);
12319   }
12320   
12321   // If extracting a specified index from the vector, see if we can recursively
12322   // find a previously computed scalar that was inserted into the vector.
12323   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12324     unsigned IndexVal = IdxC->getZExtValue();
12325     unsigned VectorWidth = 
12326       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12327       
12328     // If this is extracting an invalid index, turn this into undef, to avoid
12329     // crashing the code below.
12330     if (IndexVal >= VectorWidth)
12331       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12332     
12333     // This instruction only demands the single element from the input vector.
12334     // If the input vector has a single use, simplify it based on this use
12335     // property.
12336     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12337       APInt UndefElts(VectorWidth, 0);
12338       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12339       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12340                                                 DemandedMask, UndefElts)) {
12341         EI.setOperand(0, V);
12342         return &EI;
12343       }
12344     }
12345     
12346     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12347       return ReplaceInstUsesWith(EI, Elt);
12348     
12349     // If the this extractelement is directly using a bitcast from a vector of
12350     // the same number of elements, see if we can find the source element from
12351     // it.  In this case, we will end up needing to bitcast the scalars.
12352     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12353       if (const VectorType *VT = 
12354               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12355         if (VT->getNumElements() == VectorWidth)
12356           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12357                                              IndexVal, Context))
12358             return new BitCastInst(Elt, EI.getType());
12359     }
12360   }
12361   
12362   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12363     if (I->hasOneUse()) {
12364       // Push extractelement into predecessor operation if legal and
12365       // profitable to do so
12366       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12367         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12368         if (CheapToScalarize(BO, isConstantElt)) {
12369           ExtractElementInst *newEI0 = 
12370             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12371                                    EI.getName()+".lhs");
12372           ExtractElementInst *newEI1 =
12373             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12374                                    EI.getName()+".rhs");
12375           InsertNewInstBefore(newEI0, EI);
12376           InsertNewInstBefore(newEI1, EI);
12377           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12378         }
12379       } else if (isa<LoadInst>(I)) {
12380         unsigned AS = 
12381           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12382         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12383                                   PointerType::get(EI.getType(), AS),*I);
12384         GetElementPtrInst *GEP =
12385           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12386         cast<GEPOperator>(GEP)->setIsInBounds(true);
12387         InsertNewInstBefore(GEP, *I);
12388         LoadInst* Load = new LoadInst(GEP, "tmp");
12389         InsertNewInstBefore(Load, *I);
12390         return ReplaceInstUsesWith(EI, Load);
12391       }
12392     }
12393     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12394       // Extracting the inserted element?
12395       if (IE->getOperand(2) == EI.getOperand(1))
12396         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12397       // If the inserted and extracted elements are constants, they must not
12398       // be the same value, extract from the pre-inserted value instead.
12399       if (isa<Constant>(IE->getOperand(2)) &&
12400           isa<Constant>(EI.getOperand(1))) {
12401         Worklist.AddValue(EI.getOperand(0));
12402         EI.setOperand(0, IE->getOperand(0));
12403         return &EI;
12404       }
12405     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12406       // If this is extracting an element from a shufflevector, figure out where
12407       // it came from and extract from the appropriate input element instead.
12408       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12409         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12410         Value *Src;
12411         unsigned LHSWidth =
12412           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12413
12414         if (SrcIdx < LHSWidth)
12415           Src = SVI->getOperand(0);
12416         else if (SrcIdx < LHSWidth*2) {
12417           SrcIdx -= LHSWidth;
12418           Src = SVI->getOperand(1);
12419         } else {
12420           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12421         }
12422         return ExtractElementInst::Create(Src,
12423                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
12424       }
12425     }
12426     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12427   }
12428   return 0;
12429 }
12430
12431 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12432 /// elements from either LHS or RHS, return the shuffle mask and true. 
12433 /// Otherwise, return false.
12434 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12435                                          std::vector<Constant*> &Mask,
12436                                          LLVMContext *Context) {
12437   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12438          "Invalid CollectSingleShuffleElements");
12439   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12440
12441   if (isa<UndefValue>(V)) {
12442     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12443     return true;
12444   } else if (V == LHS) {
12445     for (unsigned i = 0; i != NumElts; ++i)
12446       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12447     return true;
12448   } else if (V == RHS) {
12449     for (unsigned i = 0; i != NumElts; ++i)
12450       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12451     return true;
12452   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12453     // If this is an insert of an extract from some other vector, include it.
12454     Value *VecOp    = IEI->getOperand(0);
12455     Value *ScalarOp = IEI->getOperand(1);
12456     Value *IdxOp    = IEI->getOperand(2);
12457     
12458     if (!isa<ConstantInt>(IdxOp))
12459       return false;
12460     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12461     
12462     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12463       // Okay, we can handle this if the vector we are insertinting into is
12464       // transitively ok.
12465       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12466         // If so, update the mask to reflect the inserted undef.
12467         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12468         return true;
12469       }      
12470     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12471       if (isa<ConstantInt>(EI->getOperand(1)) &&
12472           EI->getOperand(0)->getType() == V->getType()) {
12473         unsigned ExtractedIdx =
12474           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12475         
12476         // This must be extracting from either LHS or RHS.
12477         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12478           // Okay, we can handle this if the vector we are insertinting into is
12479           // transitively ok.
12480           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12481             // If so, update the mask to reflect the inserted value.
12482             if (EI->getOperand(0) == LHS) {
12483               Mask[InsertedIdx % NumElts] = 
12484                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12485             } else {
12486               assert(EI->getOperand(0) == RHS);
12487               Mask[InsertedIdx % NumElts] = 
12488                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12489               
12490             }
12491             return true;
12492           }
12493         }
12494       }
12495     }
12496   }
12497   // TODO: Handle shufflevector here!
12498   
12499   return false;
12500 }
12501
12502 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12503 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12504 /// that computes V and the LHS value of the shuffle.
12505 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12506                                      Value *&RHS, LLVMContext *Context) {
12507   assert(isa<VectorType>(V->getType()) && 
12508          (RHS == 0 || V->getType() == RHS->getType()) &&
12509          "Invalid shuffle!");
12510   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12511
12512   if (isa<UndefValue>(V)) {
12513     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12514     return V;
12515   } else if (isa<ConstantAggregateZero>(V)) {
12516     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12517     return V;
12518   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12519     // If this is an insert of an extract from some other vector, include it.
12520     Value *VecOp    = IEI->getOperand(0);
12521     Value *ScalarOp = IEI->getOperand(1);
12522     Value *IdxOp    = IEI->getOperand(2);
12523     
12524     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12525       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12526           EI->getOperand(0)->getType() == V->getType()) {
12527         unsigned ExtractedIdx =
12528           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12529         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12530         
12531         // Either the extracted from or inserted into vector must be RHSVec,
12532         // otherwise we'd end up with a shuffle of three inputs.
12533         if (EI->getOperand(0) == RHS || RHS == 0) {
12534           RHS = EI->getOperand(0);
12535           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12536           Mask[InsertedIdx % NumElts] = 
12537             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12538           return V;
12539         }
12540         
12541         if (VecOp == RHS) {
12542           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12543                                             RHS, Context);
12544           // Everything but the extracted element is replaced with the RHS.
12545           for (unsigned i = 0; i != NumElts; ++i) {
12546             if (i != InsertedIdx)
12547               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12548           }
12549           return V;
12550         }
12551         
12552         // If this insertelement is a chain that comes from exactly these two
12553         // vectors, return the vector and the effective shuffle.
12554         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12555                                          Context))
12556           return EI->getOperand(0);
12557         
12558       }
12559     }
12560   }
12561   // TODO: Handle shufflevector here!
12562   
12563   // Otherwise, can't do anything fancy.  Return an identity vector.
12564   for (unsigned i = 0; i != NumElts; ++i)
12565     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12566   return V;
12567 }
12568
12569 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12570   Value *VecOp    = IE.getOperand(0);
12571   Value *ScalarOp = IE.getOperand(1);
12572   Value *IdxOp    = IE.getOperand(2);
12573   
12574   // Inserting an undef or into an undefined place, remove this.
12575   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12576     ReplaceInstUsesWith(IE, VecOp);
12577   
12578   // If the inserted element was extracted from some other vector, and if the 
12579   // indexes are constant, try to turn this into a shufflevector operation.
12580   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12581     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12582         EI->getOperand(0)->getType() == IE.getType()) {
12583       unsigned NumVectorElts = IE.getType()->getNumElements();
12584       unsigned ExtractedIdx =
12585         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12586       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12587       
12588       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12589         return ReplaceInstUsesWith(IE, VecOp);
12590       
12591       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12592         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12593       
12594       // If we are extracting a value from a vector, then inserting it right
12595       // back into the same place, just use the input vector.
12596       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12597         return ReplaceInstUsesWith(IE, VecOp);      
12598       
12599       // We could theoretically do this for ANY input.  However, doing so could
12600       // turn chains of insertelement instructions into a chain of shufflevector
12601       // instructions, and right now we do not merge shufflevectors.  As such,
12602       // only do this in a situation where it is clear that there is benefit.
12603       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12604         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12605         // the values of VecOp, except then one read from EIOp0.
12606         // Build a new shuffle mask.
12607         std::vector<Constant*> Mask;
12608         if (isa<UndefValue>(VecOp))
12609           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12610         else {
12611           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12612           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12613                                                        NumVectorElts));
12614         } 
12615         Mask[InsertedIdx] = 
12616                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12617         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12618                                      ConstantVector::get(Mask));
12619       }
12620       
12621       // If this insertelement isn't used by some other insertelement, turn it
12622       // (and any insertelements it points to), into one big shuffle.
12623       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12624         std::vector<Constant*> Mask;
12625         Value *RHS = 0;
12626         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12627         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12628         // We now have a shuffle of LHS, RHS, Mask.
12629         return new ShuffleVectorInst(LHS, RHS,
12630                                      ConstantVector::get(Mask));
12631       }
12632     }
12633   }
12634
12635   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12636   APInt UndefElts(VWidth, 0);
12637   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12638   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12639     return &IE;
12640
12641   return 0;
12642 }
12643
12644
12645 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12646   Value *LHS = SVI.getOperand(0);
12647   Value *RHS = SVI.getOperand(1);
12648   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12649
12650   bool MadeChange = false;
12651
12652   // Undefined shuffle mask -> undefined value.
12653   if (isa<UndefValue>(SVI.getOperand(2)))
12654     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12655
12656   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12657
12658   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12659     return 0;
12660
12661   APInt UndefElts(VWidth, 0);
12662   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12663   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12664     LHS = SVI.getOperand(0);
12665     RHS = SVI.getOperand(1);
12666     MadeChange = true;
12667   }
12668   
12669   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12670   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12671   if (LHS == RHS || isa<UndefValue>(LHS)) {
12672     if (isa<UndefValue>(LHS) && LHS == RHS) {
12673       // shuffle(undef,undef,mask) -> undef.
12674       return ReplaceInstUsesWith(SVI, LHS);
12675     }
12676     
12677     // Remap any references to RHS to use LHS.
12678     std::vector<Constant*> Elts;
12679     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12680       if (Mask[i] >= 2*e)
12681         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12682       else {
12683         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12684             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12685           Mask[i] = 2*e;     // Turn into undef.
12686           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12687         } else {
12688           Mask[i] = Mask[i] % e;  // Force to LHS.
12689           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12690         }
12691       }
12692     }
12693     SVI.setOperand(0, SVI.getOperand(1));
12694     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12695     SVI.setOperand(2, ConstantVector::get(Elts));
12696     LHS = SVI.getOperand(0);
12697     RHS = SVI.getOperand(1);
12698     MadeChange = true;
12699   }
12700   
12701   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12702   bool isLHSID = true, isRHSID = true;
12703     
12704   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12705     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12706     // Is this an identity shuffle of the LHS value?
12707     isLHSID &= (Mask[i] == i);
12708       
12709     // Is this an identity shuffle of the RHS value?
12710     isRHSID &= (Mask[i]-e == i);
12711   }
12712
12713   // Eliminate identity shuffles.
12714   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12715   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12716   
12717   // If the LHS is a shufflevector itself, see if we can combine it with this
12718   // one without producing an unusual shuffle.  Here we are really conservative:
12719   // we are absolutely afraid of producing a shuffle mask not in the input
12720   // program, because the code gen may not be smart enough to turn a merged
12721   // shuffle into two specific shuffles: it may produce worse code.  As such,
12722   // we only merge two shuffles if the result is one of the two input shuffle
12723   // masks.  In this case, merging the shuffles just removes one instruction,
12724   // which we know is safe.  This is good for things like turning:
12725   // (splat(splat)) -> splat.
12726   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12727     if (isa<UndefValue>(RHS)) {
12728       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12729
12730       std::vector<unsigned> NewMask;
12731       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12732         if (Mask[i] >= 2*e)
12733           NewMask.push_back(2*e);
12734         else
12735           NewMask.push_back(LHSMask[Mask[i]]);
12736       
12737       // If the result mask is equal to the src shuffle or this shuffle mask, do
12738       // the replacement.
12739       if (NewMask == LHSMask || NewMask == Mask) {
12740         unsigned LHSInNElts =
12741           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12742         std::vector<Constant*> Elts;
12743         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12744           if (NewMask[i] >= LHSInNElts*2) {
12745             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12746           } else {
12747             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12748           }
12749         }
12750         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12751                                      LHSSVI->getOperand(1),
12752                                      ConstantVector::get(Elts));
12753       }
12754     }
12755   }
12756
12757   return MadeChange ? &SVI : 0;
12758 }
12759
12760
12761
12762
12763 /// TryToSinkInstruction - Try to move the specified instruction from its
12764 /// current block into the beginning of DestBlock, which can only happen if it's
12765 /// safe to move the instruction past all of the instructions between it and the
12766 /// end of its block.
12767 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12768   assert(I->hasOneUse() && "Invariants didn't hold!");
12769
12770   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12771   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12772     return false;
12773
12774   // Do not sink alloca instructions out of the entry block.
12775   if (isa<AllocaInst>(I) && I->getParent() ==
12776         &DestBlock->getParent()->getEntryBlock())
12777     return false;
12778
12779   // We can only sink load instructions if there is nothing between the load and
12780   // the end of block that could change the value.
12781   if (I->mayReadFromMemory()) {
12782     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12783          Scan != E; ++Scan)
12784       if (Scan->mayWriteToMemory())
12785         return false;
12786   }
12787
12788   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12789
12790   CopyPrecedingStopPoint(I, InsertPos);
12791   I->moveBefore(InsertPos);
12792   ++NumSunkInst;
12793   return true;
12794 }
12795
12796
12797 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12798 /// all reachable code to the worklist.
12799 ///
12800 /// This has a couple of tricks to make the code faster and more powerful.  In
12801 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12802 /// them to the worklist (this significantly speeds up instcombine on code where
12803 /// many instructions are dead or constant).  Additionally, if we find a branch
12804 /// whose condition is a known constant, we only visit the reachable successors.
12805 ///
12806 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12807                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12808                                        InstCombiner &IC,
12809                                        const TargetData *TD) {
12810   SmallVector<BasicBlock*, 256> Worklist;
12811   Worklist.push_back(BB);
12812
12813   while (!Worklist.empty()) {
12814     BB = Worklist.back();
12815     Worklist.pop_back();
12816     
12817     // We have now visited this block!  If we've already been here, ignore it.
12818     if (!Visited.insert(BB)) continue;
12819
12820     DbgInfoIntrinsic *DBI_Prev = NULL;
12821     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12822       Instruction *Inst = BBI++;
12823       
12824       // DCE instruction if trivially dead.
12825       if (isInstructionTriviallyDead(Inst)) {
12826         ++NumDeadInst;
12827         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12828         Inst->eraseFromParent();
12829         continue;
12830       }
12831       
12832       // ConstantProp instruction if trivially constant.
12833       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12834         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12835                      << *Inst << '\n');
12836         Inst->replaceAllUsesWith(C);
12837         ++NumConstProp;
12838         Inst->eraseFromParent();
12839         continue;
12840       }
12841      
12842       // If there are two consecutive llvm.dbg.stoppoint calls then
12843       // it is likely that the optimizer deleted code in between these
12844       // two intrinsics. 
12845       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12846       if (DBI_Next) {
12847         if (DBI_Prev
12848             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12849             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12850           IC.Worklist.Remove(DBI_Prev);
12851           DBI_Prev->eraseFromParent();
12852         }
12853         DBI_Prev = DBI_Next;
12854       } else {
12855         DBI_Prev = 0;
12856       }
12857
12858       IC.Worklist.Add(Inst);
12859     }
12860
12861     // Recursively visit successors.  If this is a branch or switch on a
12862     // constant, only visit the reachable successor.
12863     TerminatorInst *TI = BB->getTerminator();
12864     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12865       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12866         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12867         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12868         Worklist.push_back(ReachableBB);
12869         continue;
12870       }
12871     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12872       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12873         // See if this is an explicit destination.
12874         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12875           if (SI->getCaseValue(i) == Cond) {
12876             BasicBlock *ReachableBB = SI->getSuccessor(i);
12877             Worklist.push_back(ReachableBB);
12878             continue;
12879           }
12880         
12881         // Otherwise it is the default destination.
12882         Worklist.push_back(SI->getSuccessor(0));
12883         continue;
12884       }
12885     }
12886     
12887     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12888       Worklist.push_back(TI->getSuccessor(i));
12889   }
12890 }
12891
12892 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12893   bool Changed = false;
12894   TD = getAnalysisIfAvailable<TargetData>();
12895   
12896   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12897         << F.getNameStr() << "\n");
12898
12899   {
12900     // Do a depth-first traversal of the function, populate the worklist with
12901     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12902     // track of which blocks we visit.
12903     SmallPtrSet<BasicBlock*, 64> Visited;
12904     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12905
12906     // Do a quick scan over the function.  If we find any blocks that are
12907     // unreachable, remove any instructions inside of them.  This prevents
12908     // the instcombine code from having to deal with some bad special cases.
12909     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12910       if (!Visited.count(BB)) {
12911         Instruction *Term = BB->getTerminator();
12912         while (Term != BB->begin()) {   // Remove instrs bottom-up
12913           BasicBlock::iterator I = Term; --I;
12914
12915           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12916           // A debug intrinsic shouldn't force another iteration if we weren't
12917           // going to do one without it.
12918           if (!isa<DbgInfoIntrinsic>(I)) {
12919             ++NumDeadInst;
12920             Changed = true;
12921           }
12922           if (!I->use_empty())
12923             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12924           I->eraseFromParent();
12925         }
12926       }
12927   }
12928
12929   while (!Worklist.isEmpty()) {
12930     Instruction *I = Worklist.RemoveOne();
12931     if (I == 0) continue;  // skip null values.
12932
12933     // Check to see if we can DCE the instruction.
12934     if (isInstructionTriviallyDead(I)) {
12935       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12936       EraseInstFromFunction(*I);
12937       ++NumDeadInst;
12938       Changed = true;
12939       continue;
12940     }
12941
12942     // Instruction isn't dead, see if we can constant propagate it.
12943     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12944       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12945
12946       // Add operands to the worklist.
12947       ReplaceInstUsesWith(*I, C);
12948       ++NumConstProp;
12949       EraseInstFromFunction(*I);
12950       Changed = true;
12951       continue;
12952     }
12953
12954     if (TD) {
12955       // See if we can constant fold its operands.
12956       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12957         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12958           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
12959                                   F.getContext(), TD))
12960             if (NewC != CE) {
12961               i->set(NewC);
12962               Changed = true;
12963             }
12964     }
12965
12966     // See if we can trivially sink this instruction to a successor basic block.
12967     if (I->hasOneUse()) {
12968       BasicBlock *BB = I->getParent();
12969       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12970       if (UserParent != BB) {
12971         bool UserIsSuccessor = false;
12972         // See if the user is one of our successors.
12973         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12974           if (*SI == UserParent) {
12975             UserIsSuccessor = true;
12976             break;
12977           }
12978
12979         // If the user is one of our immediate successors, and if that successor
12980         // only has us as a predecessors (we'd have to split the critical edge
12981         // otherwise), we can keep going.
12982         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12983             next(pred_begin(UserParent)) == pred_end(UserParent))
12984           // Okay, the CFG is simple enough, try to sink this instruction.
12985           Changed |= TryToSinkInstruction(I, UserParent);
12986       }
12987     }
12988
12989     // Now that we have an instruction, try combining it to simplify it...
12990 #ifndef NDEBUG
12991     std::string OrigI;
12992 #endif
12993     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12994     if (Instruction *Result = visit(*I)) {
12995       ++NumCombined;
12996       // Should we replace the old instruction with a new one?
12997       if (Result != I) {
12998         DEBUG(errs() << "IC: Old = " << *I << '\n'
12999                      << "    New = " << *Result << '\n');
13000
13001         // Everything uses the new instruction now.
13002         I->replaceAllUsesWith(Result);
13003
13004         // Push the new instruction and any users onto the worklist.
13005         Worklist.Add(Result);
13006         Worklist.AddUsersToWorkList(*Result);
13007
13008         // Move the name to the new instruction first.
13009         Result->takeName(I);
13010
13011         // Insert the new instruction into the basic block...
13012         BasicBlock *InstParent = I->getParent();
13013         BasicBlock::iterator InsertPos = I;
13014
13015         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13016           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13017             ++InsertPos;
13018
13019         InstParent->getInstList().insert(InsertPos, Result);
13020
13021         EraseInstFromFunction(*I);
13022       } else {
13023 #ifndef NDEBUG
13024         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13025                      << "    New = " << *I << '\n');
13026 #endif
13027
13028         // If the instruction was modified, it's possible that it is now dead.
13029         // if so, remove it.
13030         if (isInstructionTriviallyDead(I)) {
13031           EraseInstFromFunction(*I);
13032         } else {
13033           Worklist.Add(I);
13034           Worklist.AddUsersToWorkList(*I);
13035         }
13036       }
13037       Changed = true;
13038     }
13039   }
13040
13041   Worklist.Zap();
13042   return Changed;
13043 }
13044
13045
13046 bool InstCombiner::runOnFunction(Function &F) {
13047   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13048   Context = &F.getContext();
13049   
13050   bool EverMadeChange = false;
13051
13052   // Iterate while there is work to do.
13053   unsigned Iteration = 0;
13054   while (DoOneIteration(F, Iteration++))
13055     EverMadeChange = true;
13056   return EverMadeChange;
13057 }
13058
13059 FunctionPass *llvm::createInstructionCombiningPass() {
13060   return new InstCombiner();
13061 }