fix a bug I introduced in r80478 found by the build bot.
[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 Remove(Instruction *I) {
98       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99       if (It == WorklistMap.end()) return; // Not in worklist.
100       
101       // Don't bother moving everything down, just null out the slot.
102       Worklist[It->second] = 0;
103       
104       WorklistMap.erase(It);
105     }
106     
107     Instruction *RemoveOne() {
108       Instruction *I = Worklist.back();
109       Worklist.pop_back();
110       WorklistMap.erase(I);
111       return I;
112     }
113
114     
115     /// Zap - check that the worklist is empty and nuke the backing store for
116     /// the map if it is large.
117     void Zap() {
118       assert(WorklistMap.empty() && "Worklist empty, but map not?");
119       
120       // Do an explicit clear, this shrinks the map if needed.
121       WorklistMap.clear();
122     }
123   };
124 } // end anonymous namespace.
125
126
127 namespace {
128   class VISIBILITY_HIDDEN InstCombiner
129     : public FunctionPass,
130       public InstVisitor<InstCombiner, Instruction*> {
131     // Worklist of all of the instructions that need to be simplified.
132     InstCombineWorklist Worklist;
133     TargetData *TD;
134     bool MustPreserveLCSSA;
135   public:
136     static char ID; // Pass identification, replacement for typeid
137     InstCombiner() : FunctionPass(&ID) {}
138
139     LLVMContext *Context;
140     LLVMContext *getContext() const { return Context; }
141
142     /// AddToWorkList - Add the specified instruction to the worklist if it
143     /// isn't already in it.
144     void AddToWorkList(Instruction *I) {
145       Worklist.Add(I);
146     }
147     
148     // RemoveFromWorkList - remove I from the worklist if it exists.
149     void RemoveFromWorkList(Instruction *I) {
150       Worklist.Remove(I);
151     }
152     
153     /// AddUsersToWorkList - When an instruction is simplified, add all users of
154     /// the instruction to the work lists because they might get more simplified
155     /// now.
156     ///
157     void AddUsersToWorkList(Value &I) {
158       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
159            UI != UE; ++UI)
160         AddToWorkList(cast<Instruction>(*UI));
161     }
162
163     /// AddUsesToWorkList - When an instruction is simplified, add operands to
164     /// the work lists because they might get more simplified now.
165     ///
166     void AddUsesToWorkList(Instruction &I) {
167       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
168         if (Instruction *Op = dyn_cast<Instruction>(*i))
169           AddToWorkList(Op);
170     }
171     
172     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
173     /// dead.  Add all of its operands to the worklist, turning them into
174     /// undef's to reduce the number of uses of those instructions.
175     ///
176     /// Return the specified operand before it is turned into an undef.
177     ///
178     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
179       Value *R = I.getOperand(op);
180       
181       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
182         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
183           AddToWorkList(Op);
184           // Set the operand to undef to drop the use.
185           *i = UndefValue::get(Op->getType());
186         }
187       
188       return R;
189     }
190
191   public:
192     virtual bool runOnFunction(Function &F);
193     
194     bool DoOneIteration(Function &F, unsigned ItNum);
195
196     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
197       AU.addPreservedID(LCSSAID);
198       AU.setPreservesCFG();
199     }
200
201     TargetData *getTargetData() const { return TD; }
202
203     // Visitation implementation - Implement instruction combining for different
204     // instruction types.  The semantics are as follows:
205     // Return Value:
206     //    null        - No change was made
207     //     I          - Change was made, I is still valid, I may be dead though
208     //   otherwise    - Change was made, replace I with returned instruction
209     //
210     Instruction *visitAdd(BinaryOperator &I);
211     Instruction *visitFAdd(BinaryOperator &I);
212     Instruction *visitSub(BinaryOperator &I);
213     Instruction *visitFSub(BinaryOperator &I);
214     Instruction *visitMul(BinaryOperator &I);
215     Instruction *visitFMul(BinaryOperator &I);
216     Instruction *visitURem(BinaryOperator &I);
217     Instruction *visitSRem(BinaryOperator &I);
218     Instruction *visitFRem(BinaryOperator &I);
219     bool SimplifyDivRemOfSelect(BinaryOperator &I);
220     Instruction *commonRemTransforms(BinaryOperator &I);
221     Instruction *commonIRemTransforms(BinaryOperator &I);
222     Instruction *commonDivTransforms(BinaryOperator &I);
223     Instruction *commonIDivTransforms(BinaryOperator &I);
224     Instruction *visitUDiv(BinaryOperator &I);
225     Instruction *visitSDiv(BinaryOperator &I);
226     Instruction *visitFDiv(BinaryOperator &I);
227     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
228     Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
229     Instruction *visitAnd(BinaryOperator &I);
230     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
231     Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
232     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
233                                      Value *A, Value *B, Value *C);
234     Instruction *visitOr (BinaryOperator &I);
235     Instruction *visitXor(BinaryOperator &I);
236     Instruction *visitShl(BinaryOperator &I);
237     Instruction *visitAShr(BinaryOperator &I);
238     Instruction *visitLShr(BinaryOperator &I);
239     Instruction *commonShiftTransforms(BinaryOperator &I);
240     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
241                                       Constant *RHSC);
242     Instruction *visitFCmpInst(FCmpInst &I);
243     Instruction *visitICmpInst(ICmpInst &I);
244     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
245     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
246                                                 Instruction *LHS,
247                                                 ConstantInt *RHS);
248     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
249                                 ConstantInt *DivRHS);
250
251     Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
252                              ICmpInst::Predicate Cond, Instruction &I);
253     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
254                                      BinaryOperator &I);
255     Instruction *commonCastTransforms(CastInst &CI);
256     Instruction *commonIntCastTransforms(CastInst &CI);
257     Instruction *commonPointerCastTransforms(CastInst &CI);
258     Instruction *visitTrunc(TruncInst &CI);
259     Instruction *visitZExt(ZExtInst &CI);
260     Instruction *visitSExt(SExtInst &CI);
261     Instruction *visitFPTrunc(FPTruncInst &CI);
262     Instruction *visitFPExt(CastInst &CI);
263     Instruction *visitFPToUI(FPToUIInst &FI);
264     Instruction *visitFPToSI(FPToSIInst &FI);
265     Instruction *visitUIToFP(CastInst &CI);
266     Instruction *visitSIToFP(CastInst &CI);
267     Instruction *visitPtrToInt(PtrToIntInst &CI);
268     Instruction *visitIntToPtr(IntToPtrInst &CI);
269     Instruction *visitBitCast(BitCastInst &CI);
270     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
271                                 Instruction *FI);
272     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
273     Instruction *visitSelectInst(SelectInst &SI);
274     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
275     Instruction *visitCallInst(CallInst &CI);
276     Instruction *visitInvokeInst(InvokeInst &II);
277     Instruction *visitPHINode(PHINode &PN);
278     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
279     Instruction *visitAllocationInst(AllocationInst &AI);
280     Instruction *visitFreeInst(FreeInst &FI);
281     Instruction *visitLoadInst(LoadInst &LI);
282     Instruction *visitStoreInst(StoreInst &SI);
283     Instruction *visitBranchInst(BranchInst &BI);
284     Instruction *visitSwitchInst(SwitchInst &SI);
285     Instruction *visitInsertElementInst(InsertElementInst &IE);
286     Instruction *visitExtractElementInst(ExtractElementInst &EI);
287     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
288     Instruction *visitExtractValueInst(ExtractValueInst &EV);
289
290     // visitInstruction - Specify what to return for unhandled instructions...
291     Instruction *visitInstruction(Instruction &I) { return 0; }
292
293   private:
294     Instruction *visitCallSite(CallSite CS);
295     bool transformConstExprCastCall(CallSite CS);
296     Instruction *transformCallThroughTrampoline(CallSite CS);
297     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
298                                    bool DoXform = true);
299     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
300     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
301
302
303   public:
304     // InsertNewInstBefore - insert an instruction New before instruction Old
305     // in the program.  Add the new instruction to the worklist.
306     //
307     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
308       assert(New && New->getParent() == 0 &&
309              "New instruction already inserted into a basic block!");
310       BasicBlock *BB = Old.getParent();
311       BB->getInstList().insert(&Old, New);  // Insert inst
312       AddToWorkList(New);
313       return New;
314     }
315
316     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
317     /// This also adds the cast to the worklist.  Finally, this returns the
318     /// cast.
319     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
320                             Instruction &Pos) {
321       if (V->getType() == Ty) return V;
322
323       if (Constant *CV = dyn_cast<Constant>(V))
324         return ConstantExpr::getCast(opc, CV, Ty);
325       
326       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
327       AddToWorkList(C);
328       return C;
329     }
330         
331     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
332       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
333     }
334
335
336     // ReplaceInstUsesWith - This method is to be used when an instruction is
337     // found to be dead, replacable with another preexisting expression.  Here
338     // we add all uses of I to the worklist, replace all uses of I with the new
339     // value, then return I, so that the inst combiner will know that I was
340     // modified.
341     //
342     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
343       AddUsersToWorkList(I);         // Add all modified instrs to worklist
344       if (&I != V) {
345         I.replaceAllUsesWith(V);
346         return &I;
347       } else {
348         // If we are replacing the instruction with itself, this must be in a
349         // segment of unreachable code, so just clobber the instruction.
350         I.replaceAllUsesWith(UndefValue::get(I.getType()));
351         return &I;
352       }
353     }
354
355     // EraseInstFromFunction - When dealing with an instruction that has side
356     // effects or produces a void value, we can't rely on DCE to delete the
357     // instruction.  Instead, visit methods should return the value returned by
358     // this function.
359     Instruction *EraseInstFromFunction(Instruction &I) {
360       assert(I.use_empty() && "Cannot erase instruction that is used!");
361       AddUsesToWorkList(I);
362       RemoveFromWorkList(&I);
363       I.eraseFromParent();
364       return 0;  // Don't do anything with FI
365     }
366         
367     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
368                            APInt &KnownOne, unsigned Depth = 0) const {
369       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
370     }
371     
372     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
373                            unsigned Depth = 0) const {
374       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
375     }
376     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
377       return llvm::ComputeNumSignBits(Op, TD, Depth);
378     }
379
380   private:
381
382     /// SimplifyCommutative - This performs a few simplifications for 
383     /// commutative operators.
384     bool SimplifyCommutative(BinaryOperator &I);
385
386     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
387     /// most-complex to least-complex order.
388     bool SimplifyCompare(CmpInst &I);
389
390     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
391     /// based on the demanded bits.
392     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
393                                    APInt& KnownZero, APInt& KnownOne,
394                                    unsigned Depth);
395     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
396                               APInt& KnownZero, APInt& KnownOne,
397                               unsigned Depth=0);
398         
399     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
400     /// SimplifyDemandedBits knows about.  See if the instruction has any
401     /// properties that allow us to simplify its operands.
402     bool SimplifyDemandedInstructionBits(Instruction &Inst);
403         
404     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
405                                       APInt& UndefElts, unsigned Depth = 0);
406       
407     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
408     // PHI node as operand #0, see if we can fold the instruction into the PHI
409     // (which is only possible if all operands to the PHI are constants).
410     Instruction *FoldOpIntoPhi(Instruction &I);
411
412     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
413     // operator and they all are only used by the PHI, PHI together their
414     // inputs, and do the operation once, to the result of the PHI.
415     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
416     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
417     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
418
419     
420     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
421                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
422     
423     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
424                               bool isSub, Instruction &I);
425     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
426                                  bool isSigned, bool Inside, Instruction &IB);
427     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
428     Instruction *MatchBSwap(BinaryOperator &I);
429     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
430     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
431     Instruction *SimplifyMemSet(MemSetInst *MI);
432
433
434     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
435
436     bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
437                                     unsigned CastOpc, int &NumCastsRemoved);
438     unsigned GetOrEnforceKnownAlignment(Value *V,
439                                         unsigned PrefAlign = 0);
440
441   };
442 } // end anonymous namespace
443
444 char InstCombiner::ID = 0;
445 static RegisterPass<InstCombiner>
446 X("instcombine", "Combine redundant instructions");
447
448 // getComplexity:  Assign a complexity or rank value to LLVM Values...
449 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
450 static unsigned getComplexity(Value *V) {
451   if (isa<Instruction>(V)) {
452     if (BinaryOperator::isNeg(V) ||
453         BinaryOperator::isFNeg(V) ||
454         BinaryOperator::isNot(V))
455       return 3;
456     return 4;
457   }
458   if (isa<Argument>(V)) return 3;
459   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
460 }
461
462 // isOnlyUse - Return true if this instruction will be deleted if we stop using
463 // it.
464 static bool isOnlyUse(Value *V) {
465   return V->hasOneUse() || isa<Constant>(V);
466 }
467
468 // getPromotedType - Return the specified type promoted as it would be to pass
469 // though a va_arg area...
470 static const Type *getPromotedType(const Type *Ty) {
471   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
472     if (ITy->getBitWidth() < 32)
473       return Type::getInt32Ty(Ty->getContext());
474   }
475   return Ty;
476 }
477
478 /// getBitCastOperand - If the specified operand is a CastInst, a constant
479 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
480 /// operand value, otherwise return null.
481 static Value *getBitCastOperand(Value *V) {
482   if (Operator *O = dyn_cast<Operator>(V)) {
483     if (O->getOpcode() == Instruction::BitCast)
484       return O->getOperand(0);
485     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
486       if (GEP->hasAllZeroIndices())
487         return GEP->getPointerOperand();
488   }
489   return 0;
490 }
491
492 /// This function is a wrapper around CastInst::isEliminableCastPair. It
493 /// simply extracts arguments and returns what that function returns.
494 static Instruction::CastOps 
495 isEliminableCastPair(
496   const CastInst *CI, ///< The first cast instruction
497   unsigned opcode,       ///< The opcode of the second cast instruction
498   const Type *DstTy,     ///< The target type for the second cast instruction
499   TargetData *TD         ///< The target data for pointer size
500 ) {
501
502   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
503   const Type *MidTy = CI->getType();                  // B from above
504
505   // Get the opcodes of the two Cast instructions
506   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
507   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
508
509   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
510                                                 DstTy,
511                                   TD ? TD->getIntPtrType(CI->getContext()) : 0);
512   
513   // We don't want to form an inttoptr or ptrtoint that converts to an integer
514   // type that differs from the pointer size.
515   if ((Res == Instruction::IntToPtr &&
516           (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
517       (Res == Instruction::PtrToInt &&
518           (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
519     Res = 0;
520   
521   return Instruction::CastOps(Res);
522 }
523
524 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
525 /// in any code being generated.  It does not require codegen if V is simple
526 /// enough or if the cast can be folded into other casts.
527 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
528                               const Type *Ty, TargetData *TD) {
529   if (V->getType() == Ty || isa<Constant>(V)) return false;
530   
531   // If this is another cast that can be eliminated, it isn't codegen either.
532   if (const CastInst *CI = dyn_cast<CastInst>(V))
533     if (isEliminableCastPair(CI, opcode, Ty, TD))
534       return false;
535   return true;
536 }
537
538 // SimplifyCommutative - This performs a few simplifications for commutative
539 // operators:
540 //
541 //  1. Order operands such that they are listed from right (least complex) to
542 //     left (most complex).  This puts constants before unary operators before
543 //     binary operators.
544 //
545 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
546 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547 //
548 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
549   bool Changed = false;
550   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
551     Changed = !I.swapOperands();
552
553   if (!I.isAssociative()) return Changed;
554   Instruction::BinaryOps Opcode = I.getOpcode();
555   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
556     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
557       if (isa<Constant>(I.getOperand(1))) {
558         Constant *Folded = ConstantExpr::get(I.getOpcode(),
559                                              cast<Constant>(I.getOperand(1)),
560                                              cast<Constant>(Op->getOperand(1)));
561         I.setOperand(0, Op->getOperand(0));
562         I.setOperand(1, Folded);
563         return true;
564       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
565         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
566             isOnlyUse(Op) && isOnlyUse(Op1)) {
567           Constant *C1 = cast<Constant>(Op->getOperand(1));
568           Constant *C2 = cast<Constant>(Op1->getOperand(1));
569
570           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
571           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
572           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
573                                                     Op1->getOperand(0),
574                                                     Op1->getName(), &I);
575           AddToWorkList(New);
576           I.setOperand(0, New);
577           I.setOperand(1, Folded);
578           return true;
579         }
580     }
581   return Changed;
582 }
583
584 /// SimplifyCompare - For a CmpInst this function just orders the operands
585 /// so that theyare listed from right (least complex) to left (most complex).
586 /// This puts constants before unary operators before binary operators.
587 bool InstCombiner::SimplifyCompare(CmpInst &I) {
588   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
589     return false;
590   I.swapOperands();
591   // Compare instructions are not associative so there's nothing else we can do.
592   return true;
593 }
594
595 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
596 // if the LHS is a constant zero (which is the 'negate' form).
597 //
598 static inline Value *dyn_castNegVal(Value *V) {
599   if (BinaryOperator::isNeg(V))
600     return BinaryOperator::getNegArgument(V);
601
602   // Constants can be considered to be negated values if they can be folded.
603   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
604     return ConstantExpr::getNeg(C);
605
606   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
607     if (C->getType()->getElementType()->isInteger())
608       return ConstantExpr::getNeg(C);
609
610   return 0;
611 }
612
613 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
614 // instruction if the LHS is a constant negative zero (which is the 'negate'
615 // form).
616 //
617 static inline Value *dyn_castFNegVal(Value *V) {
618   if (BinaryOperator::isFNeg(V))
619     return BinaryOperator::getFNegArgument(V);
620
621   // Constants can be considered to be negated values if they can be folded.
622   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
623     return ConstantExpr::getFNeg(C);
624
625   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
626     if (C->getType()->getElementType()->isFloatingPoint())
627       return ConstantExpr::getFNeg(C);
628
629   return 0;
630 }
631
632 static inline Value *dyn_castNotVal(Value *V) {
633   if (BinaryOperator::isNot(V))
634     return BinaryOperator::getNotArgument(V);
635
636   // Constants can be considered to be not'ed values...
637   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
638     return ConstantInt::get(C->getType(), ~C->getValue());
639   return 0;
640 }
641
642 // dyn_castFoldableMul - If this value is a multiply that can be folded into
643 // other computations (because it has a constant operand), return the
644 // non-constant operand of the multiply, and set CST to point to the multiplier.
645 // Otherwise, return null.
646 //
647 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
648   if (V->hasOneUse() && V->getType()->isInteger())
649     if (Instruction *I = dyn_cast<Instruction>(V)) {
650       if (I->getOpcode() == Instruction::Mul)
651         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
652           return I->getOperand(0);
653       if (I->getOpcode() == Instruction::Shl)
654         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
655           // The multiplier is really 1 << CST.
656           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
657           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
658           CST = ConstantInt::get(V->getType()->getContext(),
659                                  APInt(BitWidth, 1).shl(CSTVal));
660           return I->getOperand(0);
661         }
662     }
663   return 0;
664 }
665
666 /// AddOne - Add one to a ConstantInt
667 static Constant *AddOne(Constant *C) {
668   return ConstantExpr::getAdd(C, 
669     ConstantInt::get(C->getType(), 1));
670 }
671 /// SubOne - Subtract one from a ConstantInt
672 static Constant *SubOne(ConstantInt *C) {
673   return ConstantExpr::getSub(C, 
674     ConstantInt::get(C->getType(), 1));
675 }
676 /// MultiplyOverflows - True if the multiply can not be expressed in an int
677 /// this size.
678 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
679   uint32_t W = C1->getBitWidth();
680   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
681   if (sign) {
682     LHSExt.sext(W * 2);
683     RHSExt.sext(W * 2);
684   } else {
685     LHSExt.zext(W * 2);
686     RHSExt.zext(W * 2);
687   }
688
689   APInt MulExt = LHSExt * RHSExt;
690
691   if (sign) {
692     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
693     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
694     return MulExt.slt(Min) || MulExt.sgt(Max);
695   } else 
696     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
697 }
698
699
700 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
701 /// specified instruction is a constant integer.  If so, check to see if there
702 /// are any bits set in the constant that are not demanded.  If so, shrink the
703 /// constant and return true.
704 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
705                                    APInt Demanded) {
706   assert(I && "No instruction?");
707   assert(OpNo < I->getNumOperands() && "Operand index too large");
708
709   // If the operand is not a constant integer, nothing to do.
710   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
711   if (!OpC) return false;
712
713   // If there are no bits set that aren't demanded, nothing to do.
714   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
715   if ((~Demanded & OpC->getValue()) == 0)
716     return false;
717
718   // This instruction is producing bits that are not demanded. Shrink the RHS.
719   Demanded &= OpC->getValue();
720   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
721   return true;
722 }
723
724 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
725 // set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
727 // min/max.
728 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
729                                                    const APInt& KnownOne,
730                                                    APInt& Min, APInt& Max) {
731   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732          KnownZero.getBitWidth() == Min.getBitWidth() &&
733          KnownZero.getBitWidth() == Max.getBitWidth() &&
734          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735   APInt UnknownBits = ~(KnownZero|KnownOne);
736
737   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
738   // bit if it is unknown.
739   Min = KnownOne;
740   Max = KnownOne|UnknownBits;
741   
742   if (UnknownBits.isNegative()) { // Sign bit is unknown
743     Min.set(Min.getBitWidth()-1);
744     Max.clear(Max.getBitWidth()-1);
745   }
746 }
747
748 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
749 // a set of known zero and one bits, compute the maximum and minimum values that
750 // could have the specified known zero and known one bits, returning them in
751 // min/max.
752 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
753                                                      const APInt &KnownOne,
754                                                      APInt &Min, APInt &Max) {
755   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
756          KnownZero.getBitWidth() == Min.getBitWidth() &&
757          KnownZero.getBitWidth() == Max.getBitWidth() &&
758          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
759   APInt UnknownBits = ~(KnownZero|KnownOne);
760   
761   // The minimum value is when the unknown bits are all zeros.
762   Min = KnownOne;
763   // The maximum value is when the unknown bits are all ones.
764   Max = KnownOne|UnknownBits;
765 }
766
767 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
768 /// SimplifyDemandedBits knows about.  See if the instruction has any
769 /// properties that allow us to simplify its operands.
770 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
771   unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
772   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
773   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
774   
775   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
776                                      KnownZero, KnownOne, 0);
777   if (V == 0) return false;
778   if (V == &Inst) return true;
779   ReplaceInstUsesWith(Inst, V);
780   return true;
781 }
782
783 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
784 /// specified instruction operand if possible, updating it in place.  It returns
785 /// true if it made any change and false otherwise.
786 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
787                                         APInt &KnownZero, APInt &KnownOne,
788                                         unsigned Depth) {
789   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
790                                           KnownZero, KnownOne, Depth);
791   if (NewVal == 0) return false;
792   U.set(NewVal);
793   return true;
794 }
795
796
797 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
798 /// value based on the demanded bits.  When this function is called, it is known
799 /// that only the bits set in DemandedMask of the result of V are ever used
800 /// downstream. Consequently, depending on the mask and V, it may be possible
801 /// to replace V with a constant or one of its operands. In such cases, this
802 /// function does the replacement and returns true. In all other cases, it
803 /// returns false after analyzing the expression and setting KnownOne and known
804 /// to be one in the expression.  KnownZero contains all the bits that are known
805 /// to be zero in the expression. These are provided to potentially allow the
806 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
807 /// the expression. KnownOne and KnownZero always follow the invariant that 
808 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
809 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
810 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
811 /// and KnownOne must all be the same.
812 ///
813 /// This returns null if it did not change anything and it permits no
814 /// simplification.  This returns V itself if it did some simplification of V's
815 /// operands based on the information about what bits are demanded. This returns
816 /// some other non-null value if it found out that V is equal to another value
817 /// in the context where the specified bits are demanded, but not for all users.
818 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
819                                              APInt &KnownZero, APInt &KnownOne,
820                                              unsigned Depth) {
821   assert(V != 0 && "Null pointer of Value???");
822   assert(Depth <= 6 && "Limit Search Depth");
823   uint32_t BitWidth = DemandedMask.getBitWidth();
824   const Type *VTy = V->getType();
825   assert((TD || !isa<PointerType>(VTy)) &&
826          "SimplifyDemandedBits needs to know bit widths!");
827   assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
828          (!VTy->isIntOrIntVector() ||
829           VTy->getScalarSizeInBits() == BitWidth) &&
830          KnownZero.getBitWidth() == BitWidth &&
831          KnownOne.getBitWidth() == BitWidth &&
832          "Value *V, DemandedMask, KnownZero and KnownOne "
833          "must have same BitWidth");
834   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
835     // We know all of the bits for a constant!
836     KnownOne = CI->getValue() & DemandedMask;
837     KnownZero = ~KnownOne & DemandedMask;
838     return 0;
839   }
840   if (isa<ConstantPointerNull>(V)) {
841     // We know all of the bits for a constant!
842     KnownOne.clear();
843     KnownZero = DemandedMask;
844     return 0;
845   }
846
847   KnownZero.clear();
848   KnownOne.clear();
849   if (DemandedMask == 0) {   // Not demanding any bits from V.
850     if (isa<UndefValue>(V))
851       return 0;
852     return UndefValue::get(VTy);
853   }
854   
855   if (Depth == 6)        // Limit search depth.
856     return 0;
857   
858   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
859   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
860
861   Instruction *I = dyn_cast<Instruction>(V);
862   if (!I) {
863     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
864     return 0;        // Only analyze instructions.
865   }
866
867   // If there are multiple uses of this value and we aren't at the root, then
868   // we can't do any simplifications of the operands, because DemandedMask
869   // only reflects the bits demanded by *one* of the users.
870   if (Depth != 0 && !I->hasOneUse()) {
871     // Despite the fact that we can't simplify this instruction in all User's
872     // context, we can at least compute the knownzero/knownone bits, and we can
873     // do simplifications that apply to *just* the one user if we know that
874     // this instruction has a simpler value in that context.
875     if (I->getOpcode() == Instruction::And) {
876       // If either the LHS or the RHS are Zero, the result is zero.
877       ComputeMaskedBits(I->getOperand(1), DemandedMask,
878                         RHSKnownZero, RHSKnownOne, Depth+1);
879       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
880                         LHSKnownZero, LHSKnownOne, Depth+1);
881       
882       // If all of the demanded bits are known 1 on one side, return the other.
883       // These bits cannot contribute to the result of the 'and' in this
884       // context.
885       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
886           (DemandedMask & ~LHSKnownZero))
887         return I->getOperand(0);
888       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
889           (DemandedMask & ~RHSKnownZero))
890         return I->getOperand(1);
891       
892       // If all of the demanded bits in the inputs are known zeros, return zero.
893       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
894         return Constant::getNullValue(VTy);
895       
896     } else if (I->getOpcode() == Instruction::Or) {
897       // We can simplify (X|Y) -> X or Y in the user's context if we know that
898       // only bits from X or Y are demanded.
899       
900       // If either the LHS or the RHS are One, the result is One.
901       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
902                         RHSKnownZero, RHSKnownOne, Depth+1);
903       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
904                         LHSKnownZero, LHSKnownOne, Depth+1);
905       
906       // If all of the demanded bits are known zero on one side, return the
907       // other.  These bits cannot contribute to the result of the 'or' in this
908       // context.
909       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
910           (DemandedMask & ~LHSKnownOne))
911         return I->getOperand(0);
912       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
913           (DemandedMask & ~RHSKnownOne))
914         return I->getOperand(1);
915       
916       // If all of the potentially set bits on one side are known to be set on
917       // the other side, just use the 'other' side.
918       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
919           (DemandedMask & (~RHSKnownZero)))
920         return I->getOperand(0);
921       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
922           (DemandedMask & (~LHSKnownZero)))
923         return I->getOperand(1);
924     }
925     
926     // Compute the KnownZero/KnownOne bits to simplify things downstream.
927     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
928     return 0;
929   }
930   
931   // If this is the root being simplified, allow it to have multiple uses,
932   // just set the DemandedMask to all bits so that we can try to simplify the
933   // operands.  This allows visitTruncInst (for example) to simplify the
934   // operand of a trunc without duplicating all the logic below.
935   if (Depth == 0 && !V->hasOneUse())
936     DemandedMask = APInt::getAllOnesValue(BitWidth);
937   
938   switch (I->getOpcode()) {
939   default:
940     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
941     break;
942   case Instruction::And:
943     // If either the LHS or the RHS are Zero, the result is zero.
944     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
945                              RHSKnownZero, RHSKnownOne, Depth+1) ||
946         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
947                              LHSKnownZero, LHSKnownOne, Depth+1))
948       return I;
949     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
950     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
951
952     // If all of the demanded bits are known 1 on one side, return the other.
953     // These bits cannot contribute to the result of the 'and'.
954     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
955         (DemandedMask & ~LHSKnownZero))
956       return I->getOperand(0);
957     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
958         (DemandedMask & ~RHSKnownZero))
959       return I->getOperand(1);
960     
961     // If all of the demanded bits in the inputs are known zeros, return zero.
962     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
963       return Constant::getNullValue(VTy);
964       
965     // If the RHS is a constant, see if we can simplify it.
966     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
967       return I;
968       
969     // Output known-1 bits are only known if set in both the LHS & RHS.
970     RHSKnownOne &= LHSKnownOne;
971     // Output known-0 are known to be clear if zero in either the LHS | RHS.
972     RHSKnownZero |= LHSKnownZero;
973     break;
974   case Instruction::Or:
975     // If either the LHS or the RHS are One, the result is One.
976     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
977                              RHSKnownZero, RHSKnownOne, Depth+1) ||
978         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
979                              LHSKnownZero, LHSKnownOne, Depth+1))
980       return I;
981     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
982     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
983     
984     // If all of the demanded bits are known zero on one side, return the other.
985     // These bits cannot contribute to the result of the 'or'.
986     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
987         (DemandedMask & ~LHSKnownOne))
988       return I->getOperand(0);
989     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
990         (DemandedMask & ~RHSKnownOne))
991       return I->getOperand(1);
992
993     // If all of the potentially set bits on one side are known to be set on
994     // the other side, just use the 'other' side.
995     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
996         (DemandedMask & (~RHSKnownZero)))
997       return I->getOperand(0);
998     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
999         (DemandedMask & (~LHSKnownZero)))
1000       return I->getOperand(1);
1001         
1002     // If the RHS is a constant, see if we can simplify it.
1003     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1004       return I;
1005           
1006     // Output known-0 bits are only known if clear in both the LHS & RHS.
1007     RHSKnownZero &= LHSKnownZero;
1008     // Output known-1 are known to be set if set in either the LHS | RHS.
1009     RHSKnownOne |= LHSKnownOne;
1010     break;
1011   case Instruction::Xor: {
1012     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1013                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1014         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1015                              LHSKnownZero, LHSKnownOne, Depth+1))
1016       return I;
1017     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1018     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1019     
1020     // If all of the demanded bits are known zero on one side, return the other.
1021     // These bits cannot contribute to the result of the 'xor'.
1022     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1023       return I->getOperand(0);
1024     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1025       return I->getOperand(1);
1026     
1027     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1028     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1029                          (RHSKnownOne & LHSKnownOne);
1030     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1031     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1032                         (RHSKnownOne & LHSKnownZero);
1033     
1034     // If all of the demanded bits are known to be zero on one side or the
1035     // other, turn this into an *inclusive* or.
1036     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1037     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1038       Instruction *Or =
1039         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1040                                  I->getName());
1041       return InsertNewInstBefore(Or, *I);
1042     }
1043     
1044     // If all of the demanded bits on one side are known, and all of the set
1045     // bits on that side are also known to be set on the other side, turn this
1046     // into an AND, as we know the bits will be cleared.
1047     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1048     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1049       // all known
1050       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1051         Constant *AndC = Constant::getIntegerValue(VTy,
1052                                                    ~RHSKnownOne & DemandedMask);
1053         Instruction *And = 
1054           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1055         return InsertNewInstBefore(And, *I);
1056       }
1057     }
1058     
1059     // If the RHS is a constant, see if we can simplify it.
1060     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1061     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1062       return I;
1063     
1064     RHSKnownZero = KnownZeroOut;
1065     RHSKnownOne  = KnownOneOut;
1066     break;
1067   }
1068   case Instruction::Select:
1069     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1070                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1071         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1072                              LHSKnownZero, LHSKnownOne, Depth+1))
1073       return I;
1074     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1075     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1076     
1077     // If the operands are constants, see if we can simplify them.
1078     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1079         ShrinkDemandedConstant(I, 2, DemandedMask))
1080       return I;
1081     
1082     // Only known if known in both the LHS and RHS.
1083     RHSKnownOne &= LHSKnownOne;
1084     RHSKnownZero &= LHSKnownZero;
1085     break;
1086   case Instruction::Trunc: {
1087     unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1088     DemandedMask.zext(truncBf);
1089     RHSKnownZero.zext(truncBf);
1090     RHSKnownOne.zext(truncBf);
1091     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1092                              RHSKnownZero, RHSKnownOne, Depth+1))
1093       return I;
1094     DemandedMask.trunc(BitWidth);
1095     RHSKnownZero.trunc(BitWidth);
1096     RHSKnownOne.trunc(BitWidth);
1097     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1098     break;
1099   }
1100   case Instruction::BitCast:
1101     if (!I->getOperand(0)->getType()->isIntOrIntVector())
1102       return false;  // vector->int or fp->int?
1103
1104     if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1105       if (const VectorType *SrcVTy =
1106             dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1107         if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1108           // Don't touch a bitcast between vectors of different element counts.
1109           return false;
1110       } else
1111         // Don't touch a scalar-to-vector bitcast.
1112         return false;
1113     } else if (isa<VectorType>(I->getOperand(0)->getType()))
1114       // Don't touch a vector-to-scalar bitcast.
1115       return false;
1116
1117     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1118                              RHSKnownZero, RHSKnownOne, Depth+1))
1119       return I;
1120     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1121     break;
1122   case Instruction::ZExt: {
1123     // Compute the bits in the result that are not present in the input.
1124     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1125     
1126     DemandedMask.trunc(SrcBitWidth);
1127     RHSKnownZero.trunc(SrcBitWidth);
1128     RHSKnownOne.trunc(SrcBitWidth);
1129     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1130                              RHSKnownZero, RHSKnownOne, Depth+1))
1131       return I;
1132     DemandedMask.zext(BitWidth);
1133     RHSKnownZero.zext(BitWidth);
1134     RHSKnownOne.zext(BitWidth);
1135     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1136     // The top bits are known to be zero.
1137     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1138     break;
1139   }
1140   case Instruction::SExt: {
1141     // Compute the bits in the result that are not present in the input.
1142     unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1143     
1144     APInt InputDemandedBits = DemandedMask & 
1145                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1146
1147     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1148     // If any of the sign extended bits are demanded, we know that the sign
1149     // bit is demanded.
1150     if ((NewBits & DemandedMask) != 0)
1151       InputDemandedBits.set(SrcBitWidth-1);
1152       
1153     InputDemandedBits.trunc(SrcBitWidth);
1154     RHSKnownZero.trunc(SrcBitWidth);
1155     RHSKnownOne.trunc(SrcBitWidth);
1156     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1157                              RHSKnownZero, RHSKnownOne, Depth+1))
1158       return I;
1159     InputDemandedBits.zext(BitWidth);
1160     RHSKnownZero.zext(BitWidth);
1161     RHSKnownOne.zext(BitWidth);
1162     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1163       
1164     // If the sign bit of the input is known set or clear, then we know the
1165     // top bits of the result.
1166
1167     // If the input sign bit is known zero, or if the NewBits are not demanded
1168     // convert this into a zero extension.
1169     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1170       // Convert to ZExt cast
1171       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1172       return InsertNewInstBefore(NewCast, *I);
1173     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1174       RHSKnownOne |= NewBits;
1175     }
1176     break;
1177   }
1178   case Instruction::Add: {
1179     // Figure out what the input bits are.  If the top bits of the and result
1180     // are not demanded, then the add doesn't demand them from its input
1181     // either.
1182     unsigned NLZ = DemandedMask.countLeadingZeros();
1183       
1184     // If there is a constant on the RHS, there are a variety of xformations
1185     // we can do.
1186     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1187       // If null, this should be simplified elsewhere.  Some of the xforms here
1188       // won't work if the RHS is zero.
1189       if (RHS->isZero())
1190         break;
1191       
1192       // If the top bit of the output is demanded, demand everything from the
1193       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1194       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1195
1196       // Find information about known zero/one bits in the input.
1197       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1198                                LHSKnownZero, LHSKnownOne, Depth+1))
1199         return I;
1200
1201       // If the RHS of the add has bits set that can't affect the input, reduce
1202       // the constant.
1203       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1204         return I;
1205       
1206       // Avoid excess work.
1207       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1208         break;
1209       
1210       // Turn it into OR if input bits are zero.
1211       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1212         Instruction *Or =
1213           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1214                                    I->getName());
1215         return InsertNewInstBefore(Or, *I);
1216       }
1217       
1218       // We can say something about the output known-zero and known-one bits,
1219       // depending on potential carries from the input constant and the
1220       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1221       // bits set and the RHS constant is 0x01001, then we know we have a known
1222       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1223       
1224       // To compute this, we first compute the potential carry bits.  These are
1225       // the bits which may be modified.  I'm not aware of a better way to do
1226       // this scan.
1227       const APInt &RHSVal = RHS->getValue();
1228       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1229       
1230       // Now that we know which bits have carries, compute the known-1/0 sets.
1231       
1232       // Bits are known one if they are known zero in one operand and one in the
1233       // other, and there is no input carry.
1234       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1235                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1236       
1237       // Bits are known zero if they are known zero in both operands and there
1238       // is no input carry.
1239       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1240     } else {
1241       // If the high-bits of this ADD are not demanded, then it does not demand
1242       // the high bits of its LHS or RHS.
1243       if (DemandedMask[BitWidth-1] == 0) {
1244         // Right fill the mask of bits for this ADD to demand the most
1245         // significant bit and all those below it.
1246         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1247         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1248                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1249             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1250                                  LHSKnownZero, LHSKnownOne, Depth+1))
1251           return I;
1252       }
1253     }
1254     break;
1255   }
1256   case Instruction::Sub:
1257     // If the high-bits of this SUB are not demanded, then it does not demand
1258     // the high bits of its LHS or RHS.
1259     if (DemandedMask[BitWidth-1] == 0) {
1260       // Right fill the mask of bits for this SUB to demand the most
1261       // significant bit and all those below it.
1262       uint32_t NLZ = DemandedMask.countLeadingZeros();
1263       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1264       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1265                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1266           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1267                                LHSKnownZero, LHSKnownOne, Depth+1))
1268         return I;
1269     }
1270     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1271     // the known zeros and ones.
1272     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1273     break;
1274   case Instruction::Shl:
1275     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1276       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1277       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1278       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1279                                RHSKnownZero, RHSKnownOne, Depth+1))
1280         return I;
1281       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1282       RHSKnownZero <<= ShiftAmt;
1283       RHSKnownOne  <<= ShiftAmt;
1284       // low bits known zero.
1285       if (ShiftAmt)
1286         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1287     }
1288     break;
1289   case Instruction::LShr:
1290     // For a logical shift right
1291     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1293       
1294       // Unsigned shift right.
1295       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1296       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1297                                RHSKnownZero, RHSKnownOne, Depth+1))
1298         return I;
1299       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1300       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1301       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1302       if (ShiftAmt) {
1303         // Compute the new bits that are at the top now.
1304         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1305         RHSKnownZero |= HighBits;  // high bits known zero.
1306       }
1307     }
1308     break;
1309   case Instruction::AShr:
1310     // If this is an arithmetic shift right and only the low-bit is set, we can
1311     // always convert this into a logical shr, even if the shift amount is
1312     // variable.  The low bit of the shift cannot be an input sign bit unless
1313     // the shift amount is >= the size of the datatype, which is undefined.
1314     if (DemandedMask == 1) {
1315       // Perform the logical shift right.
1316       Instruction *NewVal = BinaryOperator::CreateLShr(
1317                         I->getOperand(0), I->getOperand(1), I->getName());
1318       return InsertNewInstBefore(NewVal, *I);
1319     }    
1320
1321     // If the sign bit is the only bit demanded by this ashr, then there is no
1322     // need to do it, the shift doesn't change the high bit.
1323     if (DemandedMask.isSignBit())
1324       return I->getOperand(0);
1325     
1326     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1327       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1328       
1329       // Signed shift right.
1330       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1331       // If any of the "high bits" are demanded, we should set the sign bit as
1332       // demanded.
1333       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1334         DemandedMaskIn.set(BitWidth-1);
1335       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1336                                RHSKnownZero, RHSKnownOne, Depth+1))
1337         return I;
1338       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1339       // Compute the new bits that are at the top now.
1340       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1341       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1342       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1343         
1344       // Handle the sign bits.
1345       APInt SignBit(APInt::getSignBit(BitWidth));
1346       // Adjust to where it is now in the mask.
1347       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1348         
1349       // If the input sign bit is known to be zero, or if none of the top bits
1350       // are demanded, turn this into an unsigned shift right.
1351       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1352           (HighBits & ~DemandedMask) == HighBits) {
1353         // Perform the logical shift right.
1354         Instruction *NewVal = BinaryOperator::CreateLShr(
1355                           I->getOperand(0), SA, I->getName());
1356         return InsertNewInstBefore(NewVal, *I);
1357       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1358         RHSKnownOne |= HighBits;
1359       }
1360     }
1361     break;
1362   case Instruction::SRem:
1363     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1364       APInt RA = Rem->getValue().abs();
1365       if (RA.isPowerOf2()) {
1366         if (DemandedMask.ult(RA))    // srem won't affect demanded bits
1367           return I->getOperand(0);
1368
1369         APInt LowBits = RA - 1;
1370         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1371         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1372                                  LHSKnownZero, LHSKnownOne, Depth+1))
1373           return I;
1374
1375         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1376           LHSKnownZero |= ~LowBits;
1377
1378         KnownZero |= LHSKnownZero & DemandedMask;
1379
1380         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1381       }
1382     }
1383     break;
1384   case Instruction::URem: {
1385     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1386     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1387     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1388                              KnownZero2, KnownOne2, Depth+1) ||
1389         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1390                              KnownZero2, KnownOne2, Depth+1))
1391       return I;
1392
1393     unsigned Leaders = KnownZero2.countLeadingOnes();
1394     Leaders = std::max(Leaders,
1395                        KnownZero2.countLeadingOnes());
1396     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1397     break;
1398   }
1399   case Instruction::Call:
1400     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1401       switch (II->getIntrinsicID()) {
1402       default: break;
1403       case Intrinsic::bswap: {
1404         // If the only bits demanded come from one byte of the bswap result,
1405         // just shift the input byte into position to eliminate the bswap.
1406         unsigned NLZ = DemandedMask.countLeadingZeros();
1407         unsigned NTZ = DemandedMask.countTrailingZeros();
1408           
1409         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1410         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1411         // have 14 leading zeros, round to 8.
1412         NLZ &= ~7;
1413         NTZ &= ~7;
1414         // If we need exactly one byte, we can do this transformation.
1415         if (BitWidth-NLZ-NTZ == 8) {
1416           unsigned ResultBit = NTZ;
1417           unsigned InputBit = BitWidth-NTZ-8;
1418           
1419           // Replace this with either a left or right shift to get the byte into
1420           // the right place.
1421           Instruction *NewVal;
1422           if (InputBit > ResultBit)
1423             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1424                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1425           else
1426             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1427                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1428           NewVal->takeName(I);
1429           return InsertNewInstBefore(NewVal, *I);
1430         }
1431           
1432         // TODO: Could compute known zero/one bits based on the input.
1433         break;
1434       }
1435       }
1436     }
1437     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1438     break;
1439   }
1440   
1441   // If the client is only demanding bits that we know, return the known
1442   // constant.
1443   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1444     return Constant::getIntegerValue(VTy, RHSKnownOne);
1445   return false;
1446 }
1447
1448
1449 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1450 /// any number of elements. DemandedElts contains the set of elements that are
1451 /// actually used by the caller.  This method analyzes which elements of the
1452 /// operand are undef and returns that information in UndefElts.
1453 ///
1454 /// If the information about demanded elements can be used to simplify the
1455 /// operation, the operation is simplified, then the resultant value is
1456 /// returned.  This returns null if no change was made.
1457 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1458                                                 APInt& UndefElts,
1459                                                 unsigned Depth) {
1460   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1461   APInt EltMask(APInt::getAllOnesValue(VWidth));
1462   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1463
1464   if (isa<UndefValue>(V)) {
1465     // If the entire vector is undefined, just return this info.
1466     UndefElts = EltMask;
1467     return 0;
1468   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1469     UndefElts = EltMask;
1470     return UndefValue::get(V->getType());
1471   }
1472
1473   UndefElts = 0;
1474   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1475     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1476     Constant *Undef = UndefValue::get(EltTy);
1477
1478     std::vector<Constant*> Elts;
1479     for (unsigned i = 0; i != VWidth; ++i)
1480       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1481         Elts.push_back(Undef);
1482         UndefElts.set(i);
1483       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1484         Elts.push_back(Undef);
1485         UndefElts.set(i);
1486       } else {                               // Otherwise, defined.
1487         Elts.push_back(CP->getOperand(i));
1488       }
1489
1490     // If we changed the constant, return it.
1491     Constant *NewCP = ConstantVector::get(Elts);
1492     return NewCP != CP ? NewCP : 0;
1493   } else if (isa<ConstantAggregateZero>(V)) {
1494     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1495     // set to undef.
1496     
1497     // Check if this is identity. If so, return 0 since we are not simplifying
1498     // anything.
1499     if (DemandedElts == ((1ULL << VWidth) -1))
1500       return 0;
1501     
1502     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1503     Constant *Zero = Constant::getNullValue(EltTy);
1504     Constant *Undef = UndefValue::get(EltTy);
1505     std::vector<Constant*> Elts;
1506     for (unsigned i = 0; i != VWidth; ++i) {
1507       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1508       Elts.push_back(Elt);
1509     }
1510     UndefElts = DemandedElts ^ EltMask;
1511     return ConstantVector::get(Elts);
1512   }
1513   
1514   // Limit search depth.
1515   if (Depth == 10)
1516     return 0;
1517
1518   // If multiple users are using the root value, procede with
1519   // simplification conservatively assuming that all elements
1520   // are needed.
1521   if (!V->hasOneUse()) {
1522     // Quit if we find multiple users of a non-root value though.
1523     // They'll be handled when it's their turn to be visited by
1524     // the main instcombine process.
1525     if (Depth != 0)
1526       // TODO: Just compute the UndefElts information recursively.
1527       return 0;
1528
1529     // Conservatively assume that all elements are needed.
1530     DemandedElts = EltMask;
1531   }
1532   
1533   Instruction *I = dyn_cast<Instruction>(V);
1534   if (!I) return 0;        // Only analyze instructions.
1535   
1536   bool MadeChange = false;
1537   APInt UndefElts2(VWidth, 0);
1538   Value *TmpV;
1539   switch (I->getOpcode()) {
1540   default: break;
1541     
1542   case Instruction::InsertElement: {
1543     // If this is a variable index, we don't know which element it overwrites.
1544     // demand exactly the same input as we produce.
1545     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1546     if (Idx == 0) {
1547       // Note that we can't propagate undef elt info, because we don't know
1548       // which elt is getting updated.
1549       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1550                                         UndefElts2, Depth+1);
1551       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1552       break;
1553     }
1554     
1555     // If this is inserting an element that isn't demanded, remove this
1556     // insertelement.
1557     unsigned IdxNo = Idx->getZExtValue();
1558     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1559       return AddSoonDeadInstToWorklist(*I, 0);
1560     
1561     // Otherwise, the element inserted overwrites whatever was there, so the
1562     // input demanded set is simpler than the output set.
1563     APInt DemandedElts2 = DemandedElts;
1564     DemandedElts2.clear(IdxNo);
1565     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1566                                       UndefElts, Depth+1);
1567     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1568
1569     // The inserted element is defined.
1570     UndefElts.clear(IdxNo);
1571     break;
1572   }
1573   case Instruction::ShuffleVector: {
1574     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1575     uint64_t LHSVWidth =
1576       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1577     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1578     for (unsigned i = 0; i < VWidth; i++) {
1579       if (DemandedElts[i]) {
1580         unsigned MaskVal = Shuffle->getMaskValue(i);
1581         if (MaskVal != -1u) {
1582           assert(MaskVal < LHSVWidth * 2 &&
1583                  "shufflevector mask index out of range!");
1584           if (MaskVal < LHSVWidth)
1585             LeftDemanded.set(MaskVal);
1586           else
1587             RightDemanded.set(MaskVal - LHSVWidth);
1588         }
1589       }
1590     }
1591
1592     APInt UndefElts4(LHSVWidth, 0);
1593     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1594                                       UndefElts4, Depth+1);
1595     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1596
1597     APInt UndefElts3(LHSVWidth, 0);
1598     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1599                                       UndefElts3, Depth+1);
1600     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1601
1602     bool NewUndefElts = false;
1603     for (unsigned i = 0; i < VWidth; i++) {
1604       unsigned MaskVal = Shuffle->getMaskValue(i);
1605       if (MaskVal == -1u) {
1606         UndefElts.set(i);
1607       } else if (MaskVal < LHSVWidth) {
1608         if (UndefElts4[MaskVal]) {
1609           NewUndefElts = true;
1610           UndefElts.set(i);
1611         }
1612       } else {
1613         if (UndefElts3[MaskVal - LHSVWidth]) {
1614           NewUndefElts = true;
1615           UndefElts.set(i);
1616         }
1617       }
1618     }
1619
1620     if (NewUndefElts) {
1621       // Add additional discovered undefs.
1622       std::vector<Constant*> Elts;
1623       for (unsigned i = 0; i < VWidth; ++i) {
1624         if (UndefElts[i])
1625           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1626         else
1627           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1628                                           Shuffle->getMaskValue(i)));
1629       }
1630       I->setOperand(2, ConstantVector::get(Elts));
1631       MadeChange = true;
1632     }
1633     break;
1634   }
1635   case Instruction::BitCast: {
1636     // Vector->vector casts only.
1637     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1638     if (!VTy) break;
1639     unsigned InVWidth = VTy->getNumElements();
1640     APInt InputDemandedElts(InVWidth, 0);
1641     unsigned Ratio;
1642
1643     if (VWidth == InVWidth) {
1644       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1645       // elements as are demanded of us.
1646       Ratio = 1;
1647       InputDemandedElts = DemandedElts;
1648     } else if (VWidth > InVWidth) {
1649       // Untested so far.
1650       break;
1651       
1652       // If there are more elements in the result than there are in the source,
1653       // then an input element is live if any of the corresponding output
1654       // elements are live.
1655       Ratio = VWidth/InVWidth;
1656       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1657         if (DemandedElts[OutIdx])
1658           InputDemandedElts.set(OutIdx/Ratio);
1659       }
1660     } else {
1661       // Untested so far.
1662       break;
1663       
1664       // If there are more elements in the source than there are in the result,
1665       // then an input element is live if the corresponding output element is
1666       // live.
1667       Ratio = InVWidth/VWidth;
1668       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1669         if (DemandedElts[InIdx/Ratio])
1670           InputDemandedElts.set(InIdx);
1671     }
1672     
1673     // div/rem demand all inputs, because they don't want divide by zero.
1674     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1675                                       UndefElts2, Depth+1);
1676     if (TmpV) {
1677       I->setOperand(0, TmpV);
1678       MadeChange = true;
1679     }
1680     
1681     UndefElts = UndefElts2;
1682     if (VWidth > InVWidth) {
1683       llvm_unreachable("Unimp");
1684       // If there are more elements in the result than there are in the source,
1685       // then an output element is undef if the corresponding input element is
1686       // undef.
1687       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1688         if (UndefElts2[OutIdx/Ratio])
1689           UndefElts.set(OutIdx);
1690     } else if (VWidth < InVWidth) {
1691       llvm_unreachable("Unimp");
1692       // If there are more elements in the source than there are in the result,
1693       // then a result element is undef if all of the corresponding input
1694       // elements are undef.
1695       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1696       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1697         if (!UndefElts2[InIdx])            // Not undef?
1698           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1699     }
1700     break;
1701   }
1702   case Instruction::And:
1703   case Instruction::Or:
1704   case Instruction::Xor:
1705   case Instruction::Add:
1706   case Instruction::Sub:
1707   case Instruction::Mul:
1708     // div/rem demand all inputs, because they don't want divide by zero.
1709     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1710                                       UndefElts, Depth+1);
1711     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1712     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1713                                       UndefElts2, Depth+1);
1714     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1715       
1716     // Output elements are undefined if both are undefined.  Consider things
1717     // like undef&0.  The result is known zero, not undef.
1718     UndefElts &= UndefElts2;
1719     break;
1720     
1721   case Instruction::Call: {
1722     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1723     if (!II) break;
1724     switch (II->getIntrinsicID()) {
1725     default: break;
1726       
1727     // Binary vector operations that work column-wise.  A dest element is a
1728     // function of the corresponding input elements from the two inputs.
1729     case Intrinsic::x86_sse_sub_ss:
1730     case Intrinsic::x86_sse_mul_ss:
1731     case Intrinsic::x86_sse_min_ss:
1732     case Intrinsic::x86_sse_max_ss:
1733     case Intrinsic::x86_sse2_sub_sd:
1734     case Intrinsic::x86_sse2_mul_sd:
1735     case Intrinsic::x86_sse2_min_sd:
1736     case Intrinsic::x86_sse2_max_sd:
1737       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1738                                         UndefElts, Depth+1);
1739       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1740       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1741                                         UndefElts2, Depth+1);
1742       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1743
1744       // If only the low elt is demanded and this is a scalarizable intrinsic,
1745       // scalarize it now.
1746       if (DemandedElts == 1) {
1747         switch (II->getIntrinsicID()) {
1748         default: break;
1749         case Intrinsic::x86_sse_sub_ss:
1750         case Intrinsic::x86_sse_mul_ss:
1751         case Intrinsic::x86_sse2_sub_sd:
1752         case Intrinsic::x86_sse2_mul_sd:
1753           // TODO: Lower MIN/MAX/ABS/etc
1754           Value *LHS = II->getOperand(1);
1755           Value *RHS = II->getOperand(2);
1756           // Extract the element as scalars.
1757           LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS, 
1758             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1759           RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1760             ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1761           
1762           switch (II->getIntrinsicID()) {
1763           default: llvm_unreachable("Case stmts out of sync!");
1764           case Intrinsic::x86_sse_sub_ss:
1765           case Intrinsic::x86_sse2_sub_sd:
1766             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1767                                                         II->getName()), *II);
1768             break;
1769           case Intrinsic::x86_sse_mul_ss:
1770           case Intrinsic::x86_sse2_mul_sd:
1771             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1772                                                          II->getName()), *II);
1773             break;
1774           }
1775           
1776           Instruction *New =
1777             InsertElementInst::Create(
1778               UndefValue::get(II->getType()), TmpV,
1779               ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1780           InsertNewInstBefore(New, *II);
1781           AddSoonDeadInstToWorklist(*II, 0);
1782           return New;
1783         }            
1784       }
1785         
1786       // Output elements are undefined if both are undefined.  Consider things
1787       // like undef&0.  The result is known zero, not undef.
1788       UndefElts &= UndefElts2;
1789       break;
1790     }
1791     break;
1792   }
1793   }
1794   return MadeChange ? I : 0;
1795 }
1796
1797
1798 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1799 /// function is designed to check a chain of associative operators for a
1800 /// potential to apply a certain optimization.  Since the optimization may be
1801 /// applicable if the expression was reassociated, this checks the chain, then
1802 /// reassociates the expression as necessary to expose the optimization
1803 /// opportunity.  This makes use of a special Functor, which must define
1804 /// 'shouldApply' and 'apply' methods.
1805 ///
1806 template<typename Functor>
1807 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1808   unsigned Opcode = Root.getOpcode();
1809   Value *LHS = Root.getOperand(0);
1810
1811   // Quick check, see if the immediate LHS matches...
1812   if (F.shouldApply(LHS))
1813     return F.apply(Root);
1814
1815   // Otherwise, if the LHS is not of the same opcode as the root, return.
1816   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1817   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1818     // Should we apply this transform to the RHS?
1819     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1820
1821     // If not to the RHS, check to see if we should apply to the LHS...
1822     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1823       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1824       ShouldApply = true;
1825     }
1826
1827     // If the functor wants to apply the optimization to the RHS of LHSI,
1828     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1829     if (ShouldApply) {
1830       // Now all of the instructions are in the current basic block, go ahead
1831       // and perform the reassociation.
1832       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1833
1834       // First move the selected RHS to the LHS of the root...
1835       Root.setOperand(0, LHSI->getOperand(1));
1836
1837       // Make what used to be the LHS of the root be the user of the root...
1838       Value *ExtraOperand = TmpLHSI->getOperand(1);
1839       if (&Root == TmpLHSI) {
1840         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1841         return 0;
1842       }
1843       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1844       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1845       BasicBlock::iterator ARI = &Root; ++ARI;
1846       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1847       ARI = Root;
1848
1849       // Now propagate the ExtraOperand down the chain of instructions until we
1850       // get to LHSI.
1851       while (TmpLHSI != LHSI) {
1852         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1853         // Move the instruction to immediately before the chain we are
1854         // constructing to avoid breaking dominance properties.
1855         NextLHSI->moveBefore(ARI);
1856         ARI = NextLHSI;
1857
1858         Value *NextOp = NextLHSI->getOperand(1);
1859         NextLHSI->setOperand(1, ExtraOperand);
1860         TmpLHSI = NextLHSI;
1861         ExtraOperand = NextOp;
1862       }
1863
1864       // Now that the instructions are reassociated, have the functor perform
1865       // the transformation...
1866       return F.apply(Root);
1867     }
1868
1869     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1870   }
1871   return 0;
1872 }
1873
1874 namespace {
1875
1876 // AddRHS - Implements: X + X --> X << 1
1877 struct AddRHS {
1878   Value *RHS;
1879   explicit AddRHS(Value *rhs) : RHS(rhs) {}
1880   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1881   Instruction *apply(BinaryOperator &Add) const {
1882     return BinaryOperator::CreateShl(Add.getOperand(0),
1883                                      ConstantInt::get(Add.getType(), 1));
1884   }
1885 };
1886
1887 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1888 //                 iff C1&C2 == 0
1889 struct AddMaskingAnd {
1890   Constant *C2;
1891   explicit AddMaskingAnd(Constant *c) : C2(c) {}
1892   bool shouldApply(Value *LHS) const {
1893     ConstantInt *C1;
1894     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1895            ConstantExpr::getAnd(C1, C2)->isNullValue();
1896   }
1897   Instruction *apply(BinaryOperator &Add) const {
1898     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1899   }
1900 };
1901
1902 }
1903
1904 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1905                                              InstCombiner *IC) {
1906   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1907     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1908   }
1909
1910   // Figure out if the constant is the left or the right argument.
1911   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1912   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1913
1914   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1915     if (ConstIsRHS)
1916       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1917     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1918   }
1919
1920   Value *Op0 = SO, *Op1 = ConstOperand;
1921   if (!ConstIsRHS)
1922     std::swap(Op0, Op1);
1923   Instruction *New;
1924   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1925     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1926   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1927     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
1928                           Op0, Op1, SO->getName()+".cmp");
1929   else {
1930     llvm_unreachable("Unknown binary instruction type!");
1931   }
1932   return IC->InsertNewInstBefore(New, I);
1933 }
1934
1935 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1936 // constant as the other operand, try to fold the binary operator into the
1937 // select arguments.  This also works for Cast instructions, which obviously do
1938 // not have a second operand.
1939 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1940                                      InstCombiner *IC) {
1941   // Don't modify shared select instructions
1942   if (!SI->hasOneUse()) return 0;
1943   Value *TV = SI->getOperand(1);
1944   Value *FV = SI->getOperand(2);
1945
1946   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1947     // Bool selects with constant operands can be folded to logical ops.
1948     if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1949
1950     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1951     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1952
1953     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1954                               SelectFalseVal);
1955   }
1956   return 0;
1957 }
1958
1959
1960 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1961 /// node as operand #0, see if we can fold the instruction into the PHI (which
1962 /// is only possible if all operands to the PHI are constants).
1963 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1964   PHINode *PN = cast<PHINode>(I.getOperand(0));
1965   unsigned NumPHIValues = PN->getNumIncomingValues();
1966   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1967
1968   // Check to see if all of the operands of the PHI are constants.  If there is
1969   // one non-constant value, remember the BB it is.  If there is more than one
1970   // or if *it* is a PHI, bail out.
1971   BasicBlock *NonConstBB = 0;
1972   for (unsigned i = 0; i != NumPHIValues; ++i)
1973     if (!isa<Constant>(PN->getIncomingValue(i))) {
1974       if (NonConstBB) return 0;  // More than one non-const value.
1975       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1976       NonConstBB = PN->getIncomingBlock(i);
1977       
1978       // If the incoming non-constant value is in I's block, we have an infinite
1979       // loop.
1980       if (NonConstBB == I.getParent())
1981         return 0;
1982     }
1983   
1984   // If there is exactly one non-constant value, we can insert a copy of the
1985   // operation in that block.  However, if this is a critical edge, we would be
1986   // inserting the computation one some other paths (e.g. inside a loop).  Only
1987   // do this if the pred block is unconditionally branching into the phi block.
1988   if (NonConstBB) {
1989     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1990     if (!BI || !BI->isUnconditional()) return 0;
1991   }
1992
1993   // Okay, we can do the transformation: create the new PHI node.
1994   PHINode *NewPN = PHINode::Create(I.getType(), "");
1995   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1996   InsertNewInstBefore(NewPN, *PN);
1997   NewPN->takeName(PN);
1998
1999   // Next, add all of the operands to the PHI.
2000   if (I.getNumOperands() == 2) {
2001     Constant *C = cast<Constant>(I.getOperand(1));
2002     for (unsigned i = 0; i != NumPHIValues; ++i) {
2003       Value *InV = 0;
2004       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2005         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2006           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2007         else
2008           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2009       } else {
2010         assert(PN->getIncomingBlock(i) == NonConstBB);
2011         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2012           InV = BinaryOperator::Create(BO->getOpcode(),
2013                                        PN->getIncomingValue(i), C, "phitmp",
2014                                        NonConstBB->getTerminator());
2015         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2016           InV = CmpInst::Create(CI->getOpcode(),
2017                                 CI->getPredicate(),
2018                                 PN->getIncomingValue(i), C, "phitmp",
2019                                 NonConstBB->getTerminator());
2020         else
2021           llvm_unreachable("Unknown binop!");
2022         
2023         AddToWorkList(cast<Instruction>(InV));
2024       }
2025       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2026     }
2027   } else { 
2028     CastInst *CI = cast<CastInst>(&I);
2029     const Type *RetTy = CI->getType();
2030     for (unsigned i = 0; i != NumPHIValues; ++i) {
2031       Value *InV;
2032       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2033         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2034       } else {
2035         assert(PN->getIncomingBlock(i) == NonConstBB);
2036         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2037                                I.getType(), "phitmp", 
2038                                NonConstBB->getTerminator());
2039         AddToWorkList(cast<Instruction>(InV));
2040       }
2041       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2042     }
2043   }
2044   return ReplaceInstUsesWith(I, NewPN);
2045 }
2046
2047
2048 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2049 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2050 /// This basically requires proving that the add in the original type would not
2051 /// overflow to change the sign bit or have a carry out.
2052 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2053   // There are different heuristics we can use for this.  Here are some simple
2054   // ones.
2055   
2056   // Add has the property that adding any two 2's complement numbers can only 
2057   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2058   // have at least two sign bits, we know that the addition of the two values will
2059   // sign extend fine.
2060   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2061     return true;
2062   
2063   
2064   // If one of the operands only has one non-zero bit, and if the other operand
2065   // has a known-zero bit in a more significant place than it (not including the
2066   // sign bit) the ripple may go up to and fill the zero, but won't change the
2067   // sign.  For example, (X & ~4) + 1.
2068   
2069   // TODO: Implement.
2070   
2071   return false;
2072 }
2073
2074
2075 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2076   bool Changed = SimplifyCommutative(I);
2077   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2078
2079   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2080     // X + undef -> undef
2081     if (isa<UndefValue>(RHS))
2082       return ReplaceInstUsesWith(I, RHS);
2083
2084     // X + 0 --> X
2085     if (RHSC->isNullValue())
2086       return ReplaceInstUsesWith(I, LHS);
2087
2088     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2089       // X + (signbit) --> X ^ signbit
2090       const APInt& Val = CI->getValue();
2091       uint32_t BitWidth = Val.getBitWidth();
2092       if (Val == APInt::getSignBit(BitWidth))
2093         return BinaryOperator::CreateXor(LHS, RHS);
2094       
2095       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2096       // (X & 254)+1 -> (X&254)|1
2097       if (SimplifyDemandedInstructionBits(I))
2098         return &I;
2099
2100       // zext(bool) + C -> bool ? C + 1 : C
2101       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2102         if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2103           return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2104     }
2105
2106     if (isa<PHINode>(LHS))
2107       if (Instruction *NV = FoldOpIntoPhi(I))
2108         return NV;
2109     
2110     ConstantInt *XorRHS = 0;
2111     Value *XorLHS = 0;
2112     if (isa<ConstantInt>(RHSC) &&
2113         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2114       uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2115       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2116       
2117       uint32_t Size = TySizeBits / 2;
2118       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2119       APInt CFF80Val(-C0080Val);
2120       do {
2121         if (TySizeBits > Size) {
2122           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2123           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2124           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2125               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2126             // This is a sign extend if the top bits are known zero.
2127             if (!MaskedValueIsZero(XorLHS, 
2128                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2129               Size = 0;  // Not a sign ext, but can't be any others either.
2130             break;
2131           }
2132         }
2133         Size >>= 1;
2134         C0080Val = APIntOps::lshr(C0080Val, Size);
2135         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2136       } while (Size >= 1);
2137       
2138       // FIXME: This shouldn't be necessary. When the backends can handle types
2139       // with funny bit widths then this switch statement should be removed. It
2140       // is just here to get the size of the "middle" type back up to something
2141       // that the back ends can handle.
2142       const Type *MiddleType = 0;
2143       switch (Size) {
2144         default: break;
2145         case 32: MiddleType = Type::getInt32Ty(*Context); break;
2146         case 16: MiddleType = Type::getInt16Ty(*Context); break;
2147         case  8: MiddleType = Type::getInt8Ty(*Context); break;
2148       }
2149       if (MiddleType) {
2150         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2151         InsertNewInstBefore(NewTrunc, I);
2152         return new SExtInst(NewTrunc, I.getType(), I.getName());
2153       }
2154     }
2155   }
2156
2157   if (I.getType() == Type::getInt1Ty(*Context))
2158     return BinaryOperator::CreateXor(LHS, RHS);
2159
2160   // X + X --> X << 1
2161   if (I.getType()->isInteger()) {
2162     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2163       return Result;
2164
2165     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2166       if (RHSI->getOpcode() == Instruction::Sub)
2167         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2168           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2169     }
2170     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2171       if (LHSI->getOpcode() == Instruction::Sub)
2172         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2173           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2174     }
2175   }
2176
2177   // -A + B  -->  B - A
2178   // -A + -B  -->  -(A + B)
2179   if (Value *LHSV = dyn_castNegVal(LHS)) {
2180     if (LHS->getType()->isIntOrIntVector()) {
2181       if (Value *RHSV = dyn_castNegVal(RHS)) {
2182         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2183         InsertNewInstBefore(NewAdd, I);
2184         return BinaryOperator::CreateNeg(NewAdd);
2185       }
2186     }
2187     
2188     return BinaryOperator::CreateSub(RHS, LHSV);
2189   }
2190
2191   // A + -B  -->  A - B
2192   if (!isa<Constant>(RHS))
2193     if (Value *V = dyn_castNegVal(RHS))
2194       return BinaryOperator::CreateSub(LHS, V);
2195
2196
2197   ConstantInt *C2;
2198   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2199     if (X == RHS)   // X*C + X --> X * (C+1)
2200       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2201
2202     // X*C1 + X*C2 --> X * (C1+C2)
2203     ConstantInt *C1;
2204     if (X == dyn_castFoldableMul(RHS, C1))
2205       return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2206   }
2207
2208   // X + X*C --> X * (C+1)
2209   if (dyn_castFoldableMul(RHS, C2) == LHS)
2210     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2211
2212   // X + ~X --> -1   since   ~X = -X-1
2213   if (dyn_castNotVal(LHS) == RHS ||
2214       dyn_castNotVal(RHS) == LHS)
2215     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2216   
2217
2218   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2219   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2220     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2221       return R;
2222   
2223   // A+B --> A|B iff A and B have no bits set in common.
2224   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2225     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2226     APInt LHSKnownOne(IT->getBitWidth(), 0);
2227     APInt LHSKnownZero(IT->getBitWidth(), 0);
2228     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2229     if (LHSKnownZero != 0) {
2230       APInt RHSKnownOne(IT->getBitWidth(), 0);
2231       APInt RHSKnownZero(IT->getBitWidth(), 0);
2232       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2233       
2234       // No bits in common -> bitwise or.
2235       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2236         return BinaryOperator::CreateOr(LHS, RHS);
2237     }
2238   }
2239
2240   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2241   if (I.getType()->isIntOrIntVector()) {
2242     Value *W, *X, *Y, *Z;
2243     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2244         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2245       if (W != Y) {
2246         if (W == Z) {
2247           std::swap(Y, Z);
2248         } else if (Y == X) {
2249           std::swap(W, X);
2250         } else if (X == Z) {
2251           std::swap(Y, Z);
2252           std::swap(W, X);
2253         }
2254       }
2255
2256       if (W == Y) {
2257         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2258                                                             LHS->getName()), I);
2259         return BinaryOperator::CreateMul(W, NewAdd);
2260       }
2261     }
2262   }
2263
2264   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2265     Value *X = 0;
2266     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2267       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2268
2269     // (X & FF00) + xx00  -> (X+xx00) & FF00
2270     if (LHS->hasOneUse() &&
2271         match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2272       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2273       if (Anded == CRHS) {
2274         // See if all bits from the first bit set in the Add RHS up are included
2275         // in the mask.  First, get the rightmost bit.
2276         const APInt& AddRHSV = CRHS->getValue();
2277
2278         // Form a mask of all bits from the lowest bit added through the top.
2279         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2280
2281         // See if the and mask includes all of these bits.
2282         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2283
2284         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2285           // Okay, the xform is safe.  Insert the new add pronto.
2286           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2287                                                             LHS->getName()), I);
2288           return BinaryOperator::CreateAnd(NewAdd, C2);
2289         }
2290       }
2291     }
2292
2293     // Try to fold constant add into select arguments.
2294     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2295       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2296         return R;
2297   }
2298
2299   // add (select X 0 (sub n A)) A  -->  select X A n
2300   {
2301     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2302     Value *A = RHS;
2303     if (!SI) {
2304       SI = dyn_cast<SelectInst>(RHS);
2305       A = LHS;
2306     }
2307     if (SI && SI->hasOneUse()) {
2308       Value *TV = SI->getTrueValue();
2309       Value *FV = SI->getFalseValue();
2310       Value *N;
2311
2312       // Can we fold the add into the argument of the select?
2313       // We check both true and false select arguments for a matching subtract.
2314       if (match(FV, m_Zero()) &&
2315           match(TV, m_Sub(m_Value(N), m_Specific(A))))
2316         // Fold the add into the true select value.
2317         return SelectInst::Create(SI->getCondition(), N, A);
2318       if (match(TV, m_Zero()) &&
2319           match(FV, m_Sub(m_Value(N), m_Specific(A))))
2320         // Fold the add into the false select value.
2321         return SelectInst::Create(SI->getCondition(), A, N);
2322     }
2323   }
2324
2325   // Check for (add (sext x), y), see if we can merge this into an
2326   // integer add followed by a sext.
2327   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2328     // (add (sext x), cst) --> (sext (add x, cst'))
2329     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2330       Constant *CI = 
2331         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2332       if (LHSConv->hasOneUse() &&
2333           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2334           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2335         // Insert the new, smaller add.
2336         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2337                                                         CI, "addconv");
2338         InsertNewInstBefore(NewAdd, I);
2339         return new SExtInst(NewAdd, I.getType());
2340       }
2341     }
2342     
2343     // (add (sext x), (sext y)) --> (sext (add int x, y))
2344     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2345       // Only do this if x/y have the same type, if at last one of them has a
2346       // single use (so we don't increase the number of sexts), and if the
2347       // integer add will not overflow.
2348       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2349           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2350           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2351                                    RHSConv->getOperand(0))) {
2352         // Insert the new integer add.
2353         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2354                                                         RHSConv->getOperand(0),
2355                                                         "addconv");
2356         InsertNewInstBefore(NewAdd, I);
2357         return new SExtInst(NewAdd, I.getType());
2358       }
2359     }
2360   }
2361
2362   return Changed ? &I : 0;
2363 }
2364
2365 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2366   bool Changed = SimplifyCommutative(I);
2367   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2368
2369   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2370     // X + 0 --> X
2371     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2372       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2373                               (I.getType())->getValueAPF()))
2374         return ReplaceInstUsesWith(I, LHS);
2375     }
2376
2377     if (isa<PHINode>(LHS))
2378       if (Instruction *NV = FoldOpIntoPhi(I))
2379         return NV;
2380   }
2381
2382   // -A + B  -->  B - A
2383   // -A + -B  -->  -(A + B)
2384   if (Value *LHSV = dyn_castFNegVal(LHS))
2385     return BinaryOperator::CreateFSub(RHS, LHSV);
2386
2387   // A + -B  -->  A - B
2388   if (!isa<Constant>(RHS))
2389     if (Value *V = dyn_castFNegVal(RHS))
2390       return BinaryOperator::CreateFSub(LHS, V);
2391
2392   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2393   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2394     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2395       return ReplaceInstUsesWith(I, LHS);
2396
2397   // Check for (add double (sitofp x), y), see if we can merge this into an
2398   // integer add followed by a promotion.
2399   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2400     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2401     // ... if the constant fits in the integer value.  This is useful for things
2402     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2403     // requires a constant pool load, and generally allows the add to be better
2404     // instcombined.
2405     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2406       Constant *CI = 
2407       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2408       if (LHSConv->hasOneUse() &&
2409           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2410           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2411         // Insert the new integer add.
2412         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2413                                                         CI, "addconv");
2414         InsertNewInstBefore(NewAdd, I);
2415         return new SIToFPInst(NewAdd, I.getType());
2416       }
2417     }
2418     
2419     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2420     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2421       // Only do this if x/y have the same type, if at last one of them has a
2422       // single use (so we don't increase the number of int->fp conversions),
2423       // and if the integer add will not overflow.
2424       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2425           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2426           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2427                                    RHSConv->getOperand(0))) {
2428         // Insert the new integer add.
2429         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2430                                                         RHSConv->getOperand(0),
2431                                                         "addconv");
2432         InsertNewInstBefore(NewAdd, I);
2433         return new SIToFPInst(NewAdd, I.getType());
2434       }
2435     }
2436   }
2437   
2438   return Changed ? &I : 0;
2439 }
2440
2441 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2442   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2443
2444   if (Op0 == Op1)                        // sub X, X  -> 0
2445     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2446
2447   // If this is a 'B = x-(-A)', change to B = x+A...
2448   if (Value *V = dyn_castNegVal(Op1))
2449     return BinaryOperator::CreateAdd(Op0, V);
2450
2451   if (isa<UndefValue>(Op0))
2452     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2453   if (isa<UndefValue>(Op1))
2454     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2455
2456   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2457     // Replace (-1 - A) with (~A)...
2458     if (C->isAllOnesValue())
2459       return BinaryOperator::CreateNot(Op1);
2460
2461     // C - ~X == X + (1+C)
2462     Value *X = 0;
2463     if (match(Op1, m_Not(m_Value(X))))
2464       return BinaryOperator::CreateAdd(X, AddOne(C));
2465
2466     // -(X >>u 31) -> (X >>s 31)
2467     // -(X >>s 31) -> (X >>u 31)
2468     if (C->isZero()) {
2469       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2470         if (SI->getOpcode() == Instruction::LShr) {
2471           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2472             // Check to see if we are shifting out everything but the sign bit.
2473             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2474                 SI->getType()->getPrimitiveSizeInBits()-1) {
2475               // Ok, the transformation is safe.  Insert AShr.
2476               return BinaryOperator::Create(Instruction::AShr, 
2477                                           SI->getOperand(0), CU, SI->getName());
2478             }
2479           }
2480         }
2481         else if (SI->getOpcode() == Instruction::AShr) {
2482           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2483             // Check to see if we are shifting out everything but the sign bit.
2484             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2485                 SI->getType()->getPrimitiveSizeInBits()-1) {
2486               // Ok, the transformation is safe.  Insert LShr. 
2487               return BinaryOperator::CreateLShr(
2488                                           SI->getOperand(0), CU, SI->getName());
2489             }
2490           }
2491         }
2492       }
2493     }
2494
2495     // Try to fold constant sub into select arguments.
2496     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2497       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2498         return R;
2499
2500     // C - zext(bool) -> bool ? C - 1 : C
2501     if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2502       if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2503         return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2504   }
2505
2506   if (I.getType() == Type::getInt1Ty(*Context))
2507     return BinaryOperator::CreateXor(Op0, Op1);
2508
2509   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2510     if (Op1I->getOpcode() == Instruction::Add) {
2511       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2512         return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2513                                          I.getName());
2514       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2515         return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2516                                          I.getName());
2517       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2518         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2519           // C1-(X+C2) --> (C1-C2)-X
2520           return BinaryOperator::CreateSub(
2521             ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2522       }
2523     }
2524
2525     if (Op1I->hasOneUse()) {
2526       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2527       // is not used by anyone else...
2528       //
2529       if (Op1I->getOpcode() == Instruction::Sub) {
2530         // Swap the two operands of the subexpr...
2531         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2532         Op1I->setOperand(0, IIOp1);
2533         Op1I->setOperand(1, IIOp0);
2534
2535         // Create the new top level add instruction...
2536         return BinaryOperator::CreateAdd(Op0, Op1);
2537       }
2538
2539       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2540       //
2541       if (Op1I->getOpcode() == Instruction::And &&
2542           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2543         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2544
2545         Value *NewNot =
2546           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2547         return BinaryOperator::CreateAnd(Op0, NewNot);
2548       }
2549
2550       // 0 - (X sdiv C)  -> (X sdiv -C)
2551       if (Op1I->getOpcode() == Instruction::SDiv)
2552         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2553           if (CSI->isZero())
2554             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2555               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2556                                           ConstantExpr::getNeg(DivRHS));
2557
2558       // X - X*C --> X * (1-C)
2559       ConstantInt *C2 = 0;
2560       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2561         Constant *CP1 = 
2562           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2563                                              C2);
2564         return BinaryOperator::CreateMul(Op0, CP1);
2565       }
2566     }
2567   }
2568
2569   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2570     if (Op0I->getOpcode() == Instruction::Add) {
2571       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2572         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2573       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2574         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2575     } else if (Op0I->getOpcode() == Instruction::Sub) {
2576       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2577         return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2578                                          I.getName());
2579     }
2580   }
2581
2582   ConstantInt *C1;
2583   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2584     if (X == Op1)  // X*C - X --> X * (C-1)
2585       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2586
2587     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2588     if (X == dyn_castFoldableMul(Op1, C2))
2589       return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2590   }
2591   return 0;
2592 }
2593
2594 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2595   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2596
2597   // If this is a 'B = x-(-A)', change to B = x+A...
2598   if (Value *V = dyn_castFNegVal(Op1))
2599     return BinaryOperator::CreateFAdd(Op0, V);
2600
2601   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2602     if (Op1I->getOpcode() == Instruction::FAdd) {
2603       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2604         return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2605                                           I.getName());
2606       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2607         return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2608                                           I.getName());
2609     }
2610   }
2611
2612   return 0;
2613 }
2614
2615 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2616 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2617 /// TrueIfSigned if the result of the comparison is true when the input value is
2618 /// signed.
2619 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2620                            bool &TrueIfSigned) {
2621   switch (pred) {
2622   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2623     TrueIfSigned = true;
2624     return RHS->isZero();
2625   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2626     TrueIfSigned = true;
2627     return RHS->isAllOnesValue();
2628   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2629     TrueIfSigned = false;
2630     return RHS->isAllOnesValue();
2631   case ICmpInst::ICMP_UGT:
2632     // True if LHS u> RHS and RHS == high-bit-mask - 1
2633     TrueIfSigned = true;
2634     return RHS->getValue() ==
2635       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2636   case ICmpInst::ICMP_UGE: 
2637     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2638     TrueIfSigned = true;
2639     return RHS->getValue().isSignBit();
2640   default:
2641     return false;
2642   }
2643 }
2644
2645 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2646   bool Changed = SimplifyCommutative(I);
2647   Value *Op0 = I.getOperand(0);
2648
2649   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2650     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2651
2652   // Simplify mul instructions with a constant RHS...
2653   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2654     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2655
2656       // ((X << C1)*C2) == (X * (C2 << C1))
2657       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2658         if (SI->getOpcode() == Instruction::Shl)
2659           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2660             return BinaryOperator::CreateMul(SI->getOperand(0),
2661                                         ConstantExpr::getShl(CI, ShOp));
2662
2663       if (CI->isZero())
2664         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2665       if (CI->equalsInt(1))                  // X * 1  == X
2666         return ReplaceInstUsesWith(I, Op0);
2667       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2668         return BinaryOperator::CreateNeg(Op0, I.getName());
2669
2670       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2671       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2672         return BinaryOperator::CreateShl(Op0,
2673                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2674       }
2675     } else if (isa<VectorType>(Op1->getType())) {
2676       if (Op1->isNullValue())
2677         return ReplaceInstUsesWith(I, Op1);
2678
2679       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2680         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2681           return BinaryOperator::CreateNeg(Op0, I.getName());
2682
2683         // As above, vector X*splat(1.0) -> X in all defined cases.
2684         if (Constant *Splat = Op1V->getSplatValue()) {
2685           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2686             if (CI->equalsInt(1))
2687               return ReplaceInstUsesWith(I, Op0);
2688         }
2689       }
2690     }
2691     
2692     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2693       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2694           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2695         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2696         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2697                                                      Op1, "tmp");
2698         InsertNewInstBefore(Add, I);
2699         Value *C1C2 = ConstantExpr::getMul(Op1, 
2700                                            cast<Constant>(Op0I->getOperand(1)));
2701         return BinaryOperator::CreateAdd(Add, C1C2);
2702         
2703       }
2704
2705     // Try to fold constant mul into select arguments.
2706     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2707       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2708         return R;
2709
2710     if (isa<PHINode>(Op0))
2711       if (Instruction *NV = FoldOpIntoPhi(I))
2712         return NV;
2713   }
2714
2715   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2716     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2717       return BinaryOperator::CreateMul(Op0v, Op1v);
2718
2719   // (X / Y) *  Y = X - (X % Y)
2720   // (X / Y) * -Y = (X % Y) - X
2721   {
2722     Value *Op1 = I.getOperand(1);
2723     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2724     if (!BO ||
2725         (BO->getOpcode() != Instruction::UDiv && 
2726          BO->getOpcode() != Instruction::SDiv)) {
2727       Op1 = Op0;
2728       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2729     }
2730     Value *Neg = dyn_castNegVal(Op1);
2731     if (BO && BO->hasOneUse() &&
2732         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2733         (BO->getOpcode() == Instruction::UDiv ||
2734          BO->getOpcode() == Instruction::SDiv)) {
2735       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2736
2737       // If the division is exact, X % Y is zero.
2738       if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2739         if (SDiv->isExact()) {
2740           if (Op1BO == Op1)
2741             return ReplaceInstUsesWith(I, Op0BO);
2742           else
2743             return BinaryOperator::CreateNeg(Op0BO);
2744         }
2745
2746       Instruction *Rem;
2747       if (BO->getOpcode() == Instruction::UDiv)
2748         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2749       else
2750         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2751
2752       InsertNewInstBefore(Rem, I);
2753       Rem->takeName(BO);
2754
2755       if (Op1BO == Op1)
2756         return BinaryOperator::CreateSub(Op0BO, Rem);
2757       else
2758         return BinaryOperator::CreateSub(Rem, Op0BO);
2759     }
2760   }
2761
2762   if (I.getType() == Type::getInt1Ty(*Context))
2763     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2764
2765   // If one of the operands of the multiply is a cast from a boolean value, then
2766   // we know the bool is either zero or one, so this is a 'masking' multiply.
2767   // See if we can simplify things based on how the boolean was originally
2768   // formed.
2769   CastInst *BoolCast = 0;
2770   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2771     if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2772       BoolCast = CI;
2773   if (!BoolCast)
2774     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2775       if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2776         BoolCast = CI;
2777   if (BoolCast) {
2778     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2779       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2780       const Type *SCOpTy = SCIOp0->getType();
2781       bool TIS = false;
2782       
2783       // If the icmp is true iff the sign bit of X is set, then convert this
2784       // multiply into a shift/and combination.
2785       if (isa<ConstantInt>(SCIOp1) &&
2786           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2787           TIS) {
2788         // Shift the X value right to turn it into "all signbits".
2789         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2790                                           SCOpTy->getPrimitiveSizeInBits()-1);
2791         Value *V =
2792           InsertNewInstBefore(
2793             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2794                                             BoolCast->getOperand(0)->getName()+
2795                                             ".mask"), I);
2796
2797         // If the multiply type is not the same as the source type, sign extend
2798         // or truncate to the multiply type.
2799         if (I.getType() != V->getType()) {
2800           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2801           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2802           Instruction::CastOps opcode = 
2803             (SrcBits == DstBits ? Instruction::BitCast : 
2804              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2805           V = InsertCastBefore(opcode, V, I.getType(), I);
2806         }
2807
2808         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2809         return BinaryOperator::CreateAnd(V, OtherOp);
2810       }
2811     }
2812   }
2813
2814   return Changed ? &I : 0;
2815 }
2816
2817 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2818   bool Changed = SimplifyCommutative(I);
2819   Value *Op0 = I.getOperand(0);
2820
2821   // Simplify mul instructions with a constant RHS...
2822   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2823     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2824       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2825       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2826       if (Op1F->isExactlyValue(1.0))
2827         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2828     } else if (isa<VectorType>(Op1->getType())) {
2829       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2830         // As above, vector X*splat(1.0) -> X in all defined cases.
2831         if (Constant *Splat = Op1V->getSplatValue()) {
2832           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2833             if (F->isExactlyValue(1.0))
2834               return ReplaceInstUsesWith(I, Op0);
2835         }
2836       }
2837     }
2838
2839     // Try to fold constant mul into select arguments.
2840     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2841       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2842         return R;
2843
2844     if (isa<PHINode>(Op0))
2845       if (Instruction *NV = FoldOpIntoPhi(I))
2846         return NV;
2847   }
2848
2849   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2850     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2851       return BinaryOperator::CreateFMul(Op0v, Op1v);
2852
2853   return Changed ? &I : 0;
2854 }
2855
2856 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2857 /// instruction.
2858 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2859   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2860   
2861   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2862   int NonNullOperand = -1;
2863   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2864     if (ST->isNullValue())
2865       NonNullOperand = 2;
2866   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2867   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2868     if (ST->isNullValue())
2869       NonNullOperand = 1;
2870   
2871   if (NonNullOperand == -1)
2872     return false;
2873   
2874   Value *SelectCond = SI->getOperand(0);
2875   
2876   // Change the div/rem to use 'Y' instead of the select.
2877   I.setOperand(1, SI->getOperand(NonNullOperand));
2878   
2879   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2880   // problem.  However, the select, or the condition of the select may have
2881   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2882   // propagate the known value for the select into other uses of it, and
2883   // propagate a known value of the condition into its other users.
2884   
2885   // If the select and condition only have a single use, don't bother with this,
2886   // early exit.
2887   if (SI->use_empty() && SelectCond->hasOneUse())
2888     return true;
2889   
2890   // Scan the current block backward, looking for other uses of SI.
2891   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2892   
2893   while (BBI != BBFront) {
2894     --BBI;
2895     // If we found a call to a function, we can't assume it will return, so
2896     // information from below it cannot be propagated above it.
2897     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2898       break;
2899     
2900     // Replace uses of the select or its condition with the known values.
2901     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2902          I != E; ++I) {
2903       if (*I == SI) {
2904         *I = SI->getOperand(NonNullOperand);
2905         AddToWorkList(BBI);
2906       } else if (*I == SelectCond) {
2907         *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2908                                    ConstantInt::getFalse(*Context);
2909         AddToWorkList(BBI);
2910       }
2911     }
2912     
2913     // If we past the instruction, quit looking for it.
2914     if (&*BBI == SI)
2915       SI = 0;
2916     if (&*BBI == SelectCond)
2917       SelectCond = 0;
2918     
2919     // If we ran out of things to eliminate, break out of the loop.
2920     if (SelectCond == 0 && SI == 0)
2921       break;
2922     
2923   }
2924   return true;
2925 }
2926
2927
2928 /// This function implements the transforms on div instructions that work
2929 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2930 /// used by the visitors to those instructions.
2931 /// @brief Transforms common to all three div instructions
2932 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2933   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2934
2935   // undef / X -> 0        for integer.
2936   // undef / X -> undef    for FP (the undef could be a snan).
2937   if (isa<UndefValue>(Op0)) {
2938     if (Op0->getType()->isFPOrFPVector())
2939       return ReplaceInstUsesWith(I, Op0);
2940     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2941   }
2942
2943   // X / undef -> undef
2944   if (isa<UndefValue>(Op1))
2945     return ReplaceInstUsesWith(I, Op1);
2946
2947   return 0;
2948 }
2949
2950 /// This function implements the transforms common to both integer division
2951 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2952 /// division instructions.
2953 /// @brief Common integer divide transforms
2954 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2955   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2956
2957   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2958   if (Op0 == Op1) {
2959     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2960       Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2961       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2962       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2963     }
2964
2965     Constant *CI = ConstantInt::get(I.getType(), 1);
2966     return ReplaceInstUsesWith(I, CI);
2967   }
2968   
2969   if (Instruction *Common = commonDivTransforms(I))
2970     return Common;
2971   
2972   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2973   // This does not apply for fdiv.
2974   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2975     return &I;
2976
2977   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2978     // div X, 1 == X
2979     if (RHS->equalsInt(1))
2980       return ReplaceInstUsesWith(I, Op0);
2981
2982     // (X / C1) / C2  -> X / (C1*C2)
2983     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2984       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2985         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2986           if (MultiplyOverflows(RHS, LHSRHS,
2987                                 I.getOpcode()==Instruction::SDiv))
2988             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2989           else 
2990             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2991                                       ConstantExpr::getMul(RHS, LHSRHS));
2992         }
2993
2994     if (!RHS->isZero()) { // avoid X udiv 0
2995       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2996         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2997           return R;
2998       if (isa<PHINode>(Op0))
2999         if (Instruction *NV = FoldOpIntoPhi(I))
3000           return NV;
3001     }
3002   }
3003
3004   // 0 / X == 0, we don't need to preserve faults!
3005   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3006     if (LHS->equalsInt(0))
3007       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3008
3009   // It can't be division by zero, hence it must be division by one.
3010   if (I.getType() == Type::getInt1Ty(*Context))
3011     return ReplaceInstUsesWith(I, Op0);
3012
3013   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3014     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3015       // div X, 1 == X
3016       if (X->isOne())
3017         return ReplaceInstUsesWith(I, Op0);
3018   }
3019
3020   return 0;
3021 }
3022
3023 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3024   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3025
3026   // Handle the integer div common cases
3027   if (Instruction *Common = commonIDivTransforms(I))
3028     return Common;
3029
3030   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3031     // X udiv C^2 -> X >> C
3032     // Check to see if this is an unsigned division with an exact power of 2,
3033     // if so, convert to a right shift.
3034     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3035       return BinaryOperator::CreateLShr(Op0, 
3036             ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3037
3038     // X udiv C, where C >= signbit
3039     if (C->getValue().isNegative()) {
3040       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3041                                       I);
3042       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3043                                 ConstantInt::get(I.getType(), 1));
3044     }
3045   }
3046
3047   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3048   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3049     if (RHSI->getOpcode() == Instruction::Shl &&
3050         isa<ConstantInt>(RHSI->getOperand(0))) {
3051       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3052       if (C1.isPowerOf2()) {
3053         Value *N = RHSI->getOperand(1);
3054         const Type *NTy = N->getType();
3055         if (uint32_t C2 = C1.logBase2()) {
3056           Constant *C2V = ConstantInt::get(NTy, C2);
3057           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3058         }
3059         return BinaryOperator::CreateLShr(Op0, N);
3060       }
3061     }
3062   }
3063   
3064   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3065   // where C1&C2 are powers of two.
3066   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3067     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3068       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3069         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3070         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3071           // Compute the shift amounts
3072           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3073           // Construct the "on true" case of the select
3074           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3075           Instruction *TSI = BinaryOperator::CreateLShr(
3076                                                  Op0, TC, SI->getName()+".t");
3077           TSI = InsertNewInstBefore(TSI, I);
3078   
3079           // Construct the "on false" case of the select
3080           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3081           Instruction *FSI = BinaryOperator::CreateLShr(
3082                                                  Op0, FC, SI->getName()+".f");
3083           FSI = InsertNewInstBefore(FSI, I);
3084
3085           // construct the select instruction and return it.
3086           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3087         }
3088       }
3089   return 0;
3090 }
3091
3092 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3093   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3094
3095   // Handle the integer div common cases
3096   if (Instruction *Common = commonIDivTransforms(I))
3097     return Common;
3098
3099   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3100     // sdiv X, -1 == -X
3101     if (RHS->isAllOnesValue())
3102       return BinaryOperator::CreateNeg(Op0);
3103
3104     // sdiv X, C  -->  ashr X, log2(C)
3105     if (cast<SDivOperator>(&I)->isExact() &&
3106         RHS->getValue().isNonNegative() &&
3107         RHS->getValue().isPowerOf2()) {
3108       Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3109                                             RHS->getValue().exactLogBase2());
3110       return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3111     }
3112
3113     // -X/C  -->  X/-C  provided the negation doesn't overflow.
3114     if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3115       if (isa<Constant>(Sub->getOperand(0)) &&
3116           cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3117           Sub->hasNoSignedWrap())
3118         return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3119                                           ConstantExpr::getNeg(RHS));
3120   }
3121
3122   // If the sign bits of both operands are zero (i.e. we can prove they are
3123   // unsigned inputs), turn this into a udiv.
3124   if (I.getType()->isInteger()) {
3125     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3126     if (MaskedValueIsZero(Op0, Mask)) {
3127       if (MaskedValueIsZero(Op1, Mask)) {
3128         // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3129         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3130       }
3131       ConstantInt *ShiftedInt;
3132       if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3133           ShiftedInt->getValue().isPowerOf2()) {
3134         // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3135         // Safe because the only negative value (1 << Y) can take on is
3136         // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3137         // the sign bit set.
3138         return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3139       }
3140     }
3141   }
3142   
3143   return 0;
3144 }
3145
3146 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3147   return commonDivTransforms(I);
3148 }
3149
3150 /// This function implements the transforms on rem instructions that work
3151 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3152 /// is used by the visitors to those instructions.
3153 /// @brief Transforms common to all three rem instructions
3154 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3155   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3156
3157   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3158     if (I.getType()->isFPOrFPVector())
3159       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3160     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3161   }
3162   if (isa<UndefValue>(Op1))
3163     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3164
3165   // Handle cases involving: rem X, (select Cond, Y, Z)
3166   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3167     return &I;
3168
3169   return 0;
3170 }
3171
3172 /// This function implements the transforms common to both integer remainder
3173 /// instructions (urem and srem). It is called by the visitors to those integer
3174 /// remainder instructions.
3175 /// @brief Common integer remainder transforms
3176 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3177   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3178
3179   if (Instruction *common = commonRemTransforms(I))
3180     return common;
3181
3182   // 0 % X == 0 for integer, we don't need to preserve faults!
3183   if (Constant *LHS = dyn_cast<Constant>(Op0))
3184     if (LHS->isNullValue())
3185       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3186
3187   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3188     // X % 0 == undef, we don't need to preserve faults!
3189     if (RHS->equalsInt(0))
3190       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3191     
3192     if (RHS->equalsInt(1))  // X % 1 == 0
3193       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3194
3195     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3196       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3197         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3198           return R;
3199       } else if (isa<PHINode>(Op0I)) {
3200         if (Instruction *NV = FoldOpIntoPhi(I))
3201           return NV;
3202       }
3203
3204       // See if we can fold away this rem instruction.
3205       if (SimplifyDemandedInstructionBits(I))
3206         return &I;
3207     }
3208   }
3209
3210   return 0;
3211 }
3212
3213 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3214   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3215
3216   if (Instruction *common = commonIRemTransforms(I))
3217     return common;
3218   
3219   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3220     // X urem C^2 -> X and C
3221     // Check to see if this is an unsigned remainder with an exact power of 2,
3222     // if so, convert to a bitwise and.
3223     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3224       if (C->getValue().isPowerOf2())
3225         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3226   }
3227
3228   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3229     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3230     if (RHSI->getOpcode() == Instruction::Shl &&
3231         isa<ConstantInt>(RHSI->getOperand(0))) {
3232       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3233         Constant *N1 = Constant::getAllOnesValue(I.getType());
3234         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3235                                                                    "tmp"), I);
3236         return BinaryOperator::CreateAnd(Op0, Add);
3237       }
3238     }
3239   }
3240
3241   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3242   // where C1&C2 are powers of two.
3243   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3244     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3245       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3246         // STO == 0 and SFO == 0 handled above.
3247         if ((STO->getValue().isPowerOf2()) && 
3248             (SFO->getValue().isPowerOf2())) {
3249           Value *TrueAnd = InsertNewInstBefore(
3250             BinaryOperator::CreateAnd(Op0, SubOne(STO),
3251                                       SI->getName()+".t"), I);
3252           Value *FalseAnd = InsertNewInstBefore(
3253             BinaryOperator::CreateAnd(Op0, SubOne(SFO),
3254                                       SI->getName()+".f"), I);
3255           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3256         }
3257       }
3258   }
3259   
3260   return 0;
3261 }
3262
3263 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3264   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3265
3266   // Handle the integer rem common cases
3267   if (Instruction *common = commonIRemTransforms(I))
3268     return common;
3269   
3270   if (Value *RHSNeg = dyn_castNegVal(Op1))
3271     if (!isa<Constant>(RHSNeg) ||
3272         (isa<ConstantInt>(RHSNeg) &&
3273          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3274       // X % -Y -> X % Y
3275       AddUsesToWorkList(I);
3276       I.setOperand(1, RHSNeg);
3277       return &I;
3278     }
3279
3280   // If the sign bits of both operands are zero (i.e. we can prove they are
3281   // unsigned inputs), turn this into a urem.
3282   if (I.getType()->isInteger()) {
3283     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3284     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3285       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3286       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3287     }
3288   }
3289
3290   // If it's a constant vector, flip any negative values positive.
3291   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3292     unsigned VWidth = RHSV->getNumOperands();
3293
3294     bool hasNegative = false;
3295     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3296       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3297         if (RHS->getValue().isNegative())
3298           hasNegative = true;
3299
3300     if (hasNegative) {
3301       std::vector<Constant *> Elts(VWidth);
3302       for (unsigned i = 0; i != VWidth; ++i) {
3303         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3304           if (RHS->getValue().isNegative())
3305             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3306           else
3307             Elts[i] = RHS;
3308         }
3309       }
3310
3311       Constant *NewRHSV = ConstantVector::get(Elts);
3312       if (NewRHSV != RHSV) {
3313         AddUsesToWorkList(I);
3314         I.setOperand(1, NewRHSV);
3315         return &I;
3316       }
3317     }
3318   }
3319
3320   return 0;
3321 }
3322
3323 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3324   return commonRemTransforms(I);
3325 }
3326
3327 // isOneBitSet - Return true if there is exactly one bit set in the specified
3328 // constant.
3329 static bool isOneBitSet(const ConstantInt *CI) {
3330   return CI->getValue().isPowerOf2();
3331 }
3332
3333 // isHighOnes - Return true if the constant is of the form 1+0+.
3334 // This is the same as lowones(~X).
3335 static bool isHighOnes(const ConstantInt *CI) {
3336   return (~CI->getValue() + 1).isPowerOf2();
3337 }
3338
3339 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3340 /// are carefully arranged to allow folding of expressions such as:
3341 ///
3342 ///      (A < B) | (A > B) --> (A != B)
3343 ///
3344 /// Note that this is only valid if the first and second predicates have the
3345 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3346 ///
3347 /// Three bits are used to represent the condition, as follows:
3348 ///   0  A > B
3349 ///   1  A == B
3350 ///   2  A < B
3351 ///
3352 /// <=>  Value  Definition
3353 /// 000     0   Always false
3354 /// 001     1   A >  B
3355 /// 010     2   A == B
3356 /// 011     3   A >= B
3357 /// 100     4   A <  B
3358 /// 101     5   A != B
3359 /// 110     6   A <= B
3360 /// 111     7   Always true
3361 ///  
3362 static unsigned getICmpCode(const ICmpInst *ICI) {
3363   switch (ICI->getPredicate()) {
3364     // False -> 0
3365   case ICmpInst::ICMP_UGT: return 1;  // 001
3366   case ICmpInst::ICMP_SGT: return 1;  // 001
3367   case ICmpInst::ICMP_EQ:  return 2;  // 010
3368   case ICmpInst::ICMP_UGE: return 3;  // 011
3369   case ICmpInst::ICMP_SGE: return 3;  // 011
3370   case ICmpInst::ICMP_ULT: return 4;  // 100
3371   case ICmpInst::ICMP_SLT: return 4;  // 100
3372   case ICmpInst::ICMP_NE:  return 5;  // 101
3373   case ICmpInst::ICMP_ULE: return 6;  // 110
3374   case ICmpInst::ICMP_SLE: return 6;  // 110
3375     // True -> 7
3376   default:
3377     llvm_unreachable("Invalid ICmp predicate!");
3378     return 0;
3379   }
3380 }
3381
3382 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3383 /// predicate into a three bit mask. It also returns whether it is an ordered
3384 /// predicate by reference.
3385 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3386   isOrdered = false;
3387   switch (CC) {
3388   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3389   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3390   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3391   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3392   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3393   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3394   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3395   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3396   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3397   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3398   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3399   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3400   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3401   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3402     // True -> 7
3403   default:
3404     // Not expecting FCMP_FALSE and FCMP_TRUE;
3405     llvm_unreachable("Unexpected FCmp predicate!");
3406     return 0;
3407   }
3408 }
3409
3410 /// getICmpValue - This is the complement of getICmpCode, which turns an
3411 /// opcode and two operands into either a constant true or false, or a brand 
3412 /// new ICmp instruction. The sign is passed in to determine which kind
3413 /// of predicate to use in the new icmp instruction.
3414 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3415                            LLVMContext *Context) {
3416   switch (code) {
3417   default: llvm_unreachable("Illegal ICmp code!");
3418   case  0: return ConstantInt::getFalse(*Context);
3419   case  1: 
3420     if (sign)
3421       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3422     else
3423       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3424   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3425   case  3: 
3426     if (sign)
3427       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3428     else
3429       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3430   case  4: 
3431     if (sign)
3432       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3433     else
3434       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3435   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3436   case  6: 
3437     if (sign)
3438       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3439     else
3440       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3441   case  7: return ConstantInt::getTrue(*Context);
3442   }
3443 }
3444
3445 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3446 /// opcode and two operands into either a FCmp instruction. isordered is passed
3447 /// in to determine which kind of predicate to use in the new fcmp instruction.
3448 static Value *getFCmpValue(bool isordered, unsigned code,
3449                            Value *LHS, Value *RHS, LLVMContext *Context) {
3450   switch (code) {
3451   default: llvm_unreachable("Illegal FCmp code!");
3452   case  0:
3453     if (isordered)
3454       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3455     else
3456       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3457   case  1: 
3458     if (isordered)
3459       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3460     else
3461       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3462   case  2: 
3463     if (isordered)
3464       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3465     else
3466       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3467   case  3: 
3468     if (isordered)
3469       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3470     else
3471       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3472   case  4: 
3473     if (isordered)
3474       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3475     else
3476       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3477   case  5: 
3478     if (isordered)
3479       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3480     else
3481       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3482   case  6: 
3483     if (isordered)
3484       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3485     else
3486       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3487   case  7: return ConstantInt::getTrue(*Context);
3488   }
3489 }
3490
3491 /// PredicatesFoldable - Return true if both predicates match sign or if at
3492 /// least one of them is an equality comparison (which is signless).
3493 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3494   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3495          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3496          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3497 }
3498
3499 namespace { 
3500 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3501 struct FoldICmpLogical {
3502   InstCombiner &IC;
3503   Value *LHS, *RHS;
3504   ICmpInst::Predicate pred;
3505   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3506     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3507       pred(ICI->getPredicate()) {}
3508   bool shouldApply(Value *V) const {
3509     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3510       if (PredicatesFoldable(pred, ICI->getPredicate()))
3511         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3512                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3513     return false;
3514   }
3515   Instruction *apply(Instruction &Log) const {
3516     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3517     if (ICI->getOperand(0) != LHS) {
3518       assert(ICI->getOperand(1) == LHS);
3519       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3520     }
3521
3522     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3523     unsigned LHSCode = getICmpCode(ICI);
3524     unsigned RHSCode = getICmpCode(RHSICI);
3525     unsigned Code;
3526     switch (Log.getOpcode()) {
3527     case Instruction::And: Code = LHSCode & RHSCode; break;
3528     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3529     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3530     default: llvm_unreachable("Illegal logical opcode!"); return 0;
3531     }
3532
3533     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3534                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3535       
3536     Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3537     if (Instruction *I = dyn_cast<Instruction>(RV))
3538       return I;
3539     // Otherwise, it's a constant boolean value...
3540     return IC.ReplaceInstUsesWith(Log, RV);
3541   }
3542 };
3543 } // end anonymous namespace
3544
3545 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3546 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3547 // guaranteed to be a binary operator.
3548 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3549                                     ConstantInt *OpRHS,
3550                                     ConstantInt *AndRHS,
3551                                     BinaryOperator &TheAnd) {
3552   Value *X = Op->getOperand(0);
3553   Constant *Together = 0;
3554   if (!Op->isShift())
3555     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3556
3557   switch (Op->getOpcode()) {
3558   case Instruction::Xor:
3559     if (Op->hasOneUse()) {
3560       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3561       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3562       InsertNewInstBefore(And, TheAnd);
3563       And->takeName(Op);
3564       return BinaryOperator::CreateXor(And, Together);
3565     }
3566     break;
3567   case Instruction::Or:
3568     if (Together == AndRHS) // (X | C) & C --> C
3569       return ReplaceInstUsesWith(TheAnd, AndRHS);
3570
3571     if (Op->hasOneUse() && Together != OpRHS) {
3572       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3573       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3574       InsertNewInstBefore(Or, TheAnd);
3575       Or->takeName(Op);
3576       return BinaryOperator::CreateAnd(Or, AndRHS);
3577     }
3578     break;
3579   case Instruction::Add:
3580     if (Op->hasOneUse()) {
3581       // Adding a one to a single bit bit-field should be turned into an XOR
3582       // of the bit.  First thing to check is to see if this AND is with a
3583       // single bit constant.
3584       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3585
3586       // If there is only one bit set...
3587       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3588         // Ok, at this point, we know that we are masking the result of the
3589         // ADD down to exactly one bit.  If the constant we are adding has
3590         // no bits set below this bit, then we can eliminate the ADD.
3591         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3592
3593         // Check to see if any bits below the one bit set in AndRHSV are set.
3594         if ((AddRHS & (AndRHSV-1)) == 0) {
3595           // If not, the only thing that can effect the output of the AND is
3596           // the bit specified by AndRHSV.  If that bit is set, the effect of
3597           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3598           // no effect.
3599           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3600             TheAnd.setOperand(0, X);
3601             return &TheAnd;
3602           } else {
3603             // Pull the XOR out of the AND.
3604             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3605             InsertNewInstBefore(NewAnd, TheAnd);
3606             NewAnd->takeName(Op);
3607             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3608           }
3609         }
3610       }
3611     }
3612     break;
3613
3614   case Instruction::Shl: {
3615     // We know that the AND will not produce any of the bits shifted in, so if
3616     // the anded constant includes them, clear them now!
3617     //
3618     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3619     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3620     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3621     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3622
3623     if (CI->getValue() == ShlMask) { 
3624     // Masking out bits that the shift already masks
3625       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3626     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3627       TheAnd.setOperand(1, CI);
3628       return &TheAnd;
3629     }
3630     break;
3631   }
3632   case Instruction::LShr:
3633   {
3634     // We know that the AND will not produce any of the bits shifted in, so if
3635     // the anded constant includes them, clear them now!  This only applies to
3636     // unsigned shifts, because a signed shr may bring in set bits!
3637     //
3638     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3639     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3640     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3641     ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3642
3643     if (CI->getValue() == ShrMask) {   
3644     // Masking out bits that the shift already masks.
3645       return ReplaceInstUsesWith(TheAnd, Op);
3646     } else if (CI != AndRHS) {
3647       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3648       return &TheAnd;
3649     }
3650     break;
3651   }
3652   case Instruction::AShr:
3653     // Signed shr.
3654     // See if this is shifting in some sign extension, then masking it out
3655     // with an and.
3656     if (Op->hasOneUse()) {
3657       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3658       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3659       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3660       Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3661       if (C == AndRHS) {          // Masking out bits shifted in.
3662         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3663         // Make the argument unsigned.
3664         Value *ShVal = Op->getOperand(0);
3665         ShVal = InsertNewInstBefore(
3666             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3667                                    Op->getName()), TheAnd);
3668         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3669       }
3670     }
3671     break;
3672   }
3673   return 0;
3674 }
3675
3676
3677 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3678 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3679 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3680 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3681 /// insert new instructions.
3682 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3683                                            bool isSigned, bool Inside, 
3684                                            Instruction &IB) {
3685   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3686             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3687          "Lo is not <= Hi in range emission code!");
3688     
3689   if (Inside) {
3690     if (Lo == Hi)  // Trivially false.
3691       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3692
3693     // V >= Min && V < Hi --> V < Hi
3694     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3695       ICmpInst::Predicate pred = (isSigned ? 
3696         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3697       return new ICmpInst(pred, V, Hi);
3698     }
3699
3700     // Emit V-Lo <u Hi-Lo
3701     Constant *NegLo = ConstantExpr::getNeg(Lo);
3702     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3703     InsertNewInstBefore(Add, IB);
3704     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3705     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3706   }
3707
3708   if (Lo == Hi)  // Trivially true.
3709     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3710
3711   // V < Min || V >= Hi -> V > Hi-1
3712   Hi = SubOne(cast<ConstantInt>(Hi));
3713   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3714     ICmpInst::Predicate pred = (isSigned ? 
3715         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3716     return new ICmpInst(pred, V, Hi);
3717   }
3718
3719   // Emit V-Lo >u Hi-1-Lo
3720   // Note that Hi has already had one subtracted from it, above.
3721   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3722   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3723   InsertNewInstBefore(Add, IB);
3724   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3725   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3726 }
3727
3728 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3729 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3730 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3731 // not, since all 1s are not contiguous.
3732 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3733   const APInt& V = Val->getValue();
3734   uint32_t BitWidth = Val->getType()->getBitWidth();
3735   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3736
3737   // look for the first zero bit after the run of ones
3738   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3739   // look for the first non-zero bit
3740   ME = V.getActiveBits(); 
3741   return true;
3742 }
3743
3744 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3745 /// where isSub determines whether the operator is a sub.  If we can fold one of
3746 /// the following xforms:
3747 /// 
3748 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3749 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3750 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3751 ///
3752 /// return (A +/- B).
3753 ///
3754 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3755                                         ConstantInt *Mask, bool isSub,
3756                                         Instruction &I) {
3757   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3758   if (!LHSI || LHSI->getNumOperands() != 2 ||
3759       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3760
3761   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3762
3763   switch (LHSI->getOpcode()) {
3764   default: return 0;
3765   case Instruction::And:
3766     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3767       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3768       if ((Mask->getValue().countLeadingZeros() + 
3769            Mask->getValue().countPopulation()) == 
3770           Mask->getValue().getBitWidth())
3771         break;
3772
3773       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3774       // part, we don't need any explicit masks to take them out of A.  If that
3775       // is all N is, ignore it.
3776       uint32_t MB = 0, ME = 0;
3777       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3778         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3779         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3780         if (MaskedValueIsZero(RHS, Mask))
3781           break;
3782       }
3783     }
3784     return 0;
3785   case Instruction::Or:
3786   case Instruction::Xor:
3787     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3788     if ((Mask->getValue().countLeadingZeros() + 
3789          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3790         && ConstantExpr::getAnd(N, Mask)->isNullValue())
3791       break;
3792     return 0;
3793   }
3794   
3795   Instruction *New;
3796   if (isSub)
3797     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3798   else
3799     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3800   return InsertNewInstBefore(New, I);
3801 }
3802
3803 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3804 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3805                                           ICmpInst *LHS, ICmpInst *RHS) {
3806   Value *Val, *Val2;
3807   ConstantInt *LHSCst, *RHSCst;
3808   ICmpInst::Predicate LHSCC, RHSCC;
3809   
3810   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3811   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3812                          m_ConstantInt(LHSCst))) ||
3813       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3814                          m_ConstantInt(RHSCst))))
3815     return 0;
3816   
3817   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3818   // where C is a power of 2
3819   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3820       LHSCst->getValue().isPowerOf2()) {
3821     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3822     InsertNewInstBefore(NewOr, I);
3823     return new ICmpInst(LHSCC, NewOr, LHSCst);
3824   }
3825   
3826   // From here on, we only handle:
3827   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3828   if (Val != Val2) return 0;
3829   
3830   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3831   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3832       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3833       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3834       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3835     return 0;
3836   
3837   // We can't fold (ugt x, C) & (sgt x, C2).
3838   if (!PredicatesFoldable(LHSCC, RHSCC))
3839     return 0;
3840     
3841   // Ensure that the larger constant is on the RHS.
3842   bool ShouldSwap;
3843   if (ICmpInst::isSignedPredicate(LHSCC) ||
3844       (ICmpInst::isEquality(LHSCC) && 
3845        ICmpInst::isSignedPredicate(RHSCC)))
3846     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3847   else
3848     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3849     
3850   if (ShouldSwap) {
3851     std::swap(LHS, RHS);
3852     std::swap(LHSCst, RHSCst);
3853     std::swap(LHSCC, RHSCC);
3854   }
3855
3856   // At this point, we know we have have two icmp instructions
3857   // comparing a value against two constants and and'ing the result
3858   // together.  Because of the above check, we know that we only have
3859   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3860   // (from the FoldICmpLogical check above), that the two constants 
3861   // are not equal and that the larger constant is on the RHS
3862   assert(LHSCst != RHSCst && "Compares not folded above?");
3863
3864   switch (LHSCC) {
3865   default: llvm_unreachable("Unknown integer condition code!");
3866   case ICmpInst::ICMP_EQ:
3867     switch (RHSCC) {
3868     default: llvm_unreachable("Unknown integer condition code!");
3869     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3870     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3871     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3872       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3873     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3874     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3875     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3876       return ReplaceInstUsesWith(I, LHS);
3877     }
3878   case ICmpInst::ICMP_NE:
3879     switch (RHSCC) {
3880     default: llvm_unreachable("Unknown integer condition code!");
3881     case ICmpInst::ICMP_ULT:
3882       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3883         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3884       break;                        // (X != 13 & X u< 15) -> no change
3885     case ICmpInst::ICMP_SLT:
3886       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3887         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3888       break;                        // (X != 13 & X s< 15) -> no change
3889     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3890     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3891     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3892       return ReplaceInstUsesWith(I, RHS);
3893     case ICmpInst::ICMP_NE:
3894       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3895         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3896         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3897                                                      Val->getName()+".off");
3898         InsertNewInstBefore(Add, I);
3899         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3900                             ConstantInt::get(Add->getType(), 1));
3901       }
3902       break;                        // (X != 13 & X != 15) -> no change
3903     }
3904     break;
3905   case ICmpInst::ICMP_ULT:
3906     switch (RHSCC) {
3907     default: llvm_unreachable("Unknown integer condition code!");
3908     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3909     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3910       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3911     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3912       break;
3913     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3914     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3915       return ReplaceInstUsesWith(I, LHS);
3916     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3917       break;
3918     }
3919     break;
3920   case ICmpInst::ICMP_SLT:
3921     switch (RHSCC) {
3922     default: llvm_unreachable("Unknown integer condition code!");
3923     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3924     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3925       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3926     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3927       break;
3928     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3929     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3930       return ReplaceInstUsesWith(I, LHS);
3931     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3932       break;
3933     }
3934     break;
3935   case ICmpInst::ICMP_UGT:
3936     switch (RHSCC) {
3937     default: llvm_unreachable("Unknown integer condition code!");
3938     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3939     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3940       return ReplaceInstUsesWith(I, RHS);
3941     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3942       break;
3943     case ICmpInst::ICMP_NE:
3944       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3945         return new ICmpInst(LHSCC, Val, RHSCst);
3946       break;                        // (X u> 13 & X != 15) -> no change
3947     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3948       return InsertRangeTest(Val, AddOne(LHSCst),
3949                              RHSCst, false, true, I);
3950     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3951       break;
3952     }
3953     break;
3954   case ICmpInst::ICMP_SGT:
3955     switch (RHSCC) {
3956     default: llvm_unreachable("Unknown integer condition code!");
3957     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3958     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3959       return ReplaceInstUsesWith(I, RHS);
3960     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3961       break;
3962     case ICmpInst::ICMP_NE:
3963       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3964         return new ICmpInst(LHSCC, Val, RHSCst);
3965       break;                        // (X s> 13 & X != 15) -> no change
3966     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3967       return InsertRangeTest(Val, AddOne(LHSCst),
3968                              RHSCst, true, true, I);
3969     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3970       break;
3971     }
3972     break;
3973   }
3974  
3975   return 0;
3976 }
3977
3978 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3979                                           FCmpInst *RHS) {
3980   
3981   if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3982       RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3983     // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3984     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3985       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3986         // If either of the constants are nans, then the whole thing returns
3987         // false.
3988         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3989           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3990         return new FCmpInst(FCmpInst::FCMP_ORD,
3991                             LHS->getOperand(0), RHS->getOperand(0));
3992       }
3993     
3994     // Handle vector zeros.  This occurs because the canonical form of
3995     // "fcmp ord x,x" is "fcmp ord x, 0".
3996     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3997         isa<ConstantAggregateZero>(RHS->getOperand(1)))
3998       return new FCmpInst(FCmpInst::FCMP_ORD,
3999                           LHS->getOperand(0), RHS->getOperand(0));
4000     return 0;
4001   }
4002   
4003   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4004   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4005   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4006   
4007   
4008   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4009     // Swap RHS operands to match LHS.
4010     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4011     std::swap(Op1LHS, Op1RHS);
4012   }
4013   
4014   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4015     // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4016     if (Op0CC == Op1CC)
4017       return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4018     
4019     if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4020       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4021     if (Op0CC == FCmpInst::FCMP_TRUE)
4022       return ReplaceInstUsesWith(I, RHS);
4023     if (Op1CC == FCmpInst::FCMP_TRUE)
4024       return ReplaceInstUsesWith(I, LHS);
4025     
4026     bool Op0Ordered;
4027     bool Op1Ordered;
4028     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4029     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4030     if (Op1Pred == 0) {
4031       std::swap(LHS, RHS);
4032       std::swap(Op0Pred, Op1Pred);
4033       std::swap(Op0Ordered, Op1Ordered);
4034     }
4035     if (Op0Pred == 0) {
4036       // uno && ueq -> uno && (uno || eq) -> ueq
4037       // ord && olt -> ord && (ord && lt) -> olt
4038       if (Op0Ordered == Op1Ordered)
4039         return ReplaceInstUsesWith(I, RHS);
4040       
4041       // uno && oeq -> uno && (ord && eq) -> false
4042       // uno && ord -> false
4043       if (!Op0Ordered)
4044         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4045       // ord && ueq -> ord && (uno || eq) -> oeq
4046       return cast<Instruction>(getFCmpValue(true, Op1Pred,
4047                                             Op0LHS, Op0RHS, Context));
4048     }
4049   }
4050
4051   return 0;
4052 }
4053
4054
4055 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4056   bool Changed = SimplifyCommutative(I);
4057   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4058
4059   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4060     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4061
4062   // and X, X = X
4063   if (Op0 == Op1)
4064     return ReplaceInstUsesWith(I, Op1);
4065
4066   // See if we can simplify any instructions used by the instruction whose sole 
4067   // purpose is to compute bits we don't care about.
4068   if (SimplifyDemandedInstructionBits(I))
4069     return &I;
4070   if (isa<VectorType>(I.getType())) {
4071     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4072       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4073         return ReplaceInstUsesWith(I, I.getOperand(0));
4074     } else if (isa<ConstantAggregateZero>(Op1)) {
4075       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4076     }
4077   }
4078
4079   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4080     const APInt& AndRHSMask = AndRHS->getValue();
4081     APInt NotAndRHS(~AndRHSMask);
4082
4083     // Optimize a variety of ((val OP C1) & C2) combinations...
4084     if (isa<BinaryOperator>(Op0)) {
4085       Instruction *Op0I = cast<Instruction>(Op0);
4086       Value *Op0LHS = Op0I->getOperand(0);
4087       Value *Op0RHS = Op0I->getOperand(1);
4088       switch (Op0I->getOpcode()) {
4089       case Instruction::Xor:
4090       case Instruction::Or:
4091         // If the mask is only needed on one incoming arm, push it up.
4092         if (Op0I->hasOneUse()) {
4093           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4094             // Not masking anything out for the LHS, move to RHS.
4095             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4096                                                    Op0RHS->getName()+".masked");
4097             InsertNewInstBefore(NewRHS, I);
4098             return BinaryOperator::Create(
4099                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4100           }
4101           if (!isa<Constant>(Op0RHS) &&
4102               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4103             // Not masking anything out for the RHS, move to LHS.
4104             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4105                                                    Op0LHS->getName()+".masked");
4106             InsertNewInstBefore(NewLHS, I);
4107             return BinaryOperator::Create(
4108                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4109           }
4110         }
4111
4112         break;
4113       case Instruction::Add:
4114         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4115         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4116         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4117         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4118           return BinaryOperator::CreateAnd(V, AndRHS);
4119         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4120           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4121         break;
4122
4123       case Instruction::Sub:
4124         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4125         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4126         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4127         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4128           return BinaryOperator::CreateAnd(V, AndRHS);
4129
4130         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4131         // has 1's for all bits that the subtraction with A might affect.
4132         if (Op0I->hasOneUse()) {
4133           uint32_t BitWidth = AndRHSMask.getBitWidth();
4134           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4135           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4136
4137           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4138           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4139               MaskedValueIsZero(Op0LHS, Mask)) {
4140             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4141             InsertNewInstBefore(NewNeg, I);
4142             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4143           }
4144         }
4145         break;
4146
4147       case Instruction::Shl:
4148       case Instruction::LShr:
4149         // (1 << x) & 1 --> zext(x == 0)
4150         // (1 >> x) & 1 --> zext(x == 0)
4151         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4152           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ,
4153                                     Op0RHS, Constant::getNullValue(I.getType()));
4154           InsertNewInstBefore(NewICmp, I);
4155           return new ZExtInst(NewICmp, I.getType());
4156         }
4157         break;
4158       }
4159
4160       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4161         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4162           return Res;
4163     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4164       // If this is an integer truncation or change from signed-to-unsigned, and
4165       // if the source is an and/or with immediate, transform it.  This
4166       // frequently occurs for bitfield accesses.
4167       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4168         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4169             CastOp->getNumOperands() == 2)
4170           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4171             if (CastOp->getOpcode() == Instruction::And) {
4172               // Change: and (cast (and X, C1) to T), C2
4173               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4174               // This will fold the two constants together, which may allow 
4175               // other simplifications.
4176               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4177                 CastOp->getOperand(0), I.getType(), 
4178                 CastOp->getName()+".shrunk");
4179               NewCast = InsertNewInstBefore(NewCast, I);
4180               // trunc_or_bitcast(C1)&C2
4181               Constant *C3 =
4182                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4183               C3 = ConstantExpr::getAnd(C3, AndRHS);
4184               return BinaryOperator::CreateAnd(NewCast, C3);
4185             } else if (CastOp->getOpcode() == Instruction::Or) {
4186               // Change: and (cast (or X, C1) to T), C2
4187               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4188               Constant *C3 =
4189                       ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4190               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4191                 // trunc(C1)&C2
4192                 return ReplaceInstUsesWith(I, AndRHS);
4193             }
4194           }
4195       }
4196     }
4197
4198     // Try to fold constant and into select arguments.
4199     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4200       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4201         return R;
4202     if (isa<PHINode>(Op0))
4203       if (Instruction *NV = FoldOpIntoPhi(I))
4204         return NV;
4205   }
4206
4207   Value *Op0NotVal = dyn_castNotVal(Op0);
4208   Value *Op1NotVal = dyn_castNotVal(Op1);
4209
4210   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4211     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4212
4213   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4214   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4215     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4216                                                I.getName()+".demorgan");
4217     InsertNewInstBefore(Or, I);
4218     return BinaryOperator::CreateNot(Or);
4219   }
4220   
4221   {
4222     Value *A = 0, *B = 0, *C = 0, *D = 0;
4223     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4224       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4225         return ReplaceInstUsesWith(I, Op1);
4226     
4227       // (A|B) & ~(A&B) -> A^B
4228       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4229         if ((A == C && B == D) || (A == D && B == C))
4230           return BinaryOperator::CreateXor(A, B);
4231       }
4232     }
4233     
4234     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4235       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4236         return ReplaceInstUsesWith(I, Op0);
4237
4238       // ~(A&B) & (A|B) -> A^B
4239       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4240         if ((A == C && B == D) || (A == D && B == C))
4241           return BinaryOperator::CreateXor(A, B);
4242       }
4243     }
4244     
4245     if (Op0->hasOneUse() &&
4246         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4247       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4248         I.swapOperands();     // Simplify below
4249         std::swap(Op0, Op1);
4250       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4251         cast<BinaryOperator>(Op0)->swapOperands();
4252         I.swapOperands();     // Simplify below
4253         std::swap(Op0, Op1);
4254       }
4255     }
4256
4257     if (Op1->hasOneUse() &&
4258         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4259       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4260         cast<BinaryOperator>(Op1)->swapOperands();
4261         std::swap(A, B);
4262       }
4263       if (A == Op0) {                                // A&(A^B) -> A & ~B
4264         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4265         InsertNewInstBefore(NotB, I);
4266         return BinaryOperator::CreateAnd(A, NotB);
4267       }
4268     }
4269
4270     // (A&((~A)|B)) -> A&B
4271     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4272         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4273       return BinaryOperator::CreateAnd(A, Op1);
4274     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4275         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4276       return BinaryOperator::CreateAnd(A, Op0);
4277   }
4278   
4279   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4280     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4281     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4282       return R;
4283
4284     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4285       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4286         return Res;
4287   }
4288
4289   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4290   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4291     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4292       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4293         const Type *SrcTy = Op0C->getOperand(0)->getType();
4294         if (SrcTy == Op1C->getOperand(0)->getType() &&
4295             SrcTy->isIntOrIntVector() &&
4296             // Only do this if the casts both really cause code to be generated.
4297             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4298                               I.getType(), TD) &&
4299             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4300                               I.getType(), TD)) {
4301           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4302                                                          Op1C->getOperand(0),
4303                                                          I.getName());
4304           InsertNewInstBefore(NewOp, I);
4305           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4306         }
4307       }
4308     
4309   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4310   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4311     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4312       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4313           SI0->getOperand(1) == SI1->getOperand(1) &&
4314           (SI0->hasOneUse() || SI1->hasOneUse())) {
4315         Instruction *NewOp =
4316           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4317                                                         SI1->getOperand(0),
4318                                                         SI0->getName()), I);
4319         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4320                                       SI1->getOperand(1));
4321       }
4322   }
4323
4324   // If and'ing two fcmp, try combine them into one.
4325   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4326     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4327       if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4328         return Res;
4329   }
4330
4331   return Changed ? &I : 0;
4332 }
4333
4334 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4335 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4336 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4337 /// the expression came from the corresponding "byte swapped" byte in some other
4338 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4339 /// we know that the expression deposits the low byte of %X into the high byte
4340 /// of the bswap result and that all other bytes are zero.  This expression is
4341 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4342 /// match.
4343 ///
4344 /// This function returns true if the match was unsuccessful and false if so.
4345 /// On entry to the function the "OverallLeftShift" is a signed integer value
4346 /// indicating the number of bytes that the subexpression is later shifted.  For
4347 /// example, if the expression is later right shifted by 16 bits, the
4348 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4349 /// byte of ByteValues is actually being set.
4350 ///
4351 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4352 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4353 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4354 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4355 /// always in the local (OverallLeftShift) coordinate space.
4356 ///
4357 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4358                               SmallVector<Value*, 8> &ByteValues) {
4359   if (Instruction *I = dyn_cast<Instruction>(V)) {
4360     // If this is an or instruction, it may be an inner node of the bswap.
4361     if (I->getOpcode() == Instruction::Or) {
4362       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4363                                ByteValues) ||
4364              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4365                                ByteValues);
4366     }
4367   
4368     // If this is a logical shift by a constant multiple of 8, recurse with
4369     // OverallLeftShift and ByteMask adjusted.
4370     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4371       unsigned ShAmt = 
4372         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4373       // Ensure the shift amount is defined and of a byte value.
4374       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4375         return true;
4376
4377       unsigned ByteShift = ShAmt >> 3;
4378       if (I->getOpcode() == Instruction::Shl) {
4379         // X << 2 -> collect(X, +2)
4380         OverallLeftShift += ByteShift;
4381         ByteMask >>= ByteShift;
4382       } else {
4383         // X >>u 2 -> collect(X, -2)
4384         OverallLeftShift -= ByteShift;
4385         ByteMask <<= ByteShift;
4386         ByteMask &= (~0U >> (32-ByteValues.size()));
4387       }
4388
4389       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4390       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4391
4392       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4393                                ByteValues);
4394     }
4395
4396     // If this is a logical 'and' with a mask that clears bytes, clear the
4397     // corresponding bytes in ByteMask.
4398     if (I->getOpcode() == Instruction::And &&
4399         isa<ConstantInt>(I->getOperand(1))) {
4400       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4401       unsigned NumBytes = ByteValues.size();
4402       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4403       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4404       
4405       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4406         // If this byte is masked out by a later operation, we don't care what
4407         // the and mask is.
4408         if ((ByteMask & (1 << i)) == 0)
4409           continue;
4410         
4411         // If the AndMask is all zeros for this byte, clear the bit.
4412         APInt MaskB = AndMask & Byte;
4413         if (MaskB == 0) {
4414           ByteMask &= ~(1U << i);
4415           continue;
4416         }
4417         
4418         // If the AndMask is not all ones for this byte, it's not a bytezap.
4419         if (MaskB != Byte)
4420           return true;
4421
4422         // Otherwise, this byte is kept.
4423       }
4424
4425       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4426                                ByteValues);
4427     }
4428   }
4429   
4430   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4431   // the input value to the bswap.  Some observations: 1) if more than one byte
4432   // is demanded from this input, then it could not be successfully assembled
4433   // into a byteswap.  At least one of the two bytes would not be aligned with
4434   // their ultimate destination.
4435   if (!isPowerOf2_32(ByteMask)) return true;
4436   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4437   
4438   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4439   // is demanded, it needs to go into byte 0 of the result.  This means that the
4440   // byte needs to be shifted until it lands in the right byte bucket.  The
4441   // shift amount depends on the position: if the byte is coming from the high
4442   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4443   // low part, it must be shifted left.
4444   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4445   if (InputByteNo < ByteValues.size()/2) {
4446     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4447       return true;
4448   } else {
4449     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4450       return true;
4451   }
4452   
4453   // If the destination byte value is already defined, the values are or'd
4454   // together, which isn't a bswap (unless it's an or of the same bits).
4455   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4456     return true;
4457   ByteValues[DestByteNo] = V;
4458   return false;
4459 }
4460
4461 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4462 /// If so, insert the new bswap intrinsic and return it.
4463 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4464   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4465   if (!ITy || ITy->getBitWidth() % 16 || 
4466       // ByteMask only allows up to 32-byte values.
4467       ITy->getBitWidth() > 32*8) 
4468     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4469   
4470   /// ByteValues - For each byte of the result, we keep track of which value
4471   /// defines each byte.
4472   SmallVector<Value*, 8> ByteValues;
4473   ByteValues.resize(ITy->getBitWidth()/8);
4474     
4475   // Try to find all the pieces corresponding to the bswap.
4476   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4477   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4478     return 0;
4479   
4480   // Check to see if all of the bytes come from the same value.
4481   Value *V = ByteValues[0];
4482   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4483   
4484   // Check to make sure that all of the bytes come from the same value.
4485   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4486     if (ByteValues[i] != V)
4487       return 0;
4488   const Type *Tys[] = { ITy };
4489   Module *M = I.getParent()->getParent()->getParent();
4490   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4491   return CallInst::Create(F, V);
4492 }
4493
4494 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4495 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4496 /// we can simplify this expression to "cond ? C : D or B".
4497 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4498                                          Value *C, Value *D,
4499                                          LLVMContext *Context) {
4500   // If A is not a select of -1/0, this cannot match.
4501   Value *Cond = 0;
4502   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4503     return 0;
4504
4505   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4506   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4507     return SelectInst::Create(Cond, C, B);
4508   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4509     return SelectInst::Create(Cond, C, B);
4510   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4511   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4512     return SelectInst::Create(Cond, C, D);
4513   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4514     return SelectInst::Create(Cond, C, D);
4515   return 0;
4516 }
4517
4518 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4519 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4520                                          ICmpInst *LHS, ICmpInst *RHS) {
4521   Value *Val, *Val2;
4522   ConstantInt *LHSCst, *RHSCst;
4523   ICmpInst::Predicate LHSCC, RHSCC;
4524   
4525   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4526   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4527              m_ConstantInt(LHSCst))) ||
4528       !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4529              m_ConstantInt(RHSCst))))
4530     return 0;
4531   
4532   // From here on, we only handle:
4533   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4534   if (Val != Val2) return 0;
4535   
4536   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4537   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4538       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4539       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4540       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4541     return 0;
4542   
4543   // We can't fold (ugt x, C) | (sgt x, C2).
4544   if (!PredicatesFoldable(LHSCC, RHSCC))
4545     return 0;
4546   
4547   // Ensure that the larger constant is on the RHS.
4548   bool ShouldSwap;
4549   if (ICmpInst::isSignedPredicate(LHSCC) ||
4550       (ICmpInst::isEquality(LHSCC) && 
4551        ICmpInst::isSignedPredicate(RHSCC)))
4552     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4553   else
4554     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4555   
4556   if (ShouldSwap) {
4557     std::swap(LHS, RHS);
4558     std::swap(LHSCst, RHSCst);
4559     std::swap(LHSCC, RHSCC);
4560   }
4561   
4562   // At this point, we know we have have two icmp instructions
4563   // comparing a value against two constants and or'ing the result
4564   // together.  Because of the above check, we know that we only have
4565   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4566   // FoldICmpLogical check above), that the two constants are not
4567   // equal.
4568   assert(LHSCst != RHSCst && "Compares not folded above?");
4569
4570   switch (LHSCC) {
4571   default: llvm_unreachable("Unknown integer condition code!");
4572   case ICmpInst::ICMP_EQ:
4573     switch (RHSCC) {
4574     default: llvm_unreachable("Unknown integer condition code!");
4575     case ICmpInst::ICMP_EQ:
4576       if (LHSCst == SubOne(RHSCst)) {
4577         // (X == 13 | X == 14) -> X-13 <u 2
4578         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4579         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4580                                                      Val->getName()+".off");
4581         InsertNewInstBefore(Add, I);
4582         AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4583         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4584       }
4585       break;                         // (X == 13 | X == 15) -> no change
4586     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4587     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4588       break;
4589     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4590     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4591     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4592       return ReplaceInstUsesWith(I, RHS);
4593     }
4594     break;
4595   case ICmpInst::ICMP_NE:
4596     switch (RHSCC) {
4597     default: llvm_unreachable("Unknown integer condition code!");
4598     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4599     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4600     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4601       return ReplaceInstUsesWith(I, LHS);
4602     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4603     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4604     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4605       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4606     }
4607     break;
4608   case ICmpInst::ICMP_ULT:
4609     switch (RHSCC) {
4610     default: llvm_unreachable("Unknown integer condition code!");
4611     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4612       break;
4613     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4614       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4615       // this can cause overflow.
4616       if (RHSCst->isMaxValue(false))
4617         return ReplaceInstUsesWith(I, LHS);
4618       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4619                              false, false, I);
4620     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4621       break;
4622     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4623     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4624       return ReplaceInstUsesWith(I, RHS);
4625     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4626       break;
4627     }
4628     break;
4629   case ICmpInst::ICMP_SLT:
4630     switch (RHSCC) {
4631     default: llvm_unreachable("Unknown integer condition code!");
4632     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4633       break;
4634     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4635       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4636       // this can cause overflow.
4637       if (RHSCst->isMaxValue(true))
4638         return ReplaceInstUsesWith(I, LHS);
4639       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4640                              true, false, I);
4641     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4642       break;
4643     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4644     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4645       return ReplaceInstUsesWith(I, RHS);
4646     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4647       break;
4648     }
4649     break;
4650   case ICmpInst::ICMP_UGT:
4651     switch (RHSCC) {
4652     default: llvm_unreachable("Unknown integer condition code!");
4653     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4654     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4655       return ReplaceInstUsesWith(I, LHS);
4656     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4657       break;
4658     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4659     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4660       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4661     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4662       break;
4663     }
4664     break;
4665   case ICmpInst::ICMP_SGT:
4666     switch (RHSCC) {
4667     default: llvm_unreachable("Unknown integer condition code!");
4668     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4669     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4670       return ReplaceInstUsesWith(I, LHS);
4671     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4672       break;
4673     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4674     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4675       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4676     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4677       break;
4678     }
4679     break;
4680   }
4681   return 0;
4682 }
4683
4684 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4685                                          FCmpInst *RHS) {
4686   if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4687       RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4688       LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4689     if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4690       if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4691         // If either of the constants are nans, then the whole thing returns
4692         // true.
4693         if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4694           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4695         
4696         // Otherwise, no need to compare the two constants, compare the
4697         // rest.
4698         return new FCmpInst(FCmpInst::FCMP_UNO,
4699                             LHS->getOperand(0), RHS->getOperand(0));
4700       }
4701     
4702     // Handle vector zeros.  This occurs because the canonical form of
4703     // "fcmp uno x,x" is "fcmp uno x, 0".
4704     if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4705         isa<ConstantAggregateZero>(RHS->getOperand(1)))
4706       return new FCmpInst(FCmpInst::FCMP_UNO,
4707                           LHS->getOperand(0), RHS->getOperand(0));
4708     
4709     return 0;
4710   }
4711   
4712   Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4713   Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4714   FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4715   
4716   if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4717     // Swap RHS operands to match LHS.
4718     Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4719     std::swap(Op1LHS, Op1RHS);
4720   }
4721   if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4722     // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4723     if (Op0CC == Op1CC)
4724       return new FCmpInst((FCmpInst::Predicate)Op0CC,
4725                           Op0LHS, Op0RHS);
4726     if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4727       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4728     if (Op0CC == FCmpInst::FCMP_FALSE)
4729       return ReplaceInstUsesWith(I, RHS);
4730     if (Op1CC == FCmpInst::FCMP_FALSE)
4731       return ReplaceInstUsesWith(I, LHS);
4732     bool Op0Ordered;
4733     bool Op1Ordered;
4734     unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4735     unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4736     if (Op0Ordered == Op1Ordered) {
4737       // If both are ordered or unordered, return a new fcmp with
4738       // or'ed predicates.
4739       Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4740                                Op0LHS, Op0RHS, Context);
4741       if (Instruction *I = dyn_cast<Instruction>(RV))
4742         return I;
4743       // Otherwise, it's a constant boolean value...
4744       return ReplaceInstUsesWith(I, RV);
4745     }
4746   }
4747   return 0;
4748 }
4749
4750 /// FoldOrWithConstants - This helper function folds:
4751 ///
4752 ///     ((A | B) & C1) | (B & C2)
4753 ///
4754 /// into:
4755 /// 
4756 ///     (A & C1) | B
4757 ///
4758 /// when the XOR of the two constants is "all ones" (-1).
4759 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4760                                                Value *A, Value *B, Value *C) {
4761   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4762   if (!CI1) return 0;
4763
4764   Value *V1 = 0;
4765   ConstantInt *CI2 = 0;
4766   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4767
4768   APInt Xor = CI1->getValue() ^ CI2->getValue();
4769   if (!Xor.isAllOnesValue()) return 0;
4770
4771   if (V1 == A || V1 == B) {
4772     Instruction *NewOp =
4773       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4774     return BinaryOperator::CreateOr(NewOp, V1);
4775   }
4776
4777   return 0;
4778 }
4779
4780 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4781   bool Changed = SimplifyCommutative(I);
4782   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4783
4784   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4785     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4786
4787   // or X, X = X
4788   if (Op0 == Op1)
4789     return ReplaceInstUsesWith(I, Op0);
4790
4791   // See if we can simplify any instructions used by the instruction whose sole 
4792   // purpose is to compute bits we don't care about.
4793   if (SimplifyDemandedInstructionBits(I))
4794     return &I;
4795   if (isa<VectorType>(I.getType())) {
4796     if (isa<ConstantAggregateZero>(Op1)) {
4797       return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4798     } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4799       if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4800         return ReplaceInstUsesWith(I, I.getOperand(1));
4801     }
4802   }
4803
4804   // or X, -1 == -1
4805   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4806     ConstantInt *C1 = 0; Value *X = 0;
4807     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4808     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4809         isOnlyUse(Op0)) {
4810       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4811       InsertNewInstBefore(Or, I);
4812       Or->takeName(Op0);
4813       return BinaryOperator::CreateAnd(Or, 
4814                ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4815     }
4816
4817     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4818     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4819         isOnlyUse(Op0)) {
4820       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4821       InsertNewInstBefore(Or, I);
4822       Or->takeName(Op0);
4823       return BinaryOperator::CreateXor(Or,
4824                  ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4825     }
4826
4827     // Try to fold constant and into select arguments.
4828     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4829       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4830         return R;
4831     if (isa<PHINode>(Op0))
4832       if (Instruction *NV = FoldOpIntoPhi(I))
4833         return NV;
4834   }
4835
4836   Value *A = 0, *B = 0;
4837   ConstantInt *C1 = 0, *C2 = 0;
4838
4839   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4840     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4841       return ReplaceInstUsesWith(I, Op1);
4842   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4843     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4844       return ReplaceInstUsesWith(I, Op0);
4845
4846   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4847   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4848   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4849       match(Op1, m_Or(m_Value(), m_Value())) ||
4850       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4851        match(Op1, m_Shift(m_Value(), m_Value())))) {
4852     if (Instruction *BSwap = MatchBSwap(I))
4853       return BSwap;
4854   }
4855   
4856   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4857   if (Op0->hasOneUse() &&
4858       match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4859       MaskedValueIsZero(Op1, C1->getValue())) {
4860     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4861     InsertNewInstBefore(NOr, I);
4862     NOr->takeName(Op0);
4863     return BinaryOperator::CreateXor(NOr, C1);
4864   }
4865
4866   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4867   if (Op1->hasOneUse() &&
4868       match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4869       MaskedValueIsZero(Op0, C1->getValue())) {
4870     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4871     InsertNewInstBefore(NOr, I);
4872     NOr->takeName(Op0);
4873     return BinaryOperator::CreateXor(NOr, C1);
4874   }
4875
4876   // (A & C)|(B & D)
4877   Value *C = 0, *D = 0;
4878   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4879       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4880     Value *V1 = 0, *V2 = 0, *V3 = 0;
4881     C1 = dyn_cast<ConstantInt>(C);
4882     C2 = dyn_cast<ConstantInt>(D);
4883     if (C1 && C2) {  // (A & C1)|(B & C2)
4884       // If we have: ((V + N) & C1) | (V & C2)
4885       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4886       // replace with V+N.
4887       if (C1->getValue() == ~C2->getValue()) {
4888         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4889             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4890           // Add commutes, try both ways.
4891           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4892             return ReplaceInstUsesWith(I, A);
4893           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4894             return ReplaceInstUsesWith(I, A);
4895         }
4896         // Or commutes, try both ways.
4897         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4898             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4899           // Add commutes, try both ways.
4900           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4901             return ReplaceInstUsesWith(I, B);
4902           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4903             return ReplaceInstUsesWith(I, B);
4904         }
4905       }
4906       V1 = 0; V2 = 0; V3 = 0;
4907     }
4908     
4909     // Check to see if we have any common things being and'ed.  If so, find the
4910     // terms for V1 & (V2|V3).
4911     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4912       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4913         V1 = A, V2 = C, V3 = D;
4914       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4915         V1 = A, V2 = B, V3 = C;
4916       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4917         V1 = C, V2 = A, V3 = D;
4918       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4919         V1 = C, V2 = A, V3 = B;
4920       
4921       if (V1) {
4922         Value *Or =
4923           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4924         return BinaryOperator::CreateAnd(V1, Or);
4925       }
4926     }
4927
4928     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4929     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4930       return Match;
4931     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4932       return Match;
4933     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4934       return Match;
4935     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4936       return Match;
4937
4938     // ((A&~B)|(~A&B)) -> A^B
4939     if ((match(C, m_Not(m_Specific(D))) &&
4940          match(B, m_Not(m_Specific(A)))))
4941       return BinaryOperator::CreateXor(A, D);
4942     // ((~B&A)|(~A&B)) -> A^B
4943     if ((match(A, m_Not(m_Specific(D))) &&
4944          match(B, m_Not(m_Specific(C)))))
4945       return BinaryOperator::CreateXor(C, D);
4946     // ((A&~B)|(B&~A)) -> A^B
4947     if ((match(C, m_Not(m_Specific(B))) &&
4948          match(D, m_Not(m_Specific(A)))))
4949       return BinaryOperator::CreateXor(A, B);
4950     // ((~B&A)|(B&~A)) -> A^B
4951     if ((match(A, m_Not(m_Specific(B))) &&
4952          match(D, m_Not(m_Specific(C)))))
4953       return BinaryOperator::CreateXor(C, B);
4954   }
4955   
4956   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4957   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4958     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4959       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4960           SI0->getOperand(1) == SI1->getOperand(1) &&
4961           (SI0->hasOneUse() || SI1->hasOneUse())) {
4962         Instruction *NewOp =
4963         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4964                                                      SI1->getOperand(0),
4965                                                      SI0->getName()), I);
4966         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4967                                       SI1->getOperand(1));
4968       }
4969   }
4970
4971   // ((A|B)&1)|(B&-2) -> (A&1) | B
4972   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4973       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4974     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4975     if (Ret) return Ret;
4976   }
4977   // (B&-2)|((A|B)&1) -> (A&1) | B
4978   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4979       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4980     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4981     if (Ret) return Ret;
4982   }
4983
4984   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4985     if (A == Op1)   // ~A | A == -1
4986       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4987   } else {
4988     A = 0;
4989   }
4990   // Note, A is still live here!
4991   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4992     if (Op0 == B)
4993       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4994
4995     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4996     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4997       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4998                                               I.getName()+".demorgan"), I);
4999       return BinaryOperator::CreateNot(And);
5000     }
5001   }
5002
5003   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5004   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5005     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5006       return R;
5007
5008     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5009       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5010         return Res;
5011   }
5012     
5013   // fold (or (cast A), (cast B)) -> (cast (or A, B))
5014   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5015     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5016       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5017         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5018             !isa<ICmpInst>(Op1C->getOperand(0))) {
5019           const Type *SrcTy = Op0C->getOperand(0)->getType();
5020           if (SrcTy == Op1C->getOperand(0)->getType() &&
5021               SrcTy->isIntOrIntVector() &&
5022               // Only do this if the casts both really cause code to be
5023               // generated.
5024               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5025                                 I.getType(), TD) &&
5026               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5027                                 I.getType(), TD)) {
5028             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
5029                                                           Op1C->getOperand(0),
5030                                                           I.getName());
5031             InsertNewInstBefore(NewOp, I);
5032             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5033           }
5034         }
5035       }
5036   }
5037   
5038     
5039   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
5040   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5041     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5042       if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5043         return Res;
5044   }
5045
5046   return Changed ? &I : 0;
5047 }
5048
5049 namespace {
5050
5051 // XorSelf - Implements: X ^ X --> 0
5052 struct XorSelf {
5053   Value *RHS;
5054   XorSelf(Value *rhs) : RHS(rhs) {}
5055   bool shouldApply(Value *LHS) const { return LHS == RHS; }
5056   Instruction *apply(BinaryOperator &Xor) const {
5057     return &Xor;
5058   }
5059 };
5060
5061 }
5062
5063 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5064   bool Changed = SimplifyCommutative(I);
5065   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5066
5067   if (isa<UndefValue>(Op1)) {
5068     if (isa<UndefValue>(Op0))
5069       // Handle undef ^ undef -> 0 special case. This is a common
5070       // idiom (misuse).
5071       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5072     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
5073   }
5074
5075   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5076   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5077     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5078     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5079   }
5080   
5081   // See if we can simplify any instructions used by the instruction whose sole 
5082   // purpose is to compute bits we don't care about.
5083   if (SimplifyDemandedInstructionBits(I))
5084     return &I;
5085   if (isa<VectorType>(I.getType()))
5086     if (isa<ConstantAggregateZero>(Op1))
5087       return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5088
5089   // Is this a ~ operation?
5090   if (Value *NotOp = dyn_castNotVal(&I)) {
5091     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5092     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5093     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5094       if (Op0I->getOpcode() == Instruction::And || 
5095           Op0I->getOpcode() == Instruction::Or) {
5096         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5097         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5098           Instruction *NotY =
5099             BinaryOperator::CreateNot(Op0I->getOperand(1),
5100                                       Op0I->getOperand(1)->getName()+".not");
5101           InsertNewInstBefore(NotY, I);
5102           if (Op0I->getOpcode() == Instruction::And)
5103             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5104           else
5105             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5106         }
5107       }
5108     }
5109   }
5110   
5111   
5112   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5113     if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5114       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5115       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5116         return new ICmpInst(ICI->getInversePredicate(),
5117                             ICI->getOperand(0), ICI->getOperand(1));
5118
5119       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5120         return new FCmpInst(FCI->getInversePredicate(),
5121                             FCI->getOperand(0), FCI->getOperand(1));
5122     }
5123
5124     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5125     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5126       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5127         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5128           Instruction::CastOps Opcode = Op0C->getOpcode();
5129           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5130             if (RHS == ConstantExpr::getCast(Opcode, 
5131                                              ConstantInt::getTrue(*Context),
5132                                              Op0C->getDestTy())) {
5133               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5134                                      CI->getOpcode(), CI->getInversePredicate(),
5135                                      CI->getOperand(0), CI->getOperand(1)), I);
5136               NewCI->takeName(CI);
5137               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5138             }
5139           }
5140         }
5141       }
5142     }
5143
5144     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5145       // ~(c-X) == X-c-1 == X+(-c-1)
5146       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5147         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5148           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5149           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5150                                       ConstantInt::get(I.getType(), 1));
5151           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5152         }
5153           
5154       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5155         if (Op0I->getOpcode() == Instruction::Add) {
5156           // ~(X-c) --> (-c-1)-X
5157           if (RHS->isAllOnesValue()) {
5158             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5159             return BinaryOperator::CreateSub(
5160                            ConstantExpr::getSub(NegOp0CI,
5161                                       ConstantInt::get(I.getType(), 1)),
5162                                       Op0I->getOperand(0));
5163           } else if (RHS->getValue().isSignBit()) {
5164             // (X + C) ^ signbit -> (X + C + signbit)
5165             Constant *C = ConstantInt::get(*Context,
5166                                            RHS->getValue() + Op0CI->getValue());
5167             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5168
5169           }
5170         } else if (Op0I->getOpcode() == Instruction::Or) {
5171           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5172           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5173             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5174             // Anything in both C1 and C2 is known to be zero, remove it from
5175             // NewRHS.
5176             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5177             NewRHS = ConstantExpr::getAnd(NewRHS, 
5178                                        ConstantExpr::getNot(CommonBits));
5179             AddToWorkList(Op0I);
5180             I.setOperand(0, Op0I->getOperand(0));
5181             I.setOperand(1, NewRHS);
5182             return &I;
5183           }
5184         }
5185       }
5186     }
5187
5188     // Try to fold constant and into select arguments.
5189     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5190       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5191         return R;
5192     if (isa<PHINode>(Op0))
5193       if (Instruction *NV = FoldOpIntoPhi(I))
5194         return NV;
5195   }
5196
5197   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5198     if (X == Op1)
5199       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5200
5201   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5202     if (X == Op0)
5203       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5204
5205   
5206   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5207   if (Op1I) {
5208     Value *A, *B;
5209     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5210       if (A == Op0) {              // B^(B|A) == (A|B)^B
5211         Op1I->swapOperands();
5212         I.swapOperands();
5213         std::swap(Op0, Op1);
5214       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5215         I.swapOperands();     // Simplified below.
5216         std::swap(Op0, Op1);
5217       }
5218     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5219       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5220     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5221       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5222     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && 
5223                Op1I->hasOneUse()){
5224       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5225         Op1I->swapOperands();
5226         std::swap(A, B);
5227       }
5228       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5229         I.swapOperands();     // Simplified below.
5230         std::swap(Op0, Op1);
5231       }
5232     }
5233   }
5234   
5235   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5236   if (Op0I) {
5237     Value *A, *B;
5238     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5239         Op0I->hasOneUse()) {
5240       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5241         std::swap(A, B);
5242       if (B == Op1) {                                // (A|B)^B == A & ~B
5243         Instruction *NotB =
5244           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5245         return BinaryOperator::CreateAnd(A, NotB);
5246       }
5247     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5248       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5249     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5250       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5251     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && 
5252                Op0I->hasOneUse()){
5253       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5254         std::swap(A, B);
5255       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5256           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5257         Instruction *N =
5258           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5259         return BinaryOperator::CreateAnd(N, Op1);
5260       }
5261     }
5262   }
5263   
5264   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5265   if (Op0I && Op1I && Op0I->isShift() && 
5266       Op0I->getOpcode() == Op1I->getOpcode() && 
5267       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5268       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5269     Instruction *NewOp =
5270       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5271                                                     Op1I->getOperand(0),
5272                                                     Op0I->getName()), I);
5273     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5274                                   Op1I->getOperand(1));
5275   }
5276     
5277   if (Op0I && Op1I) {
5278     Value *A, *B, *C, *D;
5279     // (A & B)^(A | B) -> A ^ B
5280     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5281         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5282       if ((A == C && B == D) || (A == D && B == C)) 
5283         return BinaryOperator::CreateXor(A, B);
5284     }
5285     // (A | B)^(A & B) -> A ^ B
5286     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5287         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5288       if ((A == C && B == D) || (A == D && B == C)) 
5289         return BinaryOperator::CreateXor(A, B);
5290     }
5291     
5292     // (A & B)^(C & D)
5293     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5294         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5295         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5296       // (X & Y)^(X & Y) -> (Y^Z) & X
5297       Value *X = 0, *Y = 0, *Z = 0;
5298       if (A == C)
5299         X = A, Y = B, Z = D;
5300       else if (A == D)
5301         X = A, Y = B, Z = C;
5302       else if (B == C)
5303         X = B, Y = A, Z = D;
5304       else if (B == D)
5305         X = B, Y = A, Z = C;
5306       
5307       if (X) {
5308         Instruction *NewOp =
5309         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5310         return BinaryOperator::CreateAnd(NewOp, X);
5311       }
5312     }
5313   }
5314     
5315   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5316   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5317     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5318       return R;
5319
5320   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5321   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5322     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5323       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5324         const Type *SrcTy = Op0C->getOperand(0)->getType();
5325         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5326             // Only do this if the casts both really cause code to be generated.
5327             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5328                               I.getType(), TD) &&
5329             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5330                               I.getType(), TD)) {
5331           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5332                                                          Op1C->getOperand(0),
5333                                                          I.getName());
5334           InsertNewInstBefore(NewOp, I);
5335           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5336         }
5337       }
5338   }
5339
5340   return Changed ? &I : 0;
5341 }
5342
5343 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5344                                    LLVMContext *Context) {
5345   return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5346 }
5347
5348 static bool HasAddOverflow(ConstantInt *Result,
5349                            ConstantInt *In1, ConstantInt *In2,
5350                            bool IsSigned) {
5351   if (IsSigned)
5352     if (In2->getValue().isNegative())
5353       return Result->getValue().sgt(In1->getValue());
5354     else
5355       return Result->getValue().slt(In1->getValue());
5356   else
5357     return Result->getValue().ult(In1->getValue());
5358 }
5359
5360 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5361 /// overflowed for this type.
5362 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5363                             Constant *In2, LLVMContext *Context,
5364                             bool IsSigned = false) {
5365   Result = ConstantExpr::getAdd(In1, In2);
5366
5367   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5368     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5369       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5370       if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5371                          ExtractElement(In1, Idx, Context),
5372                          ExtractElement(In2, Idx, Context),
5373                          IsSigned))
5374         return true;
5375     }
5376     return false;
5377   }
5378
5379   return HasAddOverflow(cast<ConstantInt>(Result),
5380                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5381                         IsSigned);
5382 }
5383
5384 static bool HasSubOverflow(ConstantInt *Result,
5385                            ConstantInt *In1, ConstantInt *In2,
5386                            bool IsSigned) {
5387   if (IsSigned)
5388     if (In2->getValue().isNegative())
5389       return Result->getValue().slt(In1->getValue());
5390     else
5391       return Result->getValue().sgt(In1->getValue());
5392   else
5393     return Result->getValue().ugt(In1->getValue());
5394 }
5395
5396 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5397 /// overflowed for this type.
5398 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5399                             Constant *In2, LLVMContext *Context,
5400                             bool IsSigned = false) {
5401   Result = ConstantExpr::getSub(In1, In2);
5402
5403   if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5404     for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5405       Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5406       if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5407                          ExtractElement(In1, Idx, Context),
5408                          ExtractElement(In2, Idx, Context),
5409                          IsSigned))
5410         return true;
5411     }
5412     return false;
5413   }
5414
5415   return HasSubOverflow(cast<ConstantInt>(Result),
5416                         cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5417                         IsSigned);
5418 }
5419
5420 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5421 /// code necessary to compute the offset from the base pointer (without adding
5422 /// in the base pointer).  Return the result as a signed integer of intptr size.
5423 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5424   TargetData &TD = *IC.getTargetData();
5425   gep_type_iterator GTI = gep_type_begin(GEP);
5426   const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5427   LLVMContext *Context = IC.getContext();
5428   Value *Result = Constant::getNullValue(IntPtrTy);
5429
5430   // Build a mask for high order bits.
5431   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5432   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5433
5434   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5435        ++i, ++GTI) {
5436     Value *Op = *i;
5437     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5438     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5439       if (OpC->isZero()) continue;
5440       
5441       // Handle a struct index, which adds its field offset to the pointer.
5442       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5443         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5444         
5445         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5446           Result = 
5447              ConstantInt::get(*Context, 
5448                               RC->getValue() + APInt(IntPtrWidth, Size));
5449         else
5450           Result = IC.InsertNewInstBefore(
5451                    BinaryOperator::CreateAdd(Result,
5452                                         ConstantInt::get(IntPtrTy, Size),
5453                                              GEP->getName()+".offs"), I);
5454         continue;
5455       }
5456       
5457       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5458       Constant *OC =
5459               ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5460       Scale = ConstantExpr::getMul(OC, Scale);
5461       if (Constant *RC = dyn_cast<Constant>(Result))
5462         Result = ConstantExpr::getAdd(RC, Scale);
5463       else {
5464         // Emit an add instruction.
5465         Result = IC.InsertNewInstBefore(
5466            BinaryOperator::CreateAdd(Result, Scale,
5467                                      GEP->getName()+".offs"), I);
5468       }
5469       continue;
5470     }
5471     // Convert to correct type.
5472     if (Op->getType() != IntPtrTy) {
5473       if (Constant *OpC = dyn_cast<Constant>(Op))
5474         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5475       else
5476         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5477                                                                 true,
5478                                                       Op->getName()+".c"), I);
5479     }
5480     if (Size != 1) {
5481       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5482       if (Constant *OpC = dyn_cast<Constant>(Op))
5483         Op = ConstantExpr::getMul(OpC, Scale);
5484       else    // We'll let instcombine(mul) convert this to a shl if possible.
5485         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5486                                                   GEP->getName()+".idx"), I);
5487     }
5488
5489     // Emit an add instruction.
5490     if (isa<Constant>(Op) && isa<Constant>(Result))
5491       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5492                                     cast<Constant>(Result));
5493     else
5494       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5495                                                   GEP->getName()+".offs"), I);
5496   }
5497   return Result;
5498 }
5499
5500
5501 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5502 /// the *offset* implied by a GEP to zero.  For example, if we have &A[i], we
5503 /// want to return 'i' for "icmp ne i, 0".  Note that, in general, indices can
5504 /// be complex, and scales are involved.  The above expression would also be
5505 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5506 /// This later form is less amenable to optimization though, and we are allowed
5507 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5508 ///
5509 /// If we can't emit an optimized form for this expression, this returns null.
5510 /// 
5511 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5512                                           InstCombiner &IC) {
5513   TargetData &TD = *IC.getTargetData();
5514   gep_type_iterator GTI = gep_type_begin(GEP);
5515
5516   // Check to see if this gep only has a single variable index.  If so, and if
5517   // any constant indices are a multiple of its scale, then we can compute this
5518   // in terms of the scale of the variable index.  For example, if the GEP
5519   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5520   // because the expression will cross zero at the same point.
5521   unsigned i, e = GEP->getNumOperands();
5522   int64_t Offset = 0;
5523   for (i = 1; i != e; ++i, ++GTI) {
5524     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5525       // Compute the aggregate offset of constant indices.
5526       if (CI->isZero()) continue;
5527
5528       // Handle a struct index, which adds its field offset to the pointer.
5529       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5530         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5531       } else {
5532         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5533         Offset += Size*CI->getSExtValue();
5534       }
5535     } else {
5536       // Found our variable index.
5537       break;
5538     }
5539   }
5540   
5541   // If there are no variable indices, we must have a constant offset, just
5542   // evaluate it the general way.
5543   if (i == e) return 0;
5544   
5545   Value *VariableIdx = GEP->getOperand(i);
5546   // Determine the scale factor of the variable element.  For example, this is
5547   // 4 if the variable index is into an array of i32.
5548   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5549   
5550   // Verify that there are no other variable indices.  If so, emit the hard way.
5551   for (++i, ++GTI; i != e; ++i, ++GTI) {
5552     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5553     if (!CI) return 0;
5554    
5555     // Compute the aggregate offset of constant indices.
5556     if (CI->isZero()) continue;
5557     
5558     // Handle a struct index, which adds its field offset to the pointer.
5559     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5560       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5561     } else {
5562       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5563       Offset += Size*CI->getSExtValue();
5564     }
5565   }
5566   
5567   // Okay, we know we have a single variable index, which must be a
5568   // pointer/array/vector index.  If there is no offset, life is simple, return
5569   // the index.
5570   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5571   if (Offset == 0) {
5572     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5573     // we don't need to bother extending: the extension won't affect where the
5574     // computation crosses zero.
5575     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5576       VariableIdx = new TruncInst(VariableIdx, 
5577                                   TD.getIntPtrType(VariableIdx->getContext()),
5578                                   VariableIdx->getName(), &I);
5579     return VariableIdx;
5580   }
5581   
5582   // Otherwise, there is an index.  The computation we will do will be modulo
5583   // the pointer size, so get it.
5584   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5585   
5586   Offset &= PtrSizeMask;
5587   VariableScale &= PtrSizeMask;
5588
5589   // To do this transformation, any constant index must be a multiple of the
5590   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5591   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5592   // multiple of the variable scale.
5593   int64_t NewOffs = Offset / (int64_t)VariableScale;
5594   if (Offset != NewOffs*(int64_t)VariableScale)
5595     return 0;
5596
5597   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5598   const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5599   if (VariableIdx->getType() != IntPtrTy)
5600     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5601                                               true /*SExt*/, 
5602                                               VariableIdx->getName(), &I);
5603   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5604   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5605 }
5606
5607
5608 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5609 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5610 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5611                                        ICmpInst::Predicate Cond,
5612                                        Instruction &I) {
5613   // Look through bitcasts.
5614   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5615     RHS = BCI->getOperand(0);
5616
5617   Value *PtrBase = GEPLHS->getOperand(0);
5618   if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5619     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5620     // This transformation (ignoring the base and scales) is valid because we
5621     // know pointers can't overflow since the gep is inbounds.  See if we can
5622     // output an optimized form.
5623     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5624     
5625     // If not, synthesize the offset the hard way.
5626     if (Offset == 0)
5627       Offset = EmitGEPOffset(GEPLHS, I, *this);
5628     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5629                         Constant::getNullValue(Offset->getType()));
5630   } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5631     // If the base pointers are different, but the indices are the same, just
5632     // compare the base pointer.
5633     if (PtrBase != GEPRHS->getOperand(0)) {
5634       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5635       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5636                         GEPRHS->getOperand(0)->getType();
5637       if (IndicesTheSame)
5638         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5639           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5640             IndicesTheSame = false;
5641             break;
5642           }
5643
5644       // If all indices are the same, just compare the base pointers.
5645       if (IndicesTheSame)
5646         return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5647                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5648
5649       // Otherwise, the base pointers are different and the indices are
5650       // different, bail out.
5651       return 0;
5652     }
5653
5654     // If one of the GEPs has all zero indices, recurse.
5655     bool AllZeros = true;
5656     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5657       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5658           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5659         AllZeros = false;
5660         break;
5661       }
5662     if (AllZeros)
5663       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5664                           ICmpInst::getSwappedPredicate(Cond), I);
5665
5666     // If the other GEP has all zero indices, recurse.
5667     AllZeros = true;
5668     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5669       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5670           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5671         AllZeros = false;
5672         break;
5673       }
5674     if (AllZeros)
5675       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5676
5677     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5678       // If the GEPs only differ by one index, compare it.
5679       unsigned NumDifferences = 0;  // Keep track of # differences.
5680       unsigned DiffOperand = 0;     // The operand that differs.
5681       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5682         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5683           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5684                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5685             // Irreconcilable differences.
5686             NumDifferences = 2;
5687             break;
5688           } else {
5689             if (NumDifferences++) break;
5690             DiffOperand = i;
5691           }
5692         }
5693
5694       if (NumDifferences == 0)   // SAME GEP?
5695         return ReplaceInstUsesWith(I, // No comparison is needed here.
5696                                    ConstantInt::get(Type::getInt1Ty(*Context),
5697                                              ICmpInst::isTrueWhenEqual(Cond)));
5698
5699       else if (NumDifferences == 1) {
5700         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5701         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5702         // Make sure we do a signed comparison here.
5703         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5704       }
5705     }
5706
5707     // Only lower this if the icmp is the only user of the GEP or if we expect
5708     // the result to fold to a constant!
5709     if (TD &&
5710         (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5711         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5712       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5713       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5714       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5715       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5716     }
5717   }
5718   return 0;
5719 }
5720
5721 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5722 ///
5723 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5724                                                 Instruction *LHSI,
5725                                                 Constant *RHSC) {
5726   if (!isa<ConstantFP>(RHSC)) return 0;
5727   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5728   
5729   // Get the width of the mantissa.  We don't want to hack on conversions that
5730   // might lose information from the integer, e.g. "i64 -> float"
5731   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5732   if (MantissaWidth == -1) return 0;  // Unknown.
5733   
5734   // Check to see that the input is converted from an integer type that is small
5735   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5736   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5737   unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5738   
5739   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5740   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5741   if (LHSUnsigned)
5742     ++InputSize;
5743   
5744   // If the conversion would lose info, don't hack on this.
5745   if ((int)InputSize > MantissaWidth)
5746     return 0;
5747   
5748   // Otherwise, we can potentially simplify the comparison.  We know that it
5749   // will always come through as an integer value and we know the constant is
5750   // not a NAN (it would have been previously simplified).
5751   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5752   
5753   ICmpInst::Predicate Pred;
5754   switch (I.getPredicate()) {
5755   default: llvm_unreachable("Unexpected predicate!");
5756   case FCmpInst::FCMP_UEQ:
5757   case FCmpInst::FCMP_OEQ:
5758     Pred = ICmpInst::ICMP_EQ;
5759     break;
5760   case FCmpInst::FCMP_UGT:
5761   case FCmpInst::FCMP_OGT:
5762     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5763     break;
5764   case FCmpInst::FCMP_UGE:
5765   case FCmpInst::FCMP_OGE:
5766     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5767     break;
5768   case FCmpInst::FCMP_ULT:
5769   case FCmpInst::FCMP_OLT:
5770     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5771     break;
5772   case FCmpInst::FCMP_ULE:
5773   case FCmpInst::FCMP_OLE:
5774     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5775     break;
5776   case FCmpInst::FCMP_UNE:
5777   case FCmpInst::FCMP_ONE:
5778     Pred = ICmpInst::ICMP_NE;
5779     break;
5780   case FCmpInst::FCMP_ORD:
5781     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5782   case FCmpInst::FCMP_UNO:
5783     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5784   }
5785   
5786   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5787   
5788   // Now we know that the APFloat is a normal number, zero or inf.
5789   
5790   // See if the FP constant is too large for the integer.  For example,
5791   // comparing an i8 to 300.0.
5792   unsigned IntWidth = IntTy->getScalarSizeInBits();
5793   
5794   if (!LHSUnsigned) {
5795     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5796     // and large values.
5797     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5798     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5799                           APFloat::rmNearestTiesToEven);
5800     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5801       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5802           Pred == ICmpInst::ICMP_SLE)
5803         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5804       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5805     }
5806   } else {
5807     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5808     // +INF and large values.
5809     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5810     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5811                           APFloat::rmNearestTiesToEven);
5812     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5813       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5814           Pred == ICmpInst::ICMP_ULE)
5815         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5816       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5817     }
5818   }
5819   
5820   if (!LHSUnsigned) {
5821     // See if the RHS value is < SignedMin.
5822     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5823     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5824                           APFloat::rmNearestTiesToEven);
5825     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5826       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5827           Pred == ICmpInst::ICMP_SGE)
5828         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5829       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5830     }
5831   }
5832
5833   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5834   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5835   // casting the FP value to the integer value and back, checking for equality.
5836   // Don't do this for zero, because -0.0 is not fractional.
5837   Constant *RHSInt = LHSUnsigned
5838     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5839     : ConstantExpr::getFPToSI(RHSC, IntTy);
5840   if (!RHS.isZero()) {
5841     bool Equal = LHSUnsigned
5842       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5843       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5844     if (!Equal) {
5845       // If we had a comparison against a fractional value, we have to adjust
5846       // the compare predicate and sometimes the value.  RHSC is rounded towards
5847       // zero at this point.
5848       switch (Pred) {
5849       default: llvm_unreachable("Unexpected integer comparison!");
5850       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5851         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5852       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5853         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5854       case ICmpInst::ICMP_ULE:
5855         // (float)int <= 4.4   --> int <= 4
5856         // (float)int <= -4.4  --> false
5857         if (RHS.isNegative())
5858           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5859         break;
5860       case ICmpInst::ICMP_SLE:
5861         // (float)int <= 4.4   --> int <= 4
5862         // (float)int <= -4.4  --> int < -4
5863         if (RHS.isNegative())
5864           Pred = ICmpInst::ICMP_SLT;
5865         break;
5866       case ICmpInst::ICMP_ULT:
5867         // (float)int < -4.4   --> false
5868         // (float)int < 4.4    --> int <= 4
5869         if (RHS.isNegative())
5870           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5871         Pred = ICmpInst::ICMP_ULE;
5872         break;
5873       case ICmpInst::ICMP_SLT:
5874         // (float)int < -4.4   --> int < -4
5875         // (float)int < 4.4    --> int <= 4
5876         if (!RHS.isNegative())
5877           Pred = ICmpInst::ICMP_SLE;
5878         break;
5879       case ICmpInst::ICMP_UGT:
5880         // (float)int > 4.4    --> int > 4
5881         // (float)int > -4.4   --> true
5882         if (RHS.isNegative())
5883           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5884         break;
5885       case ICmpInst::ICMP_SGT:
5886         // (float)int > 4.4    --> int > 4
5887         // (float)int > -4.4   --> int >= -4
5888         if (RHS.isNegative())
5889           Pred = ICmpInst::ICMP_SGE;
5890         break;
5891       case ICmpInst::ICMP_UGE:
5892         // (float)int >= -4.4   --> true
5893         // (float)int >= 4.4    --> int > 4
5894         if (!RHS.isNegative())
5895           return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5896         Pred = ICmpInst::ICMP_UGT;
5897         break;
5898       case ICmpInst::ICMP_SGE:
5899         // (float)int >= -4.4   --> int >= -4
5900         // (float)int >= 4.4    --> int > 4
5901         if (!RHS.isNegative())
5902           Pred = ICmpInst::ICMP_SGT;
5903         break;
5904       }
5905     }
5906   }
5907
5908   // Lower this FP comparison into an appropriate integer version of the
5909   // comparison.
5910   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5911 }
5912
5913 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5914   bool Changed = SimplifyCompare(I);
5915   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5916
5917   // Fold trivial predicates.
5918   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5919     return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5920   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5921     return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5922   
5923   // Simplify 'fcmp pred X, X'
5924   if (Op0 == Op1) {
5925     switch (I.getPredicate()) {
5926     default: llvm_unreachable("Unknown predicate!");
5927     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5928     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5929     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5930       return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5931     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5932     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5933     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5934       return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5935       
5936     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5937     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5938     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5939     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5940       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5941       I.setPredicate(FCmpInst::FCMP_UNO);
5942       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5943       return &I;
5944       
5945     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5946     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5947     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5948     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5949       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5950       I.setPredicate(FCmpInst::FCMP_ORD);
5951       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5952       return &I;
5953     }
5954   }
5955     
5956   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5957     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5958
5959   // Handle fcmp with constant RHS
5960   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5961     // If the constant is a nan, see if we can fold the comparison based on it.
5962     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5963       if (CFP->getValueAPF().isNaN()) {
5964         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5965           return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5966         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5967                "Comparison must be either ordered or unordered!");
5968         // True if unordered.
5969         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5970       }
5971     }
5972     
5973     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5974       switch (LHSI->getOpcode()) {
5975       case Instruction::PHI:
5976         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5977         // block.  If in the same block, we're encouraging jump threading.  If
5978         // not, we are just pessimizing the code by making an i1 phi.
5979         if (LHSI->getParent() == I.getParent())
5980           if (Instruction *NV = FoldOpIntoPhi(I))
5981             return NV;
5982         break;
5983       case Instruction::SIToFP:
5984       case Instruction::UIToFP:
5985         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5986           return NV;
5987         break;
5988       case Instruction::Select:
5989         // If either operand of the select is a constant, we can fold the
5990         // comparison into the select arms, which will cause one to be
5991         // constant folded and the select turned into a bitwise or.
5992         Value *Op1 = 0, *Op2 = 0;
5993         if (LHSI->hasOneUse()) {
5994           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5995             // Fold the known value into the constant operand.
5996             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5997             // Insert a new FCmp of the other select operand.
5998             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5999                                                       LHSI->getOperand(2), RHSC,
6000                                                       I.getName()), I);
6001           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6002             // Fold the known value into the constant operand.
6003             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
6004             // Insert a new FCmp of the other select operand.
6005             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
6006                                                       LHSI->getOperand(1), RHSC,
6007                                                       I.getName()), I);
6008           }
6009         }
6010
6011         if (Op1)
6012           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6013         break;
6014       }
6015   }
6016
6017   return Changed ? &I : 0;
6018 }
6019
6020 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
6021   bool Changed = SimplifyCompare(I);
6022   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6023   const Type *Ty = Op0->getType();
6024
6025   // icmp X, X
6026   if (Op0 == Op1)
6027     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6028                                                    I.isTrueWhenEqual()));
6029
6030   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
6031     return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
6032   
6033   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6034   // addresses never equal each other!  We already know that Op0 != Op1.
6035   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6036        isa<ConstantPointerNull>(Op0)) &&
6037       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6038        isa<ConstantPointerNull>(Op1)))
6039     return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context), 
6040                                                    !I.isTrueWhenEqual()));
6041
6042   // icmp's with boolean values can always be turned into bitwise operations
6043   if (Ty == Type::getInt1Ty(*Context)) {
6044     switch (I.getPredicate()) {
6045     default: llvm_unreachable("Invalid icmp instruction!");
6046     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
6047       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6048       InsertNewInstBefore(Xor, I);
6049       return BinaryOperator::CreateNot(Xor);
6050     }
6051     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
6052       return BinaryOperator::CreateXor(Op0, Op1);
6053
6054     case ICmpInst::ICMP_UGT:
6055       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
6056       // FALL THROUGH
6057     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
6058       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6059       InsertNewInstBefore(Not, I);
6060       return BinaryOperator::CreateAnd(Not, Op1);
6061     }
6062     case ICmpInst::ICMP_SGT:
6063       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
6064       // FALL THROUGH
6065     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
6066       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6067       InsertNewInstBefore(Not, I);
6068       return BinaryOperator::CreateAnd(Not, Op0);
6069     }
6070     case ICmpInst::ICMP_UGE:
6071       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
6072       // FALL THROUGH
6073     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
6074       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6075       InsertNewInstBefore(Not, I);
6076       return BinaryOperator::CreateOr(Not, Op1);
6077     }
6078     case ICmpInst::ICMP_SGE:
6079       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
6080       // FALL THROUGH
6081     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
6082       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6083       InsertNewInstBefore(Not, I);
6084       return BinaryOperator::CreateOr(Not, Op0);
6085     }
6086     }
6087   }
6088
6089   unsigned BitWidth = 0;
6090   if (TD)
6091     BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6092   else if (Ty->isIntOrIntVector())
6093     BitWidth = Ty->getScalarSizeInBits();
6094
6095   bool isSignBit = false;
6096
6097   // See if we are doing a comparison with a constant.
6098   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6099     Value *A = 0, *B = 0;
6100     
6101     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6102     if (I.isEquality() && CI->isNullValue() &&
6103         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6104       // (icmp cond A B) if cond is equality
6105       return new ICmpInst(I.getPredicate(), A, B);
6106     }
6107     
6108     // If we have an icmp le or icmp ge instruction, turn it into the
6109     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
6110     // them being folded in the code below.
6111     switch (I.getPredicate()) {
6112     default: break;
6113     case ICmpInst::ICMP_ULE:
6114       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
6115         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6116       return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6117                           AddOne(CI));
6118     case ICmpInst::ICMP_SLE:
6119       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
6120         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6121       return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6122                           AddOne(CI));
6123     case ICmpInst::ICMP_UGE:
6124       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
6125         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6126       return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6127                           SubOne(CI));
6128     case ICmpInst::ICMP_SGE:
6129       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
6130         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6131       return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6132                           SubOne(CI));
6133     }
6134     
6135     // If this comparison is a normal comparison, it demands all
6136     // bits, if it is a sign bit comparison, it only demands the sign bit.
6137     bool UnusedBit;
6138     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6139   }
6140
6141   // See if we can fold the comparison based on range information we can get
6142   // by checking whether bits are known to be zero or one in the input.
6143   if (BitWidth != 0) {
6144     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6145     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6146
6147     if (SimplifyDemandedBits(I.getOperandUse(0),
6148                              isSignBit ? APInt::getSignBit(BitWidth)
6149                                        : APInt::getAllOnesValue(BitWidth),
6150                              Op0KnownZero, Op0KnownOne, 0))
6151       return &I;
6152     if (SimplifyDemandedBits(I.getOperandUse(1),
6153                              APInt::getAllOnesValue(BitWidth),
6154                              Op1KnownZero, Op1KnownOne, 0))
6155       return &I;
6156
6157     // Given the known and unknown bits, compute a range that the LHS could be
6158     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6159     // EQ and NE we use unsigned values.
6160     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6161     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6162     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6163       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6164                                              Op0Min, Op0Max);
6165       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6166                                              Op1Min, Op1Max);
6167     } else {
6168       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6169                                                Op0Min, Op0Max);
6170       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6171                                                Op1Min, Op1Max);
6172     }
6173
6174     // If Min and Max are known to be the same, then SimplifyDemandedBits
6175     // figured out that the LHS is a constant.  Just constant fold this now so
6176     // that code below can assume that Min != Max.
6177     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6178       return new ICmpInst(I.getPredicate(),
6179                           ConstantInt::get(*Context, Op0Min), Op1);
6180     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6181       return new ICmpInst(I.getPredicate(), Op0,
6182                           ConstantInt::get(*Context, Op1Min));
6183
6184     // Based on the range information we know about the LHS, see if we can
6185     // simplify this comparison.  For example, (x&4) < 8  is always true.
6186     switch (I.getPredicate()) {
6187     default: llvm_unreachable("Unknown icmp opcode!");
6188     case ICmpInst::ICMP_EQ:
6189       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6190         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6191       break;
6192     case ICmpInst::ICMP_NE:
6193       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6194         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6195       break;
6196     case ICmpInst::ICMP_ULT:
6197       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6198         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6199       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6200         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6201       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6202         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6203       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6204         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6205           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6206                               SubOne(CI));
6207
6208         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6209         if (CI->isMinValue(true))
6210           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6211                            Constant::getAllOnesValue(Op0->getType()));
6212       }
6213       break;
6214     case ICmpInst::ICMP_UGT:
6215       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6216         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6217       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6218         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6219
6220       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6221         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6222       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6223         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6224           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6225                               AddOne(CI));
6226
6227         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6228         if (CI->isMaxValue(true))
6229           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6230                               Constant::getNullValue(Op0->getType()));
6231       }
6232       break;
6233     case ICmpInst::ICMP_SLT:
6234       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6235         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6236       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6237         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6238       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6239         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6240       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6241         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6242           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6243                               SubOne(CI));
6244       }
6245       break;
6246     case ICmpInst::ICMP_SGT:
6247       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6248         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6249       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6250         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6251
6252       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6253         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6254       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6255         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6256           return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6257                               AddOne(CI));
6258       }
6259       break;
6260     case ICmpInst::ICMP_SGE:
6261       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6262       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6263         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6264       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6265         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6266       break;
6267     case ICmpInst::ICMP_SLE:
6268       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6269       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6270         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6271       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6272         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6273       break;
6274     case ICmpInst::ICMP_UGE:
6275       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6276       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6277         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6278       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6279         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6280       break;
6281     case ICmpInst::ICMP_ULE:
6282       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6283       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6284         return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6285       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6286         return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6287       break;
6288     }
6289
6290     // Turn a signed comparison into an unsigned one if both operands
6291     // are known to have the same sign.
6292     if (I.isSignedPredicate() &&
6293         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6294          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6295       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6296   }
6297
6298   // Test if the ICmpInst instruction is used exclusively by a select as
6299   // part of a minimum or maximum operation. If so, refrain from doing
6300   // any other folding. This helps out other analyses which understand
6301   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6302   // and CodeGen. And in this case, at least one of the comparison
6303   // operands has at least one user besides the compare (the select),
6304   // which would often largely negate the benefit of folding anyway.
6305   if (I.hasOneUse())
6306     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6307       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6308           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6309         return 0;
6310
6311   // See if we are doing a comparison between a constant and an instruction that
6312   // can be folded into the comparison.
6313   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6314     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6315     // instruction, see if that instruction also has constants so that the 
6316     // instruction can be folded into the icmp 
6317     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6318       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6319         return Res;
6320   }
6321
6322   // Handle icmp with constant (but not simple integer constant) RHS
6323   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6324     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6325       switch (LHSI->getOpcode()) {
6326       case Instruction::GetElementPtr:
6327         if (RHSC->isNullValue()) {
6328           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6329           bool isAllZeros = true;
6330           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6331             if (!isa<Constant>(LHSI->getOperand(i)) ||
6332                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6333               isAllZeros = false;
6334               break;
6335             }
6336           if (isAllZeros)
6337             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6338                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6339         }
6340         break;
6341
6342       case Instruction::PHI:
6343         // Only fold icmp into the PHI if the phi and fcmp are in the same
6344         // block.  If in the same block, we're encouraging jump threading.  If
6345         // not, we are just pessimizing the code by making an i1 phi.
6346         if (LHSI->getParent() == I.getParent())
6347           if (Instruction *NV = FoldOpIntoPhi(I))
6348             return NV;
6349         break;
6350       case Instruction::Select: {
6351         // If either operand of the select is a constant, we can fold the
6352         // comparison into the select arms, which will cause one to be
6353         // constant folded and the select turned into a bitwise or.
6354         Value *Op1 = 0, *Op2 = 0;
6355         if (LHSI->hasOneUse()) {
6356           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6357             // Fold the known value into the constant operand.
6358             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6359             // Insert a new ICmp of the other select operand.
6360             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6361                                                    LHSI->getOperand(2), RHSC,
6362                                                    I.getName()), I);
6363           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6364             // Fold the known value into the constant operand.
6365             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6366             // Insert a new ICmp of the other select operand.
6367             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6368                                                    LHSI->getOperand(1), RHSC,
6369                                                    I.getName()), I);
6370           }
6371         }
6372
6373         if (Op1)
6374           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6375         break;
6376       }
6377       case Instruction::Malloc:
6378         // If we have (malloc != null), and if the malloc has a single use, we
6379         // can assume it is successful and remove the malloc.
6380         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6381           AddToWorkList(LHSI);
6382           return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6383                                                          !I.isTrueWhenEqual()));
6384         }
6385         break;
6386       }
6387   }
6388
6389   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6390   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6391     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6392       return NI;
6393   if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6394     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6395                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6396       return NI;
6397
6398   // Test to see if the operands of the icmp are casted versions of other
6399   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6400   // now.
6401   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6402     if (isa<PointerType>(Op0->getType()) && 
6403         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6404       // We keep moving the cast from the left operand over to the right
6405       // operand, where it can often be eliminated completely.
6406       Op0 = CI->getOperand(0);
6407
6408       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6409       // so eliminate it as well.
6410       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6411         Op1 = CI2->getOperand(0);
6412
6413       // If Op1 is a constant, we can fold the cast into the constant.
6414       if (Op0->getType() != Op1->getType()) {
6415         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6416           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6417         } else {
6418           // Otherwise, cast the RHS right before the icmp
6419           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6420         }
6421       }
6422       return new ICmpInst(I.getPredicate(), Op0, Op1);
6423     }
6424   }
6425   
6426   if (isa<CastInst>(Op0)) {
6427     // Handle the special case of: icmp (cast bool to X), <cst>
6428     // This comes up when you have code like
6429     //   int X = A < B;
6430     //   if (X) ...
6431     // For generality, we handle any zero-extension of any operand comparison
6432     // with a constant or another cast from the same type.
6433     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6434       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6435         return R;
6436   }
6437   
6438   // See if it's the same type of instruction on the left and right.
6439   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6440     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6441       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6442           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6443         switch (Op0I->getOpcode()) {
6444         default: break;
6445         case Instruction::Add:
6446         case Instruction::Sub:
6447         case Instruction::Xor:
6448           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6449             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6450                                 Op1I->getOperand(0));
6451           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6452           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6453             if (CI->getValue().isSignBit()) {
6454               ICmpInst::Predicate Pred = I.isSignedPredicate()
6455                                              ? I.getUnsignedPredicate()
6456                                              : I.getSignedPredicate();
6457               return new ICmpInst(Pred, Op0I->getOperand(0),
6458                                   Op1I->getOperand(0));
6459             }
6460             
6461             if (CI->getValue().isMaxSignedValue()) {
6462               ICmpInst::Predicate Pred = I.isSignedPredicate()
6463                                              ? I.getUnsignedPredicate()
6464                                              : I.getSignedPredicate();
6465               Pred = I.getSwappedPredicate(Pred);
6466               return new ICmpInst(Pred, Op0I->getOperand(0),
6467                                   Op1I->getOperand(0));
6468             }
6469           }
6470           break;
6471         case Instruction::Mul:
6472           if (!I.isEquality())
6473             break;
6474
6475           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6476             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6477             // Mask = -1 >> count-trailing-zeros(Cst).
6478             if (!CI->isZero() && !CI->isOne()) {
6479               const APInt &AP = CI->getValue();
6480               ConstantInt *Mask = ConstantInt::get(*Context, 
6481                                       APInt::getLowBitsSet(AP.getBitWidth(),
6482                                                            AP.getBitWidth() -
6483                                                       AP.countTrailingZeros()));
6484               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6485                                                             Mask);
6486               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6487                                                             Mask);
6488               InsertNewInstBefore(And1, I);
6489               InsertNewInstBefore(And2, I);
6490               return new ICmpInst(I.getPredicate(), And1, And2);
6491             }
6492           }
6493           break;
6494         }
6495       }
6496     }
6497   }
6498   
6499   // ~x < ~y --> y < x
6500   { Value *A, *B;
6501     if (match(Op0, m_Not(m_Value(A))) &&
6502         match(Op1, m_Not(m_Value(B))))
6503       return new ICmpInst(I.getPredicate(), B, A);
6504   }
6505   
6506   if (I.isEquality()) {
6507     Value *A, *B, *C, *D;
6508     
6509     // -x == -y --> x == y
6510     if (match(Op0, m_Neg(m_Value(A))) &&
6511         match(Op1, m_Neg(m_Value(B))))
6512       return new ICmpInst(I.getPredicate(), A, B);
6513     
6514     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6515       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6516         Value *OtherVal = A == Op1 ? B : A;
6517         return new ICmpInst(I.getPredicate(), OtherVal,
6518                             Constant::getNullValue(A->getType()));
6519       }
6520
6521       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6522         // A^c1 == C^c2 --> A == C^(c1^c2)
6523         ConstantInt *C1, *C2;
6524         if (match(B, m_ConstantInt(C1)) &&
6525             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6526           Constant *NC = 
6527                    ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6528           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6529           return new ICmpInst(I.getPredicate(), A,
6530                               InsertNewInstBefore(Xor, I));
6531         }
6532         
6533         // A^B == A^D -> B == D
6534         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6535         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6536         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6537         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6538       }
6539     }
6540     
6541     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6542         (A == Op0 || B == Op0)) {
6543       // A == (A^B)  ->  B == 0
6544       Value *OtherVal = A == Op0 ? B : A;
6545       return new ICmpInst(I.getPredicate(), OtherVal,
6546                           Constant::getNullValue(A->getType()));
6547     }
6548
6549     // (A-B) == A  ->  B == 0
6550     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6551       return new ICmpInst(I.getPredicate(), B, 
6552                           Constant::getNullValue(B->getType()));
6553
6554     // A == (A-B)  ->  B == 0
6555     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6556       return new ICmpInst(I.getPredicate(), B,
6557                           Constant::getNullValue(B->getType()));
6558     
6559     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6560     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6561         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6562         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6563       Value *X = 0, *Y = 0, *Z = 0;
6564       
6565       if (A == C) {
6566         X = B; Y = D; Z = A;
6567       } else if (A == D) {
6568         X = B; Y = C; Z = A;
6569       } else if (B == C) {
6570         X = A; Y = D; Z = B;
6571       } else if (B == D) {
6572         X = A; Y = C; Z = B;
6573       }
6574       
6575       if (X) {   // Build (X^Y) & Z
6576         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6577         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6578         I.setOperand(0, Op1);
6579         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6580         return &I;
6581       }
6582     }
6583   }
6584   return Changed ? &I : 0;
6585 }
6586
6587
6588 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6589 /// and CmpRHS are both known to be integer constants.
6590 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6591                                           ConstantInt *DivRHS) {
6592   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6593   const APInt &CmpRHSV = CmpRHS->getValue();
6594   
6595   // FIXME: If the operand types don't match the type of the divide 
6596   // then don't attempt this transform. The code below doesn't have the
6597   // logic to deal with a signed divide and an unsigned compare (and
6598   // vice versa). This is because (x /s C1) <s C2  produces different 
6599   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6600   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6601   // work. :(  The if statement below tests that condition and bails 
6602   // if it finds it. 
6603   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6604   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6605     return 0;
6606   if (DivRHS->isZero())
6607     return 0; // The ProdOV computation fails on divide by zero.
6608   if (DivIsSigned && DivRHS->isAllOnesValue())
6609     return 0; // The overflow computation also screws up here
6610   if (DivRHS->isOne())
6611     return 0; // Not worth bothering, and eliminates some funny cases
6612               // with INT_MIN.
6613
6614   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6615   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6616   // C2 (CI). By solving for X we can turn this into a range check 
6617   // instead of computing a divide. 
6618   Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6619
6620   // Determine if the product overflows by seeing if the product is
6621   // not equal to the divide. Make sure we do the same kind of divide
6622   // as in the LHS instruction that we're folding. 
6623   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6624                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6625
6626   // Get the ICmp opcode
6627   ICmpInst::Predicate Pred = ICI.getPredicate();
6628
6629   // Figure out the interval that is being checked.  For example, a comparison
6630   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6631   // Compute this interval based on the constants involved and the signedness of
6632   // the compare/divide.  This computes a half-open interval, keeping track of
6633   // whether either value in the interval overflows.  After analysis each
6634   // overflow variable is set to 0 if it's corresponding bound variable is valid
6635   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6636   int LoOverflow = 0, HiOverflow = 0;
6637   Constant *LoBound = 0, *HiBound = 0;
6638   
6639   if (!DivIsSigned) {  // udiv
6640     // e.g. X/5 op 3  --> [15, 20)
6641     LoBound = Prod;
6642     HiOverflow = LoOverflow = ProdOV;
6643     if (!HiOverflow)
6644       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6645   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6646     if (CmpRHSV == 0) {       // (X / pos) op 0
6647       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6648       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6649       HiBound = DivRHS;
6650     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6651       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6652       HiOverflow = LoOverflow = ProdOV;
6653       if (!HiOverflow)
6654         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6655     } else {                       // (X / pos) op neg
6656       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6657       HiBound = AddOne(Prod);
6658       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6659       if (!LoOverflow) {
6660         ConstantInt* DivNeg =
6661                          cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6662         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6663                                      true) ? -1 : 0;
6664        }
6665     }
6666   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6667     if (CmpRHSV == 0) {       // (X / neg) op 0
6668       // e.g. X/-5 op 0  --> [-4, 5)
6669       LoBound = AddOne(DivRHS);
6670       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6671       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6672         HiOverflow = 1;            // [INTMIN+1, overflow)
6673         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6674       }
6675     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6676       // e.g. X/-5 op 3  --> [-19, -14)
6677       HiBound = AddOne(Prod);
6678       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6679       if (!LoOverflow)
6680         LoOverflow = AddWithOverflow(LoBound, HiBound,
6681                                      DivRHS, Context, true) ? -1 : 0;
6682     } else {                       // (X / neg) op neg
6683       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6684       LoOverflow = HiOverflow = ProdOV;
6685       if (!HiOverflow)
6686         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6687     }
6688     
6689     // Dividing by a negative swaps the condition.  LT <-> GT
6690     Pred = ICmpInst::getSwappedPredicate(Pred);
6691   }
6692
6693   Value *X = DivI->getOperand(0);
6694   switch (Pred) {
6695   default: llvm_unreachable("Unhandled icmp opcode!");
6696   case ICmpInst::ICMP_EQ:
6697     if (LoOverflow && HiOverflow)
6698       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6699     else if (HiOverflow)
6700       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6701                           ICmpInst::ICMP_UGE, X, LoBound);
6702     else if (LoOverflow)
6703       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6704                           ICmpInst::ICMP_ULT, X, HiBound);
6705     else
6706       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6707   case ICmpInst::ICMP_NE:
6708     if (LoOverflow && HiOverflow)
6709       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6710     else if (HiOverflow)
6711       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6712                           ICmpInst::ICMP_ULT, X, LoBound);
6713     else if (LoOverflow)
6714       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6715                           ICmpInst::ICMP_UGE, X, HiBound);
6716     else
6717       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6718   case ICmpInst::ICMP_ULT:
6719   case ICmpInst::ICMP_SLT:
6720     if (LoOverflow == +1)   // Low bound is greater than input range.
6721       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6722     if (LoOverflow == -1)   // Low bound is less than input range.
6723       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6724     return new ICmpInst(Pred, X, LoBound);
6725   case ICmpInst::ICMP_UGT:
6726   case ICmpInst::ICMP_SGT:
6727     if (HiOverflow == +1)       // High bound greater than input range.
6728       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6729     else if (HiOverflow == -1)  // High bound less than input range.
6730       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6731     if (Pred == ICmpInst::ICMP_UGT)
6732       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6733     else
6734       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6735   }
6736 }
6737
6738
6739 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6740 ///
6741 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6742                                                           Instruction *LHSI,
6743                                                           ConstantInt *RHS) {
6744   const APInt &RHSV = RHS->getValue();
6745   
6746   switch (LHSI->getOpcode()) {
6747   case Instruction::Trunc:
6748     if (ICI.isEquality() && LHSI->hasOneUse()) {
6749       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6750       // of the high bits truncated out of x are known.
6751       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6752              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6753       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6754       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6755       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6756       
6757       // If all the high bits are known, we can do this xform.
6758       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6759         // Pull in the high bits from known-ones set.
6760         APInt NewRHS(RHS->getValue());
6761         NewRHS.zext(SrcBits);
6762         NewRHS |= KnownOne;
6763         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6764                             ConstantInt::get(*Context, NewRHS));
6765       }
6766     }
6767     break;
6768       
6769   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6770     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6771       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6772       // fold the xor.
6773       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6774           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6775         Value *CompareVal = LHSI->getOperand(0);
6776         
6777         // If the sign bit of the XorCST is not set, there is no change to
6778         // the operation, just stop using the Xor.
6779         if (!XorCST->getValue().isNegative()) {
6780           ICI.setOperand(0, CompareVal);
6781           AddToWorkList(LHSI);
6782           return &ICI;
6783         }
6784         
6785         // Was the old condition true if the operand is positive?
6786         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6787         
6788         // If so, the new one isn't.
6789         isTrueIfPositive ^= true;
6790         
6791         if (isTrueIfPositive)
6792           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6793                               SubOne(RHS));
6794         else
6795           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6796                               AddOne(RHS));
6797       }
6798
6799       if (LHSI->hasOneUse()) {
6800         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6801         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6802           const APInt &SignBit = XorCST->getValue();
6803           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6804                                          ? ICI.getUnsignedPredicate()
6805                                          : ICI.getSignedPredicate();
6806           return new ICmpInst(Pred, LHSI->getOperand(0),
6807                               ConstantInt::get(*Context, RHSV ^ SignBit));
6808         }
6809
6810         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6811         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6812           const APInt &NotSignBit = XorCST->getValue();
6813           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6814                                          ? ICI.getUnsignedPredicate()
6815                                          : ICI.getSignedPredicate();
6816           Pred = ICI.getSwappedPredicate(Pred);
6817           return new ICmpInst(Pred, LHSI->getOperand(0),
6818                               ConstantInt::get(*Context, RHSV ^ NotSignBit));
6819         }
6820       }
6821     }
6822     break;
6823   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6824     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6825         LHSI->getOperand(0)->hasOneUse()) {
6826       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6827       
6828       // If the LHS is an AND of a truncating cast, we can widen the
6829       // and/compare to be the input width without changing the value
6830       // produced, eliminating a cast.
6831       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6832         // We can do this transformation if either the AND constant does not
6833         // have its sign bit set or if it is an equality comparison. 
6834         // Extending a relational comparison when we're checking the sign
6835         // bit would not work.
6836         if (Cast->hasOneUse() &&
6837             (ICI.isEquality() ||
6838              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6839           uint32_t BitWidth = 
6840             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6841           APInt NewCST = AndCST->getValue();
6842           NewCST.zext(BitWidth);
6843           APInt NewCI = RHSV;
6844           NewCI.zext(BitWidth);
6845           Instruction *NewAnd = 
6846             BinaryOperator::CreateAnd(Cast->getOperand(0),
6847                            ConstantInt::get(*Context, NewCST), LHSI->getName());
6848           InsertNewInstBefore(NewAnd, ICI);
6849           return new ICmpInst(ICI.getPredicate(), NewAnd,
6850                               ConstantInt::get(*Context, NewCI));
6851         }
6852       }
6853       
6854       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6855       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6856       // happens a LOT in code produced by the C front-end, for bitfield
6857       // access.
6858       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6859       if (Shift && !Shift->isShift())
6860         Shift = 0;
6861       
6862       ConstantInt *ShAmt;
6863       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6864       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6865       const Type *AndTy = AndCST->getType();          // Type of the and.
6866       
6867       // We can fold this as long as we can't shift unknown bits
6868       // into the mask.  This can only happen with signed shift
6869       // rights, as they sign-extend.
6870       if (ShAmt) {
6871         bool CanFold = Shift->isLogicalShift();
6872         if (!CanFold) {
6873           // To test for the bad case of the signed shr, see if any
6874           // of the bits shifted in could be tested after the mask.
6875           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6876           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6877           
6878           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6879           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6880                AndCST->getValue()) == 0)
6881             CanFold = true;
6882         }
6883         
6884         if (CanFold) {
6885           Constant *NewCst;
6886           if (Shift->getOpcode() == Instruction::Shl)
6887             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6888           else
6889             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6890           
6891           // Check to see if we are shifting out any of the bits being
6892           // compared.
6893           if (ConstantExpr::get(Shift->getOpcode(),
6894                                        NewCst, ShAmt) != RHS) {
6895             // If we shifted bits out, the fold is not going to work out.
6896             // As a special case, check to see if this means that the
6897             // result is always true or false now.
6898             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6899               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6900             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6901               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6902           } else {
6903             ICI.setOperand(1, NewCst);
6904             Constant *NewAndCST;
6905             if (Shift->getOpcode() == Instruction::Shl)
6906               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6907             else
6908               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6909             LHSI->setOperand(1, NewAndCST);
6910             LHSI->setOperand(0, Shift->getOperand(0));
6911             AddToWorkList(Shift); // Shift is dead.
6912             AddUsesToWorkList(ICI);
6913             return &ICI;
6914           }
6915         }
6916       }
6917       
6918       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6919       // preferable because it allows the C<<Y expression to be hoisted out
6920       // of a loop if Y is invariant and X is not.
6921       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6922           ICI.isEquality() && !Shift->isArithmeticShift() &&
6923           !isa<Constant>(Shift->getOperand(0))) {
6924         // Compute C << Y.
6925         Value *NS;
6926         if (Shift->getOpcode() == Instruction::LShr) {
6927           NS = BinaryOperator::CreateShl(AndCST, 
6928                                          Shift->getOperand(1), "tmp");
6929         } else {
6930           // Insert a logical shift.
6931           NS = BinaryOperator::CreateLShr(AndCST,
6932                                           Shift->getOperand(1), "tmp");
6933         }
6934         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6935         
6936         // Compute X & (C << Y).
6937         Instruction *NewAnd = 
6938           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6939         InsertNewInstBefore(NewAnd, ICI);
6940         
6941         ICI.setOperand(0, NewAnd);
6942         return &ICI;
6943       }
6944     }
6945     break;
6946     
6947   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6948     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6949     if (!ShAmt) break;
6950     
6951     uint32_t TypeBits = RHSV.getBitWidth();
6952     
6953     // Check that the shift amount is in range.  If not, don't perform
6954     // undefined shifts.  When the shift is visited it will be
6955     // simplified.
6956     if (ShAmt->uge(TypeBits))
6957       break;
6958     
6959     if (ICI.isEquality()) {
6960       // If we are comparing against bits always shifted out, the
6961       // comparison cannot succeed.
6962       Constant *Comp =
6963         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6964                                                                  ShAmt);
6965       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6966         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6967         Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6968         return ReplaceInstUsesWith(ICI, Cst);
6969       }
6970       
6971       if (LHSI->hasOneUse()) {
6972         // Otherwise strength reduce the shift into an and.
6973         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6974         Constant *Mask =
6975           ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits, 
6976                                                        TypeBits-ShAmtVal));
6977         
6978         Instruction *AndI =
6979           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6980                                     Mask, LHSI->getName()+".mask");
6981         Value *And = InsertNewInstBefore(AndI, ICI);
6982         return new ICmpInst(ICI.getPredicate(), And,
6983                             ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6984       }
6985     }
6986     
6987     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6988     bool TrueIfSigned = false;
6989     if (LHSI->hasOneUse() &&
6990         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6991       // (X << 31) <s 0  --> (X&1) != 0
6992       Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6993                                            (TypeBits-ShAmt->getZExtValue()-1));
6994       Instruction *AndI =
6995         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6996                                   Mask, LHSI->getName()+".mask");
6997       Value *And = InsertNewInstBefore(AndI, ICI);
6998       
6999       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
7000                           And, Constant::getNullValue(And->getType()));
7001     }
7002     break;
7003   }
7004     
7005   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
7006   case Instruction::AShr: {
7007     // Only handle equality comparisons of shift-by-constant.
7008     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7009     if (!ShAmt || !ICI.isEquality()) break;
7010
7011     // Check that the shift amount is in range.  If not, don't perform
7012     // undefined shifts.  When the shift is visited it will be
7013     // simplified.
7014     uint32_t TypeBits = RHSV.getBitWidth();
7015     if (ShAmt->uge(TypeBits))
7016       break;
7017     
7018     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7019       
7020     // If we are comparing against bits always shifted out, the
7021     // comparison cannot succeed.
7022     APInt Comp = RHSV << ShAmtVal;
7023     if (LHSI->getOpcode() == Instruction::LShr)
7024       Comp = Comp.lshr(ShAmtVal);
7025     else
7026       Comp = Comp.ashr(ShAmtVal);
7027     
7028     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7029       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7030       Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7031       return ReplaceInstUsesWith(ICI, Cst);
7032     }
7033     
7034     // Otherwise, check to see if the bits shifted out are known to be zero.
7035     // If so, we can compare against the unshifted value:
7036     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
7037     if (LHSI->hasOneUse() &&
7038         MaskedValueIsZero(LHSI->getOperand(0), 
7039                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7040       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7041                           ConstantExpr::getShl(RHS, ShAmt));
7042     }
7043       
7044     if (LHSI->hasOneUse()) {
7045       // Otherwise strength reduce the shift into an and.
7046       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7047       Constant *Mask = ConstantInt::get(*Context, Val);
7048       
7049       Instruction *AndI =
7050         BinaryOperator::CreateAnd(LHSI->getOperand(0),
7051                                   Mask, LHSI->getName()+".mask");
7052       Value *And = InsertNewInstBefore(AndI, ICI);
7053       return new ICmpInst(ICI.getPredicate(), And,
7054                           ConstantExpr::getShl(RHS, ShAmt));
7055     }
7056     break;
7057   }
7058     
7059   case Instruction::SDiv:
7060   case Instruction::UDiv:
7061     // Fold: icmp pred ([us]div X, C1), C2 -> range test
7062     // Fold this div into the comparison, producing a range check. 
7063     // Determine, based on the divide type, what the range is being 
7064     // checked.  If there is an overflow on the low or high side, remember 
7065     // it, otherwise compute the range [low, hi) bounding the new value.
7066     // See: InsertRangeTest above for the kinds of replacements possible.
7067     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7068       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7069                                           DivRHS))
7070         return R;
7071     break;
7072
7073   case Instruction::Add:
7074     // Fold: icmp pred (add, X, C1), C2
7075
7076     if (!ICI.isEquality()) {
7077       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7078       if (!LHSC) break;
7079       const APInt &LHSV = LHSC->getValue();
7080
7081       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7082                             .subtract(LHSV);
7083
7084       if (ICI.isSignedPredicate()) {
7085         if (CR.getLower().isSignBit()) {
7086           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7087                               ConstantInt::get(*Context, CR.getUpper()));
7088         } else if (CR.getUpper().isSignBit()) {
7089           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7090                               ConstantInt::get(*Context, CR.getLower()));
7091         }
7092       } else {
7093         if (CR.getLower().isMinValue()) {
7094           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7095                               ConstantInt::get(*Context, CR.getUpper()));
7096         } else if (CR.getUpper().isMinValue()) {
7097           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7098                               ConstantInt::get(*Context, CR.getLower()));
7099         }
7100       }
7101     }
7102     break;
7103   }
7104   
7105   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7106   if (ICI.isEquality()) {
7107     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7108     
7109     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
7110     // the second operand is a constant, simplify a bit.
7111     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7112       switch (BO->getOpcode()) {
7113       case Instruction::SRem:
7114         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7115         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7116           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7117           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7118             Instruction *NewRem =
7119               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7120                                          BO->getName());
7121             InsertNewInstBefore(NewRem, ICI);
7122             return new ICmpInst(ICI.getPredicate(), NewRem,
7123                                 Constant::getNullValue(BO->getType()));
7124           }
7125         }
7126         break;
7127       case Instruction::Add:
7128         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7129         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7130           if (BO->hasOneUse())
7131             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7132                                 ConstantExpr::getSub(RHS, BOp1C));
7133         } else if (RHSV == 0) {
7134           // Replace ((add A, B) != 0) with (A != -B) if A or B is
7135           // efficiently invertible, or if the add has just this one use.
7136           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7137           
7138           if (Value *NegVal = dyn_castNegVal(BOp1))
7139             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7140           else if (Value *NegVal = dyn_castNegVal(BOp0))
7141             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7142           else if (BO->hasOneUse()) {
7143             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7144             InsertNewInstBefore(Neg, ICI);
7145             Neg->takeName(BO);
7146             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7147           }
7148         }
7149         break;
7150       case Instruction::Xor:
7151         // For the xor case, we can xor two constants together, eliminating
7152         // the explicit xor.
7153         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7154           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7155                               ConstantExpr::getXor(RHS, BOC));
7156         
7157         // FALLTHROUGH
7158       case Instruction::Sub:
7159         // Replace (([sub|xor] A, B) != 0) with (A != B)
7160         if (RHSV == 0)
7161           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7162                               BO->getOperand(1));
7163         break;
7164         
7165       case Instruction::Or:
7166         // If bits are being or'd in that are not present in the constant we
7167         // are comparing against, then the comparison could never succeed!
7168         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7169           Constant *NotCI = ConstantExpr::getNot(RHS);
7170           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7171             return ReplaceInstUsesWith(ICI,
7172                                        ConstantInt::get(Type::getInt1Ty(*Context), 
7173                                        isICMP_NE));
7174         }
7175         break;
7176         
7177       case Instruction::And:
7178         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7179           // If bits are being compared against that are and'd out, then the
7180           // comparison can never succeed!
7181           if ((RHSV & ~BOC->getValue()) != 0)
7182             return ReplaceInstUsesWith(ICI,
7183                                        ConstantInt::get(Type::getInt1Ty(*Context),
7184                                        isICMP_NE));
7185           
7186           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7187           if (RHS == BOC && RHSV.isPowerOf2())
7188             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7189                                 ICmpInst::ICMP_NE, LHSI,
7190                                 Constant::getNullValue(RHS->getType()));
7191           
7192           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7193           if (BOC->getValue().isSignBit()) {
7194             Value *X = BO->getOperand(0);
7195             Constant *Zero = Constant::getNullValue(X->getType());
7196             ICmpInst::Predicate pred = isICMP_NE ? 
7197               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7198             return new ICmpInst(pred, X, Zero);
7199           }
7200           
7201           // ((X & ~7) == 0) --> X < 8
7202           if (RHSV == 0 && isHighOnes(BOC)) {
7203             Value *X = BO->getOperand(0);
7204             Constant *NegX = ConstantExpr::getNeg(BOC);
7205             ICmpInst::Predicate pred = isICMP_NE ? 
7206               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7207             return new ICmpInst(pred, X, NegX);
7208           }
7209         }
7210       default: break;
7211       }
7212     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7213       // Handle icmp {eq|ne} <intrinsic>, intcst.
7214       if (II->getIntrinsicID() == Intrinsic::bswap) {
7215         AddToWorkList(II);
7216         ICI.setOperand(0, II->getOperand(1));
7217         ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7218         return &ICI;
7219       }
7220     }
7221   }
7222   return 0;
7223 }
7224
7225 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7226 /// We only handle extending casts so far.
7227 ///
7228 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7229   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7230   Value *LHSCIOp        = LHSCI->getOperand(0);
7231   const Type *SrcTy     = LHSCIOp->getType();
7232   const Type *DestTy    = LHSCI->getType();
7233   Value *RHSCIOp;
7234
7235   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7236   // integer type is the same size as the pointer type.
7237   if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7238       TD->getPointerSizeInBits() ==
7239          cast<IntegerType>(DestTy)->getBitWidth()) {
7240     Value *RHSOp = 0;
7241     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7242       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7243     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7244       RHSOp = RHSC->getOperand(0);
7245       // If the pointer types don't match, insert a bitcast.
7246       if (LHSCIOp->getType() != RHSOp->getType())
7247         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7248     }
7249
7250     if (RHSOp)
7251       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7252   }
7253   
7254   // The code below only handles extension cast instructions, so far.
7255   // Enforce this.
7256   if (LHSCI->getOpcode() != Instruction::ZExt &&
7257       LHSCI->getOpcode() != Instruction::SExt)
7258     return 0;
7259
7260   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7261   bool isSignedCmp = ICI.isSignedPredicate();
7262
7263   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7264     // Not an extension from the same type?
7265     RHSCIOp = CI->getOperand(0);
7266     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7267       return 0;
7268     
7269     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7270     // and the other is a zext), then we can't handle this.
7271     if (CI->getOpcode() != LHSCI->getOpcode())
7272       return 0;
7273
7274     // Deal with equality cases early.
7275     if (ICI.isEquality())
7276       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7277
7278     // A signed comparison of sign extended values simplifies into a
7279     // signed comparison.
7280     if (isSignedCmp && isSignedExt)
7281       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7282
7283     // The other three cases all fold into an unsigned comparison.
7284     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7285   }
7286
7287   // If we aren't dealing with a constant on the RHS, exit early
7288   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7289   if (!CI)
7290     return 0;
7291
7292   // Compute the constant that would happen if we truncated to SrcTy then
7293   // reextended to DestTy.
7294   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7295   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7296                                                 Res1, DestTy);
7297
7298   // If the re-extended constant didn't change...
7299   if (Res2 == CI) {
7300     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7301     // For example, we might have:
7302     //    %A = sext i16 %X to i32
7303     //    %B = icmp ugt i32 %A, 1330
7304     // It is incorrect to transform this into 
7305     //    %B = icmp ugt i16 %X, 1330
7306     // because %A may have negative value. 
7307     //
7308     // However, we allow this when the compare is EQ/NE, because they are
7309     // signless.
7310     if (isSignedExt == isSignedCmp || ICI.isEquality())
7311       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7312     return 0;
7313   }
7314
7315   // The re-extended constant changed so the constant cannot be represented 
7316   // in the shorter type. Consequently, we cannot emit a simple comparison.
7317
7318   // First, handle some easy cases. We know the result cannot be equal at this
7319   // point so handle the ICI.isEquality() cases
7320   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7321     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7322   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7323     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7324
7325   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7326   // should have been folded away previously and not enter in here.
7327   Value *Result;
7328   if (isSignedCmp) {
7329     // We're performing a signed comparison.
7330     if (cast<ConstantInt>(CI)->getValue().isNegative())
7331       Result = ConstantInt::getFalse(*Context);          // X < (small) --> false
7332     else
7333       Result = ConstantInt::getTrue(*Context);           // X < (large) --> true
7334   } else {
7335     // We're performing an unsigned comparison.
7336     if (isSignedExt) {
7337       // We're performing an unsigned comp with a sign extended value.
7338       // This is true if the input is >= 0. [aka >s -1]
7339       Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7340       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT,
7341                                    LHSCIOp, NegOne, ICI.getName()), ICI);
7342     } else {
7343       // Unsigned extend & unsigned compare -> always true.
7344       Result = ConstantInt::getTrue(*Context);
7345     }
7346   }
7347
7348   // Finally, return the value computed.
7349   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7350       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7351     return ReplaceInstUsesWith(ICI, Result);
7352
7353   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7354           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7355          "ICmp should be folded!");
7356   if (Constant *CI = dyn_cast<Constant>(Result))
7357     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7358   return BinaryOperator::CreateNot(Result);
7359 }
7360
7361 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7362   return commonShiftTransforms(I);
7363 }
7364
7365 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7366   return commonShiftTransforms(I);
7367 }
7368
7369 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7370   if (Instruction *R = commonShiftTransforms(I))
7371     return R;
7372   
7373   Value *Op0 = I.getOperand(0);
7374   
7375   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7376   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7377     if (CSI->isAllOnesValue())
7378       return ReplaceInstUsesWith(I, CSI);
7379
7380   // See if we can turn a signed shr into an unsigned shr.
7381   if (MaskedValueIsZero(Op0,
7382                         APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7383     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7384
7385   // Arithmetic shifting an all-sign-bit value is a no-op.
7386   unsigned NumSignBits = ComputeNumSignBits(Op0);
7387   if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7388     return ReplaceInstUsesWith(I, Op0);
7389
7390   return 0;
7391 }
7392
7393 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7394   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7395   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7396
7397   // shl X, 0 == X and shr X, 0 == X
7398   // shl 0, X == 0 and shr 0, X == 0
7399   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7400       Op0 == Constant::getNullValue(Op0->getType()))
7401     return ReplaceInstUsesWith(I, Op0);
7402   
7403   if (isa<UndefValue>(Op0)) {            
7404     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7405       return ReplaceInstUsesWith(I, Op0);
7406     else                                    // undef << X -> 0, undef >>u X -> 0
7407       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7408   }
7409   if (isa<UndefValue>(Op1)) {
7410     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7411       return ReplaceInstUsesWith(I, Op0);          
7412     else                                     // X << undef, X >>u undef -> 0
7413       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7414   }
7415
7416   // See if we can fold away this shift.
7417   if (SimplifyDemandedInstructionBits(I))
7418     return &I;
7419
7420   // Try to fold constant and into select arguments.
7421   if (isa<Constant>(Op0))
7422     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7423       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7424         return R;
7425
7426   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7427     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7428       return Res;
7429   return 0;
7430 }
7431
7432 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7433                                                BinaryOperator &I) {
7434   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7435
7436   // See if we can simplify any instructions used by the instruction whose sole 
7437   // purpose is to compute bits we don't care about.
7438   uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7439   
7440   // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7441   // a signed shift.
7442   //
7443   if (Op1->uge(TypeBits)) {
7444     if (I.getOpcode() != Instruction::AShr)
7445       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7446     else {
7447       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7448       return &I;
7449     }
7450   }
7451   
7452   // ((X*C1) << C2) == (X * (C1 << C2))
7453   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7454     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7455       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7456         return BinaryOperator::CreateMul(BO->getOperand(0),
7457                                         ConstantExpr::getShl(BOOp, Op1));
7458   
7459   // Try to fold constant and into select arguments.
7460   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7461     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7462       return R;
7463   if (isa<PHINode>(Op0))
7464     if (Instruction *NV = FoldOpIntoPhi(I))
7465       return NV;
7466   
7467   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7468   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7469     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7470     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7471     // place.  Don't try to do this transformation in this case.  Also, we
7472     // require that the input operand is a shift-by-constant so that we have
7473     // confidence that the shifts will get folded together.  We could do this
7474     // xform in more cases, but it is unlikely to be profitable.
7475     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7476         isa<ConstantInt>(TrOp->getOperand(1))) {
7477       // Okay, we'll do this xform.  Make the shift of shift.
7478       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7479       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7480                                                 I.getName());
7481       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7482
7483       // For logical shifts, the truncation has the effect of making the high
7484       // part of the register be zeros.  Emulate this by inserting an AND to
7485       // clear the top bits as needed.  This 'and' will usually be zapped by
7486       // other xforms later if dead.
7487       unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7488       unsigned DstSize = TI->getType()->getScalarSizeInBits();
7489       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7490       
7491       // The mask we constructed says what the trunc would do if occurring
7492       // between the shifts.  We want to know the effect *after* the second
7493       // shift.  We know that it is a logical shift by a constant, so adjust the
7494       // mask as appropriate.
7495       if (I.getOpcode() == Instruction::Shl)
7496         MaskV <<= Op1->getZExtValue();
7497       else {
7498         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7499         MaskV = MaskV.lshr(Op1->getZExtValue());
7500       }
7501
7502       Instruction *And =
7503         BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV), 
7504                                   TI->getName());
7505       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7506
7507       // Return the value truncated to the interesting size.
7508       return new TruncInst(And, I.getType());
7509     }
7510   }
7511   
7512   if (Op0->hasOneUse()) {
7513     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7514       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7515       Value *V1, *V2;
7516       ConstantInt *CC;
7517       switch (Op0BO->getOpcode()) {
7518         default: break;
7519         case Instruction::Add:
7520         case Instruction::And:
7521         case Instruction::Or:
7522         case Instruction::Xor: {
7523           // These operators commute.
7524           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7525           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7526               match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7527                     m_Specific(Op1)))){
7528             Instruction *YS = BinaryOperator::CreateShl(
7529                                             Op0BO->getOperand(0), Op1,
7530                                             Op0BO->getName());
7531             InsertNewInstBefore(YS, I); // (Y << C)
7532             Instruction *X = 
7533               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7534                                      Op0BO->getOperand(1)->getName());
7535             InsertNewInstBefore(X, I);  // (X + (Y << C))
7536             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7537             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7538                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7539           }
7540           
7541           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7542           Value *Op0BOOp1 = Op0BO->getOperand(1);
7543           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7544               match(Op0BOOp1, 
7545                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7546                           m_ConstantInt(CC))) &&
7547               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7548             Instruction *YS = BinaryOperator::CreateShl(
7549                                                      Op0BO->getOperand(0), Op1,
7550                                                      Op0BO->getName());
7551             InsertNewInstBefore(YS, I); // (Y << C)
7552             Instruction *XM =
7553               BinaryOperator::CreateAnd(V1,
7554                                         ConstantExpr::getShl(CC, Op1),
7555                                         V1->getName()+".mask");
7556             InsertNewInstBefore(XM, I); // X & (CC << C)
7557             
7558             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7559           }
7560         }
7561           
7562         // FALL THROUGH.
7563         case Instruction::Sub: {
7564           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7565           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7566               match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7567                     m_Specific(Op1)))) {
7568             Instruction *YS = BinaryOperator::CreateShl(
7569                                                      Op0BO->getOperand(1), Op1,
7570                                                      Op0BO->getName());
7571             InsertNewInstBefore(YS, I); // (Y << C)
7572             Instruction *X =
7573               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7574                                      Op0BO->getOperand(0)->getName());
7575             InsertNewInstBefore(X, I);  // (X + (Y << C))
7576             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7577             return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7578                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7579           }
7580           
7581           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7582           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7583               match(Op0BO->getOperand(0),
7584                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7585                           m_ConstantInt(CC))) && V2 == Op1 &&
7586               cast<BinaryOperator>(Op0BO->getOperand(0))
7587                   ->getOperand(0)->hasOneUse()) {
7588             Instruction *YS = BinaryOperator::CreateShl(
7589                                                      Op0BO->getOperand(1), Op1,
7590                                                      Op0BO->getName());
7591             InsertNewInstBefore(YS, I); // (Y << C)
7592             Instruction *XM =
7593               BinaryOperator::CreateAnd(V1, 
7594                                         ConstantExpr::getShl(CC, Op1),
7595                                         V1->getName()+".mask");
7596             InsertNewInstBefore(XM, I); // X & (CC << C)
7597             
7598             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7599           }
7600           
7601           break;
7602         }
7603       }
7604       
7605       
7606       // If the operand is an bitwise operator with a constant RHS, and the
7607       // shift is the only use, we can pull it out of the shift.
7608       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7609         bool isValid = true;     // Valid only for And, Or, Xor
7610         bool highBitSet = false; // Transform if high bit of constant set?
7611         
7612         switch (Op0BO->getOpcode()) {
7613           default: isValid = false; break;   // Do not perform transform!
7614           case Instruction::Add:
7615             isValid = isLeftShift;
7616             break;
7617           case Instruction::Or:
7618           case Instruction::Xor:
7619             highBitSet = false;
7620             break;
7621           case Instruction::And:
7622             highBitSet = true;
7623             break;
7624         }
7625         
7626         // If this is a signed shift right, and the high bit is modified
7627         // by the logical operation, do not perform the transformation.
7628         // The highBitSet boolean indicates the value of the high bit of
7629         // the constant which would cause it to be modified for this
7630         // operation.
7631         //
7632         if (isValid && I.getOpcode() == Instruction::AShr)
7633           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7634         
7635         if (isValid) {
7636           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7637           
7638           Instruction *NewShift =
7639             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7640           InsertNewInstBefore(NewShift, I);
7641           NewShift->takeName(Op0BO);
7642           
7643           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7644                                         NewRHS);
7645         }
7646       }
7647     }
7648   }
7649   
7650   // Find out if this is a shift of a shift by a constant.
7651   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7652   if (ShiftOp && !ShiftOp->isShift())
7653     ShiftOp = 0;
7654   
7655   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7656     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7657     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7658     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7659     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7660     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7661     Value *X = ShiftOp->getOperand(0);
7662     
7663     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7664     
7665     const IntegerType *Ty = cast<IntegerType>(I.getType());
7666     
7667     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7668     if (I.getOpcode() == ShiftOp->getOpcode()) {
7669       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7670       // saturates.
7671       if (AmtSum >= TypeBits) {
7672         if (I.getOpcode() != Instruction::AShr)
7673           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7674         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7675       }
7676       
7677       return BinaryOperator::Create(I.getOpcode(), X,
7678                                     ConstantInt::get(Ty, AmtSum));
7679     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7680                I.getOpcode() == Instruction::AShr) {
7681       if (AmtSum >= TypeBits)
7682         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7683       
7684       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7685       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7686     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7687                I.getOpcode() == Instruction::LShr) {
7688       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7689       if (AmtSum >= TypeBits)
7690         AmtSum = TypeBits-1;
7691       
7692       Instruction *Shift =
7693         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7694       InsertNewInstBefore(Shift, I);
7695
7696       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7697       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7698     }
7699     
7700     // Okay, if we get here, one shift must be left, and the other shift must be
7701     // right.  See if the amounts are equal.
7702     if (ShiftAmt1 == ShiftAmt2) {
7703       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7704       if (I.getOpcode() == Instruction::Shl) {
7705         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7706         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7707       }
7708       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7709       if (I.getOpcode() == Instruction::LShr) {
7710         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7711         return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7712       }
7713       // We can simplify ((X << C) >>s C) into a trunc + sext.
7714       // NOTE: we could do this for any C, but that would make 'unusual' integer
7715       // types.  For now, just stick to ones well-supported by the code
7716       // generators.
7717       const Type *SExtType = 0;
7718       switch (Ty->getBitWidth() - ShiftAmt1) {
7719       case 1  :
7720       case 8  :
7721       case 16 :
7722       case 32 :
7723       case 64 :
7724       case 128:
7725         SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7726         break;
7727       default: break;
7728       }
7729       if (SExtType) {
7730         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7731         InsertNewInstBefore(NewTrunc, I);
7732         return new SExtInst(NewTrunc, Ty);
7733       }
7734       // Otherwise, we can't handle it yet.
7735     } else if (ShiftAmt1 < ShiftAmt2) {
7736       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7737       
7738       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7739       if (I.getOpcode() == Instruction::Shl) {
7740         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7741                ShiftOp->getOpcode() == Instruction::AShr);
7742         Instruction *Shift =
7743           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7744         InsertNewInstBefore(Shift, I);
7745         
7746         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7747         return BinaryOperator::CreateAnd(Shift,
7748                                          ConstantInt::get(*Context, Mask));
7749       }
7750       
7751       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7752       if (I.getOpcode() == Instruction::LShr) {
7753         assert(ShiftOp->getOpcode() == Instruction::Shl);
7754         Instruction *Shift =
7755           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7756         InsertNewInstBefore(Shift, I);
7757         
7758         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7759         return BinaryOperator::CreateAnd(Shift,
7760                                          ConstantInt::get(*Context, Mask));
7761       }
7762       
7763       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7764     } else {
7765       assert(ShiftAmt2 < ShiftAmt1);
7766       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7767
7768       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7769       if (I.getOpcode() == Instruction::Shl) {
7770         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7771                ShiftOp->getOpcode() == Instruction::AShr);
7772         Instruction *Shift =
7773           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7774                                  ConstantInt::get(Ty, ShiftDiff));
7775         InsertNewInstBefore(Shift, I);
7776         
7777         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7778         return BinaryOperator::CreateAnd(Shift,
7779                                          ConstantInt::get(*Context, Mask));
7780       }
7781       
7782       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7783       if (I.getOpcode() == Instruction::LShr) {
7784         assert(ShiftOp->getOpcode() == Instruction::Shl);
7785         Instruction *Shift =
7786           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7787         InsertNewInstBefore(Shift, I);
7788         
7789         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7790         return BinaryOperator::CreateAnd(Shift,
7791                                          ConstantInt::get(*Context, Mask));
7792       }
7793       
7794       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7795     }
7796   }
7797   return 0;
7798 }
7799
7800
7801 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7802 /// expression.  If so, decompose it, returning some value X, such that Val is
7803 /// X*Scale+Offset.
7804 ///
7805 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7806                                         int &Offset, LLVMContext *Context) {
7807   assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
7808   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7809     Offset = CI->getZExtValue();
7810     Scale  = 0;
7811     return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7812   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7813     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7814       if (I->getOpcode() == Instruction::Shl) {
7815         // This is a value scaled by '1 << the shift amt'.
7816         Scale = 1U << RHS->getZExtValue();
7817         Offset = 0;
7818         return I->getOperand(0);
7819       } else if (I->getOpcode() == Instruction::Mul) {
7820         // This value is scaled by 'RHS'.
7821         Scale = RHS->getZExtValue();
7822         Offset = 0;
7823         return I->getOperand(0);
7824       } else if (I->getOpcode() == Instruction::Add) {
7825         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7826         // where C1 is divisible by C2.
7827         unsigned SubScale;
7828         Value *SubVal = 
7829           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7830                                     Offset, Context);
7831         Offset += RHS->getZExtValue();
7832         Scale = SubScale;
7833         return SubVal;
7834       }
7835     }
7836   }
7837
7838   // Otherwise, we can't look past this.
7839   Scale = 1;
7840   Offset = 0;
7841   return Val;
7842 }
7843
7844
7845 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7846 /// try to eliminate the cast by moving the type information into the alloc.
7847 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7848                                                    AllocationInst &AI) {
7849   const PointerType *PTy = cast<PointerType>(CI.getType());
7850   
7851   // Remove any uses of AI that are dead.
7852   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7853   
7854   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7855     Instruction *User = cast<Instruction>(*UI++);
7856     if (isInstructionTriviallyDead(User)) {
7857       while (UI != E && *UI == User)
7858         ++UI; // If this instruction uses AI more than once, don't break UI.
7859       
7860       ++NumDeadInst;
7861       DEBUG(errs() << "IC: DCE: " << *User << '\n');
7862       EraseInstFromFunction(*User);
7863     }
7864   }
7865
7866   // This requires TargetData to get the alloca alignment and size information.
7867   if (!TD) return 0;
7868
7869   // Get the type really allocated and the type casted to.
7870   const Type *AllocElTy = AI.getAllocatedType();
7871   const Type *CastElTy = PTy->getElementType();
7872   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7873
7874   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7875   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7876   if (CastElTyAlign < AllocElTyAlign) return 0;
7877
7878   // If the allocation has multiple uses, only promote it if we are strictly
7879   // increasing the alignment of the resultant allocation.  If we keep it the
7880   // same, we open the door to infinite loops of various kinds.  (A reference
7881   // from a dbg.declare doesn't count as a use for this purpose.)
7882   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7883       CastElTyAlign == AllocElTyAlign) return 0;
7884
7885   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7886   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7887   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7888
7889   // See if we can satisfy the modulus by pulling a scale out of the array
7890   // size argument.
7891   unsigned ArraySizeScale;
7892   int ArrayOffset;
7893   Value *NumElements = // See if the array size is a decomposable linear expr.
7894     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7895                               ArrayOffset, Context);
7896  
7897   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7898   // do the xform.
7899   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7900       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7901
7902   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7903   Value *Amt = 0;
7904   if (Scale == 1) {
7905     Amt = NumElements;
7906   } else {
7907     // If the allocation size is constant, form a constant mul expression
7908     Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7909     if (isa<ConstantInt>(NumElements))
7910       Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7911                                  cast<ConstantInt>(Amt));
7912     // otherwise multiply the amount and the number of elements
7913     else {
7914       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7915       Amt = InsertNewInstBefore(Tmp, AI);
7916     }
7917   }
7918   
7919   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7920     Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7921     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7922     Amt = InsertNewInstBefore(Tmp, AI);
7923   }
7924   
7925   AllocationInst *New;
7926   if (isa<MallocInst>(AI))
7927     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7928   else
7929     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7930   InsertNewInstBefore(New, AI);
7931   New->takeName(&AI);
7932   
7933   // If the allocation has one real use plus a dbg.declare, just remove the
7934   // declare.
7935   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7936     EraseInstFromFunction(*DI);
7937   }
7938   // If the allocation has multiple real uses, insert a cast and change all
7939   // things that used it to use the new cast.  This will also hack on CI, but it
7940   // will die soon.
7941   else if (!AI.hasOneUse()) {
7942     AddUsesToWorkList(AI);
7943     // New is the allocation instruction, pointer typed. AI is the original
7944     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7945     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7946     InsertNewInstBefore(NewCast, AI);
7947     AI.replaceAllUsesWith(NewCast);
7948   }
7949   return ReplaceInstUsesWith(CI, New);
7950 }
7951
7952 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7953 /// and return it as type Ty without inserting any new casts and without
7954 /// changing the computed value.  This is used by code that tries to decide
7955 /// whether promoting or shrinking integer operations to wider or smaller types
7956 /// will allow us to eliminate a truncate or extend.
7957 ///
7958 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7959 /// extension operation if Ty is larger.
7960 ///
7961 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7962 /// should return true if trunc(V) can be computed by computing V in the smaller
7963 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7964 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7965 /// efficiently truncated.
7966 ///
7967 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7968 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7969 /// the final result.
7970 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7971                                               unsigned CastOpc,
7972                                               int &NumCastsRemoved){
7973   // We can always evaluate constants in another type.
7974   if (isa<Constant>(V))
7975     return true;
7976   
7977   Instruction *I = dyn_cast<Instruction>(V);
7978   if (!I) return false;
7979   
7980   const Type *OrigTy = V->getType();
7981   
7982   // If this is an extension or truncate, we can often eliminate it.
7983   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7984     // If this is a cast from the destination type, we can trivially eliminate
7985     // it, and this will remove a cast overall.
7986     if (I->getOperand(0)->getType() == Ty) {
7987       // If the first operand is itself a cast, and is eliminable, do not count
7988       // this as an eliminable cast.  We would prefer to eliminate those two
7989       // casts first.
7990       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7991         ++NumCastsRemoved;
7992       return true;
7993     }
7994   }
7995
7996   // We can't extend or shrink something that has multiple uses: doing so would
7997   // require duplicating the instruction in general, which isn't profitable.
7998   if (!I->hasOneUse()) return false;
7999
8000   unsigned Opc = I->getOpcode();
8001   switch (Opc) {
8002   case Instruction::Add:
8003   case Instruction::Sub:
8004   case Instruction::Mul:
8005   case Instruction::And:
8006   case Instruction::Or:
8007   case Instruction::Xor:
8008     // These operators can all arbitrarily be extended or truncated.
8009     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8010                                       NumCastsRemoved) &&
8011            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8012                                       NumCastsRemoved);
8013
8014   case Instruction::UDiv:
8015   case Instruction::URem: {
8016     // UDiv and URem can be truncated if all the truncated bits are zero.
8017     uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8018     uint32_t BitWidth = Ty->getScalarSizeInBits();
8019     if (BitWidth < OrigBitWidth) {
8020       APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8021       if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8022           MaskedValueIsZero(I->getOperand(1), Mask)) {
8023         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8024                                           NumCastsRemoved) &&
8025                CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8026                                           NumCastsRemoved);
8027       }
8028     }
8029     break;
8030   }
8031   case Instruction::Shl:
8032     // If we are truncating the result of this SHL, and if it's a shift of a
8033     // constant amount, we can always perform a SHL in a smaller type.
8034     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8035       uint32_t BitWidth = Ty->getScalarSizeInBits();
8036       if (BitWidth < OrigTy->getScalarSizeInBits() &&
8037           CI->getLimitedValue(BitWidth) < BitWidth)
8038         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8039                                           NumCastsRemoved);
8040     }
8041     break;
8042   case Instruction::LShr:
8043     // If this is a truncate of a logical shr, we can truncate it to a smaller
8044     // lshr iff we know that the bits we would otherwise be shifting in are
8045     // already zeros.
8046     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8047       uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8048       uint32_t BitWidth = Ty->getScalarSizeInBits();
8049       if (BitWidth < OrigBitWidth &&
8050           MaskedValueIsZero(I->getOperand(0),
8051             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8052           CI->getLimitedValue(BitWidth) < BitWidth) {
8053         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8054                                           NumCastsRemoved);
8055       }
8056     }
8057     break;
8058   case Instruction::ZExt:
8059   case Instruction::SExt:
8060   case Instruction::Trunc:
8061     // If this is the same kind of case as our original (e.g. zext+zext), we
8062     // can safely replace it.  Note that replacing it does not reduce the number
8063     // of casts in the input.
8064     if (Opc == CastOpc)
8065       return true;
8066
8067     // sext (zext ty1), ty2 -> zext ty2
8068     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8069       return true;
8070     break;
8071   case Instruction::Select: {
8072     SelectInst *SI = cast<SelectInst>(I);
8073     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8074                                       NumCastsRemoved) &&
8075            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8076                                       NumCastsRemoved);
8077   }
8078   case Instruction::PHI: {
8079     // We can change a phi if we can change all operands.
8080     PHINode *PN = cast<PHINode>(I);
8081     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8082       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8083                                       NumCastsRemoved))
8084         return false;
8085     return true;
8086   }
8087   default:
8088     // TODO: Can handle more cases here.
8089     break;
8090   }
8091   
8092   return false;
8093 }
8094
8095 /// EvaluateInDifferentType - Given an expression that 
8096 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8097 /// evaluate the expression.
8098 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
8099                                              bool isSigned) {
8100   if (Constant *C = dyn_cast<Constant>(V))
8101     return ConstantExpr::getIntegerCast(C, Ty,
8102                                                isSigned /*Sext or ZExt*/);
8103
8104   // Otherwise, it must be an instruction.
8105   Instruction *I = cast<Instruction>(V);
8106   Instruction *Res = 0;
8107   unsigned Opc = I->getOpcode();
8108   switch (Opc) {
8109   case Instruction::Add:
8110   case Instruction::Sub:
8111   case Instruction::Mul:
8112   case Instruction::And:
8113   case Instruction::Or:
8114   case Instruction::Xor:
8115   case Instruction::AShr:
8116   case Instruction::LShr:
8117   case Instruction::Shl:
8118   case Instruction::UDiv:
8119   case Instruction::URem: {
8120     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8121     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8122     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8123     break;
8124   }    
8125   case Instruction::Trunc:
8126   case Instruction::ZExt:
8127   case Instruction::SExt:
8128     // If the source type of the cast is the type we're trying for then we can
8129     // just return the source.  There's no need to insert it because it is not
8130     // new.
8131     if (I->getOperand(0)->getType() == Ty)
8132       return I->getOperand(0);
8133     
8134     // Otherwise, must be the same type of cast, so just reinsert a new one.
8135     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8136                            Ty);
8137     break;
8138   case Instruction::Select: {
8139     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8140     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8141     Res = SelectInst::Create(I->getOperand(0), True, False);
8142     break;
8143   }
8144   case Instruction::PHI: {
8145     PHINode *OPN = cast<PHINode>(I);
8146     PHINode *NPN = PHINode::Create(Ty);
8147     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8148       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8149       NPN->addIncoming(V, OPN->getIncomingBlock(i));
8150     }
8151     Res = NPN;
8152     break;
8153   }
8154   default: 
8155     // TODO: Can handle more cases here.
8156     llvm_unreachable("Unreachable!");
8157     break;
8158   }
8159   
8160   Res->takeName(I);
8161   return InsertNewInstBefore(Res, *I);
8162 }
8163
8164 /// @brief Implement the transforms common to all CastInst visitors.
8165 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8166   Value *Src = CI.getOperand(0);
8167
8168   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8169   // eliminate it now.
8170   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8171     if (Instruction::CastOps opc = 
8172         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8173       // The first cast (CSrc) is eliminable so we need to fix up or replace
8174       // the second cast (CI). CSrc will then have a good chance of being dead.
8175       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8176     }
8177   }
8178
8179   // If we are casting a select then fold the cast into the select
8180   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8181     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8182       return NV;
8183
8184   // If we are casting a PHI then fold the cast into the PHI
8185   if (isa<PHINode>(Src))
8186     if (Instruction *NV = FoldOpIntoPhi(CI))
8187       return NV;
8188   
8189   return 0;
8190 }
8191
8192 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8193 /// or not there is a sequence of GEP indices into the type that will land us at
8194 /// the specified offset.  If so, fill them into NewIndices and return the
8195 /// resultant element type, otherwise return null.
8196 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8197                                        SmallVectorImpl<Value*> &NewIndices,
8198                                        const TargetData *TD,
8199                                        LLVMContext *Context) {
8200   if (!TD) return 0;
8201   if (!Ty->isSized()) return 0;
8202   
8203   // Start with the index over the outer type.  Note that the type size
8204   // might be zero (even if the offset isn't zero) if the indexed type
8205   // is something like [0 x {int, int}]
8206   const Type *IntPtrTy = TD->getIntPtrType(*Context);
8207   int64_t FirstIdx = 0;
8208   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8209     FirstIdx = Offset/TySize;
8210     Offset -= FirstIdx*TySize;
8211     
8212     // Handle hosts where % returns negative instead of values [0..TySize).
8213     if (Offset < 0) {
8214       --FirstIdx;
8215       Offset += TySize;
8216       assert(Offset >= 0);
8217     }
8218     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8219   }
8220   
8221   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8222     
8223   // Index into the types.  If we fail, set OrigBase to null.
8224   while (Offset) {
8225     // Indexing into tail padding between struct/array elements.
8226     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8227       return 0;
8228     
8229     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8230       const StructLayout *SL = TD->getStructLayout(STy);
8231       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8232              "Offset must stay within the indexed type");
8233       
8234       unsigned Elt = SL->getElementContainingOffset(Offset);
8235       NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8236       
8237       Offset -= SL->getElementOffset(Elt);
8238       Ty = STy->getElementType(Elt);
8239     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8240       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8241       assert(EltSize && "Cannot index into a zero-sized array");
8242       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8243       Offset %= EltSize;
8244       Ty = AT->getElementType();
8245     } else {
8246       // Otherwise, we can't index into the middle of this atomic type, bail.
8247       return 0;
8248     }
8249   }
8250   
8251   return Ty;
8252 }
8253
8254 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8255 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8256   Value *Src = CI.getOperand(0);
8257   
8258   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8259     // If casting the result of a getelementptr instruction with no offset, turn
8260     // this into a cast of the original pointer!
8261     if (GEP->hasAllZeroIndices()) {
8262       // Changing the cast operand is usually not a good idea but it is safe
8263       // here because the pointer operand is being replaced with another 
8264       // pointer operand so the opcode doesn't need to change.
8265       AddToWorkList(GEP);
8266       CI.setOperand(0, GEP->getOperand(0));
8267       return &CI;
8268     }
8269     
8270     // If the GEP has a single use, and the base pointer is a bitcast, and the
8271     // GEP computes a constant offset, see if we can convert these three
8272     // instructions into fewer.  This typically happens with unions and other
8273     // non-type-safe code.
8274     if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8275       if (GEP->hasAllConstantIndices()) {
8276         // We are guaranteed to get a constant from EmitGEPOffset.
8277         ConstantInt *OffsetV =
8278                       cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8279         int64_t Offset = OffsetV->getSExtValue();
8280         
8281         // Get the base pointer input of the bitcast, and the type it points to.
8282         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8283         const Type *GEPIdxTy =
8284           cast<PointerType>(OrigBase->getType())->getElementType();
8285         SmallVector<Value*, 8> NewIndices;
8286         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8287           // If we were able to index down into an element, create the GEP
8288           // and bitcast the result.  This eliminates one bitcast, potentially
8289           // two.
8290           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8291                                                         NewIndices.begin(),
8292                                                         NewIndices.end(), "");
8293           InsertNewInstBefore(NGEP, CI);
8294           NGEP->takeName(GEP);
8295           if (cast<GEPOperator>(GEP)->isInBounds())
8296             cast<GEPOperator>(NGEP)->setIsInBounds(true);
8297           
8298           if (isa<BitCastInst>(CI))
8299             return new BitCastInst(NGEP, CI.getType());
8300           assert(isa<PtrToIntInst>(CI));
8301           return new PtrToIntInst(NGEP, CI.getType());
8302         }
8303       }      
8304     }
8305   }
8306     
8307   return commonCastTransforms(CI);
8308 }
8309
8310 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8311 /// type like i42.  We don't want to introduce operations on random non-legal
8312 /// integer types where they don't already exist in the code.  In the future,
8313 /// we should consider making this based off target-data, so that 32-bit targets
8314 /// won't get i64 operations etc.
8315 static bool isSafeIntegerType(const Type *Ty) {
8316   switch (Ty->getPrimitiveSizeInBits()) {
8317   case 8:
8318   case 16:
8319   case 32:
8320   case 64:
8321     return true;
8322   default: 
8323     return false;
8324   }
8325 }
8326
8327 /// commonIntCastTransforms - This function implements the common transforms
8328 /// for trunc, zext, and sext.
8329 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8330   if (Instruction *Result = commonCastTransforms(CI))
8331     return Result;
8332
8333   Value *Src = CI.getOperand(0);
8334   const Type *SrcTy = Src->getType();
8335   const Type *DestTy = CI.getType();
8336   uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8337   uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8338
8339   // See if we can simplify any instructions used by the LHS whose sole 
8340   // purpose is to compute bits we don't care about.
8341   if (SimplifyDemandedInstructionBits(CI))
8342     return &CI;
8343
8344   // If the source isn't an instruction or has more than one use then we
8345   // can't do anything more. 
8346   Instruction *SrcI = dyn_cast<Instruction>(Src);
8347   if (!SrcI || !Src->hasOneUse())
8348     return 0;
8349
8350   // Attempt to propagate the cast into the instruction for int->int casts.
8351   int NumCastsRemoved = 0;
8352   // Only do this if the dest type is a simple type, don't convert the
8353   // expression tree to something weird like i93 unless the source is also
8354   // strange.
8355   if ((isSafeIntegerType(DestTy->getScalarType()) ||
8356        !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8357       CanEvaluateInDifferentType(SrcI, DestTy,
8358                                  CI.getOpcode(), NumCastsRemoved)) {
8359     // If this cast is a truncate, evaluting in a different type always
8360     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8361     // we need to do an AND to maintain the clear top-part of the computation,
8362     // so we require that the input have eliminated at least one cast.  If this
8363     // is a sign extension, we insert two new casts (to do the extension) so we
8364     // require that two casts have been eliminated.
8365     bool DoXForm = false;
8366     bool JustReplace = false;
8367     switch (CI.getOpcode()) {
8368     default:
8369       // All the others use floating point so we shouldn't actually 
8370       // get here because of the check above.
8371       llvm_unreachable("Unknown cast type");
8372     case Instruction::Trunc:
8373       DoXForm = true;
8374       break;
8375     case Instruction::ZExt: {
8376       DoXForm = NumCastsRemoved >= 1;
8377       if (!DoXForm && 0) {
8378         // If it's unnecessary to issue an AND to clear the high bits, it's
8379         // always profitable to do this xform.
8380         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8381         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8382         if (MaskedValueIsZero(TryRes, Mask))
8383           return ReplaceInstUsesWith(CI, TryRes);
8384         
8385         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8386           if (TryI->use_empty())
8387             EraseInstFromFunction(*TryI);
8388       }
8389       break;
8390     }
8391     case Instruction::SExt: {
8392       DoXForm = NumCastsRemoved >= 2;
8393       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8394         // If we do not have to emit the truncate + sext pair, then it's always
8395         // profitable to do this xform.
8396         //
8397         // It's not safe to eliminate the trunc + sext pair if one of the
8398         // eliminated cast is a truncate. e.g.
8399         // t2 = trunc i32 t1 to i16
8400         // t3 = sext i16 t2 to i32
8401         // !=
8402         // i32 t1
8403         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8404         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8405         if (NumSignBits > (DestBitSize - SrcBitSize))
8406           return ReplaceInstUsesWith(CI, TryRes);
8407         
8408         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8409           if (TryI->use_empty())
8410             EraseInstFromFunction(*TryI);
8411       }
8412       break;
8413     }
8414     }
8415     
8416     if (DoXForm) {
8417       DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8418             " to avoid cast: " << CI);
8419       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8420                                            CI.getOpcode() == Instruction::SExt);
8421       if (JustReplace)
8422         // Just replace this cast with the result.
8423         return ReplaceInstUsesWith(CI, Res);
8424
8425       assert(Res->getType() == DestTy);
8426       switch (CI.getOpcode()) {
8427       default: llvm_unreachable("Unknown cast type!");
8428       case Instruction::Trunc:
8429         // Just replace this cast with the result.
8430         return ReplaceInstUsesWith(CI, Res);
8431       case Instruction::ZExt: {
8432         assert(SrcBitSize < DestBitSize && "Not a zext?");
8433
8434         // If the high bits are already zero, just replace this cast with the
8435         // result.
8436         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8437         if (MaskedValueIsZero(Res, Mask))
8438           return ReplaceInstUsesWith(CI, Res);
8439
8440         // We need to emit an AND to clear the high bits.
8441         Constant *C = ConstantInt::get(*Context, 
8442                                  APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8443         return BinaryOperator::CreateAnd(Res, C);
8444       }
8445       case Instruction::SExt: {
8446         // If the high bits are already filled with sign bit, just replace this
8447         // cast with the result.
8448         unsigned NumSignBits = ComputeNumSignBits(Res);
8449         if (NumSignBits > (DestBitSize - SrcBitSize))
8450           return ReplaceInstUsesWith(CI, Res);
8451
8452         // We need to emit a cast to truncate, then a cast to sext.
8453         return CastInst::Create(Instruction::SExt,
8454             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8455                              CI), DestTy);
8456       }
8457       }
8458     }
8459   }
8460   
8461   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8462   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8463
8464   switch (SrcI->getOpcode()) {
8465   case Instruction::Add:
8466   case Instruction::Mul:
8467   case Instruction::And:
8468   case Instruction::Or:
8469   case Instruction::Xor:
8470     // If we are discarding information, rewrite.
8471     if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8472       // Don't insert two casts unless at least one can be eliminated.
8473       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8474           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8475         Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8476         Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8477         return BinaryOperator::Create(
8478             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8479       }
8480     }
8481
8482     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8483     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8484         SrcI->getOpcode() == Instruction::Xor &&
8485         Op1 == ConstantInt::getTrue(*Context) &&
8486         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8487       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8488       return BinaryOperator::CreateXor(New,
8489                                       ConstantInt::get(CI.getType(), 1));
8490     }
8491     break;
8492
8493   case Instruction::Shl: {
8494     // Canonicalize trunc inside shl, if we can.
8495     ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8496     if (CI && DestBitSize < SrcBitSize &&
8497         CI->getLimitedValue(DestBitSize) < DestBitSize) {
8498       Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8499       Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8500       return BinaryOperator::CreateShl(Op0c, Op1c);
8501     }
8502     break;
8503   }
8504   }
8505   return 0;
8506 }
8507
8508 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8509   if (Instruction *Result = commonIntCastTransforms(CI))
8510     return Result;
8511   
8512   Value *Src = CI.getOperand(0);
8513   const Type *Ty = CI.getType();
8514   uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8515   uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8516
8517   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8518   if (DestBitWidth == 1) {
8519     Constant *One = ConstantInt::get(Src->getType(), 1);
8520     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8521     Value *Zero = Constant::getNullValue(Src->getType());
8522     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8523   }
8524
8525   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8526   ConstantInt *ShAmtV = 0;
8527   Value *ShiftOp = 0;
8528   if (Src->hasOneUse() &&
8529       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8530     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8531     
8532     // Get a mask for the bits shifting in.
8533     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8534     if (MaskedValueIsZero(ShiftOp, Mask)) {
8535       if (ShAmt >= DestBitWidth)        // All zeros.
8536         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8537       
8538       // Okay, we can shrink this.  Truncate the input, then return a new
8539       // shift.
8540       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8541       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8542       return BinaryOperator::CreateLShr(V1, V2);
8543     }
8544   }
8545   
8546   return 0;
8547 }
8548
8549 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8550 /// in order to eliminate the icmp.
8551 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8552                                              bool DoXform) {
8553   // If we are just checking for a icmp eq of a single bit and zext'ing it
8554   // to an integer, then shift the bit to the appropriate place and then
8555   // cast to integer to avoid the comparison.
8556   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8557     const APInt &Op1CV = Op1C->getValue();
8558       
8559     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8560     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8561     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8562         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8563       if (!DoXform) return ICI;
8564
8565       Value *In = ICI->getOperand(0);
8566       Value *Sh = ConstantInt::get(In->getType(),
8567                                    In->getType()->getScalarSizeInBits()-1);
8568       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8569                                                         In->getName()+".lobit"),
8570                                CI);
8571       if (In->getType() != CI.getType())
8572         In = CastInst::CreateIntegerCast(In, CI.getType(),
8573                                          false/*ZExt*/, "tmp", &CI);
8574
8575       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8576         Constant *One = ConstantInt::get(In->getType(), 1);
8577         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8578                                                          In->getName()+".not"),
8579                                  CI);
8580       }
8581
8582       return ReplaceInstUsesWith(CI, In);
8583     }
8584       
8585       
8586       
8587     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8588     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8589     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8590     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8591     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8592     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8593     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8594     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8595     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8596         // This only works for EQ and NE
8597         ICI->isEquality()) {
8598       // If Op1C some other power of two, convert:
8599       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8600       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8601       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8602       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8603         
8604       APInt KnownZeroMask(~KnownZero);
8605       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8606         if (!DoXform) return ICI;
8607
8608         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8609         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8610           // (X&4) == 2 --> false
8611           // (X&4) != 2 --> true
8612           Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8613           Res = ConstantExpr::getZExt(Res, CI.getType());
8614           return ReplaceInstUsesWith(CI, Res);
8615         }
8616           
8617         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8618         Value *In = ICI->getOperand(0);
8619         if (ShiftAmt) {
8620           // Perform a logical shr by shiftamt.
8621           // Insert the shift to put the result in the low bit.
8622           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8623                               ConstantInt::get(In->getType(), ShiftAmt),
8624                                                    In->getName()+".lobit"), CI);
8625         }
8626           
8627         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8628           Constant *One = ConstantInt::get(In->getType(), 1);
8629           In = BinaryOperator::CreateXor(In, One, "tmp");
8630           InsertNewInstBefore(cast<Instruction>(In), CI);
8631         }
8632           
8633         if (CI.getType() == In->getType())
8634           return ReplaceInstUsesWith(CI, In);
8635         else
8636           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8637       }
8638     }
8639   }
8640
8641   return 0;
8642 }
8643
8644 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8645   // If one of the common conversion will work ..
8646   if (Instruction *Result = commonIntCastTransforms(CI))
8647     return Result;
8648
8649   Value *Src = CI.getOperand(0);
8650
8651   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8652   // types and if the sizes are just right we can convert this into a logical
8653   // 'and' which will be much cheaper than the pair of casts.
8654   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8655     // Get the sizes of the types involved.  We know that the intermediate type
8656     // will be smaller than A or C, but don't know the relation between A and C.
8657     Value *A = CSrc->getOperand(0);
8658     unsigned SrcSize = A->getType()->getScalarSizeInBits();
8659     unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8660     unsigned DstSize = CI.getType()->getScalarSizeInBits();
8661     // If we're actually extending zero bits, then if
8662     // SrcSize <  DstSize: zext(a & mask)
8663     // SrcSize == DstSize: a & mask
8664     // SrcSize  > DstSize: trunc(a) & mask
8665     if (SrcSize < DstSize) {
8666       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8667       Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8668       Instruction *And =
8669         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8670       InsertNewInstBefore(And, CI);
8671       return new ZExtInst(And, CI.getType());
8672     } else if (SrcSize == DstSize) {
8673       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8674       return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8675                                                            AndValue));
8676     } else if (SrcSize > DstSize) {
8677       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8678       InsertNewInstBefore(Trunc, CI);
8679       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8680       return BinaryOperator::CreateAnd(Trunc, 
8681                                        ConstantInt::get(Trunc->getType(),
8682                                                                AndValue));
8683     }
8684   }
8685
8686   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8687     return transformZExtICmp(ICI, CI);
8688
8689   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8690   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8691     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8692     // of the (zext icmp) will be transformed.
8693     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8694     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8695     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8696         (transformZExtICmp(LHS, CI, false) ||
8697          transformZExtICmp(RHS, CI, false))) {
8698       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8699       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8700       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8701     }
8702   }
8703
8704   // zext(trunc(t) & C) -> (t & zext(C)).
8705   if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8706     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8707       if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8708         Value *TI0 = TI->getOperand(0);
8709         if (TI0->getType() == CI.getType())
8710           return
8711             BinaryOperator::CreateAnd(TI0,
8712                                 ConstantExpr::getZExt(C, CI.getType()));
8713       }
8714
8715   // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8716   if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8717     if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8718       if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8719         if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8720             And->getOperand(1) == C)
8721           if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8722             Value *TI0 = TI->getOperand(0);
8723             if (TI0->getType() == CI.getType()) {
8724               Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8725               Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8726               InsertNewInstBefore(NewAnd, *And);
8727               return BinaryOperator::CreateXor(NewAnd, ZC);
8728             }
8729           }
8730
8731   return 0;
8732 }
8733
8734 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8735   if (Instruction *I = commonIntCastTransforms(CI))
8736     return I;
8737   
8738   Value *Src = CI.getOperand(0);
8739   
8740   // Canonicalize sign-extend from i1 to a select.
8741   if (Src->getType() == Type::getInt1Ty(*Context))
8742     return SelectInst::Create(Src,
8743                               Constant::getAllOnesValue(CI.getType()),
8744                               Constant::getNullValue(CI.getType()));
8745
8746   // See if the value being truncated is already sign extended.  If so, just
8747   // eliminate the trunc/sext pair.
8748   if (Operator::getOpcode(Src) == Instruction::Trunc) {
8749     Value *Op = cast<User>(Src)->getOperand(0);
8750     unsigned OpBits   = Op->getType()->getScalarSizeInBits();
8751     unsigned MidBits  = Src->getType()->getScalarSizeInBits();
8752     unsigned DestBits = CI.getType()->getScalarSizeInBits();
8753     unsigned NumSignBits = ComputeNumSignBits(Op);
8754
8755     if (OpBits == DestBits) {
8756       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8757       // bits, it is already ready.
8758       if (NumSignBits > DestBits-MidBits)
8759         return ReplaceInstUsesWith(CI, Op);
8760     } else if (OpBits < DestBits) {
8761       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8762       // bits, just sext from i32.
8763       if (NumSignBits > OpBits-MidBits)
8764         return new SExtInst(Op, CI.getType(), "tmp");
8765     } else {
8766       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8767       // bits, just truncate to i32.
8768       if (NumSignBits > OpBits-MidBits)
8769         return new TruncInst(Op, CI.getType(), "tmp");
8770     }
8771   }
8772
8773   // If the input is a shl/ashr pair of a same constant, then this is a sign
8774   // extension from a smaller value.  If we could trust arbitrary bitwidth
8775   // integers, we could turn this into a truncate to the smaller bit and then
8776   // use a sext for the whole extension.  Since we don't, look deeper and check
8777   // for a truncate.  If the source and dest are the same type, eliminate the
8778   // trunc and extend and just do shifts.  For example, turn:
8779   //   %a = trunc i32 %i to i8
8780   //   %b = shl i8 %a, 6
8781   //   %c = ashr i8 %b, 6
8782   //   %d = sext i8 %c to i32
8783   // into:
8784   //   %a = shl i32 %i, 30
8785   //   %d = ashr i32 %a, 30
8786   Value *A = 0;
8787   ConstantInt *BA = 0, *CA = 0;
8788   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8789                         m_ConstantInt(CA))) &&
8790       BA == CA && isa<TruncInst>(A)) {
8791     Value *I = cast<TruncInst>(A)->getOperand(0);
8792     if (I->getType() == CI.getType()) {
8793       unsigned MidSize = Src->getType()->getScalarSizeInBits();
8794       unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8795       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8796       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8797       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8798                                                         CI.getName()), CI);
8799       return BinaryOperator::CreateAShr(I, ShAmtV);
8800     }
8801   }
8802   
8803   return 0;
8804 }
8805
8806 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8807 /// in the specified FP type without changing its value.
8808 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8809                               LLVMContext *Context) {
8810   bool losesInfo;
8811   APFloat F = CFP->getValueAPF();
8812   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8813   if (!losesInfo)
8814     return ConstantFP::get(*Context, F);
8815   return 0;
8816 }
8817
8818 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8819 /// through it until we get the source value.
8820 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8821   if (Instruction *I = dyn_cast<Instruction>(V))
8822     if (I->getOpcode() == Instruction::FPExt)
8823       return LookThroughFPExtensions(I->getOperand(0), Context);
8824   
8825   // If this value is a constant, return the constant in the smallest FP type
8826   // that can accurately represent it.  This allows us to turn
8827   // (float)((double)X+2.0) into x+2.0f.
8828   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8829     if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8830       return V;  // No constant folding of this.
8831     // See if the value can be truncated to float and then reextended.
8832     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8833       return V;
8834     if (CFP->getType() == Type::getDoubleTy(*Context))
8835       return V;  // Won't shrink.
8836     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8837       return V;
8838     // Don't try to shrink to various long double types.
8839   }
8840   
8841   return V;
8842 }
8843
8844 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8845   if (Instruction *I = commonCastTransforms(CI))
8846     return I;
8847   
8848   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8849   // smaller than the destination type, we can eliminate the truncate by doing
8850   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8851   // many builtins (sqrt, etc).
8852   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8853   if (OpI && OpI->hasOneUse()) {
8854     switch (OpI->getOpcode()) {
8855     default: break;
8856     case Instruction::FAdd:
8857     case Instruction::FSub:
8858     case Instruction::FMul:
8859     case Instruction::FDiv:
8860     case Instruction::FRem:
8861       const Type *SrcTy = OpI->getType();
8862       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8863       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8864       if (LHSTrunc->getType() != SrcTy && 
8865           RHSTrunc->getType() != SrcTy) {
8866         unsigned DstSize = CI.getType()->getScalarSizeInBits();
8867         // If the source types were both smaller than the destination type of
8868         // the cast, do this xform.
8869         if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8870             RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8871           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8872                                       CI.getType(), CI);
8873           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8874                                       CI.getType(), CI);
8875           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8876         }
8877       }
8878       break;  
8879     }
8880   }
8881   return 0;
8882 }
8883
8884 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8885   return commonCastTransforms(CI);
8886 }
8887
8888 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8889   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8890   if (OpI == 0)
8891     return commonCastTransforms(FI);
8892
8893   // fptoui(uitofp(X)) --> X
8894   // fptoui(sitofp(X)) --> X
8895   // This is safe if the intermediate type has enough bits in its mantissa to
8896   // accurately represent all values of X.  For example, do not do this with
8897   // i64->float->i64.  This is also safe for sitofp case, because any negative
8898   // 'X' value would cause an undefined result for the fptoui. 
8899   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8900       OpI->getOperand(0)->getType() == FI.getType() &&
8901       (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8902                     OpI->getType()->getFPMantissaWidth())
8903     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8904
8905   return commonCastTransforms(FI);
8906 }
8907
8908 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8909   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8910   if (OpI == 0)
8911     return commonCastTransforms(FI);
8912   
8913   // fptosi(sitofp(X)) --> X
8914   // fptosi(uitofp(X)) --> X
8915   // This is safe if the intermediate type has enough bits in its mantissa to
8916   // accurately represent all values of X.  For example, do not do this with
8917   // i64->float->i64.  This is also safe for sitofp case, because any negative
8918   // 'X' value would cause an undefined result for the fptoui. 
8919   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8920       OpI->getOperand(0)->getType() == FI.getType() &&
8921       (int)FI.getType()->getScalarSizeInBits() <=
8922                     OpI->getType()->getFPMantissaWidth())
8923     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8924   
8925   return commonCastTransforms(FI);
8926 }
8927
8928 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8929   return commonCastTransforms(CI);
8930 }
8931
8932 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8933   return commonCastTransforms(CI);
8934 }
8935
8936 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8937   // If the destination integer type is smaller than the intptr_t type for
8938   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8939   // trunc to be exposed to other transforms.  Don't do this for extending
8940   // ptrtoint's, because we don't know if the target sign or zero extends its
8941   // pointers.
8942   if (TD &&
8943       CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8944     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8945                                              TD->getIntPtrType(CI.getContext()),
8946                                                     "tmp"), CI);
8947     return new TruncInst(P, CI.getType());
8948   }
8949   
8950   return commonPointerCastTransforms(CI);
8951 }
8952
8953 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8954   // If the source integer type is larger than the intptr_t type for
8955   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8956   // allows the trunc to be exposed to other transforms.  Don't do this for
8957   // extending inttoptr's, because we don't know if the target sign or zero
8958   // extends to pointers.
8959   if (TD &&
8960       CI.getOperand(0)->getType()->getScalarSizeInBits() >
8961       TD->getPointerSizeInBits()) {
8962     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8963                                              TD->getIntPtrType(CI.getContext()),
8964                                                  "tmp"), CI);
8965     return new IntToPtrInst(P, CI.getType());
8966   }
8967   
8968   if (Instruction *I = commonCastTransforms(CI))
8969     return I;
8970
8971   return 0;
8972 }
8973
8974 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8975   // If the operands are integer typed then apply the integer transforms,
8976   // otherwise just apply the common ones.
8977   Value *Src = CI.getOperand(0);
8978   const Type *SrcTy = Src->getType();
8979   const Type *DestTy = CI.getType();
8980
8981   if (isa<PointerType>(SrcTy)) {
8982     if (Instruction *I = commonPointerCastTransforms(CI))
8983       return I;
8984   } else {
8985     if (Instruction *Result = commonCastTransforms(CI))
8986       return Result;
8987   }
8988
8989
8990   // Get rid of casts from one type to the same type. These are useless and can
8991   // be replaced by the operand.
8992   if (DestTy == Src->getType())
8993     return ReplaceInstUsesWith(CI, Src);
8994
8995   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8996     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8997     const Type *DstElTy = DstPTy->getElementType();
8998     const Type *SrcElTy = SrcPTy->getElementType();
8999     
9000     // If the address spaces don't match, don't eliminate the bitcast, which is
9001     // required for changing types.
9002     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9003       return 0;
9004     
9005     // If we are casting a malloc or alloca to a pointer to a type of the same
9006     // size, rewrite the allocation instruction to allocate the "right" type.
9007     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9008       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9009         return V;
9010     
9011     // If the source and destination are pointers, and this cast is equivalent
9012     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
9013     // This can enhance SROA and other transforms that want type-safe pointers.
9014     Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
9015     unsigned NumZeros = 0;
9016     while (SrcElTy != DstElTy && 
9017            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9018            SrcElTy->getNumContainedTypes() /* not "{}" */) {
9019       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9020       ++NumZeros;
9021     }
9022
9023     // If we found a path from the src to dest, create the getelementptr now.
9024     if (SrcElTy == DstElTy) {
9025       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9026       Instruction *GEP = GetElementPtrInst::Create(Src,
9027                                                    Idxs.begin(), Idxs.end(), "",
9028                                                    ((Instruction*) NULL));
9029       cast<GEPOperator>(GEP)->setIsInBounds(true);
9030       return GEP;
9031     }
9032   }
9033
9034   if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9035     if (DestVTy->getNumElements() == 1) {
9036       if (!isa<VectorType>(SrcTy)) {
9037         Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9038                                        DestVTy->getElementType(), CI);
9039         return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9040                                          Constant::getNullValue(Type::getInt32Ty(*Context)));
9041       }
9042       // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9043     }
9044   }
9045
9046   if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9047     if (SrcVTy->getNumElements() == 1) {
9048       if (!isa<VectorType>(DestTy)) {
9049         Instruction *Elem =
9050           ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
9051         InsertNewInstBefore(Elem, CI);
9052         return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9053       }
9054     }
9055   }
9056
9057   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9058     if (SVI->hasOneUse()) {
9059       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
9060       // a bitconvert to a vector with the same # elts.
9061       if (isa<VectorType>(DestTy) && 
9062           cast<VectorType>(DestTy)->getNumElements() ==
9063                 SVI->getType()->getNumElements() &&
9064           SVI->getType()->getNumElements() ==
9065             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9066         CastInst *Tmp;
9067         // If either of the operands is a cast from CI.getType(), then
9068         // evaluating the shuffle in the casted destination's type will allow
9069         // us to eliminate at least one cast.
9070         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
9071              Tmp->getOperand(0)->getType() == DestTy) ||
9072             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
9073              Tmp->getOperand(0)->getType() == DestTy)) {
9074           Value *LHS = InsertCastBefore(Instruction::BitCast,
9075                                         SVI->getOperand(0), DestTy, CI);
9076           Value *RHS = InsertCastBefore(Instruction::BitCast,
9077                                         SVI->getOperand(1), DestTy, CI);
9078           // Return a new shuffle vector.  Use the same element ID's, as we
9079           // know the vector types match #elts.
9080           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9081         }
9082       }
9083     }
9084   }
9085   return 0;
9086 }
9087
9088 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9089 ///   %C = or %A, %B
9090 ///   %D = select %cond, %C, %A
9091 /// into:
9092 ///   %C = select %cond, %B, 0
9093 ///   %D = or %A, %C
9094 ///
9095 /// Assuming that the specified instruction is an operand to the select, return
9096 /// a bitmask indicating which operands of this instruction are foldable if they
9097 /// equal the other incoming value of the select.
9098 ///
9099 static unsigned GetSelectFoldableOperands(Instruction *I) {
9100   switch (I->getOpcode()) {
9101   case Instruction::Add:
9102   case Instruction::Mul:
9103   case Instruction::And:
9104   case Instruction::Or:
9105   case Instruction::Xor:
9106     return 3;              // Can fold through either operand.
9107   case Instruction::Sub:   // Can only fold on the amount subtracted.
9108   case Instruction::Shl:   // Can only fold on the shift amount.
9109   case Instruction::LShr:
9110   case Instruction::AShr:
9111     return 1;
9112   default:
9113     return 0;              // Cannot fold
9114   }
9115 }
9116
9117 /// GetSelectFoldableConstant - For the same transformation as the previous
9118 /// function, return the identity constant that goes into the select.
9119 static Constant *GetSelectFoldableConstant(Instruction *I,
9120                                            LLVMContext *Context) {
9121   switch (I->getOpcode()) {
9122   default: llvm_unreachable("This cannot happen!");
9123   case Instruction::Add:
9124   case Instruction::Sub:
9125   case Instruction::Or:
9126   case Instruction::Xor:
9127   case Instruction::Shl:
9128   case Instruction::LShr:
9129   case Instruction::AShr:
9130     return Constant::getNullValue(I->getType());
9131   case Instruction::And:
9132     return Constant::getAllOnesValue(I->getType());
9133   case Instruction::Mul:
9134     return ConstantInt::get(I->getType(), 1);
9135   }
9136 }
9137
9138 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9139 /// have the same opcode and only one use each.  Try to simplify this.
9140 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9141                                           Instruction *FI) {
9142   if (TI->getNumOperands() == 1) {
9143     // If this is a non-volatile load or a cast from the same type,
9144     // merge.
9145     if (TI->isCast()) {
9146       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9147         return 0;
9148     } else {
9149       return 0;  // unknown unary op.
9150     }
9151
9152     // Fold this by inserting a select from the input values.
9153     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9154                                           FI->getOperand(0), SI.getName()+".v");
9155     InsertNewInstBefore(NewSI, SI);
9156     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9157                             TI->getType());
9158   }
9159
9160   // Only handle binary operators here.
9161   if (!isa<BinaryOperator>(TI))
9162     return 0;
9163
9164   // Figure out if the operations have any operands in common.
9165   Value *MatchOp, *OtherOpT, *OtherOpF;
9166   bool MatchIsOpZero;
9167   if (TI->getOperand(0) == FI->getOperand(0)) {
9168     MatchOp  = TI->getOperand(0);
9169     OtherOpT = TI->getOperand(1);
9170     OtherOpF = FI->getOperand(1);
9171     MatchIsOpZero = true;
9172   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9173     MatchOp  = TI->getOperand(1);
9174     OtherOpT = TI->getOperand(0);
9175     OtherOpF = FI->getOperand(0);
9176     MatchIsOpZero = false;
9177   } else if (!TI->isCommutative()) {
9178     return 0;
9179   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9180     MatchOp  = TI->getOperand(0);
9181     OtherOpT = TI->getOperand(1);
9182     OtherOpF = FI->getOperand(0);
9183     MatchIsOpZero = true;
9184   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9185     MatchOp  = TI->getOperand(1);
9186     OtherOpT = TI->getOperand(0);
9187     OtherOpF = FI->getOperand(1);
9188     MatchIsOpZero = true;
9189   } else {
9190     return 0;
9191   }
9192
9193   // If we reach here, they do have operations in common.
9194   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9195                                          OtherOpF, SI.getName()+".v");
9196   InsertNewInstBefore(NewSI, SI);
9197
9198   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9199     if (MatchIsOpZero)
9200       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9201     else
9202       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9203   }
9204   llvm_unreachable("Shouldn't get here");
9205   return 0;
9206 }
9207
9208 static bool isSelect01(Constant *C1, Constant *C2) {
9209   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9210   if (!C1I)
9211     return false;
9212   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9213   if (!C2I)
9214     return false;
9215   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9216 }
9217
9218 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9219 /// facilitate further optimization.
9220 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9221                                             Value *FalseVal) {
9222   // See the comment above GetSelectFoldableOperands for a description of the
9223   // transformation we are doing here.
9224   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9225     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9226         !isa<Constant>(FalseVal)) {
9227       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9228         unsigned OpToFold = 0;
9229         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9230           OpToFold = 1;
9231         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9232           OpToFold = 2;
9233         }
9234
9235         if (OpToFold) {
9236           Constant *C = GetSelectFoldableConstant(TVI, Context);
9237           Value *OOp = TVI->getOperand(2-OpToFold);
9238           // Avoid creating select between 2 constants unless it's selecting
9239           // between 0 and 1.
9240           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9241             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9242             InsertNewInstBefore(NewSel, SI);
9243             NewSel->takeName(TVI);
9244             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9245               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9246             llvm_unreachable("Unknown instruction!!");
9247           }
9248         }
9249       }
9250     }
9251   }
9252
9253   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9254     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9255         !isa<Constant>(TrueVal)) {
9256       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9257         unsigned OpToFold = 0;
9258         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9259           OpToFold = 1;
9260         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9261           OpToFold = 2;
9262         }
9263
9264         if (OpToFold) {
9265           Constant *C = GetSelectFoldableConstant(FVI, Context);
9266           Value *OOp = FVI->getOperand(2-OpToFold);
9267           // Avoid creating select between 2 constants unless it's selecting
9268           // between 0 and 1.
9269           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9270             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9271             InsertNewInstBefore(NewSel, SI);
9272             NewSel->takeName(FVI);
9273             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9274               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9275             llvm_unreachable("Unknown instruction!!");
9276           }
9277         }
9278       }
9279     }
9280   }
9281
9282   return 0;
9283 }
9284
9285 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9286 /// ICmpInst as its first operand.
9287 ///
9288 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9289                                                    ICmpInst *ICI) {
9290   bool Changed = false;
9291   ICmpInst::Predicate Pred = ICI->getPredicate();
9292   Value *CmpLHS = ICI->getOperand(0);
9293   Value *CmpRHS = ICI->getOperand(1);
9294   Value *TrueVal = SI.getTrueValue();
9295   Value *FalseVal = SI.getFalseValue();
9296
9297   // Check cases where the comparison is with a constant that
9298   // can be adjusted to fit the min/max idiom. We may edit ICI in
9299   // place here, so make sure the select is the only user.
9300   if (ICI->hasOneUse())
9301     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9302       switch (Pred) {
9303       default: break;
9304       case ICmpInst::ICMP_ULT:
9305       case ICmpInst::ICMP_SLT: {
9306         // X < MIN ? T : F  -->  F
9307         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9308           return ReplaceInstUsesWith(SI, FalseVal);
9309         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9310         Constant *AdjustedRHS = SubOne(CI);
9311         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9312             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9313           Pred = ICmpInst::getSwappedPredicate(Pred);
9314           CmpRHS = AdjustedRHS;
9315           std::swap(FalseVal, TrueVal);
9316           ICI->setPredicate(Pred);
9317           ICI->setOperand(1, CmpRHS);
9318           SI.setOperand(1, TrueVal);
9319           SI.setOperand(2, FalseVal);
9320           Changed = true;
9321         }
9322         break;
9323       }
9324       case ICmpInst::ICMP_UGT:
9325       case ICmpInst::ICMP_SGT: {
9326         // X > MAX ? T : F  -->  F
9327         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9328           return ReplaceInstUsesWith(SI, FalseVal);
9329         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9330         Constant *AdjustedRHS = AddOne(CI);
9331         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9332             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9333           Pred = ICmpInst::getSwappedPredicate(Pred);
9334           CmpRHS = AdjustedRHS;
9335           std::swap(FalseVal, TrueVal);
9336           ICI->setPredicate(Pred);
9337           ICI->setOperand(1, CmpRHS);
9338           SI.setOperand(1, TrueVal);
9339           SI.setOperand(2, FalseVal);
9340           Changed = true;
9341         }
9342         break;
9343       }
9344       }
9345
9346       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9347       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9348       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9349       if (match(TrueVal, m_ConstantInt<-1>()) &&
9350           match(FalseVal, m_ConstantInt<0>()))
9351         Pred = ICI->getPredicate();
9352       else if (match(TrueVal, m_ConstantInt<0>()) &&
9353                match(FalseVal, m_ConstantInt<-1>()))
9354         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9355       
9356       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9357         // If we are just checking for a icmp eq of a single bit and zext'ing it
9358         // to an integer, then shift the bit to the appropriate place and then
9359         // cast to integer to avoid the comparison.
9360         const APInt &Op1CV = CI->getValue();
9361     
9362         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9363         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9364         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9365             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9366           Value *In = ICI->getOperand(0);
9367           Value *Sh = ConstantInt::get(In->getType(),
9368                                        In->getType()->getScalarSizeInBits()-1);
9369           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9370                                                         In->getName()+".lobit"),
9371                                    *ICI);
9372           if (In->getType() != SI.getType())
9373             In = CastInst::CreateIntegerCast(In, SI.getType(),
9374                                              true/*SExt*/, "tmp", ICI);
9375     
9376           if (Pred == ICmpInst::ICMP_SGT)
9377             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9378                                        In->getName()+".not"), *ICI);
9379     
9380           return ReplaceInstUsesWith(SI, In);
9381         }
9382       }
9383     }
9384
9385   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9386     // Transform (X == Y) ? X : Y  -> Y
9387     if (Pred == ICmpInst::ICMP_EQ)
9388       return ReplaceInstUsesWith(SI, FalseVal);
9389     // Transform (X != Y) ? X : Y  -> X
9390     if (Pred == ICmpInst::ICMP_NE)
9391       return ReplaceInstUsesWith(SI, TrueVal);
9392     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9393
9394   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9395     // Transform (X == Y) ? Y : X  -> X
9396     if (Pred == ICmpInst::ICMP_EQ)
9397       return ReplaceInstUsesWith(SI, FalseVal);
9398     // Transform (X != Y) ? Y : X  -> Y
9399     if (Pred == ICmpInst::ICMP_NE)
9400       return ReplaceInstUsesWith(SI, TrueVal);
9401     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9402   }
9403
9404   /// NOTE: if we wanted to, this is where to detect integer ABS
9405
9406   return Changed ? &SI : 0;
9407 }
9408
9409 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9410   Value *CondVal = SI.getCondition();
9411   Value *TrueVal = SI.getTrueValue();
9412   Value *FalseVal = SI.getFalseValue();
9413
9414   // select true, X, Y  -> X
9415   // select false, X, Y -> Y
9416   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9417     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9418
9419   // select C, X, X -> X
9420   if (TrueVal == FalseVal)
9421     return ReplaceInstUsesWith(SI, TrueVal);
9422
9423   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9424     return ReplaceInstUsesWith(SI, FalseVal);
9425   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9426     return ReplaceInstUsesWith(SI, TrueVal);
9427   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9428     if (isa<Constant>(TrueVal))
9429       return ReplaceInstUsesWith(SI, TrueVal);
9430     else
9431       return ReplaceInstUsesWith(SI, FalseVal);
9432   }
9433
9434   if (SI.getType() == Type::getInt1Ty(*Context)) {
9435     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9436       if (C->getZExtValue()) {
9437         // Change: A = select B, true, C --> A = or B, C
9438         return BinaryOperator::CreateOr(CondVal, FalseVal);
9439       } else {
9440         // Change: A = select B, false, C --> A = and !B, C
9441         Value *NotCond =
9442           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9443                                              "not."+CondVal->getName()), SI);
9444         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9445       }
9446     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9447       if (C->getZExtValue() == false) {
9448         // Change: A = select B, C, false --> A = and B, C
9449         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9450       } else {
9451         // Change: A = select B, C, true --> A = or !B, C
9452         Value *NotCond =
9453           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9454                                              "not."+CondVal->getName()), SI);
9455         return BinaryOperator::CreateOr(NotCond, TrueVal);
9456       }
9457     }
9458     
9459     // select a, b, a  -> a&b
9460     // select a, a, b  -> a|b
9461     if (CondVal == TrueVal)
9462       return BinaryOperator::CreateOr(CondVal, FalseVal);
9463     else if (CondVal == FalseVal)
9464       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9465   }
9466
9467   // Selecting between two integer constants?
9468   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9469     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9470       // select C, 1, 0 -> zext C to int
9471       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9472         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9473       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9474         // select C, 0, 1 -> zext !C to int
9475         Value *NotCond =
9476           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9477                                                "not."+CondVal->getName()), SI);
9478         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9479       }
9480
9481       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9482         // If one of the constants is zero (we know they can't both be) and we
9483         // have an icmp instruction with zero, and we have an 'and' with the
9484         // non-constant value, eliminate this whole mess.  This corresponds to
9485         // cases like this: ((X & 27) ? 27 : 0)
9486         if (TrueValC->isZero() || FalseValC->isZero())
9487           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9488               cast<Constant>(IC->getOperand(1))->isNullValue())
9489             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9490               if (ICA->getOpcode() == Instruction::And &&
9491                   isa<ConstantInt>(ICA->getOperand(1)) &&
9492                   (ICA->getOperand(1) == TrueValC ||
9493                    ICA->getOperand(1) == FalseValC) &&
9494                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9495                 // Okay, now we know that everything is set up, we just don't
9496                 // know whether we have a icmp_ne or icmp_eq and whether the 
9497                 // true or false val is the zero.
9498                 bool ShouldNotVal = !TrueValC->isZero();
9499                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9500                 Value *V = ICA;
9501                 if (ShouldNotVal)
9502                   V = InsertNewInstBefore(BinaryOperator::Create(
9503                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9504                 return ReplaceInstUsesWith(SI, V);
9505               }
9506       }
9507     }
9508
9509   // See if we are selecting two values based on a comparison of the two values.
9510   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9511     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9512       // Transform (X == Y) ? X : Y  -> Y
9513       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9514         // This is not safe in general for floating point:  
9515         // consider X== -0, Y== +0.
9516         // It becomes safe if either operand is a nonzero constant.
9517         ConstantFP *CFPt, *CFPf;
9518         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9519               !CFPt->getValueAPF().isZero()) ||
9520             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9521              !CFPf->getValueAPF().isZero()))
9522         return ReplaceInstUsesWith(SI, FalseVal);
9523       }
9524       // Transform (X != Y) ? X : Y  -> X
9525       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9526         return ReplaceInstUsesWith(SI, TrueVal);
9527       // NOTE: if we wanted to, this is where to detect MIN/MAX
9528
9529     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9530       // Transform (X == Y) ? Y : X  -> X
9531       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9532         // This is not safe in general for floating point:  
9533         // consider X== -0, Y== +0.
9534         // It becomes safe if either operand is a nonzero constant.
9535         ConstantFP *CFPt, *CFPf;
9536         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9537               !CFPt->getValueAPF().isZero()) ||
9538             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9539              !CFPf->getValueAPF().isZero()))
9540           return ReplaceInstUsesWith(SI, FalseVal);
9541       }
9542       // Transform (X != Y) ? Y : X  -> Y
9543       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9544         return ReplaceInstUsesWith(SI, TrueVal);
9545       // NOTE: if we wanted to, this is where to detect MIN/MAX
9546     }
9547     // NOTE: if we wanted to, this is where to detect ABS
9548   }
9549
9550   // See if we are selecting two values based on a comparison of the two values.
9551   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9552     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9553       return Result;
9554
9555   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9556     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9557       if (TI->hasOneUse() && FI->hasOneUse()) {
9558         Instruction *AddOp = 0, *SubOp = 0;
9559
9560         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9561         if (TI->getOpcode() == FI->getOpcode())
9562           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9563             return IV;
9564
9565         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9566         // even legal for FP.
9567         if ((TI->getOpcode() == Instruction::Sub &&
9568              FI->getOpcode() == Instruction::Add) ||
9569             (TI->getOpcode() == Instruction::FSub &&
9570              FI->getOpcode() == Instruction::FAdd)) {
9571           AddOp = FI; SubOp = TI;
9572         } else if ((FI->getOpcode() == Instruction::Sub &&
9573                     TI->getOpcode() == Instruction::Add) ||
9574                    (FI->getOpcode() == Instruction::FSub &&
9575                     TI->getOpcode() == Instruction::FAdd)) {
9576           AddOp = TI; SubOp = FI;
9577         }
9578
9579         if (AddOp) {
9580           Value *OtherAddOp = 0;
9581           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9582             OtherAddOp = AddOp->getOperand(1);
9583           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9584             OtherAddOp = AddOp->getOperand(0);
9585           }
9586
9587           if (OtherAddOp) {
9588             // So at this point we know we have (Y -> OtherAddOp):
9589             //        select C, (add X, Y), (sub X, Z)
9590             Value *NegVal;  // Compute -Z
9591             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9592               NegVal = ConstantExpr::getNeg(C);
9593             } else {
9594               NegVal = InsertNewInstBefore(
9595                     BinaryOperator::CreateNeg(SubOp->getOperand(1),
9596                                               "tmp"), SI);
9597             }
9598
9599             Value *NewTrueOp = OtherAddOp;
9600             Value *NewFalseOp = NegVal;
9601             if (AddOp != TI)
9602               std::swap(NewTrueOp, NewFalseOp);
9603             Instruction *NewSel =
9604               SelectInst::Create(CondVal, NewTrueOp,
9605                                  NewFalseOp, SI.getName() + ".p");
9606
9607             NewSel = InsertNewInstBefore(NewSel, SI);
9608             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9609           }
9610         }
9611       }
9612
9613   // See if we can fold the select into one of our operands.
9614   if (SI.getType()->isInteger()) {
9615     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9616     if (FoldI)
9617       return FoldI;
9618   }
9619
9620   if (BinaryOperator::isNot(CondVal)) {
9621     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9622     SI.setOperand(1, FalseVal);
9623     SI.setOperand(2, TrueVal);
9624     return &SI;
9625   }
9626
9627   return 0;
9628 }
9629
9630 /// EnforceKnownAlignment - If the specified pointer points to an object that
9631 /// we control, modify the object's alignment to PrefAlign. This isn't
9632 /// often possible though. If alignment is important, a more reliable approach
9633 /// is to simply align all global variables and allocation instructions to
9634 /// their preferred alignment from the beginning.
9635 ///
9636 static unsigned EnforceKnownAlignment(Value *V,
9637                                       unsigned Align, unsigned PrefAlign) {
9638
9639   User *U = dyn_cast<User>(V);
9640   if (!U) return Align;
9641
9642   switch (Operator::getOpcode(U)) {
9643   default: break;
9644   case Instruction::BitCast:
9645     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9646   case Instruction::GetElementPtr: {
9647     // If all indexes are zero, it is just the alignment of the base pointer.
9648     bool AllZeroOperands = true;
9649     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9650       if (!isa<Constant>(*i) ||
9651           !cast<Constant>(*i)->isNullValue()) {
9652         AllZeroOperands = false;
9653         break;
9654       }
9655
9656     if (AllZeroOperands) {
9657       // Treat this like a bitcast.
9658       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9659     }
9660     break;
9661   }
9662   }
9663
9664   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9665     // If there is a large requested alignment and we can, bump up the alignment
9666     // of the global.
9667     if (!GV->isDeclaration()) {
9668       if (GV->getAlignment() >= PrefAlign)
9669         Align = GV->getAlignment();
9670       else {
9671         GV->setAlignment(PrefAlign);
9672         Align = PrefAlign;
9673       }
9674     }
9675   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9676     // If there is a requested alignment and if this is an alloca, round up.  We
9677     // don't do this for malloc, because some systems can't respect the request.
9678     if (isa<AllocaInst>(AI)) {
9679       if (AI->getAlignment() >= PrefAlign)
9680         Align = AI->getAlignment();
9681       else {
9682         AI->setAlignment(PrefAlign);
9683         Align = PrefAlign;
9684       }
9685     }
9686   }
9687
9688   return Align;
9689 }
9690
9691 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9692 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9693 /// and it is more than the alignment of the ultimate object, see if we can
9694 /// increase the alignment of the ultimate object, making this check succeed.
9695 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9696                                                   unsigned PrefAlign) {
9697   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9698                       sizeof(PrefAlign) * CHAR_BIT;
9699   APInt Mask = APInt::getAllOnesValue(BitWidth);
9700   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9701   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9702   unsigned TrailZ = KnownZero.countTrailingOnes();
9703   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9704
9705   if (PrefAlign > Align)
9706     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9707   
9708     // We don't need to make any adjustment.
9709   return Align;
9710 }
9711
9712 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9713   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9714   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9715   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9716   unsigned CopyAlign = MI->getAlignment();
9717
9718   if (CopyAlign < MinAlign) {
9719     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 
9720                                              MinAlign, false));
9721     return MI;
9722   }
9723   
9724   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9725   // load/store.
9726   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9727   if (MemOpLength == 0) return 0;
9728   
9729   // Source and destination pointer types are always "i8*" for intrinsic.  See
9730   // if the size is something we can handle with a single primitive load/store.
9731   // A single load+store correctly handles overlapping memory in the memmove
9732   // case.
9733   unsigned Size = MemOpLength->getZExtValue();
9734   if (Size == 0) return MI;  // Delete this mem transfer.
9735   
9736   if (Size > 8 || (Size&(Size-1)))
9737     return 0;  // If not 1/2/4/8 bytes, exit.
9738   
9739   // Use an integer load+store unless we can find something better.
9740   Type *NewPtrTy =
9741                 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9742   
9743   // Memcpy forces the use of i8* for the source and destination.  That means
9744   // that if you're using memcpy to move one double around, you'll get a cast
9745   // from double* to i8*.  We'd much rather use a double load+store rather than
9746   // an i64 load+store, here because this improves the odds that the source or
9747   // dest address will be promotable.  See if we can find a better type than the
9748   // integer datatype.
9749   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9750     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9751     if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9752       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9753       // down through these levels if so.
9754       while (!SrcETy->isSingleValueType()) {
9755         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9756           if (STy->getNumElements() == 1)
9757             SrcETy = STy->getElementType(0);
9758           else
9759             break;
9760         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9761           if (ATy->getNumElements() == 1)
9762             SrcETy = ATy->getElementType();
9763           else
9764             break;
9765         } else
9766           break;
9767       }
9768       
9769       if (SrcETy->isSingleValueType())
9770         NewPtrTy = PointerType::getUnqual(SrcETy);
9771     }
9772   }
9773   
9774   
9775   // If the memcpy/memmove provides better alignment info than we can
9776   // infer, use it.
9777   SrcAlign = std::max(SrcAlign, CopyAlign);
9778   DstAlign = std::max(DstAlign, CopyAlign);
9779   
9780   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9781   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9782   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9783   InsertNewInstBefore(L, *MI);
9784   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9785
9786   // Set the size of the copy to 0, it will be deleted on the next iteration.
9787   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9788   return MI;
9789 }
9790
9791 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9792   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9793   if (MI->getAlignment() < Alignment) {
9794     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9795                                              Alignment, false));
9796     return MI;
9797   }
9798   
9799   // Extract the length and alignment and fill if they are constant.
9800   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9801   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9802   if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9803     return 0;
9804   uint64_t Len = LenC->getZExtValue();
9805   Alignment = MI->getAlignment();
9806   
9807   // If the length is zero, this is a no-op
9808   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9809   
9810   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9811   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9812     const Type *ITy = IntegerType::get(*Context, Len*8);  // n=1 -> i8.
9813     
9814     Value *Dest = MI->getDest();
9815     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9816
9817     // Alignment 0 is identity for alignment 1 for memset, but not store.
9818     if (Alignment == 0) Alignment = 1;
9819     
9820     // Extract the fill value and store.
9821     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9822     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9823                                       Dest, false, Alignment), *MI);
9824     
9825     // Set the size of the copy to 0, it will be deleted on the next iteration.
9826     MI->setLength(Constant::getNullValue(LenC->getType()));
9827     return MI;
9828   }
9829
9830   return 0;
9831 }
9832
9833
9834 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9835 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9836 /// the heavy lifting.
9837 ///
9838 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9839   // If the caller function is nounwind, mark the call as nounwind, even if the
9840   // callee isn't.
9841   if (CI.getParent()->getParent()->doesNotThrow() &&
9842       !CI.doesNotThrow()) {
9843     CI.setDoesNotThrow();
9844     return &CI;
9845   }
9846   
9847   
9848   
9849   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9850   if (!II) return visitCallSite(&CI);
9851   
9852   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9853   // visitCallSite.
9854   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9855     bool Changed = false;
9856
9857     // memmove/cpy/set of zero bytes is a noop.
9858     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9859       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9860
9861       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9862         if (CI->getZExtValue() == 1) {
9863           // Replace the instruction with just byte operations.  We would
9864           // transform other cases to loads/stores, but we don't know if
9865           // alignment is sufficient.
9866         }
9867     }
9868
9869     // If we have a memmove and the source operation is a constant global,
9870     // then the source and dest pointers can't alias, so we can change this
9871     // into a call to memcpy.
9872     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9873       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9874         if (GVSrc->isConstant()) {
9875           Module *M = CI.getParent()->getParent()->getParent();
9876           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9877           const Type *Tys[1];
9878           Tys[0] = CI.getOperand(3)->getType();
9879           CI.setOperand(0, 
9880                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9881           Changed = true;
9882         }
9883
9884       // memmove(x,x,size) -> noop.
9885       if (MMI->getSource() == MMI->getDest())
9886         return EraseInstFromFunction(CI);
9887     }
9888
9889     // If we can determine a pointer alignment that is bigger than currently
9890     // set, update the alignment.
9891     if (isa<MemTransferInst>(MI)) {
9892       if (Instruction *I = SimplifyMemTransfer(MI))
9893         return I;
9894     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9895       if (Instruction *I = SimplifyMemSet(MSI))
9896         return I;
9897     }
9898           
9899     if (Changed) return II;
9900   }
9901   
9902   switch (II->getIntrinsicID()) {
9903   default: break;
9904   case Intrinsic::bswap:
9905     // bswap(bswap(x)) -> x
9906     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9907       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9908         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9909     break;
9910   case Intrinsic::ppc_altivec_lvx:
9911   case Intrinsic::ppc_altivec_lvxl:
9912   case Intrinsic::x86_sse_loadu_ps:
9913   case Intrinsic::x86_sse2_loadu_pd:
9914   case Intrinsic::x86_sse2_loadu_dq:
9915     // Turn PPC lvx     -> load if the pointer is known aligned.
9916     // Turn X86 loadups -> load if the pointer is known aligned.
9917     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9918       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9919                                    PointerType::getUnqual(II->getType()),
9920                                        CI);
9921       return new LoadInst(Ptr);
9922     }
9923     break;
9924   case Intrinsic::ppc_altivec_stvx:
9925   case Intrinsic::ppc_altivec_stvxl:
9926     // Turn stvx -> store if the pointer is known aligned.
9927     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9928       const Type *OpPtrTy = 
9929         PointerType::getUnqual(II->getOperand(1)->getType());
9930       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9931       return new StoreInst(II->getOperand(1), Ptr);
9932     }
9933     break;
9934   case Intrinsic::x86_sse_storeu_ps:
9935   case Intrinsic::x86_sse2_storeu_pd:
9936   case Intrinsic::x86_sse2_storeu_dq:
9937     // Turn X86 storeu -> store if the pointer is known aligned.
9938     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9939       const Type *OpPtrTy = 
9940         PointerType::getUnqual(II->getOperand(2)->getType());
9941       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9942       return new StoreInst(II->getOperand(2), Ptr);
9943     }
9944     break;
9945     
9946   case Intrinsic::x86_sse_cvttss2si: {
9947     // These intrinsics only demands the 0th element of its input vector.  If
9948     // we can simplify the input based on that, do so now.
9949     unsigned VWidth =
9950       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9951     APInt DemandedElts(VWidth, 1);
9952     APInt UndefElts(VWidth, 0);
9953     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9954                                               UndefElts)) {
9955       II->setOperand(1, V);
9956       return II;
9957     }
9958     break;
9959   }
9960     
9961   case Intrinsic::ppc_altivec_vperm:
9962     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9963     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9964       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9965       
9966       // Check that all of the elements are integer constants or undefs.
9967       bool AllEltsOk = true;
9968       for (unsigned i = 0; i != 16; ++i) {
9969         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9970             !isa<UndefValue>(Mask->getOperand(i))) {
9971           AllEltsOk = false;
9972           break;
9973         }
9974       }
9975       
9976       if (AllEltsOk) {
9977         // Cast the input vectors to byte vectors.
9978         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9979         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9980         Value *Result = UndefValue::get(Op0->getType());
9981         
9982         // Only extract each element once.
9983         Value *ExtractedElts[32];
9984         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9985         
9986         for (unsigned i = 0; i != 16; ++i) {
9987           if (isa<UndefValue>(Mask->getOperand(i)))
9988             continue;
9989           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9990           Idx &= 31;  // Match the hardware behavior.
9991           
9992           if (ExtractedElts[Idx] == 0) {
9993             Instruction *Elt = 
9994               ExtractElementInst::Create(Idx < 16 ? Op0 : Op1, 
9995                   ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
9996             InsertNewInstBefore(Elt, CI);
9997             ExtractedElts[Idx] = Elt;
9998           }
9999         
10000           // Insert this value into the result vector.
10001           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10002                                ConstantInt::get(Type::getInt32Ty(*Context), i, false), 
10003                                "tmp");
10004           InsertNewInstBefore(cast<Instruction>(Result), CI);
10005         }
10006         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10007       }
10008     }
10009     break;
10010
10011   case Intrinsic::stackrestore: {
10012     // If the save is right next to the restore, remove the restore.  This can
10013     // happen when variable allocas are DCE'd.
10014     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10015       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10016         BasicBlock::iterator BI = SS;
10017         if (&*++BI == II)
10018           return EraseInstFromFunction(CI);
10019       }
10020     }
10021     
10022     // Scan down this block to see if there is another stack restore in the
10023     // same block without an intervening call/alloca.
10024     BasicBlock::iterator BI = II;
10025     TerminatorInst *TI = II->getParent()->getTerminator();
10026     bool CannotRemove = false;
10027     for (++BI; &*BI != TI; ++BI) {
10028       if (isa<AllocaInst>(BI)) {
10029         CannotRemove = true;
10030         break;
10031       }
10032       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10033         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10034           // If there is a stackrestore below this one, remove this one.
10035           if (II->getIntrinsicID() == Intrinsic::stackrestore)
10036             return EraseInstFromFunction(CI);
10037           // Otherwise, ignore the intrinsic.
10038         } else {
10039           // If we found a non-intrinsic call, we can't remove the stack
10040           // restore.
10041           CannotRemove = true;
10042           break;
10043         }
10044       }
10045     }
10046     
10047     // If the stack restore is in a return/unwind block and if there are no
10048     // allocas or calls between the restore and the return, nuke the restore.
10049     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10050       return EraseInstFromFunction(CI);
10051     break;
10052   }
10053   }
10054
10055   return visitCallSite(II);
10056 }
10057
10058 // InvokeInst simplification
10059 //
10060 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10061   return visitCallSite(&II);
10062 }
10063
10064 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
10065 /// passed through the varargs area, we can eliminate the use of the cast.
10066 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10067                                          const CastInst * const CI,
10068                                          const TargetData * const TD,
10069                                          const int ix) {
10070   if (!CI->isLosslessCast())
10071     return false;
10072
10073   // The size of ByVal arguments is derived from the type, so we
10074   // can't change to a type with a different size.  If the size were
10075   // passed explicitly we could avoid this check.
10076   if (!CS.paramHasAttr(ix, Attribute::ByVal))
10077     return true;
10078
10079   const Type* SrcTy = 
10080             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10081   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10082   if (!SrcTy->isSized() || !DstTy->isSized())
10083     return false;
10084   if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10085     return false;
10086   return true;
10087 }
10088
10089 // visitCallSite - Improvements for call and invoke instructions.
10090 //
10091 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10092   bool Changed = false;
10093
10094   // If the callee is a constexpr cast of a function, attempt to move the cast
10095   // to the arguments of the call/invoke.
10096   if (transformConstExprCastCall(CS)) return 0;
10097
10098   Value *Callee = CS.getCalledValue();
10099
10100   if (Function *CalleeF = dyn_cast<Function>(Callee))
10101     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10102       Instruction *OldCall = CS.getInstruction();
10103       // If the call and callee calling conventions don't match, this call must
10104       // be unreachable, as the call is undefined.
10105       new StoreInst(ConstantInt::getTrue(*Context),
10106                 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), 
10107                                   OldCall);
10108       if (!OldCall->use_empty())
10109         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10110       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
10111         return EraseInstFromFunction(*OldCall);
10112       return 0;
10113     }
10114
10115   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10116     // This instruction is not reachable, just remove it.  We insert a store to
10117     // undef so that we know that this code is not reachable, despite the fact
10118     // that we can't modify the CFG here.
10119     new StoreInst(ConstantInt::getTrue(*Context),
10120                UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10121                   CS.getInstruction());
10122
10123     if (!CS.getInstruction()->use_empty())
10124       CS.getInstruction()->
10125         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10126
10127     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10128       // Don't break the CFG, insert a dummy cond branch.
10129       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10130                          ConstantInt::getTrue(*Context), II);
10131     }
10132     return EraseInstFromFunction(*CS.getInstruction());
10133   }
10134
10135   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10136     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10137       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10138         return transformCallThroughTrampoline(CS);
10139
10140   const PointerType *PTy = cast<PointerType>(Callee->getType());
10141   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10142   if (FTy->isVarArg()) {
10143     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10144     // See if we can optimize any arguments passed through the varargs area of
10145     // the call.
10146     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10147            E = CS.arg_end(); I != E; ++I, ++ix) {
10148       CastInst *CI = dyn_cast<CastInst>(*I);
10149       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10150         *I = CI->getOperand(0);
10151         Changed = true;
10152       }
10153     }
10154   }
10155
10156   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10157     // Inline asm calls cannot throw - mark them 'nounwind'.
10158     CS.setDoesNotThrow();
10159     Changed = true;
10160   }
10161
10162   return Changed ? CS.getInstruction() : 0;
10163 }
10164
10165 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10166 // attempt to move the cast to the arguments of the call/invoke.
10167 //
10168 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10169   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10170   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10171   if (CE->getOpcode() != Instruction::BitCast || 
10172       !isa<Function>(CE->getOperand(0)))
10173     return false;
10174   Function *Callee = cast<Function>(CE->getOperand(0));
10175   Instruction *Caller = CS.getInstruction();
10176   const AttrListPtr &CallerPAL = CS.getAttributes();
10177
10178   // Okay, this is a cast from a function to a different type.  Unless doing so
10179   // would cause a type conversion of one of our arguments, change this call to
10180   // be a direct call with arguments casted to the appropriate types.
10181   //
10182   const FunctionType *FT = Callee->getFunctionType();
10183   const Type *OldRetTy = Caller->getType();
10184   const Type *NewRetTy = FT->getReturnType();
10185
10186   if (isa<StructType>(NewRetTy))
10187     return false; // TODO: Handle multiple return values.
10188
10189   // Check to see if we are changing the return type...
10190   if (OldRetTy != NewRetTy) {
10191     if (Callee->isDeclaration() &&
10192         // Conversion is ok if changing from one pointer type to another or from
10193         // a pointer to an integer of the same size.
10194         !((isa<PointerType>(OldRetTy) || !TD ||
10195            OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10196           (isa<PointerType>(NewRetTy) || !TD ||
10197            NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10198       return false;   // Cannot transform this return value.
10199
10200     if (!Caller->use_empty() &&
10201         // void -> non-void is handled specially
10202         NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10203       return false;   // Cannot transform this return value.
10204
10205     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10206       Attributes RAttrs = CallerPAL.getRetAttributes();
10207       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10208         return false;   // Attribute not compatible with transformed value.
10209     }
10210
10211     // If the callsite is an invoke instruction, and the return value is used by
10212     // a PHI node in a successor, we cannot change the return type of the call
10213     // because there is no place to put the cast instruction (without breaking
10214     // the critical edge).  Bail out in this case.
10215     if (!Caller->use_empty())
10216       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10217         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10218              UI != E; ++UI)
10219           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10220             if (PN->getParent() == II->getNormalDest() ||
10221                 PN->getParent() == II->getUnwindDest())
10222               return false;
10223   }
10224
10225   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10226   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10227
10228   CallSite::arg_iterator AI = CS.arg_begin();
10229   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10230     const Type *ParamTy = FT->getParamType(i);
10231     const Type *ActTy = (*AI)->getType();
10232
10233     if (!CastInst::isCastable(ActTy, ParamTy))
10234       return false;   // Cannot transform this parameter value.
10235
10236     if (CallerPAL.getParamAttributes(i + 1) 
10237         & Attribute::typeIncompatible(ParamTy))
10238       return false;   // Attribute not compatible with transformed value.
10239
10240     // Converting from one pointer type to another or between a pointer and an
10241     // integer of the same size is safe even if we do not have a body.
10242     bool isConvertible = ActTy == ParamTy ||
10243       (TD && ((isa<PointerType>(ParamTy) ||
10244       ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10245               (isa<PointerType>(ActTy) ||
10246               ActTy == TD->getIntPtrType(Caller->getContext()))));
10247     if (Callee->isDeclaration() && !isConvertible) return false;
10248   }
10249
10250   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10251       Callee->isDeclaration())
10252     return false;   // Do not delete arguments unless we have a function body.
10253
10254   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10255       !CallerPAL.isEmpty())
10256     // In this case we have more arguments than the new function type, but we
10257     // won't be dropping them.  Check that these extra arguments have attributes
10258     // that are compatible with being a vararg call argument.
10259     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10260       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10261         break;
10262       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10263       if (PAttrs & Attribute::VarArgsIncompatible)
10264         return false;
10265     }
10266
10267   // Okay, we decided that this is a safe thing to do: go ahead and start
10268   // inserting cast instructions as necessary...
10269   std::vector<Value*> Args;
10270   Args.reserve(NumActualArgs);
10271   SmallVector<AttributeWithIndex, 8> attrVec;
10272   attrVec.reserve(NumCommonArgs);
10273
10274   // Get any return attributes.
10275   Attributes RAttrs = CallerPAL.getRetAttributes();
10276
10277   // If the return value is not being used, the type may not be compatible
10278   // with the existing attributes.  Wipe out any problematic attributes.
10279   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10280
10281   // Add the new return attributes.
10282   if (RAttrs)
10283     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10284
10285   AI = CS.arg_begin();
10286   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10287     const Type *ParamTy = FT->getParamType(i);
10288     if ((*AI)->getType() == ParamTy) {
10289       Args.push_back(*AI);
10290     } else {
10291       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10292           false, ParamTy, false);
10293       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10294       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10295     }
10296
10297     // Add any parameter attributes.
10298     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10299       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10300   }
10301
10302   // If the function takes more arguments than the call was taking, add them
10303   // now...
10304   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10305     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10306
10307   // If we are removing arguments to the function, emit an obnoxious warning...
10308   if (FT->getNumParams() < NumActualArgs) {
10309     if (!FT->isVarArg()) {
10310       errs() << "WARNING: While resolving call to function '"
10311              << Callee->getName() << "' arguments were dropped!\n";
10312     } else {
10313       // Add all of the arguments in their promoted form to the arg list...
10314       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10315         const Type *PTy = getPromotedType((*AI)->getType());
10316         if (PTy != (*AI)->getType()) {
10317           // Must promote to pass through va_arg area!
10318           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10319                                                                 PTy, false);
10320           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10321           InsertNewInstBefore(Cast, *Caller);
10322           Args.push_back(Cast);
10323         } else {
10324           Args.push_back(*AI);
10325         }
10326
10327         // Add any parameter attributes.
10328         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10329           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10330       }
10331     }
10332   }
10333
10334   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10335     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10336
10337   if (NewRetTy == Type::getVoidTy(*Context))
10338     Caller->setName("");   // Void type should not have a name.
10339
10340   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10341                                                      attrVec.end());
10342
10343   Instruction *NC;
10344   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10345     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10346                             Args.begin(), Args.end(),
10347                             Caller->getName(), Caller);
10348     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10349     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10350   } else {
10351     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10352                           Caller->getName(), Caller);
10353     CallInst *CI = cast<CallInst>(Caller);
10354     if (CI->isTailCall())
10355       cast<CallInst>(NC)->setTailCall();
10356     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10357     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10358   }
10359
10360   // Insert a cast of the return type as necessary.
10361   Value *NV = NC;
10362   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10363     if (NV->getType() != Type::getVoidTy(*Context)) {
10364       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10365                                                             OldRetTy, false);
10366       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10367
10368       // If this is an invoke instruction, we should insert it after the first
10369       // non-phi, instruction in the normal successor block.
10370       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10371         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10372         InsertNewInstBefore(NC, *I);
10373       } else {
10374         // Otherwise, it's a call, just insert cast right after the call instr
10375         InsertNewInstBefore(NC, *Caller);
10376       }
10377       AddUsersToWorkList(*Caller);
10378     } else {
10379       NV = UndefValue::get(Caller->getType());
10380     }
10381   }
10382
10383   if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10384     Caller->replaceAllUsesWith(NV);
10385   Caller->eraseFromParent();
10386   RemoveFromWorkList(Caller);
10387   return true;
10388 }
10389
10390 // transformCallThroughTrampoline - Turn a call to a function created by the
10391 // init_trampoline intrinsic into a direct call to the underlying function.
10392 //
10393 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10394   Value *Callee = CS.getCalledValue();
10395   const PointerType *PTy = cast<PointerType>(Callee->getType());
10396   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10397   const AttrListPtr &Attrs = CS.getAttributes();
10398
10399   // If the call already has the 'nest' attribute somewhere then give up -
10400   // otherwise 'nest' would occur twice after splicing in the chain.
10401   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10402     return 0;
10403
10404   IntrinsicInst *Tramp =
10405     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10406
10407   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10408   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10409   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10410
10411   const AttrListPtr &NestAttrs = NestF->getAttributes();
10412   if (!NestAttrs.isEmpty()) {
10413     unsigned NestIdx = 1;
10414     const Type *NestTy = 0;
10415     Attributes NestAttr = Attribute::None;
10416
10417     // Look for a parameter marked with the 'nest' attribute.
10418     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10419          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10420       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10421         // Record the parameter type and any other attributes.
10422         NestTy = *I;
10423         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10424         break;
10425       }
10426
10427     if (NestTy) {
10428       Instruction *Caller = CS.getInstruction();
10429       std::vector<Value*> NewArgs;
10430       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10431
10432       SmallVector<AttributeWithIndex, 8> NewAttrs;
10433       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10434
10435       // Insert the nest argument into the call argument list, which may
10436       // mean appending it.  Likewise for attributes.
10437
10438       // Add any result attributes.
10439       if (Attributes Attr = Attrs.getRetAttributes())
10440         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10441
10442       {
10443         unsigned Idx = 1;
10444         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10445         do {
10446           if (Idx == NestIdx) {
10447             // Add the chain argument and attributes.
10448             Value *NestVal = Tramp->getOperand(3);
10449             if (NestVal->getType() != NestTy)
10450               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10451             NewArgs.push_back(NestVal);
10452             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10453           }
10454
10455           if (I == E)
10456             break;
10457
10458           // Add the original argument and attributes.
10459           NewArgs.push_back(*I);
10460           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10461             NewAttrs.push_back
10462               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10463
10464           ++Idx, ++I;
10465         } while (1);
10466       }
10467
10468       // Add any function attributes.
10469       if (Attributes Attr = Attrs.getFnAttributes())
10470         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10471
10472       // The trampoline may have been bitcast to a bogus type (FTy).
10473       // Handle this by synthesizing a new function type, equal to FTy
10474       // with the chain parameter inserted.
10475
10476       std::vector<const Type*> NewTypes;
10477       NewTypes.reserve(FTy->getNumParams()+1);
10478
10479       // Insert the chain's type into the list of parameter types, which may
10480       // mean appending it.
10481       {
10482         unsigned Idx = 1;
10483         FunctionType::param_iterator I = FTy->param_begin(),
10484           E = FTy->param_end();
10485
10486         do {
10487           if (Idx == NestIdx)
10488             // Add the chain's type.
10489             NewTypes.push_back(NestTy);
10490
10491           if (I == E)
10492             break;
10493
10494           // Add the original type.
10495           NewTypes.push_back(*I);
10496
10497           ++Idx, ++I;
10498         } while (1);
10499       }
10500
10501       // Replace the trampoline call with a direct call.  Let the generic
10502       // code sort out any function type mismatches.
10503       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 
10504                                                 FTy->isVarArg());
10505       Constant *NewCallee =
10506         NestF->getType() == PointerType::getUnqual(NewFTy) ?
10507         NestF : ConstantExpr::getBitCast(NestF, 
10508                                          PointerType::getUnqual(NewFTy));
10509       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10510                                                    NewAttrs.end());
10511
10512       Instruction *NewCaller;
10513       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10514         NewCaller = InvokeInst::Create(NewCallee,
10515                                        II->getNormalDest(), II->getUnwindDest(),
10516                                        NewArgs.begin(), NewArgs.end(),
10517                                        Caller->getName(), Caller);
10518         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10519         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10520       } else {
10521         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10522                                      Caller->getName(), Caller);
10523         if (cast<CallInst>(Caller)->isTailCall())
10524           cast<CallInst>(NewCaller)->setTailCall();
10525         cast<CallInst>(NewCaller)->
10526           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10527         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10528       }
10529       if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10530         Caller->replaceAllUsesWith(NewCaller);
10531       Caller->eraseFromParent();
10532       RemoveFromWorkList(Caller);
10533       return 0;
10534     }
10535   }
10536
10537   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10538   // parameter, there is no need to adjust the argument list.  Let the generic
10539   // code sort out any function type mismatches.
10540   Constant *NewCallee =
10541     NestF->getType() == PTy ? NestF : 
10542                               ConstantExpr::getBitCast(NestF, PTy);
10543   CS.setCalledFunction(NewCallee);
10544   return CS.getInstruction();
10545 }
10546
10547 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10548 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10549 /// and a single binop.
10550 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10551   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10552   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10553   unsigned Opc = FirstInst->getOpcode();
10554   Value *LHSVal = FirstInst->getOperand(0);
10555   Value *RHSVal = FirstInst->getOperand(1);
10556     
10557   const Type *LHSType = LHSVal->getType();
10558   const Type *RHSType = RHSVal->getType();
10559   
10560   // Scan to see if all operands are the same opcode, all have one use, and all
10561   // kill their operands (i.e. the operands have one use).
10562   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10563     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10564     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10565         // Verify type of the LHS matches so we don't fold cmp's of different
10566         // types or GEP's with different index types.
10567         I->getOperand(0)->getType() != LHSType ||
10568         I->getOperand(1)->getType() != RHSType)
10569       return 0;
10570
10571     // If they are CmpInst instructions, check their predicates
10572     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10573       if (cast<CmpInst>(I)->getPredicate() !=
10574           cast<CmpInst>(FirstInst)->getPredicate())
10575         return 0;
10576     
10577     // Keep track of which operand needs a phi node.
10578     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10579     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10580   }
10581   
10582   // Otherwise, this is safe to transform!
10583   
10584   Value *InLHS = FirstInst->getOperand(0);
10585   Value *InRHS = FirstInst->getOperand(1);
10586   PHINode *NewLHS = 0, *NewRHS = 0;
10587   if (LHSVal == 0) {
10588     NewLHS = PHINode::Create(LHSType,
10589                              FirstInst->getOperand(0)->getName() + ".pn");
10590     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10591     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10592     InsertNewInstBefore(NewLHS, PN);
10593     LHSVal = NewLHS;
10594   }
10595   
10596   if (RHSVal == 0) {
10597     NewRHS = PHINode::Create(RHSType,
10598                              FirstInst->getOperand(1)->getName() + ".pn");
10599     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10600     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10601     InsertNewInstBefore(NewRHS, PN);
10602     RHSVal = NewRHS;
10603   }
10604   
10605   // Add all operands to the new PHIs.
10606   if (NewLHS || NewRHS) {
10607     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10608       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10609       if (NewLHS) {
10610         Value *NewInLHS = InInst->getOperand(0);
10611         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10612       }
10613       if (NewRHS) {
10614         Value *NewInRHS = InInst->getOperand(1);
10615         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10616       }
10617     }
10618   }
10619     
10620   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10621     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10622   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10623   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10624                          LHSVal, RHSVal);
10625 }
10626
10627 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10628   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10629   
10630   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10631                                         FirstInst->op_end());
10632   // This is true if all GEP bases are allocas and if all indices into them are
10633   // constants.
10634   bool AllBasePointersAreAllocas = true;
10635   
10636   // Scan to see if all operands are the same opcode, all have one use, and all
10637   // kill their operands (i.e. the operands have one use).
10638   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10639     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10640     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10641       GEP->getNumOperands() != FirstInst->getNumOperands())
10642       return 0;
10643
10644     // Keep track of whether or not all GEPs are of alloca pointers.
10645     if (AllBasePointersAreAllocas &&
10646         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10647          !GEP->hasAllConstantIndices()))
10648       AllBasePointersAreAllocas = false;
10649     
10650     // Compare the operand lists.
10651     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10652       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10653         continue;
10654       
10655       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10656       // if one of the PHIs has a constant for the index.  The index may be
10657       // substantially cheaper to compute for the constants, so making it a
10658       // variable index could pessimize the path.  This also handles the case
10659       // for struct indices, which must always be constant.
10660       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10661           isa<ConstantInt>(GEP->getOperand(op)))
10662         return 0;
10663       
10664       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10665         return 0;
10666       FixedOperands[op] = 0;  // Needs a PHI.
10667     }
10668   }
10669   
10670   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10671   // bother doing this transformation.  At best, this will just save a bit of
10672   // offset calculation, but all the predecessors will have to materialize the
10673   // stack address into a register anyway.  We'd actually rather *clone* the
10674   // load up into the predecessors so that we have a load of a gep of an alloca,
10675   // which can usually all be folded into the load.
10676   if (AllBasePointersAreAllocas)
10677     return 0;
10678   
10679   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10680   // that is variable.
10681   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10682   
10683   bool HasAnyPHIs = false;
10684   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10685     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10686     Value *FirstOp = FirstInst->getOperand(i);
10687     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10688                                      FirstOp->getName()+".pn");
10689     InsertNewInstBefore(NewPN, PN);
10690     
10691     NewPN->reserveOperandSpace(e);
10692     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10693     OperandPhis[i] = NewPN;
10694     FixedOperands[i] = NewPN;
10695     HasAnyPHIs = true;
10696   }
10697
10698   
10699   // Add all operands to the new PHIs.
10700   if (HasAnyPHIs) {
10701     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10702       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10703       BasicBlock *InBB = PN.getIncomingBlock(i);
10704       
10705       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10706         if (PHINode *OpPhi = OperandPhis[op])
10707           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10708     }
10709   }
10710   
10711   Value *Base = FixedOperands[0];
10712   GetElementPtrInst *GEP =
10713     GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10714                               FixedOperands.end());
10715   if (cast<GEPOperator>(FirstInst)->isInBounds())
10716     cast<GEPOperator>(GEP)->setIsInBounds(true);
10717   return GEP;
10718 }
10719
10720
10721 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10722 /// sink the load out of the block that defines it.  This means that it must be
10723 /// obvious the value of the load is not changed from the point of the load to
10724 /// the end of the block it is in.
10725 ///
10726 /// Finally, it is safe, but not profitable, to sink a load targetting a
10727 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10728 /// to a register.
10729 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10730   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10731   
10732   for (++BBI; BBI != E; ++BBI)
10733     if (BBI->mayWriteToMemory())
10734       return false;
10735   
10736   // Check for non-address taken alloca.  If not address-taken already, it isn't
10737   // profitable to do this xform.
10738   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10739     bool isAddressTaken = false;
10740     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10741          UI != E; ++UI) {
10742       if (isa<LoadInst>(UI)) continue;
10743       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10744         // If storing TO the alloca, then the address isn't taken.
10745         if (SI->getOperand(1) == AI) continue;
10746       }
10747       isAddressTaken = true;
10748       break;
10749     }
10750     
10751     if (!isAddressTaken && AI->isStaticAlloca())
10752       return false;
10753   }
10754   
10755   // If this load is a load from a GEP with a constant offset from an alloca,
10756   // then we don't want to sink it.  In its present form, it will be
10757   // load [constant stack offset].  Sinking it will cause us to have to
10758   // materialize the stack addresses in each predecessor in a register only to
10759   // do a shared load from register in the successor.
10760   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10761     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10762       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10763         return false;
10764   
10765   return true;
10766 }
10767
10768
10769 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10770 // operator and they all are only used by the PHI, PHI together their
10771 // inputs, and do the operation once, to the result of the PHI.
10772 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10773   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10774
10775   // Scan the instruction, looking for input operations that can be folded away.
10776   // If all input operands to the phi are the same instruction (e.g. a cast from
10777   // the same type or "+42") we can pull the operation through the PHI, reducing
10778   // code size and simplifying code.
10779   Constant *ConstantOp = 0;
10780   const Type *CastSrcTy = 0;
10781   bool isVolatile = false;
10782   if (isa<CastInst>(FirstInst)) {
10783     CastSrcTy = FirstInst->getOperand(0)->getType();
10784   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10785     // Can fold binop, compare or shift here if the RHS is a constant, 
10786     // otherwise call FoldPHIArgBinOpIntoPHI.
10787     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10788     if (ConstantOp == 0)
10789       return FoldPHIArgBinOpIntoPHI(PN);
10790   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10791     isVolatile = LI->isVolatile();
10792     // We can't sink the load if the loaded value could be modified between the
10793     // load and the PHI.
10794     if (LI->getParent() != PN.getIncomingBlock(0) ||
10795         !isSafeAndProfitableToSinkLoad(LI))
10796       return 0;
10797     
10798     // If the PHI is of volatile loads and the load block has multiple
10799     // successors, sinking it would remove a load of the volatile value from
10800     // the path through the other successor.
10801     if (isVolatile &&
10802         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10803       return 0;
10804     
10805   } else if (isa<GetElementPtrInst>(FirstInst)) {
10806     return FoldPHIArgGEPIntoPHI(PN);
10807   } else {
10808     return 0;  // Cannot fold this operation.
10809   }
10810
10811   // Check to see if all arguments are the same operation.
10812   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10813     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10814     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10815     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10816       return 0;
10817     if (CastSrcTy) {
10818       if (I->getOperand(0)->getType() != CastSrcTy)
10819         return 0;  // Cast operation must match.
10820     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10821       // We can't sink the load if the loaded value could be modified between 
10822       // the load and the PHI.
10823       if (LI->isVolatile() != isVolatile ||
10824           LI->getParent() != PN.getIncomingBlock(i) ||
10825           !isSafeAndProfitableToSinkLoad(LI))
10826         return 0;
10827       
10828       // If the PHI is of volatile loads and the load block has multiple
10829       // successors, sinking it would remove a load of the volatile value from
10830       // the path through the other successor.
10831       if (isVolatile &&
10832           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10833         return 0;
10834       
10835     } else if (I->getOperand(1) != ConstantOp) {
10836       return 0;
10837     }
10838   }
10839
10840   // Okay, they are all the same operation.  Create a new PHI node of the
10841   // correct type, and PHI together all of the LHS's of the instructions.
10842   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10843                                    PN.getName()+".in");
10844   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10845
10846   Value *InVal = FirstInst->getOperand(0);
10847   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10848
10849   // Add all operands to the new PHI.
10850   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10851     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10852     if (NewInVal != InVal)
10853       InVal = 0;
10854     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10855   }
10856
10857   Value *PhiVal;
10858   if (InVal) {
10859     // The new PHI unions all of the same values together.  This is really
10860     // common, so we handle it intelligently here for compile-time speed.
10861     PhiVal = InVal;
10862     delete NewPN;
10863   } else {
10864     InsertNewInstBefore(NewPN, PN);
10865     PhiVal = NewPN;
10866   }
10867
10868   // Insert and return the new operation.
10869   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10870     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10871   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10872     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10873   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10874     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10875                            PhiVal, ConstantOp);
10876   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10877   
10878   // If this was a volatile load that we are merging, make sure to loop through
10879   // and mark all the input loads as non-volatile.  If we don't do this, we will
10880   // insert a new volatile load and the old ones will not be deletable.
10881   if (isVolatile)
10882     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10883       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10884   
10885   return new LoadInst(PhiVal, "", isVolatile);
10886 }
10887
10888 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10889 /// that is dead.
10890 static bool DeadPHICycle(PHINode *PN,
10891                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10892   if (PN->use_empty()) return true;
10893   if (!PN->hasOneUse()) return false;
10894
10895   // Remember this node, and if we find the cycle, return.
10896   if (!PotentiallyDeadPHIs.insert(PN))
10897     return true;
10898   
10899   // Don't scan crazily complex things.
10900   if (PotentiallyDeadPHIs.size() == 16)
10901     return false;
10902
10903   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10904     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10905
10906   return false;
10907 }
10908
10909 /// PHIsEqualValue - Return true if this phi node is always equal to
10910 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10911 ///   z = some value; x = phi (y, z); y = phi (x, z)
10912 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10913                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10914   // See if we already saw this PHI node.
10915   if (!ValueEqualPHIs.insert(PN))
10916     return true;
10917   
10918   // Don't scan crazily complex things.
10919   if (ValueEqualPHIs.size() == 16)
10920     return false;
10921  
10922   // Scan the operands to see if they are either phi nodes or are equal to
10923   // the value.
10924   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10925     Value *Op = PN->getIncomingValue(i);
10926     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10927       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10928         return false;
10929     } else if (Op != NonPhiInVal)
10930       return false;
10931   }
10932   
10933   return true;
10934 }
10935
10936
10937 // PHINode simplification
10938 //
10939 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10940   // If LCSSA is around, don't mess with Phi nodes
10941   if (MustPreserveLCSSA) return 0;
10942   
10943   if (Value *V = PN.hasConstantValue())
10944     return ReplaceInstUsesWith(PN, V);
10945
10946   // If all PHI operands are the same operation, pull them through the PHI,
10947   // reducing code size.
10948   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10949       isa<Instruction>(PN.getIncomingValue(1)) &&
10950       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10951       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10952       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10953       // than themselves more than once.
10954       PN.getIncomingValue(0)->hasOneUse())
10955     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10956       return Result;
10957
10958   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10959   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10960   // PHI)... break the cycle.
10961   if (PN.hasOneUse()) {
10962     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10963     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10964       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10965       PotentiallyDeadPHIs.insert(&PN);
10966       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10967         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10968     }
10969    
10970     // If this phi has a single use, and if that use just computes a value for
10971     // the next iteration of a loop, delete the phi.  This occurs with unused
10972     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10973     // common case here is good because the only other things that catch this
10974     // are induction variable analysis (sometimes) and ADCE, which is only run
10975     // late.
10976     if (PHIUser->hasOneUse() &&
10977         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10978         PHIUser->use_back() == &PN) {
10979       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10980     }
10981   }
10982
10983   // We sometimes end up with phi cycles that non-obviously end up being the
10984   // same value, for example:
10985   //   z = some value; x = phi (y, z); y = phi (x, z)
10986   // where the phi nodes don't necessarily need to be in the same block.  Do a
10987   // quick check to see if the PHI node only contains a single non-phi value, if
10988   // so, scan to see if the phi cycle is actually equal to that value.
10989   {
10990     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10991     // Scan for the first non-phi operand.
10992     while (InValNo != NumOperandVals && 
10993            isa<PHINode>(PN.getIncomingValue(InValNo)))
10994       ++InValNo;
10995
10996     if (InValNo != NumOperandVals) {
10997       Value *NonPhiInVal = PN.getOperand(InValNo);
10998       
10999       // Scan the rest of the operands to see if there are any conflicts, if so
11000       // there is no need to recursively scan other phis.
11001       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11002         Value *OpVal = PN.getIncomingValue(InValNo);
11003         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11004           break;
11005       }
11006       
11007       // If we scanned over all operands, then we have one unique value plus
11008       // phi values.  Scan PHI nodes to see if they all merge in each other or
11009       // the value.
11010       if (InValNo == NumOperandVals) {
11011         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11012         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11013           return ReplaceInstUsesWith(PN, NonPhiInVal);
11014       }
11015     }
11016   }
11017   return 0;
11018 }
11019
11020 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11021   Value *PtrOp = GEP.getOperand(0);
11022   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
11023   // If so, eliminate the noop.
11024   if (GEP.getNumOperands() == 1)
11025     return ReplaceInstUsesWith(GEP, PtrOp);
11026
11027   if (isa<UndefValue>(GEP.getOperand(0)))
11028     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11029
11030   bool HasZeroPointerIndex = false;
11031   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11032     HasZeroPointerIndex = C->isNullValue();
11033
11034   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11035     return ReplaceInstUsesWith(GEP, PtrOp);
11036
11037   // Eliminate unneeded casts for indices.
11038   if (TD) {
11039     bool MadeChange = false;
11040     unsigned PtrSize = TD->getPointerSizeInBits();
11041     
11042     gep_type_iterator GTI = gep_type_begin(GEP);
11043     for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11044          I != E; ++I, ++GTI) {
11045       if (!isa<SequentialType>(*GTI)) continue;
11046       
11047       // If we are using a wider index than needed for this platform, shrink it
11048       // to what we need.  If narrower, sign-extend it to what we need.  This
11049       // explicit cast can make subsequent optimizations more obvious.
11050       unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11051       
11052       if (OpBits == PtrSize)
11053         continue;
11054       
11055       Instruction::CastOps Opc =
11056         OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
11057       *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
11058       MadeChange = true;
11059     }
11060     if (MadeChange) return &GEP;
11061   }
11062
11063   // Combine Indices - If the source pointer to this getelementptr instruction
11064   // is a getelementptr instruction, combine the indices of the two
11065   // getelementptr instructions into a single instruction.
11066   //
11067   if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11068     // Note that if our source is a gep chain itself that we wait for that
11069     // chain to be resolved before we perform this transformation.  This
11070     // avoids us creating a TON of code in some cases.
11071     //
11072     if (GetElementPtrInst *SrcGEP =
11073           dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11074       if (SrcGEP->getNumOperands() == 2)
11075         return 0;   // Wait until our source is folded to completion.
11076
11077     SmallVector<Value*, 8> Indices;
11078
11079     // Find out whether the last index in the source GEP is a sequential idx.
11080     bool EndsWithSequential = false;
11081     for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11082          I != E; ++I)
11083       EndsWithSequential = !isa<StructType>(*I);
11084
11085     // Can we combine the two pointer arithmetics offsets?
11086     if (EndsWithSequential) {
11087       // Replace: gep (gep %P, long B), long A, ...
11088       // With:    T = long A+B; gep %P, T, ...
11089       //
11090       Value *Sum;
11091       Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11092       Value *GO1 = GEP.getOperand(1);
11093       if (SO1 == Constant::getNullValue(SO1->getType())) {
11094         Sum = GO1;
11095       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11096         Sum = SO1;
11097       } else {
11098         // If they aren't the same type, then the input hasn't been processed
11099         // by the loop above yet (which canonicalizes sequential index types to
11100         // intptr_t).  Just avoid transforming this until the input has been
11101         // normalized.
11102         if (SO1->getType() != GO1->getType())
11103           return 0;
11104         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11105           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11106         else {
11107           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11108           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11109         }
11110       }
11111
11112       // Update the GEP in place if possible.
11113       if (Src->getNumOperands() == 2) {
11114         GEP.setOperand(0, Src->getOperand(0));
11115         GEP.setOperand(1, Sum);
11116         return &GEP;
11117       }
11118       Indices.append(Src->op_begin()+1, Src->op_end()-1);
11119       Indices.push_back(Sum);
11120       Indices.append(GEP.op_begin()+2, GEP.op_end());
11121     } else if (isa<Constant>(*GEP.idx_begin()) &&
11122                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11123                Src->getNumOperands() != 1) {
11124       // Otherwise we can do the fold if the first index of the GEP is a zero
11125       Indices.append(Src->op_begin()+1, Src->op_end());
11126       Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11127     }
11128
11129     if (!Indices.empty()) {
11130       GetElementPtrInst *NewGEP =
11131         GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11132                                   Indices.end(), GEP.getName());
11133       if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
11134         cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11135       return NewGEP;
11136     }
11137   }
11138   
11139   // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11140   if (Value *X = getBitCastOperand(PtrOp)) {
11141     assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11142            
11143     if (HasZeroPointerIndex) {
11144       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11145       // into     : GEP [10 x i8]* X, i32 0, ...
11146       //
11147       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11148       //           into     : GEP i8* X, ...
11149       // 
11150       // This occurs when the program declares an array extern like "int X[];"
11151       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11152       const PointerType *XTy = cast<PointerType>(X->getType());
11153       if (const ArrayType *CATy =
11154           dyn_cast<ArrayType>(CPTy->getElementType())) {
11155         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11156         if (CATy->getElementType() == XTy->getElementType()) {
11157           // -> GEP i8* X, ...
11158           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11159           GetElementPtrInst *NewGEP =
11160             GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11161                                       GEP.getName());
11162           if (cast<GEPOperator>(&GEP)->isInBounds())
11163             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11164           return NewGEP;
11165         } else if (const ArrayType *XATy =
11166                  dyn_cast<ArrayType>(XTy->getElementType())) {
11167           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11168           if (CATy->getElementType() == XATy->getElementType()) {
11169             // -> GEP [10 x i8]* X, i32 0, ...
11170             // At this point, we know that the cast source type is a pointer
11171             // to an array of the same type as the destination pointer
11172             // array.  Because the array type is never stepped over (there
11173             // is a leading zero) we can fold the cast into this GEP.
11174             GEP.setOperand(0, X);
11175             return &GEP;
11176           }
11177         }
11178       }
11179     } else if (GEP.getNumOperands() == 2) {
11180       // Transform things like:
11181       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11182       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11183       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11184       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11185       if (TD && isa<ArrayType>(SrcElTy) &&
11186           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11187           TD->getTypeAllocSize(ResElTy)) {
11188         Value *Idx[2];
11189         Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11190         Idx[1] = GEP.getOperand(1);
11191         GetElementPtrInst *NewGEP =
11192           GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11193         if (cast<GEPOperator>(&GEP)->isInBounds())
11194           cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11195         Value *V = InsertNewInstBefore(NewGEP, GEP);
11196         // V and GEP are both pointer types --> BitCast
11197         return new BitCastInst(V, GEP.getType());
11198       }
11199       
11200       // Transform things like:
11201       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11202       //   (where tmp = 8*tmp2) into:
11203       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11204       
11205       if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11206         uint64_t ArrayEltSize =
11207             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11208         
11209         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11210         // allow either a mul, shift, or constant here.
11211         Value *NewIdx = 0;
11212         ConstantInt *Scale = 0;
11213         if (ArrayEltSize == 1) {
11214           NewIdx = GEP.getOperand(1);
11215           Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11216         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11217           NewIdx = ConstantInt::get(CI->getType(), 1);
11218           Scale = CI;
11219         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11220           if (Inst->getOpcode() == Instruction::Shl &&
11221               isa<ConstantInt>(Inst->getOperand(1))) {
11222             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11223             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11224             Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11225                                      1ULL << ShAmtVal);
11226             NewIdx = Inst->getOperand(0);
11227           } else if (Inst->getOpcode() == Instruction::Mul &&
11228                      isa<ConstantInt>(Inst->getOperand(1))) {
11229             Scale = cast<ConstantInt>(Inst->getOperand(1));
11230             NewIdx = Inst->getOperand(0);
11231           }
11232         }
11233         
11234         // If the index will be to exactly the right offset with the scale taken
11235         // out, perform the transformation. Note, we don't know whether Scale is
11236         // signed or not. We'll use unsigned version of division/modulo
11237         // operation after making sure Scale doesn't have the sign bit set.
11238         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11239             Scale->getZExtValue() % ArrayEltSize == 0) {
11240           Scale = ConstantInt::get(Scale->getType(),
11241                                    Scale->getZExtValue() / ArrayEltSize);
11242           if (Scale->getZExtValue() != 1) {
11243             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11244                                                        false /*ZExt*/);
11245             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11246             NewIdx = InsertNewInstBefore(Sc, GEP);
11247           }
11248
11249           // Insert the new GEP instruction.
11250           Value *Idx[2];
11251           Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11252           Idx[1] = NewIdx;
11253           Instruction *NewGEP =
11254             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11255           if (cast<GEPOperator>(&GEP)->isInBounds())
11256             cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11257           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11258           // The NewGEP must be pointer typed, so must the old one -> BitCast
11259           return new BitCastInst(NewGEP, GEP.getType());
11260         }
11261       }
11262     }
11263   }
11264   
11265   /// See if we can simplify:
11266   ///   X = bitcast A* to B*
11267   ///   Y = gep X, <...constant indices...>
11268   /// into a gep of the original struct.  This is important for SROA and alias
11269   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11270   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11271     if (TD &&
11272         !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11273       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11274       // a constant back from EmitGEPOffset.
11275       ConstantInt *OffsetV =
11276                     cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11277       int64_t Offset = OffsetV->getSExtValue();
11278       
11279       // If this GEP instruction doesn't move the pointer, just replace the GEP
11280       // with a bitcast of the real input to the dest type.
11281       if (Offset == 0) {
11282         // If the bitcast is of an allocation, and the allocation will be
11283         // converted to match the type of the cast, don't touch this.
11284         if (isa<AllocationInst>(BCI->getOperand(0))) {
11285           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11286           if (Instruction *I = visitBitCast(*BCI)) {
11287             if (I != BCI) {
11288               I->takeName(BCI);
11289               BCI->getParent()->getInstList().insert(BCI, I);
11290               ReplaceInstUsesWith(*BCI, I);
11291             }
11292             return &GEP;
11293           }
11294         }
11295         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11296       }
11297       
11298       // Otherwise, if the offset is non-zero, we need to find out if there is a
11299       // field at Offset in 'A's type.  If so, we can pull the cast through the
11300       // GEP.
11301       SmallVector<Value*, 8> NewIndices;
11302       const Type *InTy =
11303         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11304       if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11305         Instruction *NGEP =
11306            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11307                                      NewIndices.end());
11308         if (NGEP->getType() == GEP.getType()) return NGEP;
11309         if (cast<GEPOperator>(&GEP)->isInBounds())
11310           cast<GEPOperator>(NGEP)->setIsInBounds(true);
11311         InsertNewInstBefore(NGEP, GEP);
11312         NGEP->takeName(&GEP);
11313         return new BitCastInst(NGEP, GEP.getType());
11314       }
11315     }
11316   }    
11317     
11318   return 0;
11319 }
11320
11321 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11322   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11323   if (AI.isArrayAllocation()) {  // Check C != 1
11324     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11325       const Type *NewTy = 
11326         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11327       AllocationInst *New = 0;
11328
11329       // Create and insert the replacement instruction...
11330       if (isa<MallocInst>(AI))
11331         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11332       else {
11333         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11334         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11335       }
11336
11337       InsertNewInstBefore(New, AI);
11338
11339       // Scan to the end of the allocation instructions, to skip over a block of
11340       // allocas if possible...also skip interleaved debug info
11341       //
11342       BasicBlock::iterator It = New;
11343       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11344
11345       // Now that I is pointing to the first non-allocation-inst in the block,
11346       // insert our getelementptr instruction...
11347       //
11348       Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11349       Value *Idx[2];
11350       Idx[0] = NullIdx;
11351       Idx[1] = NullIdx;
11352       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11353                                            New->getName()+".sub", It);
11354       cast<GEPOperator>(V)->setIsInBounds(true);
11355
11356       // Now make everything use the getelementptr instead of the original
11357       // allocation.
11358       return ReplaceInstUsesWith(AI, V);
11359     } else if (isa<UndefValue>(AI.getArraySize())) {
11360       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11361     }
11362   }
11363
11364   if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11365     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11366     // Note that we only do this for alloca's, because malloc should allocate
11367     // and return a unique pointer, even for a zero byte allocation.
11368     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11369       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11370
11371     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11372     if (AI.getAlignment() == 0)
11373       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11374   }
11375
11376   return 0;
11377 }
11378
11379 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11380   Value *Op = FI.getOperand(0);
11381
11382   // free undef -> unreachable.
11383   if (isa<UndefValue>(Op)) {
11384     // Insert a new store to null because we cannot modify the CFG here.
11385     new StoreInst(ConstantInt::getTrue(*Context),
11386            UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11387     return EraseInstFromFunction(FI);
11388   }
11389   
11390   // If we have 'free null' delete the instruction.  This can happen in stl code
11391   // when lots of inlining happens.
11392   if (isa<ConstantPointerNull>(Op))
11393     return EraseInstFromFunction(FI);
11394   
11395   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11396   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11397     FI.setOperand(0, CI->getOperand(0));
11398     return &FI;
11399   }
11400   
11401   // Change free (gep X, 0,0,0,0) into free(X)
11402   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11403     if (GEPI->hasAllZeroIndices()) {
11404       AddToWorkList(GEPI);
11405       FI.setOperand(0, GEPI->getOperand(0));
11406       return &FI;
11407     }
11408   }
11409   
11410   // Change free(malloc) into nothing, if the malloc has a single use.
11411   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11412     if (MI->hasOneUse()) {
11413       EraseInstFromFunction(FI);
11414       return EraseInstFromFunction(*MI);
11415     }
11416
11417   return 0;
11418 }
11419
11420
11421 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11422 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11423                                         const TargetData *TD) {
11424   User *CI = cast<User>(LI.getOperand(0));
11425   Value *CastOp = CI->getOperand(0);
11426   LLVMContext *Context = IC.getContext();
11427
11428   if (TD) {
11429     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11430       // Instead of loading constant c string, use corresponding integer value
11431       // directly if string length is small enough.
11432       std::string Str;
11433       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11434         unsigned len = Str.length();
11435         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11436         unsigned numBits = Ty->getPrimitiveSizeInBits();
11437         // Replace LI with immediate integer store.
11438         if ((numBits >> 3) == len + 1) {
11439           APInt StrVal(numBits, 0);
11440           APInt SingleChar(numBits, 0);
11441           if (TD->isLittleEndian()) {
11442             for (signed i = len-1; i >= 0; i--) {
11443               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11444               StrVal = (StrVal << 8) | SingleChar;
11445             }
11446           } else {
11447             for (unsigned i = 0; i < len; i++) {
11448               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11449               StrVal = (StrVal << 8) | SingleChar;
11450             }
11451             // Append NULL at the end.
11452             SingleChar = 0;
11453             StrVal = (StrVal << 8) | SingleChar;
11454           }
11455           Value *NL = ConstantInt::get(*Context, StrVal);
11456           return IC.ReplaceInstUsesWith(LI, NL);
11457         }
11458       }
11459     }
11460   }
11461
11462   const PointerType *DestTy = cast<PointerType>(CI->getType());
11463   const Type *DestPTy = DestTy->getElementType();
11464   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11465
11466     // If the address spaces don't match, don't eliminate the cast.
11467     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11468       return 0;
11469
11470     const Type *SrcPTy = SrcTy->getElementType();
11471
11472     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11473          isa<VectorType>(DestPTy)) {
11474       // If the source is an array, the code below will not succeed.  Check to
11475       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11476       // constants.
11477       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11478         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11479           if (ASrcTy->getNumElements() != 0) {
11480             Value *Idxs[2];
11481             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11482             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11483             SrcTy = cast<PointerType>(CastOp->getType());
11484             SrcPTy = SrcTy->getElementType();
11485           }
11486
11487       if (IC.getTargetData() &&
11488           (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11489             isa<VectorType>(SrcPTy)) &&
11490           // Do not allow turning this into a load of an integer, which is then
11491           // casted to a pointer, this pessimizes pointer analysis a lot.
11492           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11493           IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11494                IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11495
11496         // Okay, we are casting from one integer or pointer type to another of
11497         // the same size.  Instead of casting the pointer before the load, cast
11498         // the result of the loaded value.
11499         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11500                                                              CI->getName(),
11501                                                          LI.isVolatile()),LI);
11502         // Now cast the result of the load.
11503         return new BitCastInst(NewLoad, LI.getType());
11504       }
11505     }
11506   }
11507   return 0;
11508 }
11509
11510 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11511   Value *Op = LI.getOperand(0);
11512
11513   // Attempt to improve the alignment.
11514   if (TD) {
11515     unsigned KnownAlign =
11516       GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11517     if (KnownAlign >
11518         (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11519                                   LI.getAlignment()))
11520       LI.setAlignment(KnownAlign);
11521   }
11522
11523   // load (cast X) --> cast (load X) iff safe
11524   if (isa<CastInst>(Op))
11525     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11526       return Res;
11527
11528   // None of the following transforms are legal for volatile loads.
11529   if (LI.isVolatile()) return 0;
11530   
11531   // Do really simple store-to-load forwarding and load CSE, to catch cases
11532   // where there are several consequtive memory accesses to the same location,
11533   // separated by a few arithmetic operations.
11534   BasicBlock::iterator BBI = &LI;
11535   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11536     return ReplaceInstUsesWith(LI, AvailableVal);
11537
11538   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11539     const Value *GEPI0 = GEPI->getOperand(0);
11540     // TODO: Consider a target hook for valid address spaces for this xform.
11541     if (isa<ConstantPointerNull>(GEPI0) &&
11542         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11543       // Insert a new store to null instruction before the load to indicate
11544       // that this code is not reachable.  We do this instead of inserting
11545       // an unreachable instruction directly because we cannot modify the
11546       // CFG.
11547       new StoreInst(UndefValue::get(LI.getType()),
11548                     Constant::getNullValue(Op->getType()), &LI);
11549       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11550     }
11551   } 
11552
11553   if (Constant *C = dyn_cast<Constant>(Op)) {
11554     // load null/undef -> undef
11555     // TODO: Consider a target hook for valid address spaces for this xform.
11556     if (isa<UndefValue>(C) || (C->isNullValue() && 
11557         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11558       // Insert a new store to null instruction before the load to indicate that
11559       // this code is not reachable.  We do this instead of inserting an
11560       // unreachable instruction directly because we cannot modify the CFG.
11561       new StoreInst(UndefValue::get(LI.getType()),
11562                     Constant::getNullValue(Op->getType()), &LI);
11563       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11564     }
11565
11566     // Instcombine load (constant global) into the value loaded.
11567     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11568       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11569         return ReplaceInstUsesWith(LI, GV->getInitializer());
11570
11571     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11572     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11573       if (CE->getOpcode() == Instruction::GetElementPtr) {
11574         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11575           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11576             if (Constant *V = 
11577                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE, 
11578                                                       *Context))
11579               return ReplaceInstUsesWith(LI, V);
11580         if (CE->getOperand(0)->isNullValue()) {
11581           // Insert a new store to null instruction before the load to indicate
11582           // that this code is not reachable.  We do this instead of inserting
11583           // an unreachable instruction directly because we cannot modify the
11584           // CFG.
11585           new StoreInst(UndefValue::get(LI.getType()),
11586                         Constant::getNullValue(Op->getType()), &LI);
11587           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11588         }
11589
11590       } else if (CE->isCast()) {
11591         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11592           return Res;
11593       }
11594     }
11595   }
11596     
11597   // If this load comes from anywhere in a constant global, and if the global
11598   // is all undef or zero, we know what it loads.
11599   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11600     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11601       if (GV->getInitializer()->isNullValue())
11602         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11603       else if (isa<UndefValue>(GV->getInitializer()))
11604         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11605     }
11606   }
11607
11608   if (Op->hasOneUse()) {
11609     // Change select and PHI nodes to select values instead of addresses: this
11610     // helps alias analysis out a lot, allows many others simplifications, and
11611     // exposes redundancy in the code.
11612     //
11613     // Note that we cannot do the transformation unless we know that the
11614     // introduced loads cannot trap!  Something like this is valid as long as
11615     // the condition is always false: load (select bool %C, int* null, int* %G),
11616     // but it would not be valid if we transformed it to load from null
11617     // unconditionally.
11618     //
11619     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11620       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11621       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11622           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11623         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11624                                      SI->getOperand(1)->getName()+".val"), LI);
11625         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11626                                      SI->getOperand(2)->getName()+".val"), LI);
11627         return SelectInst::Create(SI->getCondition(), V1, V2);
11628       }
11629
11630       // load (select (cond, null, P)) -> load P
11631       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11632         if (C->isNullValue()) {
11633           LI.setOperand(0, SI->getOperand(2));
11634           return &LI;
11635         }
11636
11637       // load (select (cond, P, null)) -> load P
11638       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11639         if (C->isNullValue()) {
11640           LI.setOperand(0, SI->getOperand(1));
11641           return &LI;
11642         }
11643     }
11644   }
11645   return 0;
11646 }
11647
11648 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11649 /// when possible.  This makes it generally easy to do alias analysis and/or
11650 /// SROA/mem2reg of the memory object.
11651 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11652   User *CI = cast<User>(SI.getOperand(1));
11653   Value *CastOp = CI->getOperand(0);
11654
11655   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11656   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11657   if (SrcTy == 0) return 0;
11658   
11659   const Type *SrcPTy = SrcTy->getElementType();
11660
11661   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11662     return 0;
11663   
11664   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11665   /// to its first element.  This allows us to handle things like:
11666   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11667   /// on 32-bit hosts.
11668   SmallVector<Value*, 4> NewGEPIndices;
11669   
11670   // If the source is an array, the code below will not succeed.  Check to
11671   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11672   // constants.
11673   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11674     // Index through pointer.
11675     Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11676     NewGEPIndices.push_back(Zero);
11677     
11678     while (1) {
11679       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11680         if (!STy->getNumElements()) /* Struct can be empty {} */
11681           break;
11682         NewGEPIndices.push_back(Zero);
11683         SrcPTy = STy->getElementType(0);
11684       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11685         NewGEPIndices.push_back(Zero);
11686         SrcPTy = ATy->getElementType();
11687       } else {
11688         break;
11689       }
11690     }
11691     
11692     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11693   }
11694
11695   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11696     return 0;
11697   
11698   // If the pointers point into different address spaces or if they point to
11699   // values with different sizes, we can't do the transformation.
11700   if (!IC.getTargetData() ||
11701       SrcTy->getAddressSpace() != 
11702         cast<PointerType>(CI->getType())->getAddressSpace() ||
11703       IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11704       IC.getTargetData()->getTypeSizeInBits(DestPTy))
11705     return 0;
11706
11707   // Okay, we are casting from one integer or pointer type to another of
11708   // the same size.  Instead of casting the pointer before 
11709   // the store, cast the value to be stored.
11710   Value *NewCast;
11711   Value *SIOp0 = SI.getOperand(0);
11712   Instruction::CastOps opcode = Instruction::BitCast;
11713   const Type* CastSrcTy = SIOp0->getType();
11714   const Type* CastDstTy = SrcPTy;
11715   if (isa<PointerType>(CastDstTy)) {
11716     if (CastSrcTy->isInteger())
11717       opcode = Instruction::IntToPtr;
11718   } else if (isa<IntegerType>(CastDstTy)) {
11719     if (isa<PointerType>(SIOp0->getType()))
11720       opcode = Instruction::PtrToInt;
11721   }
11722   
11723   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11724   // emit a GEP to index into its first field.
11725   if (!NewGEPIndices.empty()) {
11726     if (Constant *C = dyn_cast<Constant>(CastOp))
11727       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11728                                               NewGEPIndices.size());
11729     else
11730       CastOp = IC.InsertNewInstBefore(
11731               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11732                                         NewGEPIndices.end()), SI);
11733     cast<GEPOperator>(CastOp)->setIsInBounds(true);
11734   }
11735   
11736   if (Constant *C = dyn_cast<Constant>(SIOp0))
11737     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11738   else
11739     NewCast = IC.InsertNewInstBefore(
11740       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11741       SI);
11742   return new StoreInst(NewCast, CastOp);
11743 }
11744
11745 /// equivalentAddressValues - Test if A and B will obviously have the same
11746 /// value. This includes recognizing that %t0 and %t1 will have the same
11747 /// value in code like this:
11748 ///   %t0 = getelementptr \@a, 0, 3
11749 ///   store i32 0, i32* %t0
11750 ///   %t1 = getelementptr \@a, 0, 3
11751 ///   %t2 = load i32* %t1
11752 ///
11753 static bool equivalentAddressValues(Value *A, Value *B) {
11754   // Test if the values are trivially equivalent.
11755   if (A == B) return true;
11756   
11757   // Test if the values come form identical arithmetic instructions.
11758   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11759   // its only used to compare two uses within the same basic block, which
11760   // means that they'll always either have the same value or one of them
11761   // will have an undefined value.
11762   if (isa<BinaryOperator>(A) ||
11763       isa<CastInst>(A) ||
11764       isa<PHINode>(A) ||
11765       isa<GetElementPtrInst>(A))
11766     if (Instruction *BI = dyn_cast<Instruction>(B))
11767       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11768         return true;
11769   
11770   // Otherwise they may not be equivalent.
11771   return false;
11772 }
11773
11774 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11775 // return the llvm.dbg.declare.
11776 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11777   if (!V->hasNUses(2))
11778     return 0;
11779   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11780        UI != E; ++UI) {
11781     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11782       return DI;
11783     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11784       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11785         return DI;
11786       }
11787   }
11788   return 0;
11789 }
11790
11791 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11792   Value *Val = SI.getOperand(0);
11793   Value *Ptr = SI.getOperand(1);
11794
11795   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11796     EraseInstFromFunction(SI);
11797     ++NumCombined;
11798     return 0;
11799   }
11800   
11801   // If the RHS is an alloca with a single use, zapify the store, making the
11802   // alloca dead.
11803   // If the RHS is an alloca with a two uses, the other one being a 
11804   // llvm.dbg.declare, zapify the store and the declare, making the
11805   // alloca dead.  We must do this to prevent declare's from affecting
11806   // codegen.
11807   if (!SI.isVolatile()) {
11808     if (Ptr->hasOneUse()) {
11809       if (isa<AllocaInst>(Ptr)) {
11810         EraseInstFromFunction(SI);
11811         ++NumCombined;
11812         return 0;
11813       }
11814       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11815         if (isa<AllocaInst>(GEP->getOperand(0))) {
11816           if (GEP->getOperand(0)->hasOneUse()) {
11817             EraseInstFromFunction(SI);
11818             ++NumCombined;
11819             return 0;
11820           }
11821           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11822             EraseInstFromFunction(*DI);
11823             EraseInstFromFunction(SI);
11824             ++NumCombined;
11825             return 0;
11826           }
11827         }
11828       }
11829     }
11830     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11831       EraseInstFromFunction(*DI);
11832       EraseInstFromFunction(SI);
11833       ++NumCombined;
11834       return 0;
11835     }
11836   }
11837
11838   // Attempt to improve the alignment.
11839   if (TD) {
11840     unsigned KnownAlign =
11841       GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11842     if (KnownAlign >
11843         (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11844                                   SI.getAlignment()))
11845       SI.setAlignment(KnownAlign);
11846   }
11847
11848   // Do really simple DSE, to catch cases where there are several consecutive
11849   // stores to the same location, separated by a few arithmetic operations. This
11850   // situation often occurs with bitfield accesses.
11851   BasicBlock::iterator BBI = &SI;
11852   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11853        --ScanInsts) {
11854     --BBI;
11855     // Don't count debug info directives, lest they affect codegen,
11856     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11857     // It is necessary for correctness to skip those that feed into a
11858     // llvm.dbg.declare, as these are not present when debugging is off.
11859     if (isa<DbgInfoIntrinsic>(BBI) ||
11860         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11861       ScanInsts++;
11862       continue;
11863     }    
11864     
11865     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11866       // Prev store isn't volatile, and stores to the same location?
11867       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11868                                                           SI.getOperand(1))) {
11869         ++NumDeadStore;
11870         ++BBI;
11871         EraseInstFromFunction(*PrevSI);
11872         continue;
11873       }
11874       break;
11875     }
11876     
11877     // If this is a load, we have to stop.  However, if the loaded value is from
11878     // the pointer we're loading and is producing the pointer we're storing,
11879     // then *this* store is dead (X = load P; store X -> P).
11880     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11881       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11882           !SI.isVolatile()) {
11883         EraseInstFromFunction(SI);
11884         ++NumCombined;
11885         return 0;
11886       }
11887       // Otherwise, this is a load from some other location.  Stores before it
11888       // may not be dead.
11889       break;
11890     }
11891     
11892     // Don't skip over loads or things that can modify memory.
11893     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11894       break;
11895   }
11896   
11897   
11898   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11899
11900   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11901   if (isa<ConstantPointerNull>(Ptr) &&
11902       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11903     if (!isa<UndefValue>(Val)) {
11904       SI.setOperand(0, UndefValue::get(Val->getType()));
11905       if (Instruction *U = dyn_cast<Instruction>(Val))
11906         AddToWorkList(U);  // Dropped a use.
11907       ++NumCombined;
11908     }
11909     return 0;  // Do not modify these!
11910   }
11911
11912   // store undef, Ptr -> noop
11913   if (isa<UndefValue>(Val)) {
11914     EraseInstFromFunction(SI);
11915     ++NumCombined;
11916     return 0;
11917   }
11918
11919   // If the pointer destination is a cast, see if we can fold the cast into the
11920   // source instead.
11921   if (isa<CastInst>(Ptr))
11922     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11923       return Res;
11924   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11925     if (CE->isCast())
11926       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11927         return Res;
11928
11929   
11930   // If this store is the last instruction in the basic block (possibly
11931   // excepting debug info instructions and the pointer bitcasts that feed
11932   // into them), and if the block ends with an unconditional branch, try
11933   // to move it to the successor block.
11934   BBI = &SI; 
11935   do {
11936     ++BBI;
11937   } while (isa<DbgInfoIntrinsic>(BBI) ||
11938            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11939   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11940     if (BI->isUnconditional())
11941       if (SimplifyStoreAtEndOfBlock(SI))
11942         return 0;  // xform done!
11943   
11944   return 0;
11945 }
11946
11947 /// SimplifyStoreAtEndOfBlock - Turn things like:
11948 ///   if () { *P = v1; } else { *P = v2 }
11949 /// into a phi node with a store in the successor.
11950 ///
11951 /// Simplify things like:
11952 ///   *P = v1; if () { *P = v2; }
11953 /// into a phi node with a store in the successor.
11954 ///
11955 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11956   BasicBlock *StoreBB = SI.getParent();
11957   
11958   // Check to see if the successor block has exactly two incoming edges.  If
11959   // so, see if the other predecessor contains a store to the same location.
11960   // if so, insert a PHI node (if needed) and move the stores down.
11961   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11962   
11963   // Determine whether Dest has exactly two predecessors and, if so, compute
11964   // the other predecessor.
11965   pred_iterator PI = pred_begin(DestBB);
11966   BasicBlock *OtherBB = 0;
11967   if (*PI != StoreBB)
11968     OtherBB = *PI;
11969   ++PI;
11970   if (PI == pred_end(DestBB))
11971     return false;
11972   
11973   if (*PI != StoreBB) {
11974     if (OtherBB)
11975       return false;
11976     OtherBB = *PI;
11977   }
11978   if (++PI != pred_end(DestBB))
11979     return false;
11980
11981   // Bail out if all the relevant blocks aren't distinct (this can happen,
11982   // for example, if SI is in an infinite loop)
11983   if (StoreBB == DestBB || OtherBB == DestBB)
11984     return false;
11985
11986   // Verify that the other block ends in a branch and is not otherwise empty.
11987   BasicBlock::iterator BBI = OtherBB->getTerminator();
11988   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11989   if (!OtherBr || BBI == OtherBB->begin())
11990     return false;
11991   
11992   // If the other block ends in an unconditional branch, check for the 'if then
11993   // else' case.  there is an instruction before the branch.
11994   StoreInst *OtherStore = 0;
11995   if (OtherBr->isUnconditional()) {
11996     --BBI;
11997     // Skip over debugging info.
11998     while (isa<DbgInfoIntrinsic>(BBI) ||
11999            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12000       if (BBI==OtherBB->begin())
12001         return false;
12002       --BBI;
12003     }
12004     // If this isn't a store, or isn't a store to the same location, bail out.
12005     OtherStore = dyn_cast<StoreInst>(BBI);
12006     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12007       return false;
12008   } else {
12009     // Otherwise, the other block ended with a conditional branch. If one of the
12010     // destinations is StoreBB, then we have the if/then case.
12011     if (OtherBr->getSuccessor(0) != StoreBB && 
12012         OtherBr->getSuccessor(1) != StoreBB)
12013       return false;
12014     
12015     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12016     // if/then triangle.  See if there is a store to the same ptr as SI that
12017     // lives in OtherBB.
12018     for (;; --BBI) {
12019       // Check to see if we find the matching store.
12020       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12021         if (OtherStore->getOperand(1) != SI.getOperand(1))
12022           return false;
12023         break;
12024       }
12025       // If we find something that may be using or overwriting the stored
12026       // value, or if we run out of instructions, we can't do the xform.
12027       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12028           BBI == OtherBB->begin())
12029         return false;
12030     }
12031     
12032     // In order to eliminate the store in OtherBr, we have to
12033     // make sure nothing reads or overwrites the stored value in
12034     // StoreBB.
12035     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12036       // FIXME: This should really be AA driven.
12037       if (I->mayReadFromMemory() || I->mayWriteToMemory())
12038         return false;
12039     }
12040   }
12041   
12042   // Insert a PHI node now if we need it.
12043   Value *MergedVal = OtherStore->getOperand(0);
12044   if (MergedVal != SI.getOperand(0)) {
12045     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12046     PN->reserveOperandSpace(2);
12047     PN->addIncoming(SI.getOperand(0), SI.getParent());
12048     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12049     MergedVal = InsertNewInstBefore(PN, DestBB->front());
12050   }
12051   
12052   // Advance to a place where it is safe to insert the new store and
12053   // insert it.
12054   BBI = DestBB->getFirstNonPHI();
12055   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12056                                     OtherStore->isVolatile()), *BBI);
12057   
12058   // Nuke the old stores.
12059   EraseInstFromFunction(SI);
12060   EraseInstFromFunction(*OtherStore);
12061   ++NumCombined;
12062   return true;
12063 }
12064
12065
12066 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12067   // Change br (not X), label True, label False to: br X, label False, True
12068   Value *X = 0;
12069   BasicBlock *TrueDest;
12070   BasicBlock *FalseDest;
12071   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12072       !isa<Constant>(X)) {
12073     // Swap Destinations and condition...
12074     BI.setCondition(X);
12075     BI.setSuccessor(0, FalseDest);
12076     BI.setSuccessor(1, TrueDest);
12077     return &BI;
12078   }
12079
12080   // Cannonicalize fcmp_one -> fcmp_oeq
12081   FCmpInst::Predicate FPred; Value *Y;
12082   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12083                              TrueDest, FalseDest)))
12084     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12085          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12086       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12087       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12088       Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12089       NewSCC->takeName(I);
12090       // Swap Destinations and condition...
12091       BI.setCondition(NewSCC);
12092       BI.setSuccessor(0, FalseDest);
12093       BI.setSuccessor(1, TrueDest);
12094       RemoveFromWorkList(I);
12095       I->eraseFromParent();
12096       AddToWorkList(NewSCC);
12097       return &BI;
12098     }
12099
12100   // Cannonicalize icmp_ne -> icmp_eq
12101   ICmpInst::Predicate IPred;
12102   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12103                       TrueDest, FalseDest)))
12104     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12105          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12106          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12107       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12108       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12109       Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12110       NewSCC->takeName(I);
12111       // Swap Destinations and condition...
12112       BI.setCondition(NewSCC);
12113       BI.setSuccessor(0, FalseDest);
12114       BI.setSuccessor(1, TrueDest);
12115       RemoveFromWorkList(I);
12116       I->eraseFromParent();;
12117       AddToWorkList(NewSCC);
12118       return &BI;
12119     }
12120
12121   return 0;
12122 }
12123
12124 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12125   Value *Cond = SI.getCondition();
12126   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12127     if (I->getOpcode() == Instruction::Add)
12128       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12129         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12130         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12131           SI.setOperand(i,
12132                    ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12133                                                 AddRHS));
12134         SI.setOperand(0, I->getOperand(0));
12135         AddToWorkList(I);
12136         return &SI;
12137       }
12138   }
12139   return 0;
12140 }
12141
12142 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12143   Value *Agg = EV.getAggregateOperand();
12144
12145   if (!EV.hasIndices())
12146     return ReplaceInstUsesWith(EV, Agg);
12147
12148   if (Constant *C = dyn_cast<Constant>(Agg)) {
12149     if (isa<UndefValue>(C))
12150       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12151       
12152     if (isa<ConstantAggregateZero>(C))
12153       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12154
12155     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12156       // Extract the element indexed by the first index out of the constant
12157       Value *V = C->getOperand(*EV.idx_begin());
12158       if (EV.getNumIndices() > 1)
12159         // Extract the remaining indices out of the constant indexed by the
12160         // first index
12161         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12162       else
12163         return ReplaceInstUsesWith(EV, V);
12164     }
12165     return 0; // Can't handle other constants
12166   } 
12167   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12168     // We're extracting from an insertvalue instruction, compare the indices
12169     const unsigned *exti, *exte, *insi, *inse;
12170     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12171          exte = EV.idx_end(), inse = IV->idx_end();
12172          exti != exte && insi != inse;
12173          ++exti, ++insi) {
12174       if (*insi != *exti)
12175         // The insert and extract both reference distinctly different elements.
12176         // This means the extract is not influenced by the insert, and we can
12177         // replace the aggregate operand of the extract with the aggregate
12178         // operand of the insert. i.e., replace
12179         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12180         // %E = extractvalue { i32, { i32 } } %I, 0
12181         // with
12182         // %E = extractvalue { i32, { i32 } } %A, 0
12183         return ExtractValueInst::Create(IV->getAggregateOperand(),
12184                                         EV.idx_begin(), EV.idx_end());
12185     }
12186     if (exti == exte && insi == inse)
12187       // Both iterators are at the end: Index lists are identical. Replace
12188       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12189       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12190       // with "i32 42"
12191       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12192     if (exti == exte) {
12193       // The extract list is a prefix of the insert list. i.e. replace
12194       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12195       // %E = extractvalue { i32, { i32 } } %I, 1
12196       // with
12197       // %X = extractvalue { i32, { i32 } } %A, 1
12198       // %E = insertvalue { i32 } %X, i32 42, 0
12199       // by switching the order of the insert and extract (though the
12200       // insertvalue should be left in, since it may have other uses).
12201       Value *NewEV = InsertNewInstBefore(
12202         ExtractValueInst::Create(IV->getAggregateOperand(),
12203                                  EV.idx_begin(), EV.idx_end()),
12204         EV);
12205       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12206                                      insi, inse);
12207     }
12208     if (insi == inse)
12209       // The insert list is a prefix of the extract list
12210       // We can simply remove the common indices from the extract and make it
12211       // operate on the inserted value instead of the insertvalue result.
12212       // i.e., replace
12213       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12214       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12215       // with
12216       // %E extractvalue { i32 } { i32 42 }, 0
12217       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12218                                       exti, exte);
12219   }
12220   // Can't simplify extracts from other values. Note that nested extracts are
12221   // already simplified implicitely by the above (extract ( extract (insert) )
12222   // will be translated into extract ( insert ( extract ) ) first and then just
12223   // the value inserted, if appropriate).
12224   return 0;
12225 }
12226
12227 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12228 /// is to leave as a vector operation.
12229 static bool CheapToScalarize(Value *V, bool isConstant) {
12230   if (isa<ConstantAggregateZero>(V)) 
12231     return true;
12232   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12233     if (isConstant) return true;
12234     // If all elts are the same, we can extract.
12235     Constant *Op0 = C->getOperand(0);
12236     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12237       if (C->getOperand(i) != Op0)
12238         return false;
12239     return true;
12240   }
12241   Instruction *I = dyn_cast<Instruction>(V);
12242   if (!I) return false;
12243   
12244   // Insert element gets simplified to the inserted element or is deleted if
12245   // this is constant idx extract element and its a constant idx insertelt.
12246   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12247       isa<ConstantInt>(I->getOperand(2)))
12248     return true;
12249   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12250     return true;
12251   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12252     if (BO->hasOneUse() &&
12253         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12254          CheapToScalarize(BO->getOperand(1), isConstant)))
12255       return true;
12256   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12257     if (CI->hasOneUse() &&
12258         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12259          CheapToScalarize(CI->getOperand(1), isConstant)))
12260       return true;
12261   
12262   return false;
12263 }
12264
12265 /// Read and decode a shufflevector mask.
12266 ///
12267 /// It turns undef elements into values that are larger than the number of
12268 /// elements in the input.
12269 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12270   unsigned NElts = SVI->getType()->getNumElements();
12271   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12272     return std::vector<unsigned>(NElts, 0);
12273   if (isa<UndefValue>(SVI->getOperand(2)))
12274     return std::vector<unsigned>(NElts, 2*NElts);
12275
12276   std::vector<unsigned> Result;
12277   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12278   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12279     if (isa<UndefValue>(*i))
12280       Result.push_back(NElts*2);  // undef -> 8
12281     else
12282       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12283   return Result;
12284 }
12285
12286 /// FindScalarElement - Given a vector and an element number, see if the scalar
12287 /// value is already around as a register, for example if it were inserted then
12288 /// extracted from the vector.
12289 static Value *FindScalarElement(Value *V, unsigned EltNo,
12290                                 LLVMContext *Context) {
12291   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12292   const VectorType *PTy = cast<VectorType>(V->getType());
12293   unsigned Width = PTy->getNumElements();
12294   if (EltNo >= Width)  // Out of range access.
12295     return UndefValue::get(PTy->getElementType());
12296   
12297   if (isa<UndefValue>(V))
12298     return UndefValue::get(PTy->getElementType());
12299   else if (isa<ConstantAggregateZero>(V))
12300     return Constant::getNullValue(PTy->getElementType());
12301   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12302     return CP->getOperand(EltNo);
12303   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12304     // If this is an insert to a variable element, we don't know what it is.
12305     if (!isa<ConstantInt>(III->getOperand(2))) 
12306       return 0;
12307     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12308     
12309     // If this is an insert to the element we are looking for, return the
12310     // inserted value.
12311     if (EltNo == IIElt) 
12312       return III->getOperand(1);
12313     
12314     // Otherwise, the insertelement doesn't modify the value, recurse on its
12315     // vector input.
12316     return FindScalarElement(III->getOperand(0), EltNo, Context);
12317   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12318     unsigned LHSWidth =
12319       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12320     unsigned InEl = getShuffleMask(SVI)[EltNo];
12321     if (InEl < LHSWidth)
12322       return FindScalarElement(SVI->getOperand(0), InEl, Context);
12323     else if (InEl < LHSWidth*2)
12324       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12325     else
12326       return UndefValue::get(PTy->getElementType());
12327   }
12328   
12329   // Otherwise, we don't know.
12330   return 0;
12331 }
12332
12333 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12334   // If vector val is undef, replace extract with scalar undef.
12335   if (isa<UndefValue>(EI.getOperand(0)))
12336     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12337
12338   // If vector val is constant 0, replace extract with scalar 0.
12339   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12340     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12341   
12342   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12343     // If vector val is constant with all elements the same, replace EI with
12344     // that element. When the elements are not identical, we cannot replace yet
12345     // (we do that below, but only when the index is constant).
12346     Constant *op0 = C->getOperand(0);
12347     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12348       if (C->getOperand(i) != op0) {
12349         op0 = 0; 
12350         break;
12351       }
12352     if (op0)
12353       return ReplaceInstUsesWith(EI, op0);
12354   }
12355   
12356   // If extracting a specified index from the vector, see if we can recursively
12357   // find a previously computed scalar that was inserted into the vector.
12358   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12359     unsigned IndexVal = IdxC->getZExtValue();
12360     unsigned VectorWidth = 
12361       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12362       
12363     // If this is extracting an invalid index, turn this into undef, to avoid
12364     // crashing the code below.
12365     if (IndexVal >= VectorWidth)
12366       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12367     
12368     // This instruction only demands the single element from the input vector.
12369     // If the input vector has a single use, simplify it based on this use
12370     // property.
12371     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12372       APInt UndefElts(VectorWidth, 0);
12373       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12374       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12375                                                 DemandedMask, UndefElts)) {
12376         EI.setOperand(0, V);
12377         return &EI;
12378       }
12379     }
12380     
12381     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12382       return ReplaceInstUsesWith(EI, Elt);
12383     
12384     // If the this extractelement is directly using a bitcast from a vector of
12385     // the same number of elements, see if we can find the source element from
12386     // it.  In this case, we will end up needing to bitcast the scalars.
12387     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12388       if (const VectorType *VT = 
12389               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12390         if (VT->getNumElements() == VectorWidth)
12391           if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12392                                              IndexVal, Context))
12393             return new BitCastInst(Elt, EI.getType());
12394     }
12395   }
12396   
12397   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12398     if (I->hasOneUse()) {
12399       // Push extractelement into predecessor operation if legal and
12400       // profitable to do so
12401       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12402         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12403         if (CheapToScalarize(BO, isConstantElt)) {
12404           ExtractElementInst *newEI0 = 
12405             ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12406                                    EI.getName()+".lhs");
12407           ExtractElementInst *newEI1 =
12408             ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12409                                    EI.getName()+".rhs");
12410           InsertNewInstBefore(newEI0, EI);
12411           InsertNewInstBefore(newEI1, EI);
12412           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12413         }
12414       } else if (isa<LoadInst>(I)) {
12415         unsigned AS = 
12416           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12417         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12418                                   PointerType::get(EI.getType(), AS),*I);
12419         GetElementPtrInst *GEP =
12420           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12421         cast<GEPOperator>(GEP)->setIsInBounds(true);
12422         InsertNewInstBefore(GEP, *I);
12423         LoadInst* Load = new LoadInst(GEP, "tmp");
12424         InsertNewInstBefore(Load, *I);
12425         return ReplaceInstUsesWith(EI, Load);
12426       }
12427     }
12428     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12429       // Extracting the inserted element?
12430       if (IE->getOperand(2) == EI.getOperand(1))
12431         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12432       // If the inserted and extracted elements are constants, they must not
12433       // be the same value, extract from the pre-inserted value instead.
12434       if (isa<Constant>(IE->getOperand(2)) &&
12435           isa<Constant>(EI.getOperand(1))) {
12436         AddUsesToWorkList(EI);
12437         EI.setOperand(0, IE->getOperand(0));
12438         return &EI;
12439       }
12440     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12441       // If this is extracting an element from a shufflevector, figure out where
12442       // it came from and extract from the appropriate input element instead.
12443       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12444         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12445         Value *Src;
12446         unsigned LHSWidth =
12447           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12448
12449         if (SrcIdx < LHSWidth)
12450           Src = SVI->getOperand(0);
12451         else if (SrcIdx < LHSWidth*2) {
12452           SrcIdx -= LHSWidth;
12453           Src = SVI->getOperand(1);
12454         } else {
12455           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12456         }
12457         return ExtractElementInst::Create(Src,
12458                          ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
12459       }
12460     }
12461     // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12462   }
12463   return 0;
12464 }
12465
12466 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12467 /// elements from either LHS or RHS, return the shuffle mask and true. 
12468 /// Otherwise, return false.
12469 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12470                                          std::vector<Constant*> &Mask,
12471                                          LLVMContext *Context) {
12472   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12473          "Invalid CollectSingleShuffleElements");
12474   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12475
12476   if (isa<UndefValue>(V)) {
12477     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12478     return true;
12479   } else if (V == LHS) {
12480     for (unsigned i = 0; i != NumElts; ++i)
12481       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12482     return true;
12483   } else if (V == RHS) {
12484     for (unsigned i = 0; i != NumElts; ++i)
12485       Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12486     return true;
12487   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12488     // If this is an insert of an extract from some other vector, include it.
12489     Value *VecOp    = IEI->getOperand(0);
12490     Value *ScalarOp = IEI->getOperand(1);
12491     Value *IdxOp    = IEI->getOperand(2);
12492     
12493     if (!isa<ConstantInt>(IdxOp))
12494       return false;
12495     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12496     
12497     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12498       // Okay, we can handle this if the vector we are insertinting into is
12499       // transitively ok.
12500       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12501         // If so, update the mask to reflect the inserted undef.
12502         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12503         return true;
12504       }      
12505     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12506       if (isa<ConstantInt>(EI->getOperand(1)) &&
12507           EI->getOperand(0)->getType() == V->getType()) {
12508         unsigned ExtractedIdx =
12509           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12510         
12511         // This must be extracting from either LHS or RHS.
12512         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12513           // Okay, we can handle this if the vector we are insertinting into is
12514           // transitively ok.
12515           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12516             // If so, update the mask to reflect the inserted value.
12517             if (EI->getOperand(0) == LHS) {
12518               Mask[InsertedIdx % NumElts] = 
12519                  ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12520             } else {
12521               assert(EI->getOperand(0) == RHS);
12522               Mask[InsertedIdx % NumElts] = 
12523                 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12524               
12525             }
12526             return true;
12527           }
12528         }
12529       }
12530     }
12531   }
12532   // TODO: Handle shufflevector here!
12533   
12534   return false;
12535 }
12536
12537 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12538 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12539 /// that computes V and the LHS value of the shuffle.
12540 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12541                                      Value *&RHS, LLVMContext *Context) {
12542   assert(isa<VectorType>(V->getType()) && 
12543          (RHS == 0 || V->getType() == RHS->getType()) &&
12544          "Invalid shuffle!");
12545   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12546
12547   if (isa<UndefValue>(V)) {
12548     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12549     return V;
12550   } else if (isa<ConstantAggregateZero>(V)) {
12551     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12552     return V;
12553   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12554     // If this is an insert of an extract from some other vector, include it.
12555     Value *VecOp    = IEI->getOperand(0);
12556     Value *ScalarOp = IEI->getOperand(1);
12557     Value *IdxOp    = IEI->getOperand(2);
12558     
12559     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12560       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12561           EI->getOperand(0)->getType() == V->getType()) {
12562         unsigned ExtractedIdx =
12563           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12564         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12565         
12566         // Either the extracted from or inserted into vector must be RHSVec,
12567         // otherwise we'd end up with a shuffle of three inputs.
12568         if (EI->getOperand(0) == RHS || RHS == 0) {
12569           RHS = EI->getOperand(0);
12570           Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12571           Mask[InsertedIdx % NumElts] = 
12572             ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12573           return V;
12574         }
12575         
12576         if (VecOp == RHS) {
12577           Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12578                                             RHS, Context);
12579           // Everything but the extracted element is replaced with the RHS.
12580           for (unsigned i = 0; i != NumElts; ++i) {
12581             if (i != InsertedIdx)
12582               Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12583           }
12584           return V;
12585         }
12586         
12587         // If this insertelement is a chain that comes from exactly these two
12588         // vectors, return the vector and the effective shuffle.
12589         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12590                                          Context))
12591           return EI->getOperand(0);
12592         
12593       }
12594     }
12595   }
12596   // TODO: Handle shufflevector here!
12597   
12598   // Otherwise, can't do anything fancy.  Return an identity vector.
12599   for (unsigned i = 0; i != NumElts; ++i)
12600     Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12601   return V;
12602 }
12603
12604 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12605   Value *VecOp    = IE.getOperand(0);
12606   Value *ScalarOp = IE.getOperand(1);
12607   Value *IdxOp    = IE.getOperand(2);
12608   
12609   // Inserting an undef or into an undefined place, remove this.
12610   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12611     ReplaceInstUsesWith(IE, VecOp);
12612   
12613   // If the inserted element was extracted from some other vector, and if the 
12614   // indexes are constant, try to turn this into a shufflevector operation.
12615   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12616     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12617         EI->getOperand(0)->getType() == IE.getType()) {
12618       unsigned NumVectorElts = IE.getType()->getNumElements();
12619       unsigned ExtractedIdx =
12620         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12621       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12622       
12623       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12624         return ReplaceInstUsesWith(IE, VecOp);
12625       
12626       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12627         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12628       
12629       // If we are extracting a value from a vector, then inserting it right
12630       // back into the same place, just use the input vector.
12631       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12632         return ReplaceInstUsesWith(IE, VecOp);      
12633       
12634       // We could theoretically do this for ANY input.  However, doing so could
12635       // turn chains of insertelement instructions into a chain of shufflevector
12636       // instructions, and right now we do not merge shufflevectors.  As such,
12637       // only do this in a situation where it is clear that there is benefit.
12638       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12639         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12640         // the values of VecOp, except then one read from EIOp0.
12641         // Build a new shuffle mask.
12642         std::vector<Constant*> Mask;
12643         if (isa<UndefValue>(VecOp))
12644           Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12645         else {
12646           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12647           Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12648                                                        NumVectorElts));
12649         } 
12650         Mask[InsertedIdx] = 
12651                            ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12652         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12653                                      ConstantVector::get(Mask));
12654       }
12655       
12656       // If this insertelement isn't used by some other insertelement, turn it
12657       // (and any insertelements it points to), into one big shuffle.
12658       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12659         std::vector<Constant*> Mask;
12660         Value *RHS = 0;
12661         Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12662         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12663         // We now have a shuffle of LHS, RHS, Mask.
12664         return new ShuffleVectorInst(LHS, RHS,
12665                                      ConstantVector::get(Mask));
12666       }
12667     }
12668   }
12669
12670   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12671   APInt UndefElts(VWidth, 0);
12672   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12673   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12674     return &IE;
12675
12676   return 0;
12677 }
12678
12679
12680 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12681   Value *LHS = SVI.getOperand(0);
12682   Value *RHS = SVI.getOperand(1);
12683   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12684
12685   bool MadeChange = false;
12686
12687   // Undefined shuffle mask -> undefined value.
12688   if (isa<UndefValue>(SVI.getOperand(2)))
12689     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12690
12691   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12692
12693   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12694     return 0;
12695
12696   APInt UndefElts(VWidth, 0);
12697   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12698   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12699     LHS = SVI.getOperand(0);
12700     RHS = SVI.getOperand(1);
12701     MadeChange = true;
12702   }
12703   
12704   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12705   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12706   if (LHS == RHS || isa<UndefValue>(LHS)) {
12707     if (isa<UndefValue>(LHS) && LHS == RHS) {
12708       // shuffle(undef,undef,mask) -> undef.
12709       return ReplaceInstUsesWith(SVI, LHS);
12710     }
12711     
12712     // Remap any references to RHS to use LHS.
12713     std::vector<Constant*> Elts;
12714     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12715       if (Mask[i] >= 2*e)
12716         Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12717       else {
12718         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12719             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12720           Mask[i] = 2*e;     // Turn into undef.
12721           Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12722         } else {
12723           Mask[i] = Mask[i] % e;  // Force to LHS.
12724           Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12725         }
12726       }
12727     }
12728     SVI.setOperand(0, SVI.getOperand(1));
12729     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12730     SVI.setOperand(2, ConstantVector::get(Elts));
12731     LHS = SVI.getOperand(0);
12732     RHS = SVI.getOperand(1);
12733     MadeChange = true;
12734   }
12735   
12736   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12737   bool isLHSID = true, isRHSID = true;
12738     
12739   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12740     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12741     // Is this an identity shuffle of the LHS value?
12742     isLHSID &= (Mask[i] == i);
12743       
12744     // Is this an identity shuffle of the RHS value?
12745     isRHSID &= (Mask[i]-e == i);
12746   }
12747
12748   // Eliminate identity shuffles.
12749   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12750   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12751   
12752   // If the LHS is a shufflevector itself, see if we can combine it with this
12753   // one without producing an unusual shuffle.  Here we are really conservative:
12754   // we are absolutely afraid of producing a shuffle mask not in the input
12755   // program, because the code gen may not be smart enough to turn a merged
12756   // shuffle into two specific shuffles: it may produce worse code.  As such,
12757   // we only merge two shuffles if the result is one of the two input shuffle
12758   // masks.  In this case, merging the shuffles just removes one instruction,
12759   // which we know is safe.  This is good for things like turning:
12760   // (splat(splat)) -> splat.
12761   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12762     if (isa<UndefValue>(RHS)) {
12763       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12764
12765       std::vector<unsigned> NewMask;
12766       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12767         if (Mask[i] >= 2*e)
12768           NewMask.push_back(2*e);
12769         else
12770           NewMask.push_back(LHSMask[Mask[i]]);
12771       
12772       // If the result mask is equal to the src shuffle or this shuffle mask, do
12773       // the replacement.
12774       if (NewMask == LHSMask || NewMask == Mask) {
12775         unsigned LHSInNElts =
12776           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12777         std::vector<Constant*> Elts;
12778         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12779           if (NewMask[i] >= LHSInNElts*2) {
12780             Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12781           } else {
12782             Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12783           }
12784         }
12785         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12786                                      LHSSVI->getOperand(1),
12787                                      ConstantVector::get(Elts));
12788       }
12789     }
12790   }
12791
12792   return MadeChange ? &SVI : 0;
12793 }
12794
12795
12796
12797
12798 /// TryToSinkInstruction - Try to move the specified instruction from its
12799 /// current block into the beginning of DestBlock, which can only happen if it's
12800 /// safe to move the instruction past all of the instructions between it and the
12801 /// end of its block.
12802 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12803   assert(I->hasOneUse() && "Invariants didn't hold!");
12804
12805   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12806   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12807     return false;
12808
12809   // Do not sink alloca instructions out of the entry block.
12810   if (isa<AllocaInst>(I) && I->getParent() ==
12811         &DestBlock->getParent()->getEntryBlock())
12812     return false;
12813
12814   // We can only sink load instructions if there is nothing between the load and
12815   // the end of block that could change the value.
12816   if (I->mayReadFromMemory()) {
12817     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12818          Scan != E; ++Scan)
12819       if (Scan->mayWriteToMemory())
12820         return false;
12821   }
12822
12823   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12824
12825   CopyPrecedingStopPoint(I, InsertPos);
12826   I->moveBefore(InsertPos);
12827   ++NumSunkInst;
12828   return true;
12829 }
12830
12831
12832 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12833 /// all reachable code to the worklist.
12834 ///
12835 /// This has a couple of tricks to make the code faster and more powerful.  In
12836 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12837 /// them to the worklist (this significantly speeds up instcombine on code where
12838 /// many instructions are dead or constant).  Additionally, if we find a branch
12839 /// whose condition is a known constant, we only visit the reachable successors.
12840 ///
12841 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12842                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12843                                        InstCombiner &IC,
12844                                        const TargetData *TD) {
12845   SmallVector<BasicBlock*, 256> Worklist;
12846   Worklist.push_back(BB);
12847
12848   while (!Worklist.empty()) {
12849     BB = Worklist.back();
12850     Worklist.pop_back();
12851     
12852     // We have now visited this block!  If we've already been here, ignore it.
12853     if (!Visited.insert(BB)) continue;
12854
12855     DbgInfoIntrinsic *DBI_Prev = NULL;
12856     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12857       Instruction *Inst = BBI++;
12858       
12859       // DCE instruction if trivially dead.
12860       if (isInstructionTriviallyDead(Inst)) {
12861         ++NumDeadInst;
12862         DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12863         Inst->eraseFromParent();
12864         continue;
12865       }
12866       
12867       // ConstantProp instruction if trivially constant.
12868       if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12869         DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12870                      << *Inst << '\n');
12871         Inst->replaceAllUsesWith(C);
12872         ++NumConstProp;
12873         Inst->eraseFromParent();
12874         continue;
12875       }
12876      
12877       // If there are two consecutive llvm.dbg.stoppoint calls then
12878       // it is likely that the optimizer deleted code in between these
12879       // two intrinsics. 
12880       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12881       if (DBI_Next) {
12882         if (DBI_Prev
12883             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12884             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12885           IC.RemoveFromWorkList(DBI_Prev);
12886           DBI_Prev->eraseFromParent();
12887         }
12888         DBI_Prev = DBI_Next;
12889       } else {
12890         DBI_Prev = 0;
12891       }
12892
12893       IC.AddToWorkList(Inst);
12894     }
12895
12896     // Recursively visit successors.  If this is a branch or switch on a
12897     // constant, only visit the reachable successor.
12898     TerminatorInst *TI = BB->getTerminator();
12899     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12900       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12901         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12902         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12903         Worklist.push_back(ReachableBB);
12904         continue;
12905       }
12906     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12907       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12908         // See if this is an explicit destination.
12909         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12910           if (SI->getCaseValue(i) == Cond) {
12911             BasicBlock *ReachableBB = SI->getSuccessor(i);
12912             Worklist.push_back(ReachableBB);
12913             continue;
12914           }
12915         
12916         // Otherwise it is the default destination.
12917         Worklist.push_back(SI->getSuccessor(0));
12918         continue;
12919       }
12920     }
12921     
12922     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12923       Worklist.push_back(TI->getSuccessor(i));
12924   }
12925 }
12926
12927 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12928   bool Changed = false;
12929   TD = getAnalysisIfAvailable<TargetData>();
12930   
12931   DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12932         << F.getNameStr() << "\n");
12933
12934   {
12935     // Do a depth-first traversal of the function, populate the worklist with
12936     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12937     // track of which blocks we visit.
12938     SmallPtrSet<BasicBlock*, 64> Visited;
12939     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12940
12941     // Do a quick scan over the function.  If we find any blocks that are
12942     // unreachable, remove any instructions inside of them.  This prevents
12943     // the instcombine code from having to deal with some bad special cases.
12944     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12945       if (!Visited.count(BB)) {
12946         Instruction *Term = BB->getTerminator();
12947         while (Term != BB->begin()) {   // Remove instrs bottom-up
12948           BasicBlock::iterator I = Term; --I;
12949
12950           DEBUG(errs() << "IC: DCE: " << *I << '\n');
12951           // A debug intrinsic shouldn't force another iteration if we weren't
12952           // going to do one without it.
12953           if (!isa<DbgInfoIntrinsic>(I)) {
12954             ++NumDeadInst;
12955             Changed = true;
12956           }
12957           if (!I->use_empty())
12958             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12959           I->eraseFromParent();
12960         }
12961       }
12962   }
12963
12964   while (!Worklist.isEmpty()) {
12965     Instruction *I = Worklist.RemoveOne();
12966     if (I == 0) continue;  // skip null values.
12967
12968     // Check to see if we can DCE the instruction.
12969     if (isInstructionTriviallyDead(I)) {
12970       // Add operands to the worklist.
12971       if (I->getNumOperands() < 4)
12972         AddUsesToWorkList(*I);
12973       ++NumDeadInst;
12974
12975       DEBUG(errs() << "IC: DCE: " << *I << '\n');
12976
12977       I->eraseFromParent();
12978       RemoveFromWorkList(I);
12979       Changed = true;
12980       continue;
12981     }
12982
12983     // Instruction isn't dead, see if we can constant propagate it.
12984     if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12985       DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12986
12987       // Add operands to the worklist.
12988       AddUsesToWorkList(*I);
12989       ReplaceInstUsesWith(*I, C);
12990
12991       ++NumConstProp;
12992       I->eraseFromParent();
12993       RemoveFromWorkList(I);
12994       Changed = true;
12995       continue;
12996     }
12997
12998     if (TD) {
12999       // See if we can constant fold its operands.
13000       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13001         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13002           if (Constant *NewC = ConstantFoldConstantExpression(CE,   
13003                                   F.getContext(), TD))
13004             if (NewC != CE) {
13005               i->set(NewC);
13006               Changed = true;
13007             }
13008     }
13009
13010     // See if we can trivially sink this instruction to a successor basic block.
13011     if (I->hasOneUse()) {
13012       BasicBlock *BB = I->getParent();
13013       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13014       if (UserParent != BB) {
13015         bool UserIsSuccessor = false;
13016         // See if the user is one of our successors.
13017         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13018           if (*SI == UserParent) {
13019             UserIsSuccessor = true;
13020             break;
13021           }
13022
13023         // If the user is one of our immediate successors, and if that successor
13024         // only has us as a predecessors (we'd have to split the critical edge
13025         // otherwise), we can keep going.
13026         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13027             next(pred_begin(UserParent)) == pred_end(UserParent))
13028           // Okay, the CFG is simple enough, try to sink this instruction.
13029           Changed |= TryToSinkInstruction(I, UserParent);
13030       }
13031     }
13032
13033     // Now that we have an instruction, try combining it to simplify it...
13034 #ifndef NDEBUG
13035     std::string OrigI;
13036 #endif
13037     DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
13038     if (Instruction *Result = visit(*I)) {
13039       ++NumCombined;
13040       // Should we replace the old instruction with a new one?
13041       if (Result != I) {
13042         DEBUG(errs() << "IC: Old = " << *I << '\n'
13043                      << "    New = " << *Result << '\n');
13044
13045         // Everything uses the new instruction now.
13046         I->replaceAllUsesWith(Result);
13047
13048         // Push the new instruction and any users onto the worklist.
13049         AddToWorkList(Result);
13050         AddUsersToWorkList(*Result);
13051
13052         // Move the name to the new instruction first.
13053         Result->takeName(I);
13054
13055         // Insert the new instruction into the basic block...
13056         BasicBlock *InstParent = I->getParent();
13057         BasicBlock::iterator InsertPos = I;
13058
13059         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
13060           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13061             ++InsertPos;
13062
13063         InstParent->getInstList().insert(InsertPos, Result);
13064
13065         // Make sure that we reprocess all operands now that we reduced their
13066         // use counts.
13067         AddUsesToWorkList(*I);
13068
13069         // Instructions can end up on the worklist more than once.  Make sure
13070         // we do not process an instruction that has been deleted.
13071         RemoveFromWorkList(I);
13072
13073         // Erase the old instruction.
13074         InstParent->getInstList().erase(I);
13075       } else {
13076 #ifndef NDEBUG
13077         DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13078                      << "    New = " << *I << '\n');
13079 #endif
13080
13081         // If the instruction was modified, it's possible that it is now dead.
13082         // if so, remove it.
13083         if (isInstructionTriviallyDead(I)) {
13084           // Make sure we process all operands now that we are reducing their
13085           // use counts.
13086           AddUsesToWorkList(*I);
13087
13088           // Instructions may end up in the worklist more than once.  Erase all
13089           // occurrences of this instruction.
13090           RemoveFromWorkList(I);
13091           I->eraseFromParent();
13092         } else {
13093           AddToWorkList(I);
13094           AddUsersToWorkList(*I);
13095         }
13096       }
13097       Changed = true;
13098     }
13099   }
13100
13101   Worklist.Zap();
13102   return Changed;
13103 }
13104
13105
13106 bool InstCombiner::runOnFunction(Function &F) {
13107   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13108   Context = &F.getContext();
13109   
13110   bool EverMadeChange = false;
13111
13112   // Iterate while there is work to do.
13113   unsigned Iteration = 0;
13114   while (DoOneIteration(F, Iteration++))
13115     EverMadeChange = true;
13116   return EverMadeChange;
13117 }
13118
13119 FunctionPass *llvm::createInstructionCombiningPass() {
13120   return new InstCombiner();
13121 }