Fix 4366: store to null in non-default addr space should not be
[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/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     SmallVector<Instruction*, 256> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass(&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitFAdd(BinaryOperator &I);
171     Instruction *visitSub(BinaryOperator &I);
172     Instruction *visitFSub(BinaryOperator &I);
173     Instruction *visitMul(BinaryOperator &I);
174     Instruction *visitFMul(BinaryOperator &I);
175     Instruction *visitURem(BinaryOperator &I);
176     Instruction *visitSRem(BinaryOperator &I);
177     Instruction *visitFRem(BinaryOperator &I);
178     bool SimplifyDivRemOfSelect(BinaryOperator &I);
179     Instruction *commonRemTransforms(BinaryOperator &I);
180     Instruction *commonIRemTransforms(BinaryOperator &I);
181     Instruction *commonDivTransforms(BinaryOperator &I);
182     Instruction *commonIDivTransforms(BinaryOperator &I);
183     Instruction *visitUDiv(BinaryOperator &I);
184     Instruction *visitSDiv(BinaryOperator &I);
185     Instruction *visitFDiv(BinaryOperator &I);
186     Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
187     Instruction *visitAnd(BinaryOperator &I);
188     Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
189     Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
190                                      Value *A, Value *B, Value *C);
191     Instruction *visitOr (BinaryOperator &I);
192     Instruction *visitXor(BinaryOperator &I);
193     Instruction *visitShl(BinaryOperator &I);
194     Instruction *visitAShr(BinaryOperator &I);
195     Instruction *visitLShr(BinaryOperator &I);
196     Instruction *commonShiftTransforms(BinaryOperator &I);
197     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
198                                       Constant *RHSC);
199     Instruction *visitFCmpInst(FCmpInst &I);
200     Instruction *visitICmpInst(ICmpInst &I);
201     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
202     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
203                                                 Instruction *LHS,
204                                                 ConstantInt *RHS);
205     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
206                                 ConstantInt *DivRHS);
207
208     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
209                              ICmpInst::Predicate Cond, Instruction &I);
210     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
211                                      BinaryOperator &I);
212     Instruction *commonCastTransforms(CastInst &CI);
213     Instruction *commonIntCastTransforms(CastInst &CI);
214     Instruction *commonPointerCastTransforms(CastInst &CI);
215     Instruction *visitTrunc(TruncInst &CI);
216     Instruction *visitZExt(ZExtInst &CI);
217     Instruction *visitSExt(SExtInst &CI);
218     Instruction *visitFPTrunc(FPTruncInst &CI);
219     Instruction *visitFPExt(CastInst &CI);
220     Instruction *visitFPToUI(FPToUIInst &FI);
221     Instruction *visitFPToSI(FPToSIInst &FI);
222     Instruction *visitUIToFP(CastInst &CI);
223     Instruction *visitSIToFP(CastInst &CI);
224     Instruction *visitPtrToInt(PtrToIntInst &CI);
225     Instruction *visitIntToPtr(IntToPtrInst &CI);
226     Instruction *visitBitCast(BitCastInst &CI);
227     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
228                                 Instruction *FI);
229     Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
230     Instruction *visitSelectInst(SelectInst &SI);
231     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
232     Instruction *visitCallInst(CallInst &CI);
233     Instruction *visitInvokeInst(InvokeInst &II);
234     Instruction *visitPHINode(PHINode &PN);
235     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
236     Instruction *visitAllocationInst(AllocationInst &AI);
237     Instruction *visitFreeInst(FreeInst &FI);
238     Instruction *visitLoadInst(LoadInst &LI);
239     Instruction *visitStoreInst(StoreInst &SI);
240     Instruction *visitBranchInst(BranchInst &BI);
241     Instruction *visitSwitchInst(SwitchInst &SI);
242     Instruction *visitInsertElementInst(InsertElementInst &IE);
243     Instruction *visitExtractElementInst(ExtractElementInst &EI);
244     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
245     Instruction *visitExtractValueInst(ExtractValueInst &EV);
246
247     // visitInstruction - Specify what to return for unhandled instructions...
248     Instruction *visitInstruction(Instruction &I) { return 0; }
249
250   private:
251     Instruction *visitCallSite(CallSite CS);
252     bool transformConstExprCastCall(CallSite CS);
253     Instruction *transformCallThroughTrampoline(CallSite CS);
254     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
255                                    bool DoXform = true);
256     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
257     DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
258
259
260   public:
261     // InsertNewInstBefore - insert an instruction New before instruction Old
262     // in the program.  Add the new instruction to the worklist.
263     //
264     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
265       assert(New && New->getParent() == 0 &&
266              "New instruction already inserted into a basic block!");
267       BasicBlock *BB = Old.getParent();
268       BB->getInstList().insert(&Old, New);  // Insert inst
269       AddToWorkList(New);
270       return New;
271     }
272
273     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
274     /// This also adds the cast to the worklist.  Finally, this returns the
275     /// cast.
276     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
277                             Instruction &Pos) {
278       if (V->getType() == Ty) return V;
279
280       if (Constant *CV = dyn_cast<Constant>(V))
281         return ConstantExpr::getCast(opc, CV, Ty);
282       
283       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
284       AddToWorkList(C);
285       return C;
286     }
287         
288     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
289       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
290     }
291
292
293     // ReplaceInstUsesWith - This method is to be used when an instruction is
294     // found to be dead, replacable with another preexisting expression.  Here
295     // we add all uses of I to the worklist, replace all uses of I with the new
296     // value, then return I, so that the inst combiner will know that I was
297     // modified.
298     //
299     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
300       AddUsersToWorkList(I);         // Add all modified instrs to worklist
301       if (&I != V) {
302         I.replaceAllUsesWith(V);
303         return &I;
304       } else {
305         // If we are replacing the instruction with itself, this must be in a
306         // segment of unreachable code, so just clobber the instruction.
307         I.replaceAllUsesWith(UndefValue::get(I.getType()));
308         return &I;
309       }
310     }
311
312     // EraseInstFromFunction - When dealing with an instruction that has side
313     // effects or produces a void value, we can't rely on DCE to delete the
314     // instruction.  Instead, visit methods should return the value returned by
315     // this function.
316     Instruction *EraseInstFromFunction(Instruction &I) {
317       assert(I.use_empty() && "Cannot erase instruction that is used!");
318       AddUsesToWorkList(I);
319       RemoveFromWorkList(&I);
320       I.eraseFromParent();
321       return 0;  // Don't do anything with FI
322     }
323         
324     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
325                            APInt &KnownOne, unsigned Depth = 0) const {
326       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
327     }
328     
329     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
330                            unsigned Depth = 0) const {
331       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
332     }
333     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
334       return llvm::ComputeNumSignBits(Op, TD, Depth);
335     }
336
337   private:
338
339     /// SimplifyCommutative - This performs a few simplifications for 
340     /// commutative operators.
341     bool SimplifyCommutative(BinaryOperator &I);
342
343     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
344     /// most-complex to least-complex order.
345     bool SimplifyCompare(CmpInst &I);
346
347     /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
348     /// based on the demanded bits.
349     Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
350                                    APInt& KnownZero, APInt& KnownOne,
351                                    unsigned Depth);
352     bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
353                               APInt& KnownZero, APInt& KnownOne,
354                               unsigned Depth=0);
355         
356     /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
357     /// SimplifyDemandedBits knows about.  See if the instruction has any
358     /// properties that allow us to simplify its operands.
359     bool SimplifyDemandedInstructionBits(Instruction &Inst);
360         
361     Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
362                                       APInt& UndefElts, unsigned Depth = 0);
363       
364     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
365     // PHI node as operand #0, see if we can fold the instruction into the PHI
366     // (which is only possible if all operands to the PHI are constants).
367     Instruction *FoldOpIntoPhi(Instruction &I);
368
369     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
370     // operator and they all are only used by the PHI, PHI together their
371     // inputs, and do the operation once, to the result of the PHI.
372     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
373     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
374     Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
375
376     
377     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
378                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
379     
380     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
381                               bool isSub, Instruction &I);
382     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
383                                  bool isSigned, bool Inside, Instruction &IB);
384     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
385     Instruction *MatchBSwap(BinaryOperator &I);
386     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
387     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
388     Instruction *SimplifyMemSet(MemSetInst *MI);
389
390
391     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
392
393     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
394                                     unsigned CastOpc, int &NumCastsRemoved);
395     unsigned GetOrEnforceKnownAlignment(Value *V,
396                                         unsigned PrefAlign = 0);
397
398   };
399 }
400
401 char InstCombiner::ID = 0;
402 static RegisterPass<InstCombiner>
403 X("instcombine", "Combine redundant instructions");
404
405 // getComplexity:  Assign a complexity or rank value to LLVM Values...
406 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
407 static unsigned getComplexity(Value *V) {
408   if (isa<Instruction>(V)) {
409     if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
410         BinaryOperator::isNot(V))
411       return 3;
412     return 4;
413   }
414   if (isa<Argument>(V)) return 3;
415   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
416 }
417
418 // isOnlyUse - Return true if this instruction will be deleted if we stop using
419 // it.
420 static bool isOnlyUse(Value *V) {
421   return V->hasOneUse() || isa<Constant>(V);
422 }
423
424 // getPromotedType - Return the specified type promoted as it would be to pass
425 // though a va_arg area...
426 static const Type *getPromotedType(const Type *Ty) {
427   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
428     if (ITy->getBitWidth() < 32)
429       return Type::Int32Ty;
430   }
431   return Ty;
432 }
433
434 /// getBitCastOperand - If the specified operand is a CastInst, a constant
435 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
436 /// operand value, otherwise return null.
437 static Value *getBitCastOperand(Value *V) {
438   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
439     // BitCastInst?
440     return I->getOperand(0);
441   else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
442     // GetElementPtrInst?
443     if (GEP->hasAllZeroIndices())
444       return GEP->getOperand(0);
445   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
446     if (CE->getOpcode() == Instruction::BitCast)
447       // BitCast ConstantExp?
448       return CE->getOperand(0);
449     else if (CE->getOpcode() == Instruction::GetElementPtr) {
450       // GetElementPtr ConstantExp?
451       for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
452            I != E; ++I) {
453         ConstantInt *CI = dyn_cast<ConstantInt>(I);
454         if (!CI || !CI->isZero())
455           // Any non-zero indices? Not cast-like.
456           return 0;
457       }
458       // All-zero indices? This is just like casting.
459       return CE->getOperand(0);
460     }
461   }
462   return 0;
463 }
464
465 /// This function is a wrapper around CastInst::isEliminableCastPair. It
466 /// simply extracts arguments and returns what that function returns.
467 static Instruction::CastOps 
468 isEliminableCastPair(
469   const CastInst *CI, ///< The first cast instruction
470   unsigned opcode,       ///< The opcode of the second cast instruction
471   const Type *DstTy,     ///< The target type for the second cast instruction
472   TargetData *TD         ///< The target data for pointer size
473 ) {
474   
475   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
476   const Type *MidTy = CI->getType();                  // B from above
477
478   // Get the opcodes of the two Cast instructions
479   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
480   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
481
482   unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
483                                                 DstTy, TD->getIntPtrType());
484   
485   // We don't want to form an inttoptr or ptrtoint that converts to an integer
486   // type that differs from the pointer size.
487   if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
488       (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
489     Res = 0;
490   
491   return Instruction::CastOps(Res);
492 }
493
494 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
495 /// in any code being generated.  It does not require codegen if V is simple
496 /// enough or if the cast can be folded into other casts.
497 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
498                               const Type *Ty, TargetData *TD) {
499   if (V->getType() == Ty || isa<Constant>(V)) return false;
500   
501   // If this is another cast that can be eliminated, it isn't codegen either.
502   if (const CastInst *CI = dyn_cast<CastInst>(V))
503     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
504       return false;
505   return true;
506 }
507
508 // SimplifyCommutative - This performs a few simplifications for commutative
509 // operators:
510 //
511 //  1. Order operands such that they are listed from right (least complex) to
512 //     left (most complex).  This puts constants before unary operators before
513 //     binary operators.
514 //
515 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
516 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
517 //
518 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
519   bool Changed = false;
520   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
521     Changed = !I.swapOperands();
522
523   if (!I.isAssociative()) return Changed;
524   Instruction::BinaryOps Opcode = I.getOpcode();
525   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
526     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
527       if (isa<Constant>(I.getOperand(1))) {
528         Constant *Folded = ConstantExpr::get(I.getOpcode(),
529                                              cast<Constant>(I.getOperand(1)),
530                                              cast<Constant>(Op->getOperand(1)));
531         I.setOperand(0, Op->getOperand(0));
532         I.setOperand(1, Folded);
533         return true;
534       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
535         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
536             isOnlyUse(Op) && isOnlyUse(Op1)) {
537           Constant *C1 = cast<Constant>(Op->getOperand(1));
538           Constant *C2 = cast<Constant>(Op1->getOperand(1));
539
540           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
541           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
542           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
543                                                     Op1->getOperand(0),
544                                                     Op1->getName(), &I);
545           AddToWorkList(New);
546           I.setOperand(0, New);
547           I.setOperand(1, Folded);
548           return true;
549         }
550     }
551   return Changed;
552 }
553
554 /// SimplifyCompare - For a CmpInst this function just orders the operands
555 /// so that theyare listed from right (least complex) to left (most complex).
556 /// This puts constants before unary operators before binary operators.
557 bool InstCombiner::SimplifyCompare(CmpInst &I) {
558   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
559     return false;
560   I.swapOperands();
561   // Compare instructions are not associative so there's nothing else we can do.
562   return true;
563 }
564
565 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
566 // if the LHS is a constant zero (which is the 'negate' form).
567 //
568 static inline Value *dyn_castNegVal(Value *V) {
569   if (BinaryOperator::isNeg(V))
570     return BinaryOperator::getNegArgument(V);
571
572   // Constants can be considered to be negated values if they can be folded.
573   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
574     return ConstantExpr::getNeg(C);
575
576   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
577     if (C->getType()->getElementType()->isInteger())
578       return ConstantExpr::getNeg(C);
579
580   return 0;
581 }
582
583 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
584 // instruction if the LHS is a constant negative zero (which is the 'negate'
585 // form).
586 //
587 static inline Value *dyn_castFNegVal(Value *V) {
588   if (BinaryOperator::isFNeg(V))
589     return BinaryOperator::getFNegArgument(V);
590
591   // Constants can be considered to be negated values if they can be folded.
592   if (ConstantFP *C = dyn_cast<ConstantFP>(V))
593     return ConstantExpr::getFNeg(C);
594
595   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
596     if (C->getType()->getElementType()->isFloatingPoint())
597       return ConstantExpr::getFNeg(C);
598
599   return 0;
600 }
601
602 static inline Value *dyn_castNotVal(Value *V) {
603   if (BinaryOperator::isNot(V))
604     return BinaryOperator::getNotArgument(V);
605
606   // Constants can be considered to be not'ed values...
607   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
608     return ConstantInt::get(~C->getValue());
609   return 0;
610 }
611
612 // dyn_castFoldableMul - If this value is a multiply that can be folded into
613 // other computations (because it has a constant operand), return the
614 // non-constant operand of the multiply, and set CST to point to the multiplier.
615 // Otherwise, return null.
616 //
617 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
618   if (V->hasOneUse() && V->getType()->isInteger())
619     if (Instruction *I = dyn_cast<Instruction>(V)) {
620       if (I->getOpcode() == Instruction::Mul)
621         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
622           return I->getOperand(0);
623       if (I->getOpcode() == Instruction::Shl)
624         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
625           // The multiplier is really 1 << CST.
626           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
627           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
628           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
629           return I->getOperand(0);
630         }
631     }
632   return 0;
633 }
634
635 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
636 /// expression, return it.
637 static User *dyn_castGetElementPtr(Value *V) {
638   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
639   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
640     if (CE->getOpcode() == Instruction::GetElementPtr)
641       return cast<User>(V);
642   return false;
643 }
644
645 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
646 /// opcode value. Otherwise return UserOp1.
647 static unsigned getOpcode(const Value *V) {
648   if (const Instruction *I = dyn_cast<Instruction>(V))
649     return I->getOpcode();
650   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
651     return CE->getOpcode();
652   // Use UserOp1 to mean there's no opcode.
653   return Instruction::UserOp1;
654 }
655
656 /// AddOne - Add one to a ConstantInt
657 static ConstantInt *AddOne(ConstantInt *C) {
658   APInt Val(C->getValue());
659   return ConstantInt::get(++Val);
660 }
661 /// SubOne - Subtract one from a ConstantInt
662 static ConstantInt *SubOne(ConstantInt *C) {
663   APInt Val(C->getValue());
664   return ConstantInt::get(--Val);
665 }
666 /// Add - Add two ConstantInts together
667 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
668   return ConstantInt::get(C1->getValue() + C2->getValue());
669 }
670 /// And - Bitwise AND two ConstantInts together
671 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
672   return ConstantInt::get(C1->getValue() & C2->getValue());
673 }
674 /// Subtract - Subtract one ConstantInt from another
675 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
676   return ConstantInt::get(C1->getValue() - C2->getValue());
677 }
678 /// Multiply - Multiply two ConstantInts together
679 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
680   return ConstantInt::get(C1->getValue() * C2->getValue());
681 }
682 /// MultiplyOverflows - True if the multiply can not be expressed in an int
683 /// this size.
684 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
685   uint32_t W = C1->getBitWidth();
686   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
687   if (sign) {
688     LHSExt.sext(W * 2);
689     RHSExt.sext(W * 2);
690   } else {
691     LHSExt.zext(W * 2);
692     RHSExt.zext(W * 2);
693   }
694
695   APInt MulExt = LHSExt * RHSExt;
696
697   if (sign) {
698     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
699     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
700     return MulExt.slt(Min) || MulExt.sgt(Max);
701   } else 
702     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
703 }
704
705
706 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
707 /// specified instruction is a constant integer.  If so, check to see if there
708 /// are any bits set in the constant that are not demanded.  If so, shrink the
709 /// constant and return true.
710 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
711                                    APInt Demanded) {
712   assert(I && "No instruction?");
713   assert(OpNo < I->getNumOperands() && "Operand index too large");
714
715   // If the operand is not a constant integer, nothing to do.
716   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
717   if (!OpC) return false;
718
719   // If there are no bits set that aren't demanded, nothing to do.
720   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
721   if ((~Demanded & OpC->getValue()) == 0)
722     return false;
723
724   // This instruction is producing bits that are not demanded. Shrink the RHS.
725   Demanded &= OpC->getValue();
726   I->setOperand(OpNo, ConstantInt::get(Demanded));
727   return true;
728 }
729
730 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
731 // set of known zero and one bits, compute the maximum and minimum values that
732 // could have the specified known zero and known one bits, returning them in
733 // min/max.
734 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
735                                                    const APInt& KnownOne,
736                                                    APInt& Min, APInt& Max) {
737   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
738          KnownZero.getBitWidth() == Min.getBitWidth() &&
739          KnownZero.getBitWidth() == Max.getBitWidth() &&
740          "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
741   APInt UnknownBits = ~(KnownZero|KnownOne);
742
743   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
744   // bit if it is unknown.
745   Min = KnownOne;
746   Max = KnownOne|UnknownBits;
747   
748   if (UnknownBits.isNegative()) { // Sign bit is unknown
749     Min.set(Min.getBitWidth()-1);
750     Max.clear(Max.getBitWidth()-1);
751   }
752 }
753
754 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
755 // a set of known zero and one bits, compute the maximum and minimum values that
756 // could have the specified known zero and known one bits, returning them in
757 // min/max.
758 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
759                                                      const APInt &KnownOne,
760                                                      APInt &Min, APInt &Max) {
761   assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
762          KnownZero.getBitWidth() == Min.getBitWidth() &&
763          KnownZero.getBitWidth() == Max.getBitWidth() &&
764          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
765   APInt UnknownBits = ~(KnownZero|KnownOne);
766   
767   // The minimum value is when the unknown bits are all zeros.
768   Min = KnownOne;
769   // The maximum value is when the unknown bits are all ones.
770   Max = KnownOne|UnknownBits;
771 }
772
773 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
774 /// SimplifyDemandedBits knows about.  See if the instruction has any
775 /// properties that allow us to simplify its operands.
776 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
777   unsigned BitWidth = cast<IntegerType>(Inst.getType())->getBitWidth();
778   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
779   APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
780   
781   Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask, 
782                                      KnownZero, KnownOne, 0);
783   if (V == 0) return false;
784   if (V == &Inst) return true;
785   ReplaceInstUsesWith(Inst, V);
786   return true;
787 }
788
789 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
790 /// specified instruction operand if possible, updating it in place.  It returns
791 /// true if it made any change and false otherwise.
792 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask, 
793                                         APInt &KnownZero, APInt &KnownOne,
794                                         unsigned Depth) {
795   Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
796                                           KnownZero, KnownOne, Depth);
797   if (NewVal == 0) return false;
798   U.set(NewVal);
799   return true;
800 }
801
802
803 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
804 /// value based on the demanded bits.  When this function is called, it is known
805 /// that only the bits set in DemandedMask of the result of V are ever used
806 /// downstream. Consequently, depending on the mask and V, it may be possible
807 /// to replace V with a constant or one of its operands. In such cases, this
808 /// function does the replacement and returns true. In all other cases, it
809 /// returns false after analyzing the expression and setting KnownOne and known
810 /// to be one in the expression.  KnownZero contains all the bits that are known
811 /// to be zero in the expression. These are provided to potentially allow the
812 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
813 /// the expression. KnownOne and KnownZero always follow the invariant that 
814 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
815 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
816 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
817 /// and KnownOne must all be the same.
818 ///
819 /// This returns null if it did not change anything and it permits no
820 /// simplification.  This returns V itself if it did some simplification of V's
821 /// operands based on the information about what bits are demanded. This returns
822 /// some other non-null value if it found out that V is equal to another value
823 /// in the context where the specified bits are demanded, but not for all users.
824 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
825                                              APInt &KnownZero, APInt &KnownOne,
826                                              unsigned Depth) {
827   assert(V != 0 && "Null pointer of Value???");
828   assert(Depth <= 6 && "Limit Search Depth");
829   uint32_t BitWidth = DemandedMask.getBitWidth();
830   const Type *VTy = V->getType();
831   assert((TD || !isa<PointerType>(VTy)) &&
832          "SimplifyDemandedBits needs to know bit widths!");
833   assert((!TD || TD->getTypeSizeInBits(VTy) == BitWidth) &&
834          (!isa<IntegerType>(VTy) ||
835           VTy->getPrimitiveSizeInBits() == BitWidth) &&
836          KnownZero.getBitWidth() == BitWidth &&
837          KnownOne.getBitWidth() == BitWidth &&
838          "Value *V, DemandedMask, KnownZero and KnownOne \
839           must have same BitWidth");
840   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
841     // We know all of the bits for a constant!
842     KnownOne = CI->getValue() & DemandedMask;
843     KnownZero = ~KnownOne & DemandedMask;
844     return 0;
845   }
846   if (isa<ConstantPointerNull>(V)) {
847     // We know all of the bits for a constant!
848     KnownOne.clear();
849     KnownZero = DemandedMask;
850     return 0;
851   }
852
853   KnownZero.clear();
854   KnownOne.clear();
855   if (DemandedMask == 0) {   // Not demanding any bits from V.
856     if (isa<UndefValue>(V))
857       return 0;
858     return UndefValue::get(VTy);
859   }
860   
861   if (Depth == 6)        // Limit search depth.
862     return 0;
863   
864   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
865   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
866
867   Instruction *I = dyn_cast<Instruction>(V);
868   if (!I) {
869     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
870     return 0;        // Only analyze instructions.
871   }
872
873   // If there are multiple uses of this value and we aren't at the root, then
874   // we can't do any simplifications of the operands, because DemandedMask
875   // only reflects the bits demanded by *one* of the users.
876   if (Depth != 0 && !I->hasOneUse()) {
877     // Despite the fact that we can't simplify this instruction in all User's
878     // context, we can at least compute the knownzero/knownone bits, and we can
879     // do simplifications that apply to *just* the one user if we know that
880     // this instruction has a simpler value in that context.
881     if (I->getOpcode() == Instruction::And) {
882       // If either the LHS or the RHS are Zero, the result is zero.
883       ComputeMaskedBits(I->getOperand(1), DemandedMask,
884                         RHSKnownZero, RHSKnownOne, Depth+1);
885       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
886                         LHSKnownZero, LHSKnownOne, Depth+1);
887       
888       // If all of the demanded bits are known 1 on one side, return the other.
889       // These bits cannot contribute to the result of the 'and' in this
890       // context.
891       if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
892           (DemandedMask & ~LHSKnownZero))
893         return I->getOperand(0);
894       if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
895           (DemandedMask & ~RHSKnownZero))
896         return I->getOperand(1);
897       
898       // If all of the demanded bits in the inputs are known zeros, return zero.
899       if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
900         return Constant::getNullValue(VTy);
901       
902     } else if (I->getOpcode() == Instruction::Or) {
903       // We can simplify (X|Y) -> X or Y in the user's context if we know that
904       // only bits from X or Y are demanded.
905       
906       // If either the LHS or the RHS are One, the result is One.
907       ComputeMaskedBits(I->getOperand(1), DemandedMask, 
908                         RHSKnownZero, RHSKnownOne, Depth+1);
909       ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
910                         LHSKnownZero, LHSKnownOne, Depth+1);
911       
912       // If all of the demanded bits are known zero on one side, return the
913       // other.  These bits cannot contribute to the result of the 'or' in this
914       // context.
915       if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
916           (DemandedMask & ~LHSKnownOne))
917         return I->getOperand(0);
918       if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
919           (DemandedMask & ~RHSKnownOne))
920         return I->getOperand(1);
921       
922       // If all of the potentially set bits on one side are known to be set on
923       // the other side, just use the 'other' side.
924       if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
925           (DemandedMask & (~RHSKnownZero)))
926         return I->getOperand(0);
927       if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
928           (DemandedMask & (~LHSKnownZero)))
929         return I->getOperand(1);
930     }
931     
932     // Compute the KnownZero/KnownOne bits to simplify things downstream.
933     ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
934     return 0;
935   }
936   
937   // If this is the root being simplified, allow it to have multiple uses,
938   // just set the DemandedMask to all bits so that we can try to simplify the
939   // operands.  This allows visitTruncInst (for example) to simplify the
940   // operand of a trunc without duplicating all the logic below.
941   if (Depth == 0 && !V->hasOneUse())
942     DemandedMask = APInt::getAllOnesValue(BitWidth);
943   
944   switch (I->getOpcode()) {
945   default:
946     ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
947     break;
948   case Instruction::And:
949     // If either the LHS or the RHS are Zero, the result is zero.
950     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
951                              RHSKnownZero, RHSKnownOne, Depth+1) ||
952         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
953                              LHSKnownZero, LHSKnownOne, Depth+1))
954       return I;
955     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
956     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
957
958     // If all of the demanded bits are known 1 on one side, return the other.
959     // These bits cannot contribute to the result of the 'and'.
960     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
961         (DemandedMask & ~LHSKnownZero))
962       return I->getOperand(0);
963     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
964         (DemandedMask & ~RHSKnownZero))
965       return I->getOperand(1);
966     
967     // If all of the demanded bits in the inputs are known zeros, return zero.
968     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
969       return Constant::getNullValue(VTy);
970       
971     // If the RHS is a constant, see if we can simplify it.
972     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
973       return I;
974       
975     // Output known-1 bits are only known if set in both the LHS & RHS.
976     RHSKnownOne &= LHSKnownOne;
977     // Output known-0 are known to be clear if zero in either the LHS | RHS.
978     RHSKnownZero |= LHSKnownZero;
979     break;
980   case Instruction::Or:
981     // If either the LHS or the RHS are One, the result is One.
982     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
983                              RHSKnownZero, RHSKnownOne, Depth+1) ||
984         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne, 
985                              LHSKnownZero, LHSKnownOne, Depth+1))
986       return I;
987     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
988     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
989     
990     // If all of the demanded bits are known zero on one side, return the other.
991     // These bits cannot contribute to the result of the 'or'.
992     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
993         (DemandedMask & ~LHSKnownOne))
994       return I->getOperand(0);
995     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
996         (DemandedMask & ~RHSKnownOne))
997       return I->getOperand(1);
998
999     // If all of the potentially set bits on one side are known to be set on
1000     // the other side, just use the 'other' side.
1001     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1002         (DemandedMask & (~RHSKnownZero)))
1003       return I->getOperand(0);
1004     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1005         (DemandedMask & (~LHSKnownZero)))
1006       return I->getOperand(1);
1007         
1008     // If the RHS is a constant, see if we can simplify it.
1009     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1010       return I;
1011           
1012     // Output known-0 bits are only known if clear in both the LHS & RHS.
1013     RHSKnownZero &= LHSKnownZero;
1014     // Output known-1 are known to be set if set in either the LHS | RHS.
1015     RHSKnownOne |= LHSKnownOne;
1016     break;
1017   case Instruction::Xor: {
1018     if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1019                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1020         SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1021                              LHSKnownZero, LHSKnownOne, Depth+1))
1022       return I;
1023     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1024     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1025     
1026     // If all of the demanded bits are known zero on one side, return the other.
1027     // These bits cannot contribute to the result of the 'xor'.
1028     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1029       return I->getOperand(0);
1030     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1031       return I->getOperand(1);
1032     
1033     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1034     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1035                          (RHSKnownOne & LHSKnownOne);
1036     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1037     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1038                         (RHSKnownOne & LHSKnownZero);
1039     
1040     // If all of the demanded bits are known to be zero on one side or the
1041     // other, turn this into an *inclusive* or.
1042     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1043     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1044       Instruction *Or =
1045         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1046                                  I->getName());
1047       return InsertNewInstBefore(Or, *I);
1048     }
1049     
1050     // If all of the demanded bits on one side are known, and all of the set
1051     // bits on that side are also known to be set on the other side, turn this
1052     // into an AND, as we know the bits will be cleared.
1053     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1054     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1055       // all known
1056       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1057         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1058         Instruction *And = 
1059           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1060         return InsertNewInstBefore(And, *I);
1061       }
1062     }
1063     
1064     // If the RHS is a constant, see if we can simplify it.
1065     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1066     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1067       return I;
1068     
1069     RHSKnownZero = KnownZeroOut;
1070     RHSKnownOne  = KnownOneOut;
1071     break;
1072   }
1073   case Instruction::Select:
1074     if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1075                              RHSKnownZero, RHSKnownOne, Depth+1) ||
1076         SimplifyDemandedBits(I->getOperandUse(1), DemandedMask, 
1077                              LHSKnownZero, LHSKnownOne, Depth+1))
1078       return I;
1079     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1080     assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?"); 
1081     
1082     // If the operands are constants, see if we can simplify them.
1083     if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1084         ShrinkDemandedConstant(I, 2, DemandedMask))
1085       return I;
1086     
1087     // Only known if known in both the LHS and RHS.
1088     RHSKnownOne &= LHSKnownOne;
1089     RHSKnownZero &= LHSKnownZero;
1090     break;
1091   case Instruction::Trunc: {
1092     unsigned truncBf = I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1093     DemandedMask.zext(truncBf);
1094     RHSKnownZero.zext(truncBf);
1095     RHSKnownOne.zext(truncBf);
1096     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask, 
1097                              RHSKnownZero, RHSKnownOne, Depth+1))
1098       return I;
1099     DemandedMask.trunc(BitWidth);
1100     RHSKnownZero.trunc(BitWidth);
1101     RHSKnownOne.trunc(BitWidth);
1102     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1103     break;
1104   }
1105   case Instruction::BitCast:
1106     if (!I->getOperand(0)->getType()->isInteger())
1107       return false;  // vector->int or fp->int?
1108     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1109                              RHSKnownZero, RHSKnownOne, Depth+1))
1110       return I;
1111     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1112     break;
1113   case Instruction::ZExt: {
1114     // Compute the bits in the result that are not present in the input.
1115     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1116     
1117     DemandedMask.trunc(SrcBitWidth);
1118     RHSKnownZero.trunc(SrcBitWidth);
1119     RHSKnownOne.trunc(SrcBitWidth);
1120     if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1121                              RHSKnownZero, RHSKnownOne, Depth+1))
1122       return I;
1123     DemandedMask.zext(BitWidth);
1124     RHSKnownZero.zext(BitWidth);
1125     RHSKnownOne.zext(BitWidth);
1126     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1127     // The top bits are known to be zero.
1128     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1129     break;
1130   }
1131   case Instruction::SExt: {
1132     // Compute the bits in the result that are not present in the input.
1133     unsigned SrcBitWidth =I->getOperand(0)->getType()->getPrimitiveSizeInBits();
1134     
1135     APInt InputDemandedBits = DemandedMask & 
1136                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1137
1138     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1139     // If any of the sign extended bits are demanded, we know that the sign
1140     // bit is demanded.
1141     if ((NewBits & DemandedMask) != 0)
1142       InputDemandedBits.set(SrcBitWidth-1);
1143       
1144     InputDemandedBits.trunc(SrcBitWidth);
1145     RHSKnownZero.trunc(SrcBitWidth);
1146     RHSKnownOne.trunc(SrcBitWidth);
1147     if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1148                              RHSKnownZero, RHSKnownOne, Depth+1))
1149       return I;
1150     InputDemandedBits.zext(BitWidth);
1151     RHSKnownZero.zext(BitWidth);
1152     RHSKnownOne.zext(BitWidth);
1153     assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?"); 
1154       
1155     // If the sign bit of the input is known set or clear, then we know the
1156     // top bits of the result.
1157
1158     // If the input sign bit is known zero, or if the NewBits are not demanded
1159     // convert this into a zero extension.
1160     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1161       // Convert to ZExt cast
1162       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1163       return InsertNewInstBefore(NewCast, *I);
1164     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1165       RHSKnownOne |= NewBits;
1166     }
1167     break;
1168   }
1169   case Instruction::Add: {
1170     // Figure out what the input bits are.  If the top bits of the and result
1171     // are not demanded, then the add doesn't demand them from its input
1172     // either.
1173     unsigned NLZ = DemandedMask.countLeadingZeros();
1174       
1175     // If there is a constant on the RHS, there are a variety of xformations
1176     // we can do.
1177     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178       // If null, this should be simplified elsewhere.  Some of the xforms here
1179       // won't work if the RHS is zero.
1180       if (RHS->isZero())
1181         break;
1182       
1183       // If the top bit of the output is demanded, demand everything from the
1184       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1185       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1186
1187       // Find information about known zero/one bits in the input.
1188       if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits, 
1189                                LHSKnownZero, LHSKnownOne, Depth+1))
1190         return I;
1191
1192       // If the RHS of the add has bits set that can't affect the input, reduce
1193       // the constant.
1194       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1195         return I;
1196       
1197       // Avoid excess work.
1198       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1199         break;
1200       
1201       // Turn it into OR if input bits are zero.
1202       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1203         Instruction *Or =
1204           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1205                                    I->getName());
1206         return InsertNewInstBefore(Or, *I);
1207       }
1208       
1209       // We can say something about the output known-zero and known-one bits,
1210       // depending on potential carries from the input constant and the
1211       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1212       // bits set and the RHS constant is 0x01001, then we know we have a known
1213       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1214       
1215       // To compute this, we first compute the potential carry bits.  These are
1216       // the bits which may be modified.  I'm not aware of a better way to do
1217       // this scan.
1218       const APInt &RHSVal = RHS->getValue();
1219       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1220       
1221       // Now that we know which bits have carries, compute the known-1/0 sets.
1222       
1223       // Bits are known one if they are known zero in one operand and one in the
1224       // other, and there is no input carry.
1225       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1226                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1227       
1228       // Bits are known zero if they are known zero in both operands and there
1229       // is no input carry.
1230       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1231     } else {
1232       // If the high-bits of this ADD are not demanded, then it does not demand
1233       // the high bits of its LHS or RHS.
1234       if (DemandedMask[BitWidth-1] == 0) {
1235         // Right fill the mask of bits for this ADD to demand the most
1236         // significant bit and all those below it.
1237         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1238         if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1239                                  LHSKnownZero, LHSKnownOne, Depth+1) ||
1240             SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1241                                  LHSKnownZero, LHSKnownOne, Depth+1))
1242           return I;
1243       }
1244     }
1245     break;
1246   }
1247   case Instruction::Sub:
1248     // If the high-bits of this SUB are not demanded, then it does not demand
1249     // the high bits of its LHS or RHS.
1250     if (DemandedMask[BitWidth-1] == 0) {
1251       // Right fill the mask of bits for this SUB to demand the most
1252       // significant bit and all those below it.
1253       uint32_t NLZ = DemandedMask.countLeadingZeros();
1254       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1255       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1256                                LHSKnownZero, LHSKnownOne, Depth+1) ||
1257           SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1258                                LHSKnownZero, LHSKnownOne, Depth+1))
1259         return I;
1260     }
1261     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1262     // the known zeros and ones.
1263     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1264     break;
1265   case Instruction::Shl:
1266     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1267       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1268       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1269       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn, 
1270                                RHSKnownZero, RHSKnownOne, Depth+1))
1271         return I;
1272       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1273       RHSKnownZero <<= ShiftAmt;
1274       RHSKnownOne  <<= ShiftAmt;
1275       // low bits known zero.
1276       if (ShiftAmt)
1277         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1278     }
1279     break;
1280   case Instruction::LShr:
1281     // For a logical shift right
1282     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1283       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1284       
1285       // Unsigned shift right.
1286       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1287       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1288                                RHSKnownZero, RHSKnownOne, Depth+1))
1289         return I;
1290       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1291       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1292       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1293       if (ShiftAmt) {
1294         // Compute the new bits that are at the top now.
1295         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1296         RHSKnownZero |= HighBits;  // high bits known zero.
1297       }
1298     }
1299     break;
1300   case Instruction::AShr:
1301     // If this is an arithmetic shift right and only the low-bit is set, we can
1302     // always convert this into a logical shr, even if the shift amount is
1303     // variable.  The low bit of the shift cannot be an input sign bit unless
1304     // the shift amount is >= the size of the datatype, which is undefined.
1305     if (DemandedMask == 1) {
1306       // Perform the logical shift right.
1307       Instruction *NewVal = BinaryOperator::CreateLShr(
1308                         I->getOperand(0), I->getOperand(1), I->getName());
1309       return InsertNewInstBefore(NewVal, *I);
1310     }    
1311
1312     // If the sign bit is the only bit demanded by this ashr, then there is no
1313     // need to do it, the shift doesn't change the high bit.
1314     if (DemandedMask.isSignBit())
1315       return I->getOperand(0);
1316     
1317     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1318       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1319       
1320       // Signed shift right.
1321       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1322       // If any of the "high bits" are demanded, we should set the sign bit as
1323       // demanded.
1324       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1325         DemandedMaskIn.set(BitWidth-1);
1326       if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1327                                RHSKnownZero, RHSKnownOne, Depth+1))
1328         return I;
1329       assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1330       // Compute the new bits that are at the top now.
1331       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1332       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1334         
1335       // Handle the sign bits.
1336       APInt SignBit(APInt::getSignBit(BitWidth));
1337       // Adjust to where it is now in the mask.
1338       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1339         
1340       // If the input sign bit is known to be zero, or if none of the top bits
1341       // are demanded, turn this into an unsigned shift right.
1342       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1343           (HighBits & ~DemandedMask) == HighBits) {
1344         // Perform the logical shift right.
1345         Instruction *NewVal = BinaryOperator::CreateLShr(
1346                           I->getOperand(0), SA, I->getName());
1347         return InsertNewInstBefore(NewVal, *I);
1348       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1349         RHSKnownOne |= HighBits;
1350       }
1351     }
1352     break;
1353   case Instruction::SRem:
1354     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1355       APInt RA = Rem->getValue().abs();
1356       if (RA.isPowerOf2()) {
1357         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1358           return I->getOperand(0);
1359
1360         APInt LowBits = RA - 1;
1361         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1362         if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1363                                  LHSKnownZero, LHSKnownOne, Depth+1))
1364           return I;
1365
1366         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1367           LHSKnownZero |= ~LowBits;
1368
1369         KnownZero |= LHSKnownZero & DemandedMask;
1370
1371         assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?"); 
1372       }
1373     }
1374     break;
1375   case Instruction::URem: {
1376     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1377     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1378     if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1379                              KnownZero2, KnownOne2, Depth+1) ||
1380         SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1381                              KnownZero2, KnownOne2, Depth+1))
1382       return I;
1383
1384     unsigned Leaders = KnownZero2.countLeadingOnes();
1385     Leaders = std::max(Leaders,
1386                        KnownZero2.countLeadingOnes());
1387     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1388     break;
1389   }
1390   case Instruction::Call:
1391     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1392       switch (II->getIntrinsicID()) {
1393       default: break;
1394       case Intrinsic::bswap: {
1395         // If the only bits demanded come from one byte of the bswap result,
1396         // just shift the input byte into position to eliminate the bswap.
1397         unsigned NLZ = DemandedMask.countLeadingZeros();
1398         unsigned NTZ = DemandedMask.countTrailingZeros();
1399           
1400         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1401         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1402         // have 14 leading zeros, round to 8.
1403         NLZ &= ~7;
1404         NTZ &= ~7;
1405         // If we need exactly one byte, we can do this transformation.
1406         if (BitWidth-NLZ-NTZ == 8) {
1407           unsigned ResultBit = NTZ;
1408           unsigned InputBit = BitWidth-NTZ-8;
1409           
1410           // Replace this with either a left or right shift to get the byte into
1411           // the right place.
1412           Instruction *NewVal;
1413           if (InputBit > ResultBit)
1414             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1415                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1416           else
1417             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1418                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1419           NewVal->takeName(I);
1420           return InsertNewInstBefore(NewVal, *I);
1421         }
1422           
1423         // TODO: Could compute known zero/one bits based on the input.
1424         break;
1425       }
1426       }
1427     }
1428     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1429     break;
1430   }
1431   
1432   // If the client is only demanding bits that we know, return the known
1433   // constant.
1434   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1435     Constant *C = ConstantInt::get(RHSKnownOne);
1436     if (isa<PointerType>(V->getType()))
1437       C = ConstantExpr::getIntToPtr(C, V->getType());
1438     return C;
1439   }
1440   return false;
1441 }
1442
1443
1444 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1445 /// any number of elements. DemandedElts contains the set of elements that are
1446 /// actually used by the caller.  This method analyzes which elements of the
1447 /// operand are undef and returns that information in UndefElts.
1448 ///
1449 /// If the information about demanded elements can be used to simplify the
1450 /// operation, the operation is simplified, then the resultant value is
1451 /// returned.  This returns null if no change was made.
1452 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1453                                                 APInt& UndefElts,
1454                                                 unsigned Depth) {
1455   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1456   APInt EltMask(APInt::getAllOnesValue(VWidth));
1457   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1458
1459   if (isa<UndefValue>(V)) {
1460     // If the entire vector is undefined, just return this info.
1461     UndefElts = EltMask;
1462     return 0;
1463   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1464     UndefElts = EltMask;
1465     return UndefValue::get(V->getType());
1466   }
1467
1468   UndefElts = 0;
1469   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1470     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1471     Constant *Undef = UndefValue::get(EltTy);
1472
1473     std::vector<Constant*> Elts;
1474     for (unsigned i = 0; i != VWidth; ++i)
1475       if (!DemandedElts[i]) {   // If not demanded, set to undef.
1476         Elts.push_back(Undef);
1477         UndefElts.set(i);
1478       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1479         Elts.push_back(Undef);
1480         UndefElts.set(i);
1481       } else {                               // Otherwise, defined.
1482         Elts.push_back(CP->getOperand(i));
1483       }
1484
1485     // If we changed the constant, return it.
1486     Constant *NewCP = ConstantVector::get(Elts);
1487     return NewCP != CP ? NewCP : 0;
1488   } else if (isa<ConstantAggregateZero>(V)) {
1489     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1490     // set to undef.
1491     
1492     // Check if this is identity. If so, return 0 since we are not simplifying
1493     // anything.
1494     if (DemandedElts == ((1ULL << VWidth) -1))
1495       return 0;
1496     
1497     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1498     Constant *Zero = Constant::getNullValue(EltTy);
1499     Constant *Undef = UndefValue::get(EltTy);
1500     std::vector<Constant*> Elts;
1501     for (unsigned i = 0; i != VWidth; ++i) {
1502       Constant *Elt = DemandedElts[i] ? Zero : Undef;
1503       Elts.push_back(Elt);
1504     }
1505     UndefElts = DemandedElts ^ EltMask;
1506     return ConstantVector::get(Elts);
1507   }
1508   
1509   // Limit search depth.
1510   if (Depth == 10)
1511     return 0;
1512
1513   // If multiple users are using the root value, procede with
1514   // simplification conservatively assuming that all elements
1515   // are needed.
1516   if (!V->hasOneUse()) {
1517     // Quit if we find multiple users of a non-root value though.
1518     // They'll be handled when it's their turn to be visited by
1519     // the main instcombine process.
1520     if (Depth != 0)
1521       // TODO: Just compute the UndefElts information recursively.
1522       return 0;
1523
1524     // Conservatively assume that all elements are needed.
1525     DemandedElts = EltMask;
1526   }
1527   
1528   Instruction *I = dyn_cast<Instruction>(V);
1529   if (!I) return 0;        // Only analyze instructions.
1530   
1531   bool MadeChange = false;
1532   APInt UndefElts2(VWidth, 0);
1533   Value *TmpV;
1534   switch (I->getOpcode()) {
1535   default: break;
1536     
1537   case Instruction::InsertElement: {
1538     // If this is a variable index, we don't know which element it overwrites.
1539     // demand exactly the same input as we produce.
1540     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1541     if (Idx == 0) {
1542       // Note that we can't propagate undef elt info, because we don't know
1543       // which elt is getting updated.
1544       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1545                                         UndefElts2, Depth+1);
1546       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1547       break;
1548     }
1549     
1550     // If this is inserting an element that isn't demanded, remove this
1551     // insertelement.
1552     unsigned IdxNo = Idx->getZExtValue();
1553     if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1554       return AddSoonDeadInstToWorklist(*I, 0);
1555     
1556     // Otherwise, the element inserted overwrites whatever was there, so the
1557     // input demanded set is simpler than the output set.
1558     APInt DemandedElts2 = DemandedElts;
1559     DemandedElts2.clear(IdxNo);
1560     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1561                                       UndefElts, Depth+1);
1562     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1563
1564     // The inserted element is defined.
1565     UndefElts.clear(IdxNo);
1566     break;
1567   }
1568   case Instruction::ShuffleVector: {
1569     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1570     uint64_t LHSVWidth =
1571       cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1572     APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1573     for (unsigned i = 0; i < VWidth; i++) {
1574       if (DemandedElts[i]) {
1575         unsigned MaskVal = Shuffle->getMaskValue(i);
1576         if (MaskVal != -1u) {
1577           assert(MaskVal < LHSVWidth * 2 &&
1578                  "shufflevector mask index out of range!");
1579           if (MaskVal < LHSVWidth)
1580             LeftDemanded.set(MaskVal);
1581           else
1582             RightDemanded.set(MaskVal - LHSVWidth);
1583         }
1584       }
1585     }
1586
1587     APInt UndefElts4(LHSVWidth, 0);
1588     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1589                                       UndefElts4, Depth+1);
1590     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1591
1592     APInt UndefElts3(LHSVWidth, 0);
1593     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1594                                       UndefElts3, Depth+1);
1595     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597     bool NewUndefElts = false;
1598     for (unsigned i = 0; i < VWidth; i++) {
1599       unsigned MaskVal = Shuffle->getMaskValue(i);
1600       if (MaskVal == -1u) {
1601         UndefElts.set(i);
1602       } else if (MaskVal < LHSVWidth) {
1603         if (UndefElts4[MaskVal]) {
1604           NewUndefElts = true;
1605           UndefElts.set(i);
1606         }
1607       } else {
1608         if (UndefElts3[MaskVal - LHSVWidth]) {
1609           NewUndefElts = true;
1610           UndefElts.set(i);
1611         }
1612       }
1613     }
1614
1615     if (NewUndefElts) {
1616       // Add additional discovered undefs.
1617       std::vector<Constant*> Elts;
1618       for (unsigned i = 0; i < VWidth; ++i) {
1619         if (UndefElts[i])
1620           Elts.push_back(UndefValue::get(Type::Int32Ty));
1621         else
1622           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1623                                           Shuffle->getMaskValue(i)));
1624       }
1625       I->setOperand(2, ConstantVector::get(Elts));
1626       MadeChange = true;
1627     }
1628     break;
1629   }
1630   case Instruction::BitCast: {
1631     // Vector->vector casts only.
1632     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1633     if (!VTy) break;
1634     unsigned InVWidth = VTy->getNumElements();
1635     APInt InputDemandedElts(InVWidth, 0);
1636     unsigned Ratio;
1637
1638     if (VWidth == InVWidth) {
1639       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1640       // elements as are demanded of us.
1641       Ratio = 1;
1642       InputDemandedElts = DemandedElts;
1643     } else if (VWidth > InVWidth) {
1644       // Untested so far.
1645       break;
1646       
1647       // If there are more elements in the result than there are in the source,
1648       // then an input element is live if any of the corresponding output
1649       // elements are live.
1650       Ratio = VWidth/InVWidth;
1651       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1652         if (DemandedElts[OutIdx])
1653           InputDemandedElts.set(OutIdx/Ratio);
1654       }
1655     } else {
1656       // Untested so far.
1657       break;
1658       
1659       // If there are more elements in the source than there are in the result,
1660       // then an input element is live if the corresponding output element is
1661       // live.
1662       Ratio = InVWidth/VWidth;
1663       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1664         if (DemandedElts[InIdx/Ratio])
1665           InputDemandedElts.set(InIdx);
1666     }
1667     
1668     // div/rem demand all inputs, because they don't want divide by zero.
1669     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1670                                       UndefElts2, Depth+1);
1671     if (TmpV) {
1672       I->setOperand(0, TmpV);
1673       MadeChange = true;
1674     }
1675     
1676     UndefElts = UndefElts2;
1677     if (VWidth > InVWidth) {
1678       assert(0 && "Unimp");
1679       // If there are more elements in the result than there are in the source,
1680       // then an output element is undef if the corresponding input element is
1681       // undef.
1682       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1683         if (UndefElts2[OutIdx/Ratio])
1684           UndefElts.set(OutIdx);
1685     } else if (VWidth < InVWidth) {
1686       assert(0 && "Unimp");
1687       // If there are more elements in the source than there are in the result,
1688       // then a result element is undef if all of the corresponding input
1689       // elements are undef.
1690       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1691       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1692         if (!UndefElts2[InIdx])            // Not undef?
1693           UndefElts.clear(InIdx/Ratio);    // Clear undef bit.
1694     }
1695     break;
1696   }
1697   case Instruction::And:
1698   case Instruction::Or:
1699   case Instruction::Xor:
1700   case Instruction::Add:
1701   case Instruction::Sub:
1702   case Instruction::Mul:
1703     // div/rem demand all inputs, because they don't want divide by zero.
1704     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1705                                       UndefElts, Depth+1);
1706     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1707     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1708                                       UndefElts2, Depth+1);
1709     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1710       
1711     // Output elements are undefined if both are undefined.  Consider things
1712     // like undef&0.  The result is known zero, not undef.
1713     UndefElts &= UndefElts2;
1714     break;
1715     
1716   case Instruction::Call: {
1717     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1718     if (!II) break;
1719     switch (II->getIntrinsicID()) {
1720     default: break;
1721       
1722     // Binary vector operations that work column-wise.  A dest element is a
1723     // function of the corresponding input elements from the two inputs.
1724     case Intrinsic::x86_sse_sub_ss:
1725     case Intrinsic::x86_sse_mul_ss:
1726     case Intrinsic::x86_sse_min_ss:
1727     case Intrinsic::x86_sse_max_ss:
1728     case Intrinsic::x86_sse2_sub_sd:
1729     case Intrinsic::x86_sse2_mul_sd:
1730     case Intrinsic::x86_sse2_min_sd:
1731     case Intrinsic::x86_sse2_max_sd:
1732       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1733                                         UndefElts, Depth+1);
1734       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1735       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1736                                         UndefElts2, Depth+1);
1737       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1738
1739       // If only the low elt is demanded and this is a scalarizable intrinsic,
1740       // scalarize it now.
1741       if (DemandedElts == 1) {
1742         switch (II->getIntrinsicID()) {
1743         default: break;
1744         case Intrinsic::x86_sse_sub_ss:
1745         case Intrinsic::x86_sse_mul_ss:
1746         case Intrinsic::x86_sse2_sub_sd:
1747         case Intrinsic::x86_sse2_mul_sd:
1748           // TODO: Lower MIN/MAX/ABS/etc
1749           Value *LHS = II->getOperand(1);
1750           Value *RHS = II->getOperand(2);
1751           // Extract the element as scalars.
1752           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1753           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1754           
1755           switch (II->getIntrinsicID()) {
1756           default: assert(0 && "Case stmts out of sync!");
1757           case Intrinsic::x86_sse_sub_ss:
1758           case Intrinsic::x86_sse2_sub_sd:
1759             TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1760                                                         II->getName()), *II);
1761             break;
1762           case Intrinsic::x86_sse_mul_ss:
1763           case Intrinsic::x86_sse2_mul_sd:
1764             TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1765                                                          II->getName()), *II);
1766             break;
1767           }
1768           
1769           Instruction *New =
1770             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1771                                       II->getName());
1772           InsertNewInstBefore(New, *II);
1773           AddSoonDeadInstToWorklist(*II, 0);
1774           return New;
1775         }            
1776       }
1777         
1778       // Output elements are undefined if both are undefined.  Consider things
1779       // like undef&0.  The result is known zero, not undef.
1780       UndefElts &= UndefElts2;
1781       break;
1782     }
1783     break;
1784   }
1785   }
1786   return MadeChange ? I : 0;
1787 }
1788
1789
1790 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1791 /// function is designed to check a chain of associative operators for a
1792 /// potential to apply a certain optimization.  Since the optimization may be
1793 /// applicable if the expression was reassociated, this checks the chain, then
1794 /// reassociates the expression as necessary to expose the optimization
1795 /// opportunity.  This makes use of a special Functor, which must define
1796 /// 'shouldApply' and 'apply' methods.
1797 ///
1798 template<typename Functor>
1799 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1800   unsigned Opcode = Root.getOpcode();
1801   Value *LHS = Root.getOperand(0);
1802
1803   // Quick check, see if the immediate LHS matches...
1804   if (F.shouldApply(LHS))
1805     return F.apply(Root);
1806
1807   // Otherwise, if the LHS is not of the same opcode as the root, return.
1808   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1809   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1810     // Should we apply this transform to the RHS?
1811     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1812
1813     // If not to the RHS, check to see if we should apply to the LHS...
1814     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1815       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1816       ShouldApply = true;
1817     }
1818
1819     // If the functor wants to apply the optimization to the RHS of LHSI,
1820     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1821     if (ShouldApply) {
1822       // Now all of the instructions are in the current basic block, go ahead
1823       // and perform the reassociation.
1824       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1825
1826       // First move the selected RHS to the LHS of the root...
1827       Root.setOperand(0, LHSI->getOperand(1));
1828
1829       // Make what used to be the LHS of the root be the user of the root...
1830       Value *ExtraOperand = TmpLHSI->getOperand(1);
1831       if (&Root == TmpLHSI) {
1832         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1833         return 0;
1834       }
1835       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1836       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1837       BasicBlock::iterator ARI = &Root; ++ARI;
1838       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1839       ARI = Root;
1840
1841       // Now propagate the ExtraOperand down the chain of instructions until we
1842       // get to LHSI.
1843       while (TmpLHSI != LHSI) {
1844         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1845         // Move the instruction to immediately before the chain we are
1846         // constructing to avoid breaking dominance properties.
1847         NextLHSI->moveBefore(ARI);
1848         ARI = NextLHSI;
1849
1850         Value *NextOp = NextLHSI->getOperand(1);
1851         NextLHSI->setOperand(1, ExtraOperand);
1852         TmpLHSI = NextLHSI;
1853         ExtraOperand = NextOp;
1854       }
1855
1856       // Now that the instructions are reassociated, have the functor perform
1857       // the transformation...
1858       return F.apply(Root);
1859     }
1860
1861     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1862   }
1863   return 0;
1864 }
1865
1866 namespace {
1867
1868 // AddRHS - Implements: X + X --> X << 1
1869 struct AddRHS {
1870   Value *RHS;
1871   AddRHS(Value *rhs) : RHS(rhs) {}
1872   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1873   Instruction *apply(BinaryOperator &Add) const {
1874     return BinaryOperator::CreateShl(Add.getOperand(0),
1875                                      ConstantInt::get(Add.getType(), 1));
1876   }
1877 };
1878
1879 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1880 //                 iff C1&C2 == 0
1881 struct AddMaskingAnd {
1882   Constant *C2;
1883   AddMaskingAnd(Constant *c) : C2(c) {}
1884   bool shouldApply(Value *LHS) const {
1885     ConstantInt *C1;
1886     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1887            ConstantExpr::getAnd(C1, C2)->isNullValue();
1888   }
1889   Instruction *apply(BinaryOperator &Add) const {
1890     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1891   }
1892 };
1893
1894 }
1895
1896 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1897                                              InstCombiner *IC) {
1898   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1899     return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1900   }
1901
1902   // Figure out if the constant is the left or the right argument.
1903   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1904   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1905
1906   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1907     if (ConstIsRHS)
1908       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1909     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1910   }
1911
1912   Value *Op0 = SO, *Op1 = ConstOperand;
1913   if (!ConstIsRHS)
1914     std::swap(Op0, Op1);
1915   Instruction *New;
1916   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1917     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1918   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1919     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1920                           SO->getName()+".cmp");
1921   else {
1922     assert(0 && "Unknown binary instruction type!");
1923     abort();
1924   }
1925   return IC->InsertNewInstBefore(New, I);
1926 }
1927
1928 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1929 // constant as the other operand, try to fold the binary operator into the
1930 // select arguments.  This also works for Cast instructions, which obviously do
1931 // not have a second operand.
1932 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1933                                      InstCombiner *IC) {
1934   // Don't modify shared select instructions
1935   if (!SI->hasOneUse()) return 0;
1936   Value *TV = SI->getOperand(1);
1937   Value *FV = SI->getOperand(2);
1938
1939   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1940     // Bool selects with constant operands can be folded to logical ops.
1941     if (SI->getType() == Type::Int1Ty) return 0;
1942
1943     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1944     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1945
1946     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1947                               SelectFalseVal);
1948   }
1949   return 0;
1950 }
1951
1952
1953 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1954 /// node as operand #0, see if we can fold the instruction into the PHI (which
1955 /// is only possible if all operands to the PHI are constants).
1956 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1957   PHINode *PN = cast<PHINode>(I.getOperand(0));
1958   unsigned NumPHIValues = PN->getNumIncomingValues();
1959   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1960
1961   // Check to see if all of the operands of the PHI are constants.  If there is
1962   // one non-constant value, remember the BB it is.  If there is more than one
1963   // or if *it* is a PHI, bail out.
1964   BasicBlock *NonConstBB = 0;
1965   for (unsigned i = 0; i != NumPHIValues; ++i)
1966     if (!isa<Constant>(PN->getIncomingValue(i))) {
1967       if (NonConstBB) return 0;  // More than one non-const value.
1968       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1969       NonConstBB = PN->getIncomingBlock(i);
1970       
1971       // If the incoming non-constant value is in I's block, we have an infinite
1972       // loop.
1973       if (NonConstBB == I.getParent())
1974         return 0;
1975     }
1976   
1977   // If there is exactly one non-constant value, we can insert a copy of the
1978   // operation in that block.  However, if this is a critical edge, we would be
1979   // inserting the computation one some other paths (e.g. inside a loop).  Only
1980   // do this if the pred block is unconditionally branching into the phi block.
1981   if (NonConstBB) {
1982     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1983     if (!BI || !BI->isUnconditional()) return 0;
1984   }
1985
1986   // Okay, we can do the transformation: create the new PHI node.
1987   PHINode *NewPN = PHINode::Create(I.getType(), "");
1988   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1989   InsertNewInstBefore(NewPN, *PN);
1990   NewPN->takeName(PN);
1991
1992   // Next, add all of the operands to the PHI.
1993   if (I.getNumOperands() == 2) {
1994     Constant *C = cast<Constant>(I.getOperand(1));
1995     for (unsigned i = 0; i != NumPHIValues; ++i) {
1996       Value *InV = 0;
1997       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1998         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1999           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2000         else
2001           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2002       } else {
2003         assert(PN->getIncomingBlock(i) == NonConstBB);
2004         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2005           InV = BinaryOperator::Create(BO->getOpcode(),
2006                                        PN->getIncomingValue(i), C, "phitmp",
2007                                        NonConstBB->getTerminator());
2008         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2009           InV = CmpInst::Create(CI->getOpcode(), 
2010                                 CI->getPredicate(),
2011                                 PN->getIncomingValue(i), C, "phitmp",
2012                                 NonConstBB->getTerminator());
2013         else
2014           assert(0 && "Unknown binop!");
2015         
2016         AddToWorkList(cast<Instruction>(InV));
2017       }
2018       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2019     }
2020   } else { 
2021     CastInst *CI = cast<CastInst>(&I);
2022     const Type *RetTy = CI->getType();
2023     for (unsigned i = 0; i != NumPHIValues; ++i) {
2024       Value *InV;
2025       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2026         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2027       } else {
2028         assert(PN->getIncomingBlock(i) == NonConstBB);
2029         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2030                                I.getType(), "phitmp", 
2031                                NonConstBB->getTerminator());
2032         AddToWorkList(cast<Instruction>(InV));
2033       }
2034       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2035     }
2036   }
2037   return ReplaceInstUsesWith(I, NewPN);
2038 }
2039
2040
2041 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2042 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2043 /// This basically requires proving that the add in the original type would not
2044 /// overflow to change the sign bit or have a carry out.
2045 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2046   // There are different heuristics we can use for this.  Here are some simple
2047   // ones.
2048   
2049   // Add has the property that adding any two 2's complement numbers can only 
2050   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2051   // have at least two sign bits, we know that the addition of the two values will
2052   // sign extend fine.
2053   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2054     return true;
2055   
2056   
2057   // If one of the operands only has one non-zero bit, and if the other operand
2058   // has a known-zero bit in a more significant place than it (not including the
2059   // sign bit) the ripple may go up to and fill the zero, but won't change the
2060   // sign.  For example, (X & ~4) + 1.
2061   
2062   // TODO: Implement.
2063   
2064   return false;
2065 }
2066
2067
2068 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2069   bool Changed = SimplifyCommutative(I);
2070   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2071
2072   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2073     // X + undef -> undef
2074     if (isa<UndefValue>(RHS))
2075       return ReplaceInstUsesWith(I, RHS);
2076
2077     // X + 0 --> X
2078     if (RHSC->isNullValue())
2079       return ReplaceInstUsesWith(I, LHS);
2080
2081     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2082       // X + (signbit) --> X ^ signbit
2083       const APInt& Val = CI->getValue();
2084       uint32_t BitWidth = Val.getBitWidth();
2085       if (Val == APInt::getSignBit(BitWidth))
2086         return BinaryOperator::CreateXor(LHS, RHS);
2087       
2088       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2089       // (X & 254)+1 -> (X&254)|1
2090       if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
2091         return &I;
2092
2093       // zext(i1) - 1  ->  select i1, 0, -1
2094       if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2095         if (CI->isAllOnesValue() &&
2096             ZI->getOperand(0)->getType() == Type::Int1Ty)
2097           return SelectInst::Create(ZI->getOperand(0),
2098                                     Constant::getNullValue(I.getType()),
2099                                     ConstantInt::getAllOnesValue(I.getType()));
2100     }
2101
2102     if (isa<PHINode>(LHS))
2103       if (Instruction *NV = FoldOpIntoPhi(I))
2104         return NV;
2105     
2106     ConstantInt *XorRHS = 0;
2107     Value *XorLHS = 0;
2108     if (isa<ConstantInt>(RHSC) &&
2109         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2110       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2111       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2112       
2113       uint32_t Size = TySizeBits / 2;
2114       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2115       APInt CFF80Val(-C0080Val);
2116       do {
2117         if (TySizeBits > Size) {
2118           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2119           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2120           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2121               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2122             // This is a sign extend if the top bits are known zero.
2123             if (!MaskedValueIsZero(XorLHS, 
2124                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2125               Size = 0;  // Not a sign ext, but can't be any others either.
2126             break;
2127           }
2128         }
2129         Size >>= 1;
2130         C0080Val = APIntOps::lshr(C0080Val, Size);
2131         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2132       } while (Size >= 1);
2133       
2134       // FIXME: This shouldn't be necessary. When the backends can handle types
2135       // with funny bit widths then this switch statement should be removed. It
2136       // is just here to get the size of the "middle" type back up to something
2137       // that the back ends can handle.
2138       const Type *MiddleType = 0;
2139       switch (Size) {
2140         default: break;
2141         case 32: MiddleType = Type::Int32Ty; break;
2142         case 16: MiddleType = Type::Int16Ty; break;
2143         case  8: MiddleType = Type::Int8Ty; break;
2144       }
2145       if (MiddleType) {
2146         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2147         InsertNewInstBefore(NewTrunc, I);
2148         return new SExtInst(NewTrunc, I.getType(), I.getName());
2149       }
2150     }
2151   }
2152
2153   if (I.getType() == Type::Int1Ty)
2154     return BinaryOperator::CreateXor(LHS, RHS);
2155
2156   // X + X --> X << 1
2157   if (I.getType()->isInteger()) {
2158     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2159
2160     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2161       if (RHSI->getOpcode() == Instruction::Sub)
2162         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2163           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2164     }
2165     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2166       if (LHSI->getOpcode() == Instruction::Sub)
2167         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2168           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2169     }
2170   }
2171
2172   // -A + B  -->  B - A
2173   // -A + -B  -->  -(A + B)
2174   if (Value *LHSV = dyn_castNegVal(LHS)) {
2175     if (LHS->getType()->isIntOrIntVector()) {
2176       if (Value *RHSV = dyn_castNegVal(RHS)) {
2177         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2178         InsertNewInstBefore(NewAdd, I);
2179         return BinaryOperator::CreateNeg(NewAdd);
2180       }
2181     }
2182     
2183     return BinaryOperator::CreateSub(RHS, LHSV);
2184   }
2185
2186   // A + -B  -->  A - B
2187   if (!isa<Constant>(RHS))
2188     if (Value *V = dyn_castNegVal(RHS))
2189       return BinaryOperator::CreateSub(LHS, V);
2190
2191
2192   ConstantInt *C2;
2193   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2194     if (X == RHS)   // X*C + X --> X * (C+1)
2195       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2196
2197     // X*C1 + X*C2 --> X * (C1+C2)
2198     ConstantInt *C1;
2199     if (X == dyn_castFoldableMul(RHS, C1))
2200       return BinaryOperator::CreateMul(X, Add(C1, C2));
2201   }
2202
2203   // X + X*C --> X * (C+1)
2204   if (dyn_castFoldableMul(RHS, C2) == LHS)
2205     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2206
2207   // X + ~X --> -1   since   ~X = -X-1
2208   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2209     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2210   
2211
2212   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2213   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2214     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2215       return R;
2216   
2217   // A+B --> A|B iff A and B have no bits set in common.
2218   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2219     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2220     APInt LHSKnownOne(IT->getBitWidth(), 0);
2221     APInt LHSKnownZero(IT->getBitWidth(), 0);
2222     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2223     if (LHSKnownZero != 0) {
2224       APInt RHSKnownOne(IT->getBitWidth(), 0);
2225       APInt RHSKnownZero(IT->getBitWidth(), 0);
2226       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2227       
2228       // No bits in common -> bitwise or.
2229       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2230         return BinaryOperator::CreateOr(LHS, RHS);
2231     }
2232   }
2233
2234   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2235   if (I.getType()->isIntOrIntVector()) {
2236     Value *W, *X, *Y, *Z;
2237     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2238         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2239       if (W != Y) {
2240         if (W == Z) {
2241           std::swap(Y, Z);
2242         } else if (Y == X) {
2243           std::swap(W, X);
2244         } else if (X == Z) {
2245           std::swap(Y, Z);
2246           std::swap(W, X);
2247         }
2248       }
2249
2250       if (W == Y) {
2251         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2252                                                             LHS->getName()), I);
2253         return BinaryOperator::CreateMul(W, NewAdd);
2254       }
2255     }
2256   }
2257
2258   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2259     Value *X = 0;
2260     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2261       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2262
2263     // (X & FF00) + xx00  -> (X+xx00) & FF00
2264     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2265       Constant *Anded = And(CRHS, C2);
2266       if (Anded == CRHS) {
2267         // See if all bits from the first bit set in the Add RHS up are included
2268         // in the mask.  First, get the rightmost bit.
2269         const APInt& AddRHSV = CRHS->getValue();
2270
2271         // Form a mask of all bits from the lowest bit added through the top.
2272         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2273
2274         // See if the and mask includes all of these bits.
2275         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2276
2277         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2278           // Okay, the xform is safe.  Insert the new add pronto.
2279           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2280                                                             LHS->getName()), I);
2281           return BinaryOperator::CreateAnd(NewAdd, C2);
2282         }
2283       }
2284     }
2285
2286     // Try to fold constant add into select arguments.
2287     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2288       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2289         return R;
2290   }
2291
2292   // add (cast *A to intptrtype) B -> 
2293   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2294   {
2295     CastInst *CI = dyn_cast<CastInst>(LHS);
2296     Value *Other = RHS;
2297     if (!CI) {
2298       CI = dyn_cast<CastInst>(RHS);
2299       Other = LHS;
2300     }
2301     if (CI && CI->getType()->isSized() && 
2302         (CI->getType()->getPrimitiveSizeInBits() == 
2303          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2304         && isa<PointerType>(CI->getOperand(0)->getType())) {
2305       unsigned AS =
2306         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2307       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2308                                       PointerType::get(Type::Int8Ty, AS), I);
2309       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2310       return new PtrToIntInst(I2, CI->getType());
2311     }
2312   }
2313   
2314   // add (select X 0 (sub n A)) A  -->  select X A n
2315   {
2316     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2317     Value *A = RHS;
2318     if (!SI) {
2319       SI = dyn_cast<SelectInst>(RHS);
2320       A = LHS;
2321     }
2322     if (SI && SI->hasOneUse()) {
2323       Value *TV = SI->getTrueValue();
2324       Value *FV = SI->getFalseValue();
2325       Value *N;
2326
2327       // Can we fold the add into the argument of the select?
2328       // We check both true and false select arguments for a matching subtract.
2329       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2330         // Fold the add into the true select value.
2331         return SelectInst::Create(SI->getCondition(), N, A);
2332       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2333         // Fold the add into the false select value.
2334         return SelectInst::Create(SI->getCondition(), A, N);
2335     }
2336   }
2337
2338   // Check for (add (sext x), y), see if we can merge this into an
2339   // integer add followed by a sext.
2340   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2341     // (add (sext x), cst) --> (sext (add x, cst'))
2342     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2343       Constant *CI = 
2344         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2345       if (LHSConv->hasOneUse() &&
2346           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2347           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2348         // Insert the new, smaller add.
2349         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2350                                                         CI, "addconv");
2351         InsertNewInstBefore(NewAdd, I);
2352         return new SExtInst(NewAdd, I.getType());
2353       }
2354     }
2355     
2356     // (add (sext x), (sext y)) --> (sext (add int x, y))
2357     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2358       // Only do this if x/y have the same type, if at last one of them has a
2359       // single use (so we don't increase the number of sexts), and if the
2360       // integer add will not overflow.
2361       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2362           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2363           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2364                                    RHSConv->getOperand(0))) {
2365         // Insert the new integer add.
2366         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2367                                                         RHSConv->getOperand(0),
2368                                                         "addconv");
2369         InsertNewInstBefore(NewAdd, I);
2370         return new SExtInst(NewAdd, I.getType());
2371       }
2372     }
2373   }
2374
2375   return Changed ? &I : 0;
2376 }
2377
2378 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2379   bool Changed = SimplifyCommutative(I);
2380   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2381
2382   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2383     // X + 0 --> X
2384     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2385       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2386                               (I.getType())->getValueAPF()))
2387         return ReplaceInstUsesWith(I, LHS);
2388     }
2389
2390     if (isa<PHINode>(LHS))
2391       if (Instruction *NV = FoldOpIntoPhi(I))
2392         return NV;
2393   }
2394
2395   // -A + B  -->  B - A
2396   // -A + -B  -->  -(A + B)
2397   if (Value *LHSV = dyn_castFNegVal(LHS))
2398     return BinaryOperator::CreateFSub(RHS, LHSV);
2399
2400   // A + -B  -->  A - B
2401   if (!isa<Constant>(RHS))
2402     if (Value *V = dyn_castFNegVal(RHS))
2403       return BinaryOperator::CreateFSub(LHS, V);
2404
2405   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2406   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2407     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2408       return ReplaceInstUsesWith(I, LHS);
2409
2410   // Check for (add double (sitofp x), y), see if we can merge this into an
2411   // integer add followed by a promotion.
2412   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2413     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2414     // ... if the constant fits in the integer value.  This is useful for things
2415     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2416     // requires a constant pool load, and generally allows the add to be better
2417     // instcombined.
2418     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2419       Constant *CI = 
2420       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2421       if (LHSConv->hasOneUse() &&
2422           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2423           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2424         // Insert the new integer add.
2425         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2426                                                         CI, "addconv");
2427         InsertNewInstBefore(NewAdd, I);
2428         return new SIToFPInst(NewAdd, I.getType());
2429       }
2430     }
2431     
2432     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2433     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2434       // Only do this if x/y have the same type, if at last one of them has a
2435       // single use (so we don't increase the number of int->fp conversions),
2436       // and if the integer add will not overflow.
2437       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2438           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2439           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2440                                    RHSConv->getOperand(0))) {
2441         // Insert the new integer add.
2442         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2443                                                         RHSConv->getOperand(0),
2444                                                         "addconv");
2445         InsertNewInstBefore(NewAdd, I);
2446         return new SIToFPInst(NewAdd, I.getType());
2447       }
2448     }
2449   }
2450   
2451   return Changed ? &I : 0;
2452 }
2453
2454 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2455   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2456
2457   if (Op0 == Op1)                        // sub X, X  -> 0
2458     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2459
2460   // If this is a 'B = x-(-A)', change to B = x+A...
2461   if (Value *V = dyn_castNegVal(Op1))
2462     return BinaryOperator::CreateAdd(Op0, V);
2463
2464   if (isa<UndefValue>(Op0))
2465     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2466   if (isa<UndefValue>(Op1))
2467     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2468
2469   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2470     // Replace (-1 - A) with (~A)...
2471     if (C->isAllOnesValue())
2472       return BinaryOperator::CreateNot(Op1);
2473
2474     // C - ~X == X + (1+C)
2475     Value *X = 0;
2476     if (match(Op1, m_Not(m_Value(X))))
2477       return BinaryOperator::CreateAdd(X, AddOne(C));
2478
2479     // -(X >>u 31) -> (X >>s 31)
2480     // -(X >>s 31) -> (X >>u 31)
2481     if (C->isZero()) {
2482       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2483         if (SI->getOpcode() == Instruction::LShr) {
2484           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2485             // Check to see if we are shifting out everything but the sign bit.
2486             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2487                 SI->getType()->getPrimitiveSizeInBits()-1) {
2488               // Ok, the transformation is safe.  Insert AShr.
2489               return BinaryOperator::Create(Instruction::AShr, 
2490                                           SI->getOperand(0), CU, SI->getName());
2491             }
2492           }
2493         }
2494         else if (SI->getOpcode() == Instruction::AShr) {
2495           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2496             // Check to see if we are shifting out everything but the sign bit.
2497             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2498                 SI->getType()->getPrimitiveSizeInBits()-1) {
2499               // Ok, the transformation is safe.  Insert LShr. 
2500               return BinaryOperator::CreateLShr(
2501                                           SI->getOperand(0), CU, SI->getName());
2502             }
2503           }
2504         }
2505       }
2506     }
2507
2508     // Try to fold constant sub into select arguments.
2509     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2510       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2511         return R;
2512   }
2513
2514   if (I.getType() == Type::Int1Ty)
2515     return BinaryOperator::CreateXor(Op0, Op1);
2516
2517   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2518     if (Op1I->getOpcode() == Instruction::Add) {
2519       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2520         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2521       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2522         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2523       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2524         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2525           // C1-(X+C2) --> (C1-C2)-X
2526           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2527                                            Op1I->getOperand(0));
2528       }
2529     }
2530
2531     if (Op1I->hasOneUse()) {
2532       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2533       // is not used by anyone else...
2534       //
2535       if (Op1I->getOpcode() == Instruction::Sub) {
2536         // Swap the two operands of the subexpr...
2537         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2538         Op1I->setOperand(0, IIOp1);
2539         Op1I->setOperand(1, IIOp0);
2540
2541         // Create the new top level add instruction...
2542         return BinaryOperator::CreateAdd(Op0, Op1);
2543       }
2544
2545       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2546       //
2547       if (Op1I->getOpcode() == Instruction::And &&
2548           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2549         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2550
2551         Value *NewNot =
2552           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2553         return BinaryOperator::CreateAnd(Op0, NewNot);
2554       }
2555
2556       // 0 - (X sdiv C)  -> (X sdiv -C)
2557       if (Op1I->getOpcode() == Instruction::SDiv)
2558         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2559           if (CSI->isZero())
2560             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2561               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2562                                                ConstantExpr::getNeg(DivRHS));
2563
2564       // X - X*C --> X * (1-C)
2565       ConstantInt *C2 = 0;
2566       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2567         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2568         return BinaryOperator::CreateMul(Op0, CP1);
2569       }
2570     }
2571   }
2572
2573   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2574     if (Op0I->getOpcode() == Instruction::Add) {
2575       if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2576         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2577       else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2578         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2579     } else if (Op0I->getOpcode() == Instruction::Sub) {
2580       if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2581         return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2582     }
2583   }
2584
2585   ConstantInt *C1;
2586   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2587     if (X == Op1)  // X*C - X --> X * (C-1)
2588       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2589
2590     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2591     if (X == dyn_castFoldableMul(Op1, C2))
2592       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2593   }
2594   return 0;
2595 }
2596
2597 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2598   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2599
2600   // If this is a 'B = x-(-A)', change to B = x+A...
2601   if (Value *V = dyn_castFNegVal(Op1))
2602     return BinaryOperator::CreateFAdd(Op0, V);
2603
2604   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2605     if (Op1I->getOpcode() == Instruction::FAdd) {
2606       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2607         return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2608       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2609         return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2610     }
2611
2612     if (Op1I->hasOneUse()) {
2613       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2614       // is not used by anyone else...
2615       //
2616       if (Op1I->getOpcode() == Instruction::FSub) {
2617         // Swap the two operands of the subexpr...
2618         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2619         Op1I->setOperand(0, IIOp1);
2620         Op1I->setOperand(1, IIOp0);
2621
2622         // Create the new top level fadd instruction...
2623         return BinaryOperator::CreateFAdd(Op0, Op1);
2624       }
2625     }
2626   }
2627
2628   return 0;
2629 }
2630
2631 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2632 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2633 /// TrueIfSigned if the result of the comparison is true when the input value is
2634 /// signed.
2635 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2636                            bool &TrueIfSigned) {
2637   switch (pred) {
2638   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2639     TrueIfSigned = true;
2640     return RHS->isZero();
2641   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2642     TrueIfSigned = true;
2643     return RHS->isAllOnesValue();
2644   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2645     TrueIfSigned = false;
2646     return RHS->isAllOnesValue();
2647   case ICmpInst::ICMP_UGT:
2648     // True if LHS u> RHS and RHS == high-bit-mask - 1
2649     TrueIfSigned = true;
2650     return RHS->getValue() ==
2651       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2652   case ICmpInst::ICMP_UGE: 
2653     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2654     TrueIfSigned = true;
2655     return RHS->getValue().isSignBit();
2656   default:
2657     return false;
2658   }
2659 }
2660
2661 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2662   bool Changed = SimplifyCommutative(I);
2663   Value *Op0 = I.getOperand(0);
2664
2665   // TODO: If Op1 is undef and Op0 is finite, return zero.
2666   if (!I.getType()->isFPOrFPVector() &&
2667       isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2668     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2669
2670   // Simplify mul instructions with a constant RHS...
2671   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2672     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2673
2674       // ((X << C1)*C2) == (X * (C2 << C1))
2675       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2676         if (SI->getOpcode() == Instruction::Shl)
2677           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2678             return BinaryOperator::CreateMul(SI->getOperand(0),
2679                                              ConstantExpr::getShl(CI, ShOp));
2680
2681       if (CI->isZero())
2682         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2683       if (CI->equalsInt(1))                  // X * 1  == X
2684         return ReplaceInstUsesWith(I, Op0);
2685       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2686         return BinaryOperator::CreateNeg(Op0, I.getName());
2687
2688       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2689       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2690         return BinaryOperator::CreateShl(Op0,
2691                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2692       }
2693     } else if (isa<VectorType>(Op1->getType())) {
2694       // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2695
2696       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2697         if (Op1V->isAllOnesValue())              // X * -1 == 0 - X
2698           return BinaryOperator::CreateNeg(Op0, I.getName());
2699
2700         // As above, vector X*splat(1.0) -> X in all defined cases.
2701         if (Constant *Splat = Op1V->getSplatValue()) {
2702           if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2703             if (CI->equalsInt(1))
2704               return ReplaceInstUsesWith(I, Op0);
2705         }
2706       }
2707     }
2708     
2709     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2710       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2711           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2712         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2713         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2714                                                      Op1, "tmp");
2715         InsertNewInstBefore(Add, I);
2716         Value *C1C2 = ConstantExpr::getMul(Op1, 
2717                                            cast<Constant>(Op0I->getOperand(1)));
2718         return BinaryOperator::CreateAdd(Add, C1C2);
2719         
2720       }
2721
2722     // Try to fold constant mul into select arguments.
2723     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2724       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2725         return R;
2726
2727     if (isa<PHINode>(Op0))
2728       if (Instruction *NV = FoldOpIntoPhi(I))
2729         return NV;
2730   }
2731
2732   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2733     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2734       return BinaryOperator::CreateMul(Op0v, Op1v);
2735
2736   // (X / Y) *  Y = X - (X % Y)
2737   // (X / Y) * -Y = (X % Y) - X
2738   {
2739     Value *Op1 = I.getOperand(1);
2740     BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2741     if (!BO ||
2742         (BO->getOpcode() != Instruction::UDiv && 
2743          BO->getOpcode() != Instruction::SDiv)) {
2744       Op1 = Op0;
2745       BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2746     }
2747     Value *Neg = dyn_castNegVal(Op1);
2748     if (BO && BO->hasOneUse() &&
2749         (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2750         (BO->getOpcode() == Instruction::UDiv ||
2751          BO->getOpcode() == Instruction::SDiv)) {
2752       Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2753
2754       Instruction *Rem;
2755       if (BO->getOpcode() == Instruction::UDiv)
2756         Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2757       else
2758         Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2759
2760       InsertNewInstBefore(Rem, I);
2761       Rem->takeName(BO);
2762
2763       if (Op1BO == Op1)
2764         return BinaryOperator::CreateSub(Op0BO, Rem);
2765       else
2766         return BinaryOperator::CreateSub(Rem, Op0BO);
2767     }
2768   }
2769
2770   if (I.getType() == Type::Int1Ty)
2771     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2772
2773   // If one of the operands of the multiply is a cast from a boolean value, then
2774   // we know the bool is either zero or one, so this is a 'masking' multiply.
2775   // See if we can simplify things based on how the boolean was originally
2776   // formed.
2777   CastInst *BoolCast = 0;
2778   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2779     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2780       BoolCast = CI;
2781   if (!BoolCast)
2782     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2783       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2784         BoolCast = CI;
2785   if (BoolCast) {
2786     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2787       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2788       const Type *SCOpTy = SCIOp0->getType();
2789       bool TIS = false;
2790       
2791       // If the icmp is true iff the sign bit of X is set, then convert this
2792       // multiply into a shift/and combination.
2793       if (isa<ConstantInt>(SCIOp1) &&
2794           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2795           TIS) {
2796         // Shift the X value right to turn it into "all signbits".
2797         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2798                                           SCOpTy->getPrimitiveSizeInBits()-1);
2799         Value *V =
2800           InsertNewInstBefore(
2801             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2802                                             BoolCast->getOperand(0)->getName()+
2803                                             ".mask"), I);
2804
2805         // If the multiply type is not the same as the source type, sign extend
2806         // or truncate to the multiply type.
2807         if (I.getType() != V->getType()) {
2808           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2809           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2810           Instruction::CastOps opcode = 
2811             (SrcBits == DstBits ? Instruction::BitCast : 
2812              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2813           V = InsertCastBefore(opcode, V, I.getType(), I);
2814         }
2815
2816         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2817         return BinaryOperator::CreateAnd(V, OtherOp);
2818       }
2819     }
2820   }
2821
2822   return Changed ? &I : 0;
2823 }
2824
2825 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2826   bool Changed = SimplifyCommutative(I);
2827   Value *Op0 = I.getOperand(0);
2828
2829   // Simplify mul instructions with a constant RHS...
2830   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2831     if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2832       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2833       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2834       if (Op1F->isExactlyValue(1.0))
2835         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2836     } else if (isa<VectorType>(Op1->getType())) {
2837       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2838         // As above, vector X*splat(1.0) -> X in all defined cases.
2839         if (Constant *Splat = Op1V->getSplatValue()) {
2840           if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2841             if (F->isExactlyValue(1.0))
2842               return ReplaceInstUsesWith(I, Op0);
2843         }
2844       }
2845     }
2846
2847     // Try to fold constant mul into select arguments.
2848     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2849       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2850         return R;
2851
2852     if (isa<PHINode>(Op0))
2853       if (Instruction *NV = FoldOpIntoPhi(I))
2854         return NV;
2855   }
2856
2857   if (Value *Op0v = dyn_castFNegVal(Op0))     // -X * -Y = X*Y
2858     if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2859       return BinaryOperator::CreateFMul(Op0v, Op1v);
2860
2861   return Changed ? &I : 0;
2862 }
2863
2864 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2865 /// instruction.
2866 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2867   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2868   
2869   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2870   int NonNullOperand = -1;
2871   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2872     if (ST->isNullValue())
2873       NonNullOperand = 2;
2874   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2875   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2876     if (ST->isNullValue())
2877       NonNullOperand = 1;
2878   
2879   if (NonNullOperand == -1)
2880     return false;
2881   
2882   Value *SelectCond = SI->getOperand(0);
2883   
2884   // Change the div/rem to use 'Y' instead of the select.
2885   I.setOperand(1, SI->getOperand(NonNullOperand));
2886   
2887   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2888   // problem.  However, the select, or the condition of the select may have
2889   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2890   // propagate the known value for the select into other uses of it, and
2891   // propagate a known value of the condition into its other users.
2892   
2893   // If the select and condition only have a single use, don't bother with this,
2894   // early exit.
2895   if (SI->use_empty() && SelectCond->hasOneUse())
2896     return true;
2897   
2898   // Scan the current block backward, looking for other uses of SI.
2899   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2900   
2901   while (BBI != BBFront) {
2902     --BBI;
2903     // If we found a call to a function, we can't assume it will return, so
2904     // information from below it cannot be propagated above it.
2905     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2906       break;
2907     
2908     // Replace uses of the select or its condition with the known values.
2909     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2910          I != E; ++I) {
2911       if (*I == SI) {
2912         *I = SI->getOperand(NonNullOperand);
2913         AddToWorkList(BBI);
2914       } else if (*I == SelectCond) {
2915         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2916                                    ConstantInt::getFalse();
2917         AddToWorkList(BBI);
2918       }
2919     }
2920     
2921     // If we past the instruction, quit looking for it.
2922     if (&*BBI == SI)
2923       SI = 0;
2924     if (&*BBI == SelectCond)
2925       SelectCond = 0;
2926     
2927     // If we ran out of things to eliminate, break out of the loop.
2928     if (SelectCond == 0 && SI == 0)
2929       break;
2930     
2931   }
2932   return true;
2933 }
2934
2935
2936 /// This function implements the transforms on div instructions that work
2937 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2938 /// used by the visitors to those instructions.
2939 /// @brief Transforms common to all three div instructions
2940 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2941   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2942
2943   // undef / X -> 0        for integer.
2944   // undef / X -> undef    for FP (the undef could be a snan).
2945   if (isa<UndefValue>(Op0)) {
2946     if (Op0->getType()->isFPOrFPVector())
2947       return ReplaceInstUsesWith(I, Op0);
2948     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2949   }
2950
2951   // X / undef -> undef
2952   if (isa<UndefValue>(Op1))
2953     return ReplaceInstUsesWith(I, Op1);
2954
2955   return 0;
2956 }
2957
2958 /// This function implements the transforms common to both integer division
2959 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2960 /// division instructions.
2961 /// @brief Common integer divide transforms
2962 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2963   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
2965   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2966   if (Op0 == Op1) {
2967     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2968       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2969       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2970       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2971     }
2972
2973     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2974     return ReplaceInstUsesWith(I, CI);
2975   }
2976   
2977   if (Instruction *Common = commonDivTransforms(I))
2978     return Common;
2979   
2980   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2981   // This does not apply for fdiv.
2982   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2983     return &I;
2984
2985   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2986     // div X, 1 == X
2987     if (RHS->equalsInt(1))
2988       return ReplaceInstUsesWith(I, Op0);
2989
2990     // (X / C1) / C2  -> X / (C1*C2)
2991     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2992       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2993         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2994           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2995             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2996           else 
2997             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2998                                           Multiply(RHS, LHSRHS));
2999         }
3000
3001     if (!RHS->isZero()) { // avoid X udiv 0
3002       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3003         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3004           return R;
3005       if (isa<PHINode>(Op0))
3006         if (Instruction *NV = FoldOpIntoPhi(I))
3007           return NV;
3008     }
3009   }
3010
3011   // 0 / X == 0, we don't need to preserve faults!
3012   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3013     if (LHS->equalsInt(0))
3014       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3015
3016   // It can't be division by zero, hence it must be division by one.
3017   if (I.getType() == Type::Int1Ty)
3018     return ReplaceInstUsesWith(I, Op0);
3019
3020   if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3021     if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3022       // div X, 1 == X
3023       if (X->isOne())
3024         return ReplaceInstUsesWith(I, Op0);
3025   }
3026
3027   return 0;
3028 }
3029
3030 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3031   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3032
3033   // Handle the integer div common cases
3034   if (Instruction *Common = commonIDivTransforms(I))
3035     return Common;
3036
3037   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3038     // X udiv C^2 -> X >> C
3039     // Check to see if this is an unsigned division with an exact power of 2,
3040     // if so, convert to a right shift.
3041     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3042       return BinaryOperator::CreateLShr(Op0, 
3043                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3044
3045     // X udiv C, where C >= signbit
3046     if (C->getValue().isNegative()) {
3047       Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
3048                                       I);
3049       return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3050                                 ConstantInt::get(I.getType(), 1));
3051     }
3052   }
3053
3054   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3055   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3056     if (RHSI->getOpcode() == Instruction::Shl &&
3057         isa<ConstantInt>(RHSI->getOperand(0))) {
3058       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3059       if (C1.isPowerOf2()) {
3060         Value *N = RHSI->getOperand(1);
3061         const Type *NTy = N->getType();
3062         if (uint32_t C2 = C1.logBase2()) {
3063           Constant *C2V = ConstantInt::get(NTy, C2);
3064           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3065         }
3066         return BinaryOperator::CreateLShr(Op0, N);
3067       }
3068     }
3069   }
3070   
3071   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3072   // where C1&C2 are powers of two.
3073   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3074     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3075       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3076         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3077         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3078           // Compute the shift amounts
3079           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3080           // Construct the "on true" case of the select
3081           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3082           Instruction *TSI = BinaryOperator::CreateLShr(
3083                                                  Op0, TC, SI->getName()+".t");
3084           TSI = InsertNewInstBefore(TSI, I);
3085   
3086           // Construct the "on false" case of the select
3087           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3088           Instruction *FSI = BinaryOperator::CreateLShr(
3089                                                  Op0, FC, SI->getName()+".f");
3090           FSI = InsertNewInstBefore(FSI, I);
3091
3092           // construct the select instruction and return it.
3093           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3094         }
3095       }
3096   return 0;
3097 }
3098
3099 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3100   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3101
3102   // Handle the integer div common cases
3103   if (Instruction *Common = commonIDivTransforms(I))
3104     return Common;
3105
3106   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3107     // sdiv X, -1 == -X
3108     if (RHS->isAllOnesValue())
3109       return BinaryOperator::CreateNeg(Op0);
3110   }
3111
3112   // If the sign bits of both operands are zero (i.e. we can prove they are
3113   // unsigned inputs), turn this into a udiv.
3114   if (I.getType()->isInteger()) {
3115     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3116     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3117       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3118       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3119     }
3120   }      
3121   
3122   return 0;
3123 }
3124
3125 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3126   return commonDivTransforms(I);
3127 }
3128
3129 /// This function implements the transforms on rem instructions that work
3130 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3131 /// is used by the visitors to those instructions.
3132 /// @brief Transforms common to all three rem instructions
3133 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3134   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3135
3136   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3137     if (I.getType()->isFPOrFPVector())
3138       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3139     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3140   }
3141   if (isa<UndefValue>(Op1))
3142     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3143
3144   // Handle cases involving: rem X, (select Cond, Y, Z)
3145   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3146     return &I;
3147
3148   return 0;
3149 }
3150
3151 /// This function implements the transforms common to both integer remainder
3152 /// instructions (urem and srem). It is called by the visitors to those integer
3153 /// remainder instructions.
3154 /// @brief Common integer remainder transforms
3155 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3156   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3157
3158   if (Instruction *common = commonRemTransforms(I))
3159     return common;
3160
3161   // 0 % X == 0 for integer, we don't need to preserve faults!
3162   if (Constant *LHS = dyn_cast<Constant>(Op0))
3163     if (LHS->isNullValue())
3164       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3165
3166   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3167     // X % 0 == undef, we don't need to preserve faults!
3168     if (RHS->equalsInt(0))
3169       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3170     
3171     if (RHS->equalsInt(1))  // X % 1 == 0
3172       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3173
3174     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3175       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3176         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3177           return R;
3178       } else if (isa<PHINode>(Op0I)) {
3179         if (Instruction *NV = FoldOpIntoPhi(I))
3180           return NV;
3181       }
3182
3183       // See if we can fold away this rem instruction.
3184       if (SimplifyDemandedInstructionBits(I))
3185         return &I;
3186     }
3187   }
3188
3189   return 0;
3190 }
3191
3192 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3193   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3194
3195   if (Instruction *common = commonIRemTransforms(I))
3196     return common;
3197   
3198   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3199     // X urem C^2 -> X and C
3200     // Check to see if this is an unsigned remainder with an exact power of 2,
3201     // if so, convert to a bitwise and.
3202     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3203       if (C->getValue().isPowerOf2())
3204         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3205   }
3206
3207   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3208     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3209     if (RHSI->getOpcode() == Instruction::Shl &&
3210         isa<ConstantInt>(RHSI->getOperand(0))) {
3211       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3212         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3213         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3214                                                                    "tmp"), I);
3215         return BinaryOperator::CreateAnd(Op0, Add);
3216       }
3217     }
3218   }
3219
3220   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3221   // where C1&C2 are powers of two.
3222   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3223     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3224       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3225         // STO == 0 and SFO == 0 handled above.
3226         if ((STO->getValue().isPowerOf2()) && 
3227             (SFO->getValue().isPowerOf2())) {
3228           Value *TrueAnd = InsertNewInstBefore(
3229             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3230           Value *FalseAnd = InsertNewInstBefore(
3231             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3232           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3233         }
3234       }
3235   }
3236   
3237   return 0;
3238 }
3239
3240 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3241   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3242
3243   // Handle the integer rem common cases
3244   if (Instruction *common = commonIRemTransforms(I))
3245     return common;
3246   
3247   if (Value *RHSNeg = dyn_castNegVal(Op1))
3248     if (!isa<Constant>(RHSNeg) ||
3249         (isa<ConstantInt>(RHSNeg) &&
3250          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3251       // X % -Y -> X % Y
3252       AddUsesToWorkList(I);
3253       I.setOperand(1, RHSNeg);
3254       return &I;
3255     }
3256
3257   // If the sign bits of both operands are zero (i.e. we can prove they are
3258   // unsigned inputs), turn this into a urem.
3259   if (I.getType()->isInteger()) {
3260     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3261     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3262       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3263       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3264     }
3265   }
3266
3267   // If it's a constant vector, flip any negative values positive.
3268   if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3269     unsigned VWidth = RHSV->getNumOperands();
3270
3271     bool hasNegative = false;
3272     for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3273       if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3274         if (RHS->getValue().isNegative())
3275           hasNegative = true;
3276
3277     if (hasNegative) {
3278       std::vector<Constant *> Elts(VWidth);
3279       for (unsigned i = 0; i != VWidth; ++i) {
3280         if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3281           if (RHS->getValue().isNegative())
3282             Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3283           else
3284             Elts[i] = RHS;
3285         }
3286       }
3287
3288       Constant *NewRHSV = ConstantVector::get(Elts);
3289       if (NewRHSV != RHSV) {
3290         AddUsesToWorkList(I);
3291         I.setOperand(1, NewRHSV);
3292         return &I;
3293       }
3294     }
3295   }
3296
3297   return 0;
3298 }
3299
3300 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3301   return commonRemTransforms(I);
3302 }
3303
3304 // isOneBitSet - Return true if there is exactly one bit set in the specified
3305 // constant.
3306 static bool isOneBitSet(const ConstantInt *CI) {
3307   return CI->getValue().isPowerOf2();
3308 }
3309
3310 // isHighOnes - Return true if the constant is of the form 1+0+.
3311 // This is the same as lowones(~X).
3312 static bool isHighOnes(const ConstantInt *CI) {
3313   return (~CI->getValue() + 1).isPowerOf2();
3314 }
3315
3316 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3317 /// are carefully arranged to allow folding of expressions such as:
3318 ///
3319 ///      (A < B) | (A > B) --> (A != B)
3320 ///
3321 /// Note that this is only valid if the first and second predicates have the
3322 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3323 ///
3324 /// Three bits are used to represent the condition, as follows:
3325 ///   0  A > B
3326 ///   1  A == B
3327 ///   2  A < B
3328 ///
3329 /// <=>  Value  Definition
3330 /// 000     0   Always false
3331 /// 001     1   A >  B
3332 /// 010     2   A == B
3333 /// 011     3   A >= B
3334 /// 100     4   A <  B
3335 /// 101     5   A != B
3336 /// 110     6   A <= B
3337 /// 111     7   Always true
3338 ///  
3339 static unsigned getICmpCode(const ICmpInst *ICI) {
3340   switch (ICI->getPredicate()) {
3341     // False -> 0
3342   case ICmpInst::ICMP_UGT: return 1;  // 001
3343   case ICmpInst::ICMP_SGT: return 1;  // 001
3344   case ICmpInst::ICMP_EQ:  return 2;  // 010
3345   case ICmpInst::ICMP_UGE: return 3;  // 011
3346   case ICmpInst::ICMP_SGE: return 3;  // 011
3347   case ICmpInst::ICMP_ULT: return 4;  // 100
3348   case ICmpInst::ICMP_SLT: return 4;  // 100
3349   case ICmpInst::ICMP_NE:  return 5;  // 101
3350   case ICmpInst::ICMP_ULE: return 6;  // 110
3351   case ICmpInst::ICMP_SLE: return 6;  // 110
3352     // True -> 7
3353   default:
3354     assert(0 && "Invalid ICmp predicate!");
3355     return 0;
3356   }
3357 }
3358
3359 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3360 /// predicate into a three bit mask. It also returns whether it is an ordered
3361 /// predicate by reference.
3362 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3363   isOrdered = false;
3364   switch (CC) {
3365   case FCmpInst::FCMP_ORD: isOrdered = true; return 0;  // 000
3366   case FCmpInst::FCMP_UNO:                   return 0;  // 000
3367   case FCmpInst::FCMP_OGT: isOrdered = true; return 1;  // 001
3368   case FCmpInst::FCMP_UGT:                   return 1;  // 001
3369   case FCmpInst::FCMP_OEQ: isOrdered = true; return 2;  // 010
3370   case FCmpInst::FCMP_UEQ:                   return 2;  // 010
3371   case FCmpInst::FCMP_OGE: isOrdered = true; return 3;  // 011
3372   case FCmpInst::FCMP_UGE:                   return 3;  // 011
3373   case FCmpInst::FCMP_OLT: isOrdered = true; return 4;  // 100
3374   case FCmpInst::FCMP_ULT:                   return 4;  // 100
3375   case FCmpInst::FCMP_ONE: isOrdered = true; return 5;  // 101
3376   case FCmpInst::FCMP_UNE:                   return 5;  // 101
3377   case FCmpInst::FCMP_OLE: isOrdered = true; return 6;  // 110
3378   case FCmpInst::FCMP_ULE:                   return 6;  // 110
3379     // True -> 7
3380   default:
3381     // Not expecting FCMP_FALSE and FCMP_TRUE;
3382     assert(0 && "Unexpected FCmp predicate!");
3383     return 0;
3384   }
3385 }
3386
3387 /// getICmpValue - This is the complement of getICmpCode, which turns an
3388 /// opcode and two operands into either a constant true or false, or a brand 
3389 /// new ICmp instruction. The sign is passed in to determine which kind
3390 /// of predicate to use in the new icmp instruction.
3391 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3392   switch (code) {
3393   default: assert(0 && "Illegal ICmp code!");
3394   case  0: return ConstantInt::getFalse();
3395   case  1: 
3396     if (sign)
3397       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3398     else
3399       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3400   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3401   case  3: 
3402     if (sign)
3403       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3404     else
3405       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3406   case  4: 
3407     if (sign)
3408       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3409     else
3410       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3411   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3412   case  6: 
3413     if (sign)
3414       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3415     else
3416       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3417   case  7: return ConstantInt::getTrue();
3418   }
3419 }
3420
3421 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3422 /// opcode and two operands into either a FCmp instruction. isordered is passed
3423 /// in to determine which kind of predicate to use in the new fcmp instruction.
3424 static Value *getFCmpValue(bool isordered, unsigned code,
3425                            Value *LHS, Value *RHS) {
3426   switch (code) {
3427   default: assert(0 && "Illegal FCmp code!");
3428   case  0:
3429     if (isordered)
3430       return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3431     else
3432       return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3433   case  1: 
3434     if (isordered)
3435       return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3436     else
3437       return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3438   case  2: 
3439     if (isordered)
3440       return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3441     else
3442       return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3443   case  3: 
3444     if (isordered)
3445       return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3446     else
3447       return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3448   case  4: 
3449     if (isordered)
3450       return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3451     else
3452       return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3453   case  5: 
3454     if (isordered)
3455       return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3456     else
3457       return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3458   case  6: 
3459     if (isordered)
3460       return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3461     else
3462       return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3463   case  7: return ConstantInt::getTrue();
3464   }
3465 }
3466
3467 /// PredicatesFoldable - Return true if both predicates match sign or if at
3468 /// least one of them is an equality comparison (which is signless).
3469 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3470   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3471          (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3472          (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3473 }
3474
3475 namespace { 
3476 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3477 struct FoldICmpLogical {
3478   InstCombiner &IC;
3479   Value *LHS, *RHS;
3480   ICmpInst::Predicate pred;
3481   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3482     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3483       pred(ICI->getPredicate()) {}
3484   bool shouldApply(Value *V) const {
3485     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3486       if (PredicatesFoldable(pred, ICI->getPredicate()))
3487         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3488                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3489     return false;
3490   }
3491   Instruction *apply(Instruction &Log) const {
3492     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3493     if (ICI->getOperand(0) != LHS) {
3494       assert(ICI->getOperand(1) == LHS);
3495       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3496     }
3497
3498     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3499     unsigned LHSCode = getICmpCode(ICI);
3500     unsigned RHSCode = getICmpCode(RHSICI);
3501     unsigned Code;
3502     switch (Log.getOpcode()) {
3503     case Instruction::And: Code = LHSCode & RHSCode; break;
3504     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3505     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3506     default: assert(0 && "Illegal logical opcode!"); return 0;
3507     }
3508
3509     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3510                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3511       
3512     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3513     if (Instruction *I = dyn_cast<Instruction>(RV))
3514       return I;
3515     // Otherwise, it's a constant boolean value...
3516     return IC.ReplaceInstUsesWith(Log, RV);
3517   }
3518 };
3519 } // end anonymous namespace
3520
3521 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3522 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3523 // guaranteed to be a binary operator.
3524 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3525                                     ConstantInt *OpRHS,
3526                                     ConstantInt *AndRHS,
3527                                     BinaryOperator &TheAnd) {
3528   Value *X = Op->getOperand(0);
3529   Constant *Together = 0;
3530   if (!Op->isShift())
3531     Together = And(AndRHS, OpRHS);
3532
3533   switch (Op->getOpcode()) {
3534   case Instruction::Xor:
3535     if (Op->hasOneUse()) {
3536       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3537       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3538       InsertNewInstBefore(And, TheAnd);
3539       And->takeName(Op);
3540       return BinaryOperator::CreateXor(And, Together);
3541     }
3542     break;
3543   case Instruction::Or:
3544     if (Together == AndRHS) // (X | C) & C --> C
3545       return ReplaceInstUsesWith(TheAnd, AndRHS);
3546
3547     if (Op->hasOneUse() && Together != OpRHS) {
3548       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3549       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3550       InsertNewInstBefore(Or, TheAnd);
3551       Or->takeName(Op);
3552       return BinaryOperator::CreateAnd(Or, AndRHS);
3553     }
3554     break;
3555   case Instruction::Add:
3556     if (Op->hasOneUse()) {
3557       // Adding a one to a single bit bit-field should be turned into an XOR
3558       // of the bit.  First thing to check is to see if this AND is with a
3559       // single bit constant.
3560       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3561
3562       // If there is only one bit set...
3563       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3564         // Ok, at this point, we know that we are masking the result of the
3565         // ADD down to exactly one bit.  If the constant we are adding has
3566         // no bits set below this bit, then we can eliminate the ADD.
3567         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3568
3569         // Check to see if any bits below the one bit set in AndRHSV are set.
3570         if ((AddRHS & (AndRHSV-1)) == 0) {
3571           // If not, the only thing that can effect the output of the AND is
3572           // the bit specified by AndRHSV.  If that bit is set, the effect of
3573           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3574           // no effect.
3575           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3576             TheAnd.setOperand(0, X);
3577             return &TheAnd;
3578           } else {
3579             // Pull the XOR out of the AND.
3580             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3581             InsertNewInstBefore(NewAnd, TheAnd);
3582             NewAnd->takeName(Op);
3583             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3584           }
3585         }
3586       }
3587     }
3588     break;
3589
3590   case Instruction::Shl: {
3591     // We know that the AND will not produce any of the bits shifted in, so if
3592     // the anded constant includes them, clear them now!
3593     //
3594     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3595     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3596     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3597     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3598
3599     if (CI->getValue() == ShlMask) { 
3600     // Masking out bits that the shift already masks
3601       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3602     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3603       TheAnd.setOperand(1, CI);
3604       return &TheAnd;
3605     }
3606     break;
3607   }
3608   case Instruction::LShr:
3609   {
3610     // We know that the AND will not produce any of the bits shifted in, so if
3611     // the anded constant includes them, clear them now!  This only applies to
3612     // unsigned shifts, because a signed shr may bring in set bits!
3613     //
3614     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3615     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3616     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3617     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3618
3619     if (CI->getValue() == ShrMask) {   
3620     // Masking out bits that the shift already masks.
3621       return ReplaceInstUsesWith(TheAnd, Op);
3622     } else if (CI != AndRHS) {
3623       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3624       return &TheAnd;
3625     }
3626     break;
3627   }
3628   case Instruction::AShr:
3629     // Signed shr.
3630     // See if this is shifting in some sign extension, then masking it out
3631     // with an and.
3632     if (Op->hasOneUse()) {
3633       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3634       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3635       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3636       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3637       if (C == AndRHS) {          // Masking out bits shifted in.
3638         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3639         // Make the argument unsigned.
3640         Value *ShVal = Op->getOperand(0);
3641         ShVal = InsertNewInstBefore(
3642             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3643                                    Op->getName()), TheAnd);
3644         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3645       }
3646     }
3647     break;
3648   }
3649   return 0;
3650 }
3651
3652
3653 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3654 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3655 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3656 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3657 /// insert new instructions.
3658 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3659                                            bool isSigned, bool Inside, 
3660                                            Instruction &IB) {
3661   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3662             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3663          "Lo is not <= Hi in range emission code!");
3664     
3665   if (Inside) {
3666     if (Lo == Hi)  // Trivially false.
3667       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3668
3669     // V >= Min && V < Hi --> V < Hi
3670     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3671       ICmpInst::Predicate pred = (isSigned ? 
3672         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3673       return new ICmpInst(pred, V, Hi);
3674     }
3675
3676     // Emit V-Lo <u Hi-Lo
3677     Constant *NegLo = ConstantExpr::getNeg(Lo);
3678     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3679     InsertNewInstBefore(Add, IB);
3680     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3681     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3682   }
3683
3684   if (Lo == Hi)  // Trivially true.
3685     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3686
3687   // V < Min || V >= Hi -> V > Hi-1
3688   Hi = SubOne(cast<ConstantInt>(Hi));
3689   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3690     ICmpInst::Predicate pred = (isSigned ? 
3691         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3692     return new ICmpInst(pred, V, Hi);
3693   }
3694
3695   // Emit V-Lo >u Hi-1-Lo
3696   // Note that Hi has already had one subtracted from it, above.
3697   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3698   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3699   InsertNewInstBefore(Add, IB);
3700   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3701   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3702 }
3703
3704 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3705 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3706 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3707 // not, since all 1s are not contiguous.
3708 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3709   const APInt& V = Val->getValue();
3710   uint32_t BitWidth = Val->getType()->getBitWidth();
3711   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3712
3713   // look for the first zero bit after the run of ones
3714   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3715   // look for the first non-zero bit
3716   ME = V.getActiveBits(); 
3717   return true;
3718 }
3719
3720 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3721 /// where isSub determines whether the operator is a sub.  If we can fold one of
3722 /// the following xforms:
3723 /// 
3724 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3725 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3726 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3727 ///
3728 /// return (A +/- B).
3729 ///
3730 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3731                                         ConstantInt *Mask, bool isSub,
3732                                         Instruction &I) {
3733   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3734   if (!LHSI || LHSI->getNumOperands() != 2 ||
3735       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3736
3737   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3738
3739   switch (LHSI->getOpcode()) {
3740   default: return 0;
3741   case Instruction::And:
3742     if (And(N, Mask) == Mask) {
3743       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3744       if ((Mask->getValue().countLeadingZeros() + 
3745            Mask->getValue().countPopulation()) == 
3746           Mask->getValue().getBitWidth())
3747         break;
3748
3749       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3750       // part, we don't need any explicit masks to take them out of A.  If that
3751       // is all N is, ignore it.
3752       uint32_t MB = 0, ME = 0;
3753       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3754         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3755         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3756         if (MaskedValueIsZero(RHS, Mask))
3757           break;
3758       }
3759     }
3760     return 0;
3761   case Instruction::Or:
3762   case Instruction::Xor:
3763     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3764     if ((Mask->getValue().countLeadingZeros() + 
3765          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3766         && And(N, Mask)->isZero())
3767       break;
3768     return 0;
3769   }
3770   
3771   Instruction *New;
3772   if (isSub)
3773     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3774   else
3775     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3776   return InsertNewInstBefore(New, I);
3777 }
3778
3779 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3780 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3781                                           ICmpInst *LHS, ICmpInst *RHS) {
3782   Value *Val, *Val2;
3783   ConstantInt *LHSCst, *RHSCst;
3784   ICmpInst::Predicate LHSCC, RHSCC;
3785   
3786   // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3787   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3788       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3789     return 0;
3790   
3791   // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3792   // where C is a power of 2
3793   if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3794       LHSCst->getValue().isPowerOf2()) {
3795     Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3796     InsertNewInstBefore(NewOr, I);
3797     return new ICmpInst(LHSCC, NewOr, LHSCst);
3798   }
3799   
3800   // From here on, we only handle:
3801   //    (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3802   if (Val != Val2) return 0;
3803   
3804   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3805   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3806       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3807       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3808       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3809     return 0;
3810   
3811   // We can't fold (ugt x, C) & (sgt x, C2).
3812   if (!PredicatesFoldable(LHSCC, RHSCC))
3813     return 0;
3814     
3815   // Ensure that the larger constant is on the RHS.
3816   bool ShouldSwap;
3817   if (ICmpInst::isSignedPredicate(LHSCC) ||
3818       (ICmpInst::isEquality(LHSCC) && 
3819        ICmpInst::isSignedPredicate(RHSCC)))
3820     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3821   else
3822     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3823     
3824   if (ShouldSwap) {
3825     std::swap(LHS, RHS);
3826     std::swap(LHSCst, RHSCst);
3827     std::swap(LHSCC, RHSCC);
3828   }
3829
3830   // At this point, we know we have have two icmp instructions
3831   // comparing a value against two constants and and'ing the result
3832   // together.  Because of the above check, we know that we only have
3833   // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3834   // (from the FoldICmpLogical check above), that the two constants 
3835   // are not equal and that the larger constant is on the RHS
3836   assert(LHSCst != RHSCst && "Compares not folded above?");
3837
3838   switch (LHSCC) {
3839   default: assert(0 && "Unknown integer condition code!");
3840   case ICmpInst::ICMP_EQ:
3841     switch (RHSCC) {
3842     default: assert(0 && "Unknown integer condition code!");
3843     case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3844     case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3845     case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3846       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3847     case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3848     case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3849     case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3850       return ReplaceInstUsesWith(I, LHS);
3851     }
3852   case ICmpInst::ICMP_NE:
3853     switch (RHSCC) {
3854     default: assert(0 && "Unknown integer condition code!");
3855     case ICmpInst::ICMP_ULT:
3856       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3857         return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3858       break;                        // (X != 13 & X u< 15) -> no change
3859     case ICmpInst::ICMP_SLT:
3860       if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3861         return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3862       break;                        // (X != 13 & X s< 15) -> no change
3863     case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3864     case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3865     case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3866       return ReplaceInstUsesWith(I, RHS);
3867     case ICmpInst::ICMP_NE:
3868       if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3869         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3870         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3871                                                      Val->getName()+".off");
3872         InsertNewInstBefore(Add, I);
3873         return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3874                             ConstantInt::get(Add->getType(), 1));
3875       }
3876       break;                        // (X != 13 & X != 15) -> no change
3877     }
3878     break;
3879   case ICmpInst::ICMP_ULT:
3880     switch (RHSCC) {
3881     default: assert(0 && "Unknown integer condition code!");
3882     case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3883     case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3884       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3885     case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3886       break;
3887     case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3888     case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3889       return ReplaceInstUsesWith(I, LHS);
3890     case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3891       break;
3892     }
3893     break;
3894   case ICmpInst::ICMP_SLT:
3895     switch (RHSCC) {
3896     default: assert(0 && "Unknown integer condition code!");
3897     case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3898     case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3899       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3900     case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3901       break;
3902     case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3903     case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3904       return ReplaceInstUsesWith(I, LHS);
3905     case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3906       break;
3907     }
3908     break;
3909   case ICmpInst::ICMP_UGT:
3910     switch (RHSCC) {
3911     default: assert(0 && "Unknown integer condition code!");
3912     case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3913     case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3914       return ReplaceInstUsesWith(I, RHS);
3915     case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3916       break;
3917     case ICmpInst::ICMP_NE:
3918       if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3919         return new ICmpInst(LHSCC, Val, RHSCst);
3920       break;                        // (X u> 13 & X != 15) -> no change
3921     case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) -> (X-14) <u 1
3922       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3923     case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3924       break;
3925     }
3926     break;
3927   case ICmpInst::ICMP_SGT:
3928     switch (RHSCC) {
3929     default: assert(0 && "Unknown integer condition code!");
3930     case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3931     case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3932       return ReplaceInstUsesWith(I, RHS);
3933     case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3934       break;
3935     case ICmpInst::ICMP_NE:
3936       if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3937         return new ICmpInst(LHSCC, Val, RHSCst);
3938       break;                        // (X s> 13 & X != 15) -> no change
3939     case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) -> (X-14) s< 1
3940       return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3941     case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3942       break;
3943     }
3944     break;
3945   }
3946  
3947   return 0;
3948 }
3949
3950
3951 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3952   bool Changed = SimplifyCommutative(I);
3953   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3954
3955   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3956     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3957
3958   // and X, X = X
3959   if (Op0 == Op1)
3960     return ReplaceInstUsesWith(I, Op1);
3961
3962   // See if we can simplify any instructions used by the instruction whose sole 
3963   // purpose is to compute bits we don't care about.
3964   if (!isa<VectorType>(I.getType())) {
3965     if (SimplifyDemandedInstructionBits(I))
3966       return &I;
3967   } else {
3968     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3969       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3970         return ReplaceInstUsesWith(I, I.getOperand(0));
3971     } else if (isa<ConstantAggregateZero>(Op1)) {
3972       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3973     }
3974   }
3975   
3976   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3977     const APInt& AndRHSMask = AndRHS->getValue();
3978     APInt NotAndRHS(~AndRHSMask);
3979
3980     // Optimize a variety of ((val OP C1) & C2) combinations...
3981     if (isa<BinaryOperator>(Op0)) {
3982       Instruction *Op0I = cast<Instruction>(Op0);
3983       Value *Op0LHS = Op0I->getOperand(0);
3984       Value *Op0RHS = Op0I->getOperand(1);
3985       switch (Op0I->getOpcode()) {
3986       case Instruction::Xor:
3987       case Instruction::Or:
3988         // If the mask is only needed on one incoming arm, push it up.
3989         if (Op0I->hasOneUse()) {
3990           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3991             // Not masking anything out for the LHS, move to RHS.
3992             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3993                                                    Op0RHS->getName()+".masked");
3994             InsertNewInstBefore(NewRHS, I);
3995             return BinaryOperator::Create(
3996                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3997           }
3998           if (!isa<Constant>(Op0RHS) &&
3999               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4000             // Not masking anything out for the RHS, move to LHS.
4001             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4002                                                    Op0LHS->getName()+".masked");
4003             InsertNewInstBefore(NewLHS, I);
4004             return BinaryOperator::Create(
4005                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4006           }
4007         }
4008
4009         break;
4010       case Instruction::Add:
4011         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4012         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4013         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4014         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4015           return BinaryOperator::CreateAnd(V, AndRHS);
4016         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4017           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4018         break;
4019
4020       case Instruction::Sub:
4021         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4022         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4023         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4024         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4025           return BinaryOperator::CreateAnd(V, AndRHS);
4026
4027         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4028         // has 1's for all bits that the subtraction with A might affect.
4029         if (Op0I->hasOneUse()) {
4030           uint32_t BitWidth = AndRHSMask.getBitWidth();
4031           uint32_t Zeros = AndRHSMask.countLeadingZeros();
4032           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4033
4034           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4035           if (!(A && A->isZero()) &&               // avoid infinite recursion.
4036               MaskedValueIsZero(Op0LHS, Mask)) {
4037             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4038             InsertNewInstBefore(NewNeg, I);
4039             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4040           }
4041         }
4042         break;
4043
4044       case Instruction::Shl:
4045       case Instruction::LShr:
4046         // (1 << x) & 1 --> zext(x == 0)
4047         // (1 >> x) & 1 --> zext(x == 0)
4048         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4049           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
4050                                            Constant::getNullValue(I.getType()));
4051           InsertNewInstBefore(NewICmp, I);
4052           return new ZExtInst(NewICmp, I.getType());
4053         }
4054         break;
4055       }
4056
4057       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4058         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4059           return Res;
4060     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4061       // If this is an integer truncation or change from signed-to-unsigned, and
4062       // if the source is an and/or with immediate, transform it.  This
4063       // frequently occurs for bitfield accesses.
4064       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4065         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4066             CastOp->getNumOperands() == 2)
4067           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4068             if (CastOp->getOpcode() == Instruction::And) {
4069               // Change: and (cast (and X, C1) to T), C2
4070               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4071               // This will fold the two constants together, which may allow 
4072               // other simplifications.
4073               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4074                 CastOp->getOperand(0), I.getType(), 
4075                 CastOp->getName()+".shrunk");
4076               NewCast = InsertNewInstBefore(NewCast, I);
4077               // trunc_or_bitcast(C1)&C2
4078               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4079               C3 = ConstantExpr::getAnd(C3, AndRHS);
4080               return BinaryOperator::CreateAnd(NewCast, C3);
4081             } else if (CastOp->getOpcode() == Instruction::Or) {
4082               // Change: and (cast (or X, C1) to T), C2
4083               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4084               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4085               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4086                 return ReplaceInstUsesWith(I, AndRHS);
4087             }
4088           }
4089       }
4090     }
4091
4092     // Try to fold constant and into select arguments.
4093     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4094       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4095         return R;
4096     if (isa<PHINode>(Op0))
4097       if (Instruction *NV = FoldOpIntoPhi(I))
4098         return NV;
4099   }
4100
4101   Value *Op0NotVal = dyn_castNotVal(Op0);
4102   Value *Op1NotVal = dyn_castNotVal(Op1);
4103
4104   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4105     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4106
4107   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4108   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4109     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4110                                                I.getName()+".demorgan");
4111     InsertNewInstBefore(Or, I);
4112     return BinaryOperator::CreateNot(Or);
4113   }
4114   
4115   {
4116     Value *A = 0, *B = 0, *C = 0, *D = 0;
4117     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4118       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4119         return ReplaceInstUsesWith(I, Op1);
4120     
4121       // (A|B) & ~(A&B) -> A^B
4122       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4123         if ((A == C && B == D) || (A == D && B == C))
4124           return BinaryOperator::CreateXor(A, B);
4125       }
4126     }
4127     
4128     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4129       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4130         return ReplaceInstUsesWith(I, Op0);
4131
4132       // ~(A&B) & (A|B) -> A^B
4133       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4134         if ((A == C && B == D) || (A == D && B == C))
4135           return BinaryOperator::CreateXor(A, B);
4136       }
4137     }
4138     
4139     if (Op0->hasOneUse() &&
4140         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4141       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4142         I.swapOperands();     // Simplify below
4143         std::swap(Op0, Op1);
4144       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4145         cast<BinaryOperator>(Op0)->swapOperands();
4146         I.swapOperands();     // Simplify below
4147         std::swap(Op0, Op1);
4148       }
4149     }
4150
4151     if (Op1->hasOneUse() &&
4152         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4153       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4154         cast<BinaryOperator>(Op1)->swapOperands();
4155         std::swap(A, B);
4156       }
4157       if (A == Op0) {                                // A&(A^B) -> A & ~B
4158         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4159         InsertNewInstBefore(NotB, I);
4160         return BinaryOperator::CreateAnd(A, NotB);
4161       }
4162     }
4163
4164     // (A&((~A)|B)) -> A&B
4165     if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4166         match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4167       return BinaryOperator::CreateAnd(A, Op1);
4168     if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4169         match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4170       return BinaryOperator::CreateAnd(A, Op0);
4171   }
4172   
4173   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4174     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4175     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4176       return R;
4177
4178     if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4179       if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4180         return Res;
4181   }
4182
4183   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4184   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4185     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4186       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4187         const Type *SrcTy = Op0C->getOperand(0)->getType();
4188         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4189             // Only do this if the casts both really cause code to be generated.
4190             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4191                               I.getType(), TD) &&
4192             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4193                               I.getType(), TD)) {
4194           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4195                                                          Op1C->getOperand(0),
4196                                                          I.getName());
4197           InsertNewInstBefore(NewOp, I);
4198           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4199         }
4200       }
4201     
4202   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4203   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4204     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4205       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4206           SI0->getOperand(1) == SI1->getOperand(1) &&
4207           (SI0->hasOneUse() || SI1->hasOneUse())) {
4208         Instruction *NewOp =
4209           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4210                                                         SI1->getOperand(0),
4211                                                         SI0->getName()), I);
4212         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4213                                       SI1->getOperand(1));
4214       }
4215   }
4216
4217   // If and'ing two fcmp, try combine them into one.
4218   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4219     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4220       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4221           RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4222         // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4223         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4224           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4225             // If either of the constants are nans, then the whole thing returns
4226             // false.
4227             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4228               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4229             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4230                                 RHS->getOperand(0));
4231           }
4232       } else {
4233         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4234         FCmpInst::Predicate Op0CC, Op1CC;
4235         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4236             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4237           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4238             // Swap RHS operands to match LHS.
4239             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4240             std::swap(Op1LHS, Op1RHS);
4241           }
4242           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4243             // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4244             if (Op0CC == Op1CC)
4245               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4246             else if (Op0CC == FCmpInst::FCMP_FALSE ||
4247                      Op1CC == FCmpInst::FCMP_FALSE)
4248               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4249             else if (Op0CC == FCmpInst::FCMP_TRUE)
4250               return ReplaceInstUsesWith(I, Op1);
4251             else if (Op1CC == FCmpInst::FCMP_TRUE)
4252               return ReplaceInstUsesWith(I, Op0);
4253             bool Op0Ordered;
4254             bool Op1Ordered;
4255             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4256             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4257             if (Op1Pred == 0) {
4258               std::swap(Op0, Op1);
4259               std::swap(Op0Pred, Op1Pred);
4260               std::swap(Op0Ordered, Op1Ordered);
4261             }
4262             if (Op0Pred == 0) {
4263               // uno && ueq -> uno && (uno || eq) -> ueq
4264               // ord && olt -> ord && (ord && lt) -> olt
4265               if (Op0Ordered == Op1Ordered)
4266                 return ReplaceInstUsesWith(I, Op1);
4267               // uno && oeq -> uno && (ord && eq) -> false
4268               // uno && ord -> false
4269               if (!Op0Ordered)
4270                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4271               // ord && ueq -> ord && (uno || eq) -> oeq
4272               return cast<Instruction>(getFCmpValue(true, Op1Pred,
4273                                                     Op0LHS, Op0RHS));
4274             }
4275           }
4276         }
4277       }
4278     }
4279   }
4280
4281   return Changed ? &I : 0;
4282 }
4283
4284 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4285 /// capable of providing pieces of a bswap.  The subexpression provides pieces
4286 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4287 /// the expression came from the corresponding "byte swapped" byte in some other
4288 /// value.  For example, if the current subexpression is "(shl i32 %X, 24)" then
4289 /// we know that the expression deposits the low byte of %X into the high byte
4290 /// of the bswap result and that all other bytes are zero.  This expression is
4291 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4292 /// match.
4293 ///
4294 /// This function returns true if the match was unsuccessful and false if so.
4295 /// On entry to the function the "OverallLeftShift" is a signed integer value
4296 /// indicating the number of bytes that the subexpression is later shifted.  For
4297 /// example, if the expression is later right shifted by 16 bits, the
4298 /// OverallLeftShift value would be -2 on entry.  This is used to specify which
4299 /// byte of ByteValues is actually being set.
4300 ///
4301 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4302 /// byte is masked to zero by a user.  For example, in (X & 255), X will be
4303 /// processed with a bytemask of 1.  Because bytemask is 32-bits, this limits
4304 /// this function to working on up to 32-byte (256 bit) values.  ByteMask is
4305 /// always in the local (OverallLeftShift) coordinate space.
4306 ///
4307 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4308                               SmallVector<Value*, 8> &ByteValues) {
4309   if (Instruction *I = dyn_cast<Instruction>(V)) {
4310     // If this is an or instruction, it may be an inner node of the bswap.
4311     if (I->getOpcode() == Instruction::Or) {
4312       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4313                                ByteValues) ||
4314              CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4315                                ByteValues);
4316     }
4317   
4318     // If this is a logical shift by a constant multiple of 8, recurse with
4319     // OverallLeftShift and ByteMask adjusted.
4320     if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4321       unsigned ShAmt = 
4322         cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4323       // Ensure the shift amount is defined and of a byte value.
4324       if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4325         return true;
4326
4327       unsigned ByteShift = ShAmt >> 3;
4328       if (I->getOpcode() == Instruction::Shl) {
4329         // X << 2 -> collect(X, +2)
4330         OverallLeftShift += ByteShift;
4331         ByteMask >>= ByteShift;
4332       } else {
4333         // X >>u 2 -> collect(X, -2)
4334         OverallLeftShift -= ByteShift;
4335         ByteMask <<= ByteShift;
4336         ByteMask &= (~0U >> (32-ByteValues.size()));
4337       }
4338
4339       if (OverallLeftShift >= (int)ByteValues.size()) return true;
4340       if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4341
4342       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4343                                ByteValues);
4344     }
4345
4346     // If this is a logical 'and' with a mask that clears bytes, clear the
4347     // corresponding bytes in ByteMask.
4348     if (I->getOpcode() == Instruction::And &&
4349         isa<ConstantInt>(I->getOperand(1))) {
4350       // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4351       unsigned NumBytes = ByteValues.size();
4352       APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4353       const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4354       
4355       for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4356         // If this byte is masked out by a later operation, we don't care what
4357         // the and mask is.
4358         if ((ByteMask & (1 << i)) == 0)
4359           continue;
4360         
4361         // If the AndMask is all zeros for this byte, clear the bit.
4362         APInt MaskB = AndMask & Byte;
4363         if (MaskB == 0) {
4364           ByteMask &= ~(1U << i);
4365           continue;
4366         }
4367         
4368         // If the AndMask is not all ones for this byte, it's not a bytezap.
4369         if (MaskB != Byte)
4370           return true;
4371
4372         // Otherwise, this byte is kept.
4373       }
4374
4375       return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask, 
4376                                ByteValues);
4377     }
4378   }
4379   
4380   // Okay, we got to something that isn't a shift, 'or' or 'and'.  This must be
4381   // the input value to the bswap.  Some observations: 1) if more than one byte
4382   // is demanded from this input, then it could not be successfully assembled
4383   // into a byteswap.  At least one of the two bytes would not be aligned with
4384   // their ultimate destination.
4385   if (!isPowerOf2_32(ByteMask)) return true;
4386   unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4387   
4388   // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4389   // is demanded, it needs to go into byte 0 of the result.  This means that the
4390   // byte needs to be shifted until it lands in the right byte bucket.  The
4391   // shift amount depends on the position: if the byte is coming from the high
4392   // part of the value (e.g. byte 3) then it must be shifted right.  If from the
4393   // low part, it must be shifted left.
4394   unsigned DestByteNo = InputByteNo + OverallLeftShift;
4395   if (InputByteNo < ByteValues.size()/2) {
4396     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4397       return true;
4398   } else {
4399     if (ByteValues.size()-1-DestByteNo != InputByteNo)
4400       return true;
4401   }
4402   
4403   // If the destination byte value is already defined, the values are or'd
4404   // together, which isn't a bswap (unless it's an or of the same bits).
4405   if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4406     return true;
4407   ByteValues[DestByteNo] = V;
4408   return false;
4409 }
4410
4411 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4412 /// If so, insert the new bswap intrinsic and return it.
4413 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4414   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4415   if (!ITy || ITy->getBitWidth() % 16 || 
4416       // ByteMask only allows up to 32-byte values.
4417       ITy->getBitWidth() > 32*8) 
4418     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4419   
4420   /// ByteValues - For each byte of the result, we keep track of which value
4421   /// defines each byte.
4422   SmallVector<Value*, 8> ByteValues;
4423   ByteValues.resize(ITy->getBitWidth()/8);
4424     
4425   // Try to find all the pieces corresponding to the bswap.
4426   uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4427   if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4428     return 0;
4429   
4430   // Check to see if all of the bytes come from the same value.
4431   Value *V = ByteValues[0];
4432   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4433   
4434   // Check to make sure that all of the bytes come from the same value.
4435   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4436     if (ByteValues[i] != V)
4437       return 0;
4438   const Type *Tys[] = { ITy };
4439   Module *M = I.getParent()->getParent()->getParent();
4440   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4441   return CallInst::Create(F, V);
4442 }
4443
4444 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D).  Check
4445 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4446 /// we can simplify this expression to "cond ? C : D or B".
4447 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4448                                          Value *C, Value *D) {
4449   // If A is not a select of -1/0, this cannot match.
4450   Value *Cond = 0;
4451   if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4452     return 0;
4453
4454   // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4455   if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4456     return SelectInst::Create(Cond, C, B);
4457   if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4458     return SelectInst::Create(Cond, C, B);
4459   // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4460   if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4461     return SelectInst::Create(Cond, C, D);
4462   if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4463     return SelectInst::Create(Cond, C, D);
4464   return 0;
4465 }
4466
4467 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4468 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4469                                          ICmpInst *LHS, ICmpInst *RHS) {
4470   Value *Val, *Val2;
4471   ConstantInt *LHSCst, *RHSCst;
4472   ICmpInst::Predicate LHSCC, RHSCC;
4473   
4474   // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4475   if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4476       !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4477     return 0;
4478   
4479   // From here on, we only handle:
4480   //    (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4481   if (Val != Val2) return 0;
4482   
4483   // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4484   if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4485       RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4486       LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4487       RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4488     return 0;
4489   
4490   // We can't fold (ugt x, C) | (sgt x, C2).
4491   if (!PredicatesFoldable(LHSCC, RHSCC))
4492     return 0;
4493   
4494   // Ensure that the larger constant is on the RHS.
4495   bool ShouldSwap;
4496   if (ICmpInst::isSignedPredicate(LHSCC) ||
4497       (ICmpInst::isEquality(LHSCC) && 
4498        ICmpInst::isSignedPredicate(RHSCC)))
4499     ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4500   else
4501     ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4502   
4503   if (ShouldSwap) {
4504     std::swap(LHS, RHS);
4505     std::swap(LHSCst, RHSCst);
4506     std::swap(LHSCC, RHSCC);
4507   }
4508   
4509   // At this point, we know we have have two icmp instructions
4510   // comparing a value against two constants and or'ing the result
4511   // together.  Because of the above check, we know that we only have
4512   // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4513   // FoldICmpLogical check above), that the two constants are not
4514   // equal.
4515   assert(LHSCst != RHSCst && "Compares not folded above?");
4516
4517   switch (LHSCC) {
4518   default: assert(0 && "Unknown integer condition code!");
4519   case ICmpInst::ICMP_EQ:
4520     switch (RHSCC) {
4521     default: assert(0 && "Unknown integer condition code!");
4522     case ICmpInst::ICMP_EQ:
4523       if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4524         Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4525         Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4526                                                      Val->getName()+".off");
4527         InsertNewInstBefore(Add, I);
4528         AddCST = Subtract(AddOne(RHSCst), LHSCst);
4529         return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4530       }
4531       break;                         // (X == 13 | X == 15) -> no change
4532     case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4533     case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4534       break;
4535     case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4536     case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4537     case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4538       return ReplaceInstUsesWith(I, RHS);
4539     }
4540     break;
4541   case ICmpInst::ICMP_NE:
4542     switch (RHSCC) {
4543     default: assert(0 && "Unknown integer condition code!");
4544     case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4545     case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4546     case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4547       return ReplaceInstUsesWith(I, LHS);
4548     case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4549     case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4550     case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4551       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4552     }
4553     break;
4554   case ICmpInst::ICMP_ULT:
4555     switch (RHSCC) {
4556     default: assert(0 && "Unknown integer condition code!");
4557     case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4558       break;
4559     case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) -> (X-13) u> 2
4560       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4561       // this can cause overflow.
4562       if (RHSCst->isMaxValue(false))
4563         return ReplaceInstUsesWith(I, LHS);
4564       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4565     case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4566       break;
4567     case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4568     case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4569       return ReplaceInstUsesWith(I, RHS);
4570     case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4571       break;
4572     }
4573     break;
4574   case ICmpInst::ICMP_SLT:
4575     switch (RHSCC) {
4576     default: assert(0 && "Unknown integer condition code!");
4577     case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4578       break;
4579     case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) -> (X-13) s> 2
4580       // If RHSCst is [us]MAXINT, it is always false.  Not handling
4581       // this can cause overflow.
4582       if (RHSCst->isMaxValue(true))
4583         return ReplaceInstUsesWith(I, LHS);
4584       return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4585     case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4586       break;
4587     case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4588     case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4589       return ReplaceInstUsesWith(I, RHS);
4590     case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4591       break;
4592     }
4593     break;
4594   case ICmpInst::ICMP_UGT:
4595     switch (RHSCC) {
4596     default: assert(0 && "Unknown integer condition code!");
4597     case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4598     case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4599       return ReplaceInstUsesWith(I, LHS);
4600     case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4601       break;
4602     case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4603     case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4604       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4605     case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4606       break;
4607     }
4608     break;
4609   case ICmpInst::ICMP_SGT:
4610     switch (RHSCC) {
4611     default: assert(0 && "Unknown integer condition code!");
4612     case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4613     case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4614       return ReplaceInstUsesWith(I, LHS);
4615     case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4616       break;
4617     case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4618     case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4619       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4620     case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4621       break;
4622     }
4623     break;
4624   }
4625   return 0;
4626 }
4627
4628 /// FoldOrWithConstants - This helper function folds:
4629 ///
4630 ///     ((A | B) & C1) | (B & C2)
4631 ///
4632 /// into:
4633 /// 
4634 ///     (A & C1) | B
4635 ///
4636 /// when the XOR of the two constants is "all ones" (-1).
4637 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4638                                                Value *A, Value *B, Value *C) {
4639   ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4640   if (!CI1) return 0;
4641
4642   Value *V1 = 0;
4643   ConstantInt *CI2 = 0;
4644   if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4645
4646   APInt Xor = CI1->getValue() ^ CI2->getValue();
4647   if (!Xor.isAllOnesValue()) return 0;
4648
4649   if (V1 == A || V1 == B) {
4650     Instruction *NewOp =
4651       InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4652     return BinaryOperator::CreateOr(NewOp, V1);
4653   }
4654
4655   return 0;
4656 }
4657
4658 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4659   bool Changed = SimplifyCommutative(I);
4660   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4661
4662   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4663     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4664
4665   // or X, X = X
4666   if (Op0 == Op1)
4667     return ReplaceInstUsesWith(I, Op0);
4668
4669   // See if we can simplify any instructions used by the instruction whose sole 
4670   // purpose is to compute bits we don't care about.
4671   if (!isa<VectorType>(I.getType())) {
4672     if (SimplifyDemandedInstructionBits(I))
4673       return &I;
4674   } else if (isa<ConstantAggregateZero>(Op1)) {
4675     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4676   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4677     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4678       return ReplaceInstUsesWith(I, I.getOperand(1));
4679   }
4680     
4681
4682   
4683   // or X, -1 == -1
4684   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4685     ConstantInt *C1 = 0; Value *X = 0;
4686     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4687     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4688       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4689       InsertNewInstBefore(Or, I);
4690       Or->takeName(Op0);
4691       return BinaryOperator::CreateAnd(Or, 
4692                ConstantInt::get(RHS->getValue() | C1->getValue()));
4693     }
4694
4695     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4696     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4697       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4698       InsertNewInstBefore(Or, I);
4699       Or->takeName(Op0);
4700       return BinaryOperator::CreateXor(Or,
4701                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4702     }
4703
4704     // Try to fold constant and into select arguments.
4705     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4706       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4707         return R;
4708     if (isa<PHINode>(Op0))
4709       if (Instruction *NV = FoldOpIntoPhi(I))
4710         return NV;
4711   }
4712
4713   Value *A = 0, *B = 0;
4714   ConstantInt *C1 = 0, *C2 = 0;
4715
4716   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4717     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4718       return ReplaceInstUsesWith(I, Op1);
4719   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4720     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4721       return ReplaceInstUsesWith(I, Op0);
4722
4723   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4724   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4725   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4726       match(Op1, m_Or(m_Value(), m_Value())) ||
4727       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4728        match(Op1, m_Shift(m_Value(), m_Value())))) {
4729     if (Instruction *BSwap = MatchBSwap(I))
4730       return BSwap;
4731   }
4732   
4733   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4734   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4735       MaskedValueIsZero(Op1, C1->getValue())) {
4736     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4737     InsertNewInstBefore(NOr, I);
4738     NOr->takeName(Op0);
4739     return BinaryOperator::CreateXor(NOr, C1);
4740   }
4741
4742   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4743   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4744       MaskedValueIsZero(Op0, C1->getValue())) {
4745     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4746     InsertNewInstBefore(NOr, I);
4747     NOr->takeName(Op0);
4748     return BinaryOperator::CreateXor(NOr, C1);
4749   }
4750
4751   // (A & C)|(B & D)
4752   Value *C = 0, *D = 0;
4753   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4754       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4755     Value *V1 = 0, *V2 = 0, *V3 = 0;
4756     C1 = dyn_cast<ConstantInt>(C);
4757     C2 = dyn_cast<ConstantInt>(D);
4758     if (C1 && C2) {  // (A & C1)|(B & C2)
4759       // If we have: ((V + N) & C1) | (V & C2)
4760       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4761       // replace with V+N.
4762       if (C1->getValue() == ~C2->getValue()) {
4763         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4764             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4765           // Add commutes, try both ways.
4766           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4767             return ReplaceInstUsesWith(I, A);
4768           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4769             return ReplaceInstUsesWith(I, A);
4770         }
4771         // Or commutes, try both ways.
4772         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4773             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4774           // Add commutes, try both ways.
4775           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4776             return ReplaceInstUsesWith(I, B);
4777           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4778             return ReplaceInstUsesWith(I, B);
4779         }
4780       }
4781       V1 = 0; V2 = 0; V3 = 0;
4782     }
4783     
4784     // Check to see if we have any common things being and'ed.  If so, find the
4785     // terms for V1 & (V2|V3).
4786     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4787       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4788         V1 = A, V2 = C, V3 = D;
4789       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4790         V1 = A, V2 = B, V3 = C;
4791       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4792         V1 = C, V2 = A, V3 = D;
4793       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4794         V1 = C, V2 = A, V3 = B;
4795       
4796       if (V1) {
4797         Value *Or =
4798           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4799         return BinaryOperator::CreateAnd(V1, Or);
4800       }
4801     }
4802
4803     // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) ->  C0 ? A : B, and commuted variants
4804     if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4805       return Match;
4806     if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4807       return Match;
4808     if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4809       return Match;
4810     if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4811       return Match;
4812
4813     // ((A&~B)|(~A&B)) -> A^B
4814     if ((match(C, m_Not(m_Specific(D))) &&
4815          match(B, m_Not(m_Specific(A)))))
4816       return BinaryOperator::CreateXor(A, D);
4817     // ((~B&A)|(~A&B)) -> A^B
4818     if ((match(A, m_Not(m_Specific(D))) &&
4819          match(B, m_Not(m_Specific(C)))))
4820       return BinaryOperator::CreateXor(C, D);
4821     // ((A&~B)|(B&~A)) -> A^B
4822     if ((match(C, m_Not(m_Specific(B))) &&
4823          match(D, m_Not(m_Specific(A)))))
4824       return BinaryOperator::CreateXor(A, B);
4825     // ((~B&A)|(B&~A)) -> A^B
4826     if ((match(A, m_Not(m_Specific(B))) &&
4827          match(D, m_Not(m_Specific(C)))))
4828       return BinaryOperator::CreateXor(C, B);
4829   }
4830   
4831   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4832   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4833     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4834       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4835           SI0->getOperand(1) == SI1->getOperand(1) &&
4836           (SI0->hasOneUse() || SI1->hasOneUse())) {
4837         Instruction *NewOp =
4838         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4839                                                      SI1->getOperand(0),
4840                                                      SI0->getName()), I);
4841         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4842                                       SI1->getOperand(1));
4843       }
4844   }
4845
4846   // ((A|B)&1)|(B&-2) -> (A&1) | B
4847   if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4848       match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4849     Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4850     if (Ret) return Ret;
4851   }
4852   // (B&-2)|((A|B)&1) -> (A&1) | B
4853   if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4854       match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4855     Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4856     if (Ret) return Ret;
4857   }
4858
4859   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4860     if (A == Op1)   // ~A | A == -1
4861       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4862   } else {
4863     A = 0;
4864   }
4865   // Note, A is still live here!
4866   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4867     if (Op0 == B)
4868       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4869
4870     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4871     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4872       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4873                                               I.getName()+".demorgan"), I);
4874       return BinaryOperator::CreateNot(And);
4875     }
4876   }
4877
4878   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4879   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4880     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4881       return R;
4882
4883     if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4884       if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4885         return Res;
4886   }
4887     
4888   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4889   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4890     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4891       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4892         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4893             !isa<ICmpInst>(Op1C->getOperand(0))) {
4894           const Type *SrcTy = Op0C->getOperand(0)->getType();
4895           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4896               // Only do this if the casts both really cause code to be
4897               // generated.
4898               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4899                                 I.getType(), TD) &&
4900               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4901                                 I.getType(), TD)) {
4902             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4903                                                           Op1C->getOperand(0),
4904                                                           I.getName());
4905             InsertNewInstBefore(NewOp, I);
4906             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4907           }
4908         }
4909       }
4910   }
4911   
4912     
4913   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4914   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4915     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4916       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4917           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4918           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4919         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4920           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4921             // If either of the constants are nans, then the whole thing returns
4922             // true.
4923             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4924               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4925             
4926             // Otherwise, no need to compare the two constants, compare the
4927             // rest.
4928             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4929                                 RHS->getOperand(0));
4930           }
4931       } else {
4932         Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4933         FCmpInst::Predicate Op0CC, Op1CC;
4934         if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4935             match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4936           if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4937             // Swap RHS operands to match LHS.
4938             Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4939             std::swap(Op1LHS, Op1RHS);
4940           }
4941           if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4942             // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4943             if (Op0CC == Op1CC)
4944               return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4945             else if (Op0CC == FCmpInst::FCMP_TRUE ||
4946                      Op1CC == FCmpInst::FCMP_TRUE)
4947               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4948             else if (Op0CC == FCmpInst::FCMP_FALSE)
4949               return ReplaceInstUsesWith(I, Op1);
4950             else if (Op1CC == FCmpInst::FCMP_FALSE)
4951               return ReplaceInstUsesWith(I, Op0);
4952             bool Op0Ordered;
4953             bool Op1Ordered;
4954             unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4955             unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4956             if (Op0Ordered == Op1Ordered) {
4957               // If both are ordered or unordered, return a new fcmp with
4958               // or'ed predicates.
4959               Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4960                                        Op0LHS, Op0RHS);
4961               if (Instruction *I = dyn_cast<Instruction>(RV))
4962                 return I;
4963               // Otherwise, it's a constant boolean value...
4964               return ReplaceInstUsesWith(I, RV);
4965             }
4966           }
4967         }
4968       }
4969     }
4970   }
4971
4972   return Changed ? &I : 0;
4973 }
4974
4975 namespace {
4976
4977 // XorSelf - Implements: X ^ X --> 0
4978 struct XorSelf {
4979   Value *RHS;
4980   XorSelf(Value *rhs) : RHS(rhs) {}
4981   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4982   Instruction *apply(BinaryOperator &Xor) const {
4983     return &Xor;
4984   }
4985 };
4986
4987 }
4988
4989 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4990   bool Changed = SimplifyCommutative(I);
4991   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4992
4993   if (isa<UndefValue>(Op1)) {
4994     if (isa<UndefValue>(Op0))
4995       // Handle undef ^ undef -> 0 special case. This is a common
4996       // idiom (misuse).
4997       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4998     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4999   }
5000
5001   // xor X, X = 0, even if X is nested in a sequence of Xor's.
5002   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5003     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5004     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5005   }
5006   
5007   // See if we can simplify any instructions used by the instruction whose sole 
5008   // purpose is to compute bits we don't care about.
5009   if (!isa<VectorType>(I.getType())) {
5010     if (SimplifyDemandedInstructionBits(I))
5011       return &I;
5012   } else if (isa<ConstantAggregateZero>(Op1)) {
5013     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
5014   }
5015
5016   // Is this a ~ operation?
5017   if (Value *NotOp = dyn_castNotVal(&I)) {
5018     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5019     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5020     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5021       if (Op0I->getOpcode() == Instruction::And || 
5022           Op0I->getOpcode() == Instruction::Or) {
5023         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5024         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5025           Instruction *NotY =
5026             BinaryOperator::CreateNot(Op0I->getOperand(1),
5027                                       Op0I->getOperand(1)->getName()+".not");
5028           InsertNewInstBefore(NotY, I);
5029           if (Op0I->getOpcode() == Instruction::And)
5030             return BinaryOperator::CreateOr(Op0NotVal, NotY);
5031           else
5032             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5033         }
5034       }
5035     }
5036   }
5037   
5038   
5039   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5040     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5041       // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5042       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5043         return new ICmpInst(ICI->getInversePredicate(),
5044                             ICI->getOperand(0), ICI->getOperand(1));
5045
5046       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5047         return new FCmpInst(FCI->getInversePredicate(),
5048                             FCI->getOperand(0), FCI->getOperand(1));
5049     }
5050
5051     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5052     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5053       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5054         if (CI->hasOneUse() && Op0C->hasOneUse()) {
5055           Instruction::CastOps Opcode = Op0C->getOpcode();
5056           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5057             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
5058                                              Op0C->getDestTy())) {
5059               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5060                                      CI->getOpcode(), CI->getInversePredicate(),
5061                                      CI->getOperand(0), CI->getOperand(1)), I);
5062               NewCI->takeName(CI);
5063               return CastInst::Create(Opcode, NewCI, Op0C->getType());
5064             }
5065           }
5066         }
5067       }
5068     }
5069
5070     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5071       // ~(c-X) == X-c-1 == X+(-c-1)
5072       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5073         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5074           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5075           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5076                                               ConstantInt::get(I.getType(), 1));
5077           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5078         }
5079           
5080       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5081         if (Op0I->getOpcode() == Instruction::Add) {
5082           // ~(X-c) --> (-c-1)-X
5083           if (RHS->isAllOnesValue()) {
5084             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5085             return BinaryOperator::CreateSub(
5086                            ConstantExpr::getSub(NegOp0CI,
5087                                              ConstantInt::get(I.getType(), 1)),
5088                                           Op0I->getOperand(0));
5089           } else if (RHS->getValue().isSignBit()) {
5090             // (X + C) ^ signbit -> (X + C + signbit)
5091             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5092             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5093
5094           }
5095         } else if (Op0I->getOpcode() == Instruction::Or) {
5096           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5097           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5098             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5099             // Anything in both C1 and C2 is known to be zero, remove it from
5100             // NewRHS.
5101             Constant *CommonBits = And(Op0CI, RHS);
5102             NewRHS = ConstantExpr::getAnd(NewRHS, 
5103                                           ConstantExpr::getNot(CommonBits));
5104             AddToWorkList(Op0I);
5105             I.setOperand(0, Op0I->getOperand(0));
5106             I.setOperand(1, NewRHS);
5107             return &I;
5108           }
5109         }
5110       }
5111     }
5112
5113     // Try to fold constant and into select arguments.
5114     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5115       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5116         return R;
5117     if (isa<PHINode>(Op0))
5118       if (Instruction *NV = FoldOpIntoPhi(I))
5119         return NV;
5120   }
5121
5122   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5123     if (X == Op1)
5124       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5125
5126   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5127     if (X == Op0)
5128       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5129
5130   
5131   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5132   if (Op1I) {
5133     Value *A, *B;
5134     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5135       if (A == Op0) {              // B^(B|A) == (A|B)^B
5136         Op1I->swapOperands();
5137         I.swapOperands();
5138         std::swap(Op0, Op1);
5139       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5140         I.swapOperands();     // Simplified below.
5141         std::swap(Op0, Op1);
5142       }
5143     } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5144       return ReplaceInstUsesWith(I, B);                      // A^(A^B) == B
5145     } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5146       return ReplaceInstUsesWith(I, A);                      // A^(B^A) == B
5147     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5148       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5149         Op1I->swapOperands();
5150         std::swap(A, B);
5151       }
5152       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5153         I.swapOperands();     // Simplified below.
5154         std::swap(Op0, Op1);
5155       }
5156     }
5157   }
5158   
5159   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5160   if (Op0I) {
5161     Value *A, *B;
5162     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5163       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5164         std::swap(A, B);
5165       if (B == Op1) {                                // (A|B)^B == A & ~B
5166         Instruction *NotB =
5167           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5168         return BinaryOperator::CreateAnd(A, NotB);
5169       }
5170     } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5171       return ReplaceInstUsesWith(I, B);                      // (A^B)^A == B
5172     } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5173       return ReplaceInstUsesWith(I, A);                      // (B^A)^A == B
5174     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5175       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5176         std::swap(A, B);
5177       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5178           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5179         Instruction *N =
5180           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5181         return BinaryOperator::CreateAnd(N, Op1);
5182       }
5183     }
5184   }
5185   
5186   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5187   if (Op0I && Op1I && Op0I->isShift() && 
5188       Op0I->getOpcode() == Op1I->getOpcode() && 
5189       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5190       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5191     Instruction *NewOp =
5192       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5193                                                     Op1I->getOperand(0),
5194                                                     Op0I->getName()), I);
5195     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5196                                   Op1I->getOperand(1));
5197   }
5198     
5199   if (Op0I && Op1I) {
5200     Value *A, *B, *C, *D;
5201     // (A & B)^(A | B) -> A ^ B
5202     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5203         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5204       if ((A == C && B == D) || (A == D && B == C)) 
5205         return BinaryOperator::CreateXor(A, B);
5206     }
5207     // (A | B)^(A & B) -> A ^ B
5208     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5209         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5210       if ((A == C && B == D) || (A == D && B == C)) 
5211         return BinaryOperator::CreateXor(A, B);
5212     }
5213     
5214     // (A & B)^(C & D)
5215     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5216         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5217         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5218       // (X & Y)^(X & Y) -> (Y^Z) & X
5219       Value *X = 0, *Y = 0, *Z = 0;
5220       if (A == C)
5221         X = A, Y = B, Z = D;
5222       else if (A == D)
5223         X = A, Y = B, Z = C;
5224       else if (B == C)
5225         X = B, Y = A, Z = D;
5226       else if (B == D)
5227         X = B, Y = A, Z = C;
5228       
5229       if (X) {
5230         Instruction *NewOp =
5231         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5232         return BinaryOperator::CreateAnd(NewOp, X);
5233       }
5234     }
5235   }
5236     
5237   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5238   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5239     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5240       return R;
5241
5242   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5243   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5244     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5245       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5246         const Type *SrcTy = Op0C->getOperand(0)->getType();
5247         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5248             // Only do this if the casts both really cause code to be generated.
5249             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5250                               I.getType(), TD) &&
5251             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5252                               I.getType(), TD)) {
5253           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5254                                                          Op1C->getOperand(0),
5255                                                          I.getName());
5256           InsertNewInstBefore(NewOp, I);
5257           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5258         }
5259       }
5260   }
5261
5262   return Changed ? &I : 0;
5263 }
5264
5265 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5266 /// overflowed for this type.
5267 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5268                             ConstantInt *In2, bool IsSigned = false) {
5269   Result = cast<ConstantInt>(Add(In1, In2));
5270
5271   if (IsSigned)
5272     if (In2->getValue().isNegative())
5273       return Result->getValue().sgt(In1->getValue());
5274     else
5275       return Result->getValue().slt(In1->getValue());
5276   else
5277     return Result->getValue().ult(In1->getValue());
5278 }
5279
5280 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5281 /// overflowed for this type.
5282 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5283                             ConstantInt *In2, bool IsSigned = false) {
5284   Result = cast<ConstantInt>(Subtract(In1, In2));
5285
5286   if (IsSigned)
5287     if (In2->getValue().isNegative())
5288       return Result->getValue().slt(In1->getValue());
5289     else
5290       return Result->getValue().sgt(In1->getValue());
5291   else
5292     return Result->getValue().ugt(In1->getValue());
5293 }
5294
5295 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5296 /// code necessary to compute the offset from the base pointer (without adding
5297 /// in the base pointer).  Return the result as a signed integer of intptr size.
5298 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5299   TargetData &TD = IC.getTargetData();
5300   gep_type_iterator GTI = gep_type_begin(GEP);
5301   const Type *IntPtrTy = TD.getIntPtrType();
5302   Value *Result = Constant::getNullValue(IntPtrTy);
5303
5304   // Build a mask for high order bits.
5305   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5306   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5307
5308   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5309        ++i, ++GTI) {
5310     Value *Op = *i;
5311     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5312     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5313       if (OpC->isZero()) continue;
5314       
5315       // Handle a struct index, which adds its field offset to the pointer.
5316       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5317         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5318         
5319         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5320           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5321         else
5322           Result = IC.InsertNewInstBefore(
5323                    BinaryOperator::CreateAdd(Result,
5324                                              ConstantInt::get(IntPtrTy, Size),
5325                                              GEP->getName()+".offs"), I);
5326         continue;
5327       }
5328       
5329       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5330       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5331       Scale = ConstantExpr::getMul(OC, Scale);
5332       if (Constant *RC = dyn_cast<Constant>(Result))
5333         Result = ConstantExpr::getAdd(RC, Scale);
5334       else {
5335         // Emit an add instruction.
5336         Result = IC.InsertNewInstBefore(
5337            BinaryOperator::CreateAdd(Result, Scale,
5338                                      GEP->getName()+".offs"), I);
5339       }
5340       continue;
5341     }
5342     // Convert to correct type.
5343     if (Op->getType() != IntPtrTy) {
5344       if (Constant *OpC = dyn_cast<Constant>(Op))
5345         Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5346       else
5347         Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5348                                                                 true,
5349                                                       Op->getName()+".c"), I);
5350     }
5351     if (Size != 1) {
5352       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5353       if (Constant *OpC = dyn_cast<Constant>(Op))
5354         Op = ConstantExpr::getMul(OpC, Scale);
5355       else    // We'll let instcombine(mul) convert this to a shl if possible.
5356         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5357                                                   GEP->getName()+".idx"), I);
5358     }
5359
5360     // Emit an add instruction.
5361     if (isa<Constant>(Op) && isa<Constant>(Result))
5362       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5363                                     cast<Constant>(Result));
5364     else
5365       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5366                                                   GEP->getName()+".offs"), I);
5367   }
5368   return Result;
5369 }
5370
5371
5372 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5373 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5374 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5375 /// complex, and scales are involved.  The above expression would also be legal
5376 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5377 /// later form is less amenable to optimization though, and we are allowed to
5378 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5379 ///
5380 /// If we can't emit an optimized form for this expression, this returns null.
5381 /// 
5382 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5383                                           InstCombiner &IC) {
5384   TargetData &TD = IC.getTargetData();
5385   gep_type_iterator GTI = gep_type_begin(GEP);
5386
5387   // Check to see if this gep only has a single variable index.  If so, and if
5388   // any constant indices are a multiple of its scale, then we can compute this
5389   // in terms of the scale of the variable index.  For example, if the GEP
5390   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5391   // because the expression will cross zero at the same point.
5392   unsigned i, e = GEP->getNumOperands();
5393   int64_t Offset = 0;
5394   for (i = 1; i != e; ++i, ++GTI) {
5395     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5396       // Compute the aggregate offset of constant indices.
5397       if (CI->isZero()) continue;
5398
5399       // Handle a struct index, which adds its field offset to the pointer.
5400       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5401         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5402       } else {
5403         uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5404         Offset += Size*CI->getSExtValue();
5405       }
5406     } else {
5407       // Found our variable index.
5408       break;
5409     }
5410   }
5411   
5412   // If there are no variable indices, we must have a constant offset, just
5413   // evaluate it the general way.
5414   if (i == e) return 0;
5415   
5416   Value *VariableIdx = GEP->getOperand(i);
5417   // Determine the scale factor of the variable element.  For example, this is
5418   // 4 if the variable index is into an array of i32.
5419   uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5420   
5421   // Verify that there are no other variable indices.  If so, emit the hard way.
5422   for (++i, ++GTI; i != e; ++i, ++GTI) {
5423     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5424     if (!CI) return 0;
5425    
5426     // Compute the aggregate offset of constant indices.
5427     if (CI->isZero()) continue;
5428     
5429     // Handle a struct index, which adds its field offset to the pointer.
5430     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5431       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5432     } else {
5433       uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5434       Offset += Size*CI->getSExtValue();
5435     }
5436   }
5437   
5438   // Okay, we know we have a single variable index, which must be a
5439   // pointer/array/vector index.  If there is no offset, life is simple, return
5440   // the index.
5441   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5442   if (Offset == 0) {
5443     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5444     // we don't need to bother extending: the extension won't affect where the
5445     // computation crosses zero.
5446     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5447       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5448                                   VariableIdx->getNameStart(), &I);
5449     return VariableIdx;
5450   }
5451   
5452   // Otherwise, there is an index.  The computation we will do will be modulo
5453   // the pointer size, so get it.
5454   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5455   
5456   Offset &= PtrSizeMask;
5457   VariableScale &= PtrSizeMask;
5458
5459   // To do this transformation, any constant index must be a multiple of the
5460   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5461   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5462   // multiple of the variable scale.
5463   int64_t NewOffs = Offset / (int64_t)VariableScale;
5464   if (Offset != NewOffs*(int64_t)VariableScale)
5465     return 0;
5466
5467   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5468   const Type *IntPtrTy = TD.getIntPtrType();
5469   if (VariableIdx->getType() != IntPtrTy)
5470     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5471                                               true /*SExt*/, 
5472                                               VariableIdx->getNameStart(), &I);
5473   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5474   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5475 }
5476
5477
5478 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5479 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5480 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5481                                        ICmpInst::Predicate Cond,
5482                                        Instruction &I) {
5483   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5484
5485   // Look through bitcasts.
5486   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5487     RHS = BCI->getOperand(0);
5488
5489   Value *PtrBase = GEPLHS->getOperand(0);
5490   if (PtrBase == RHS) {
5491     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5492     // This transformation (ignoring the base and scales) is valid because we
5493     // know pointers can't overflow.  See if we can output an optimized form.
5494     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5495     
5496     // If not, synthesize the offset the hard way.
5497     if (Offset == 0)
5498       Offset = EmitGEPOffset(GEPLHS, I, *this);
5499     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5500                         Constant::getNullValue(Offset->getType()));
5501   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5502     // If the base pointers are different, but the indices are the same, just
5503     // compare the base pointer.
5504     if (PtrBase != GEPRHS->getOperand(0)) {
5505       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5506       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5507                         GEPRHS->getOperand(0)->getType();
5508       if (IndicesTheSame)
5509         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5510           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5511             IndicesTheSame = false;
5512             break;
5513           }
5514
5515       // If all indices are the same, just compare the base pointers.
5516       if (IndicesTheSame)
5517         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5518                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5519
5520       // Otherwise, the base pointers are different and the indices are
5521       // different, bail out.
5522       return 0;
5523     }
5524
5525     // If one of the GEPs has all zero indices, recurse.
5526     bool AllZeros = true;
5527     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5528       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5529           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5530         AllZeros = false;
5531         break;
5532       }
5533     if (AllZeros)
5534       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5535                           ICmpInst::getSwappedPredicate(Cond), I);
5536
5537     // If the other GEP has all zero indices, recurse.
5538     AllZeros = true;
5539     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5540       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5541           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5542         AllZeros = false;
5543         break;
5544       }
5545     if (AllZeros)
5546       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5547
5548     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5549       // If the GEPs only differ by one index, compare it.
5550       unsigned NumDifferences = 0;  // Keep track of # differences.
5551       unsigned DiffOperand = 0;     // The operand that differs.
5552       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5553         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5554           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5555                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5556             // Irreconcilable differences.
5557             NumDifferences = 2;
5558             break;
5559           } else {
5560             if (NumDifferences++) break;
5561             DiffOperand = i;
5562           }
5563         }
5564
5565       if (NumDifferences == 0)   // SAME GEP?
5566         return ReplaceInstUsesWith(I, // No comparison is needed here.
5567                                    ConstantInt::get(Type::Int1Ty,
5568                                              ICmpInst::isTrueWhenEqual(Cond)));
5569
5570       else if (NumDifferences == 1) {
5571         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5572         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5573         // Make sure we do a signed comparison here.
5574         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5575       }
5576     }
5577
5578     // Only lower this if the icmp is the only user of the GEP or if we expect
5579     // the result to fold to a constant!
5580     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5581         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5582       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5583       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5584       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5585       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5586     }
5587   }
5588   return 0;
5589 }
5590
5591 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5592 ///
5593 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5594                                                 Instruction *LHSI,
5595                                                 Constant *RHSC) {
5596   if (!isa<ConstantFP>(RHSC)) return 0;
5597   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5598   
5599   // Get the width of the mantissa.  We don't want to hack on conversions that
5600   // might lose information from the integer, e.g. "i64 -> float"
5601   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5602   if (MantissaWidth == -1) return 0;  // Unknown.
5603   
5604   // Check to see that the input is converted from an integer type that is small
5605   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5606   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5607   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5608   
5609   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5610   bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5611   if (LHSUnsigned)
5612     ++InputSize;
5613   
5614   // If the conversion would lose info, don't hack on this.
5615   if ((int)InputSize > MantissaWidth)
5616     return 0;
5617   
5618   // Otherwise, we can potentially simplify the comparison.  We know that it
5619   // will always come through as an integer value and we know the constant is
5620   // not a NAN (it would have been previously simplified).
5621   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5622   
5623   ICmpInst::Predicate Pred;
5624   switch (I.getPredicate()) {
5625   default: assert(0 && "Unexpected predicate!");
5626   case FCmpInst::FCMP_UEQ:
5627   case FCmpInst::FCMP_OEQ:
5628     Pred = ICmpInst::ICMP_EQ;
5629     break;
5630   case FCmpInst::FCMP_UGT:
5631   case FCmpInst::FCMP_OGT:
5632     Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5633     break;
5634   case FCmpInst::FCMP_UGE:
5635   case FCmpInst::FCMP_OGE:
5636     Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5637     break;
5638   case FCmpInst::FCMP_ULT:
5639   case FCmpInst::FCMP_OLT:
5640     Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5641     break;
5642   case FCmpInst::FCMP_ULE:
5643   case FCmpInst::FCMP_OLE:
5644     Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5645     break;
5646   case FCmpInst::FCMP_UNE:
5647   case FCmpInst::FCMP_ONE:
5648     Pred = ICmpInst::ICMP_NE;
5649     break;
5650   case FCmpInst::FCMP_ORD:
5651     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5652   case FCmpInst::FCMP_UNO:
5653     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5654   }
5655   
5656   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5657   
5658   // Now we know that the APFloat is a normal number, zero or inf.
5659   
5660   // See if the FP constant is too large for the integer.  For example,
5661   // comparing an i8 to 300.0.
5662   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5663   
5664   if (!LHSUnsigned) {
5665     // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5666     // and large values.
5667     APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5668     SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5669                           APFloat::rmNearestTiesToEven);
5670     if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5671       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_SLT ||
5672           Pred == ICmpInst::ICMP_SLE)
5673         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5674       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5675     }
5676   } else {
5677     // If the RHS value is > UnsignedMax, fold the comparison. This handles
5678     // +INF and large values.
5679     APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5680     UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5681                           APFloat::rmNearestTiesToEven);
5682     if (UMax.compare(RHS) == APFloat::cmpLessThan) {  // umax < 13123.0
5683       if (Pred == ICmpInst::ICMP_NE  || Pred == ICmpInst::ICMP_ULT ||
5684           Pred == ICmpInst::ICMP_ULE)
5685         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5686       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5687     }
5688   }
5689   
5690   if (!LHSUnsigned) {
5691     // See if the RHS value is < SignedMin.
5692     APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5693     SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5694                           APFloat::rmNearestTiesToEven);
5695     if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5696       if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5697           Pred == ICmpInst::ICMP_SGE)
5698         return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5699       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5700     }
5701   }
5702
5703   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5704   // [0, UMAX], but it may still be fractional.  See if it is fractional by
5705   // casting the FP value to the integer value and back, checking for equality.
5706   // Don't do this for zero, because -0.0 is not fractional.
5707   Constant *RHSInt = LHSUnsigned
5708     ? ConstantExpr::getFPToUI(RHSC, IntTy)
5709     : ConstantExpr::getFPToSI(RHSC, IntTy);
5710   if (!RHS.isZero()) {
5711     bool Equal = LHSUnsigned
5712       ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5713       : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5714     if (!Equal) {
5715       // If we had a comparison against a fractional value, we have to adjust
5716       // the compare predicate and sometimes the value.  RHSC is rounded towards
5717       // zero at this point.
5718       switch (Pred) {
5719       default: assert(0 && "Unexpected integer comparison!");
5720       case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5721         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5722       case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5723         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5724       case ICmpInst::ICMP_ULE:
5725         // (float)int <= 4.4   --> int <= 4
5726         // (float)int <= -4.4  --> false
5727         if (RHS.isNegative())
5728           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5729         break;
5730       case ICmpInst::ICMP_SLE:
5731         // (float)int <= 4.4   --> int <= 4
5732         // (float)int <= -4.4  --> int < -4
5733         if (RHS.isNegative())
5734           Pred = ICmpInst::ICMP_SLT;
5735         break;
5736       case ICmpInst::ICMP_ULT:
5737         // (float)int < -4.4   --> false
5738         // (float)int < 4.4    --> int <= 4
5739         if (RHS.isNegative())
5740           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5741         Pred = ICmpInst::ICMP_ULE;
5742         break;
5743       case ICmpInst::ICMP_SLT:
5744         // (float)int < -4.4   --> int < -4
5745         // (float)int < 4.4    --> int <= 4
5746         if (!RHS.isNegative())
5747           Pred = ICmpInst::ICMP_SLE;
5748         break;
5749       case ICmpInst::ICMP_UGT:
5750         // (float)int > 4.4    --> int > 4
5751         // (float)int > -4.4   --> true
5752         if (RHS.isNegative())
5753           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5754         break;
5755       case ICmpInst::ICMP_SGT:
5756         // (float)int > 4.4    --> int > 4
5757         // (float)int > -4.4   --> int >= -4
5758         if (RHS.isNegative())
5759           Pred = ICmpInst::ICMP_SGE;
5760         break;
5761       case ICmpInst::ICMP_UGE:
5762         // (float)int >= -4.4   --> true
5763         // (float)int >= 4.4    --> int > 4
5764         if (!RHS.isNegative())
5765           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5766         Pred = ICmpInst::ICMP_UGT;
5767         break;
5768       case ICmpInst::ICMP_SGE:
5769         // (float)int >= -4.4   --> int >= -4
5770         // (float)int >= 4.4    --> int > 4
5771         if (!RHS.isNegative())
5772           Pred = ICmpInst::ICMP_SGT;
5773         break;
5774       }
5775     }
5776   }
5777
5778   // Lower this FP comparison into an appropriate integer version of the
5779   // comparison.
5780   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5781 }
5782
5783 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5784   bool Changed = SimplifyCompare(I);
5785   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5786
5787   // Fold trivial predicates.
5788   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5789     return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5790   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5791     return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5792   
5793   // Simplify 'fcmp pred X, X'
5794   if (Op0 == Op1) {
5795     switch (I.getPredicate()) {
5796     default: assert(0 && "Unknown predicate!");
5797     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5798     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5799     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5800       return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5801     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5802     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5803     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5804       return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5805       
5806     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5807     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5808     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5809     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5810       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5811       I.setPredicate(FCmpInst::FCMP_UNO);
5812       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5813       return &I;
5814       
5815     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5816     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5817     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5818     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5819       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5820       I.setPredicate(FCmpInst::FCMP_ORD);
5821       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5822       return &I;
5823     }
5824   }
5825     
5826   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5827     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5828
5829   // Handle fcmp with constant RHS
5830   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5831     // If the constant is a nan, see if we can fold the comparison based on it.
5832     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5833       if (CFP->getValueAPF().isNaN()) {
5834         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5835           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5836         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5837                "Comparison must be either ordered or unordered!");
5838         // True if unordered.
5839         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5840       }
5841     }
5842     
5843     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5844       switch (LHSI->getOpcode()) {
5845       case Instruction::PHI:
5846         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5847         // block.  If in the same block, we're encouraging jump threading.  If
5848         // not, we are just pessimizing the code by making an i1 phi.
5849         if (LHSI->getParent() == I.getParent())
5850           if (Instruction *NV = FoldOpIntoPhi(I))
5851             return NV;
5852         break;
5853       case Instruction::SIToFP:
5854       case Instruction::UIToFP:
5855         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5856           return NV;
5857         break;
5858       case Instruction::Select:
5859         // If either operand of the select is a constant, we can fold the
5860         // comparison into the select arms, which will cause one to be
5861         // constant folded and the select turned into a bitwise or.
5862         Value *Op1 = 0, *Op2 = 0;
5863         if (LHSI->hasOneUse()) {
5864           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5865             // Fold the known value into the constant operand.
5866             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5867             // Insert a new FCmp of the other select operand.
5868             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5869                                                       LHSI->getOperand(2), RHSC,
5870                                                       I.getName()), I);
5871           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5872             // Fold the known value into the constant operand.
5873             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5874             // Insert a new FCmp of the other select operand.
5875             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5876                                                       LHSI->getOperand(1), RHSC,
5877                                                       I.getName()), I);
5878           }
5879         }
5880
5881         if (Op1)
5882           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5883         break;
5884       }
5885   }
5886
5887   return Changed ? &I : 0;
5888 }
5889
5890 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5891   bool Changed = SimplifyCompare(I);
5892   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5893   const Type *Ty = Op0->getType();
5894
5895   // icmp X, X
5896   if (Op0 == Op1)
5897     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5898                                                    I.isTrueWhenEqual()));
5899
5900   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5901     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5902   
5903   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5904   // addresses never equal each other!  We already know that Op0 != Op1.
5905   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5906        isa<ConstantPointerNull>(Op0)) &&
5907       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5908        isa<ConstantPointerNull>(Op1)))
5909     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5910                                                    !I.isTrueWhenEqual()));
5911
5912   // icmp's with boolean values can always be turned into bitwise operations
5913   if (Ty == Type::Int1Ty) {
5914     switch (I.getPredicate()) {
5915     default: assert(0 && "Invalid icmp instruction!");
5916     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5917       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5918       InsertNewInstBefore(Xor, I);
5919       return BinaryOperator::CreateNot(Xor);
5920     }
5921     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5922       return BinaryOperator::CreateXor(Op0, Op1);
5923
5924     case ICmpInst::ICMP_UGT:
5925       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5926       // FALL THROUGH
5927     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5928       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5929       InsertNewInstBefore(Not, I);
5930       return BinaryOperator::CreateAnd(Not, Op1);
5931     }
5932     case ICmpInst::ICMP_SGT:
5933       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5934       // FALL THROUGH
5935     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5936       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5937       InsertNewInstBefore(Not, I);
5938       return BinaryOperator::CreateAnd(Not, Op0);
5939     }
5940     case ICmpInst::ICMP_UGE:
5941       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5942       // FALL THROUGH
5943     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5944       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5945       InsertNewInstBefore(Not, I);
5946       return BinaryOperator::CreateOr(Not, Op1);
5947     }
5948     case ICmpInst::ICMP_SGE:
5949       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5950       // FALL THROUGH
5951     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5952       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5953       InsertNewInstBefore(Not, I);
5954       return BinaryOperator::CreateOr(Not, Op0);
5955     }
5956     }
5957   }
5958
5959   unsigned BitWidth = 0;
5960   if (TD)
5961     BitWidth = TD->getTypeSizeInBits(Ty);
5962   else if (isa<IntegerType>(Ty))
5963     BitWidth = Ty->getPrimitiveSizeInBits();
5964
5965   bool isSignBit = false;
5966
5967   // See if we are doing a comparison with a constant.
5968   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5969     Value *A = 0, *B = 0;
5970     
5971     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5972     if (I.isEquality() && CI->isNullValue() &&
5973         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5974       // (icmp cond A B) if cond is equality
5975       return new ICmpInst(I.getPredicate(), A, B);
5976     }
5977     
5978     // If we have an icmp le or icmp ge instruction, turn it into the
5979     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5980     // them being folded in the code below.
5981     switch (I.getPredicate()) {
5982     default: break;
5983     case ICmpInst::ICMP_ULE:
5984       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5985         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5986       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5987     case ICmpInst::ICMP_SLE:
5988       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5989         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5990       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5991     case ICmpInst::ICMP_UGE:
5992       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5993         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5994       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5995     case ICmpInst::ICMP_SGE:
5996       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5997         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5998       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5999     }
6000     
6001     // If this comparison is a normal comparison, it demands all
6002     // bits, if it is a sign bit comparison, it only demands the sign bit.
6003     bool UnusedBit;
6004     isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6005   }
6006
6007   // See if we can fold the comparison based on range information we can get
6008   // by checking whether bits are known to be zero or one in the input.
6009   if (BitWidth != 0) {
6010     APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6011     APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6012
6013     if (SimplifyDemandedBits(I.getOperandUse(0),
6014                              isSignBit ? APInt::getSignBit(BitWidth)
6015                                        : APInt::getAllOnesValue(BitWidth),
6016                              Op0KnownZero, Op0KnownOne, 0))
6017       return &I;
6018     if (SimplifyDemandedBits(I.getOperandUse(1),
6019                              APInt::getAllOnesValue(BitWidth),
6020                              Op1KnownZero, Op1KnownOne, 0))
6021       return &I;
6022
6023     // Given the known and unknown bits, compute a range that the LHS could be
6024     // in.  Compute the Min, Max and RHS values based on the known bits. For the
6025     // EQ and NE we use unsigned values.
6026     APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6027     APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6028     if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6029       ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6030                                              Op0Min, Op0Max);
6031       ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6032                                              Op1Min, Op1Max);
6033     } else {
6034       ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6035                                                Op0Min, Op0Max);
6036       ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6037                                                Op1Min, Op1Max);
6038     }
6039
6040     // If Min and Max are known to be the same, then SimplifyDemandedBits
6041     // figured out that the LHS is a constant.  Just constant fold this now so
6042     // that code below can assume that Min != Max.
6043     if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6044       return new ICmpInst(I.getPredicate(), ConstantInt::get(Op0Min), Op1);
6045     if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6046       return new ICmpInst(I.getPredicate(), Op0, ConstantInt::get(Op1Min));
6047
6048     // Based on the range information we know about the LHS, see if we can
6049     // simplify this comparison.  For example, (x&4) < 8  is always true.
6050     switch (I.getPredicate()) {
6051     default: assert(0 && "Unknown icmp opcode!");
6052     case ICmpInst::ICMP_EQ:
6053       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6054         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6055       break;
6056     case ICmpInst::ICMP_NE:
6057       if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6058         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6059       break;
6060     case ICmpInst::ICMP_ULT:
6061       if (Op0Max.ult(Op1Min))          // A <u B -> true if max(A) < min(B)
6062         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6063       if (Op0Min.uge(Op1Max))          // A <u B -> false if min(A) >= max(B)
6064         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6065       if (Op1Min == Op0Max)            // A <u B -> A != B if max(A) == min(B)
6066         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6067       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6068         if (Op1Max == Op0Min+1)        // A <u C -> A == C-1 if min(A)+1 == C
6069           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6070
6071         // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
6072         if (CI->isMinValue(true))
6073           return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6074                             ConstantInt::getAllOnesValue(Op0->getType()));
6075       }
6076       break;
6077     case ICmpInst::ICMP_UGT:
6078       if (Op0Min.ugt(Op1Max))          // A >u B -> true if min(A) > max(B)
6079         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6080       if (Op0Max.ule(Op1Min))          // A >u B -> false if max(A) <= max(B)
6081         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6082
6083       if (Op1Max == Op0Min)            // A >u B -> A != B if min(A) == max(B)
6084         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6085       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6086         if (Op1Min == Op0Max-1)        // A >u C -> A == C+1 if max(a)-1 == C
6087           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6088
6089         // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
6090         if (CI->isMaxValue(true))
6091           return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6092                               ConstantInt::getNullValue(Op0->getType()));
6093       }
6094       break;
6095     case ICmpInst::ICMP_SLT:
6096       if (Op0Max.slt(Op1Min))          // A <s B -> true if max(A) < min(C)
6097         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6098       if (Op0Min.sge(Op1Max))          // A <s B -> false if min(A) >= max(C)
6099         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6100       if (Op1Min == Op0Max)            // A <s B -> A != B if max(A) == min(B)
6101         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6102       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6103         if (Op1Max == Op0Min+1)        // A <s C -> A == C-1 if min(A)+1 == C
6104           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
6105       }
6106       break;
6107     case ICmpInst::ICMP_SGT:
6108       if (Op0Min.sgt(Op1Max))          // A >s B -> true if min(A) > max(B)
6109         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6110       if (Op0Max.sle(Op1Min))          // A >s B -> false if max(A) <= min(B)
6111         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6112
6113       if (Op1Max == Op0Min)            // A >s B -> A != B if min(A) == max(B)
6114         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6115       if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6116         if (Op1Min == Op0Max-1)        // A >s C -> A == C+1 if max(A)-1 == C
6117           return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
6118       }
6119       break;
6120     case ICmpInst::ICMP_SGE:
6121       assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6122       if (Op0Min.sge(Op1Max))          // A >=s B -> true if min(A) >= max(B)
6123         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6124       if (Op0Max.slt(Op1Min))          // A >=s B -> false if max(A) < min(B)
6125         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6126       break;
6127     case ICmpInst::ICMP_SLE:
6128       assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6129       if (Op0Max.sle(Op1Min))          // A <=s B -> true if max(A) <= min(B)
6130         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6131       if (Op0Min.sgt(Op1Max))          // A <=s B -> false if min(A) > max(B)
6132         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6133       break;
6134     case ICmpInst::ICMP_UGE:
6135       assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6136       if (Op0Min.uge(Op1Max))          // A >=u B -> true if min(A) >= max(B)
6137         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6138       if (Op0Max.ult(Op1Min))          // A >=u B -> false if max(A) < min(B)
6139         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6140       break;
6141     case ICmpInst::ICMP_ULE:
6142       assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6143       if (Op0Max.ule(Op1Min))          // A <=u B -> true if max(A) <= min(B)
6144         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
6145       if (Op0Min.ugt(Op1Max))          // A <=u B -> false if min(A) > max(B)
6146         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
6147       break;
6148     }
6149
6150     // Turn a signed comparison into an unsigned one if both operands
6151     // are known to have the same sign.
6152     if (I.isSignedPredicate() &&
6153         ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6154          (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6155       return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6156   }
6157
6158   // Test if the ICmpInst instruction is used exclusively by a select as
6159   // part of a minimum or maximum operation. If so, refrain from doing
6160   // any other folding. This helps out other analyses which understand
6161   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6162   // and CodeGen. And in this case, at least one of the comparison
6163   // operands has at least one user besides the compare (the select),
6164   // which would often largely negate the benefit of folding anyway.
6165   if (I.hasOneUse())
6166     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6167       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6168           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6169         return 0;
6170
6171   // See if we are doing a comparison between a constant and an instruction that
6172   // can be folded into the comparison.
6173   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6174     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
6175     // instruction, see if that instruction also has constants so that the 
6176     // instruction can be folded into the icmp 
6177     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6178       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6179         return Res;
6180   }
6181
6182   // Handle icmp with constant (but not simple integer constant) RHS
6183   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6184     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6185       switch (LHSI->getOpcode()) {
6186       case Instruction::GetElementPtr:
6187         if (RHSC->isNullValue()) {
6188           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6189           bool isAllZeros = true;
6190           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6191             if (!isa<Constant>(LHSI->getOperand(i)) ||
6192                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6193               isAllZeros = false;
6194               break;
6195             }
6196           if (isAllZeros)
6197             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6198                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6199         }
6200         break;
6201
6202       case Instruction::PHI:
6203         // Only fold icmp into the PHI if the phi and fcmp are in the same
6204         // block.  If in the same block, we're encouraging jump threading.  If
6205         // not, we are just pessimizing the code by making an i1 phi.
6206         if (LHSI->getParent() == I.getParent())
6207           if (Instruction *NV = FoldOpIntoPhi(I))
6208             return NV;
6209         break;
6210       case Instruction::Select: {
6211         // If either operand of the select is a constant, we can fold the
6212         // comparison into the select arms, which will cause one to be
6213         // constant folded and the select turned into a bitwise or.
6214         Value *Op1 = 0, *Op2 = 0;
6215         if (LHSI->hasOneUse()) {
6216           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6217             // Fold the known value into the constant operand.
6218             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6219             // Insert a new ICmp of the other select operand.
6220             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6221                                                    LHSI->getOperand(2), RHSC,
6222                                                    I.getName()), I);
6223           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6224             // Fold the known value into the constant operand.
6225             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6226             // Insert a new ICmp of the other select operand.
6227             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6228                                                    LHSI->getOperand(1), RHSC,
6229                                                    I.getName()), I);
6230           }
6231         }
6232
6233         if (Op1)
6234           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6235         break;
6236       }
6237       case Instruction::Malloc:
6238         // If we have (malloc != null), and if the malloc has a single use, we
6239         // can assume it is successful and remove the malloc.
6240         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6241           AddToWorkList(LHSI);
6242           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6243                                                          !I.isTrueWhenEqual()));
6244         }
6245         break;
6246       }
6247   }
6248
6249   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6250   if (User *GEP = dyn_castGetElementPtr(Op0))
6251     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6252       return NI;
6253   if (User *GEP = dyn_castGetElementPtr(Op1))
6254     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6255                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6256       return NI;
6257
6258   // Test to see if the operands of the icmp are casted versions of other
6259   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6260   // now.
6261   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6262     if (isa<PointerType>(Op0->getType()) && 
6263         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6264       // We keep moving the cast from the left operand over to the right
6265       // operand, where it can often be eliminated completely.
6266       Op0 = CI->getOperand(0);
6267
6268       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6269       // so eliminate it as well.
6270       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6271         Op1 = CI2->getOperand(0);
6272
6273       // If Op1 is a constant, we can fold the cast into the constant.
6274       if (Op0->getType() != Op1->getType()) {
6275         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6276           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6277         } else {
6278           // Otherwise, cast the RHS right before the icmp
6279           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6280         }
6281       }
6282       return new ICmpInst(I.getPredicate(), Op0, Op1);
6283     }
6284   }
6285   
6286   if (isa<CastInst>(Op0)) {
6287     // Handle the special case of: icmp (cast bool to X), <cst>
6288     // This comes up when you have code like
6289     //   int X = A < B;
6290     //   if (X) ...
6291     // For generality, we handle any zero-extension of any operand comparison
6292     // with a constant or another cast from the same type.
6293     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6294       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6295         return R;
6296   }
6297   
6298   // See if it's the same type of instruction on the left and right.
6299   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6300     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6301       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6302           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6303         switch (Op0I->getOpcode()) {
6304         default: break;
6305         case Instruction::Add:
6306         case Instruction::Sub:
6307         case Instruction::Xor:
6308           if (I.isEquality())    // a+x icmp eq/ne b+x --> a icmp b
6309             return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6310                                 Op1I->getOperand(0));
6311           // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6312           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6313             if (CI->getValue().isSignBit()) {
6314               ICmpInst::Predicate Pred = I.isSignedPredicate()
6315                                              ? I.getUnsignedPredicate()
6316                                              : I.getSignedPredicate();
6317               return new ICmpInst(Pred, Op0I->getOperand(0),
6318                                   Op1I->getOperand(0));
6319             }
6320             
6321             if (CI->getValue().isMaxSignedValue()) {
6322               ICmpInst::Predicate Pred = I.isSignedPredicate()
6323                                              ? I.getUnsignedPredicate()
6324                                              : I.getSignedPredicate();
6325               Pred = I.getSwappedPredicate(Pred);
6326               return new ICmpInst(Pred, Op0I->getOperand(0),
6327                                   Op1I->getOperand(0));
6328             }
6329           }
6330           break;
6331         case Instruction::Mul:
6332           if (!I.isEquality())
6333             break;
6334
6335           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6336             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6337             // Mask = -1 >> count-trailing-zeros(Cst).
6338             if (!CI->isZero() && !CI->isOne()) {
6339               const APInt &AP = CI->getValue();
6340               ConstantInt *Mask = ConstantInt::get(
6341                                       APInt::getLowBitsSet(AP.getBitWidth(),
6342                                                            AP.getBitWidth() -
6343                                                       AP.countTrailingZeros()));
6344               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6345                                                             Mask);
6346               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6347                                                             Mask);
6348               InsertNewInstBefore(And1, I);
6349               InsertNewInstBefore(And2, I);
6350               return new ICmpInst(I.getPredicate(), And1, And2);
6351             }
6352           }
6353           break;
6354         }
6355       }
6356     }
6357   }
6358   
6359   // ~x < ~y --> y < x
6360   { Value *A, *B;
6361     if (match(Op0, m_Not(m_Value(A))) &&
6362         match(Op1, m_Not(m_Value(B))))
6363       return new ICmpInst(I.getPredicate(), B, A);
6364   }
6365   
6366   if (I.isEquality()) {
6367     Value *A, *B, *C, *D;
6368     
6369     // -x == -y --> x == y
6370     if (match(Op0, m_Neg(m_Value(A))) &&
6371         match(Op1, m_Neg(m_Value(B))))
6372       return new ICmpInst(I.getPredicate(), A, B);
6373     
6374     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6375       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6376         Value *OtherVal = A == Op1 ? B : A;
6377         return new ICmpInst(I.getPredicate(), OtherVal,
6378                             Constant::getNullValue(A->getType()));
6379       }
6380
6381       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6382         // A^c1 == C^c2 --> A == C^(c1^c2)
6383         ConstantInt *C1, *C2;
6384         if (match(B, m_ConstantInt(C1)) &&
6385             match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6386           Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6387           Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6388           return new ICmpInst(I.getPredicate(), A,
6389                               InsertNewInstBefore(Xor, I));
6390         }
6391         
6392         // A^B == A^D -> B == D
6393         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6394         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6395         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6396         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6397       }
6398     }
6399     
6400     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6401         (A == Op0 || B == Op0)) {
6402       // A == (A^B)  ->  B == 0
6403       Value *OtherVal = A == Op0 ? B : A;
6404       return new ICmpInst(I.getPredicate(), OtherVal,
6405                           Constant::getNullValue(A->getType()));
6406     }
6407
6408     // (A-B) == A  ->  B == 0
6409     if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6410       return new ICmpInst(I.getPredicate(), B, 
6411                           Constant::getNullValue(B->getType()));
6412
6413     // A == (A-B)  ->  B == 0
6414     if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6415       return new ICmpInst(I.getPredicate(), B,
6416                           Constant::getNullValue(B->getType()));
6417     
6418     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6419     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6420         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6421         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6422       Value *X = 0, *Y = 0, *Z = 0;
6423       
6424       if (A == C) {
6425         X = B; Y = D; Z = A;
6426       } else if (A == D) {
6427         X = B; Y = C; Z = A;
6428       } else if (B == C) {
6429         X = A; Y = D; Z = B;
6430       } else if (B == D) {
6431         X = A; Y = C; Z = B;
6432       }
6433       
6434       if (X) {   // Build (X^Y) & Z
6435         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6436         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6437         I.setOperand(0, Op1);
6438         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6439         return &I;
6440       }
6441     }
6442   }
6443   return Changed ? &I : 0;
6444 }
6445
6446
6447 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6448 /// and CmpRHS are both known to be integer constants.
6449 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6450                                           ConstantInt *DivRHS) {
6451   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6452   const APInt &CmpRHSV = CmpRHS->getValue();
6453   
6454   // FIXME: If the operand types don't match the type of the divide 
6455   // then don't attempt this transform. The code below doesn't have the
6456   // logic to deal with a signed divide and an unsigned compare (and
6457   // vice versa). This is because (x /s C1) <s C2  produces different 
6458   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6459   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6460   // work. :(  The if statement below tests that condition and bails 
6461   // if it finds it. 
6462   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6463   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6464     return 0;
6465   if (DivRHS->isZero())
6466     return 0; // The ProdOV computation fails on divide by zero.
6467   if (DivIsSigned && DivRHS->isAllOnesValue())
6468     return 0; // The overflow computation also screws up here
6469   if (DivRHS->isOne())
6470     return 0; // Not worth bothering, and eliminates some funny cases
6471               // with INT_MIN.
6472
6473   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6474   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6475   // C2 (CI). By solving for X we can turn this into a range check 
6476   // instead of computing a divide. 
6477   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6478
6479   // Determine if the product overflows by seeing if the product is
6480   // not equal to the divide. Make sure we do the same kind of divide
6481   // as in the LHS instruction that we're folding. 
6482   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6483                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6484
6485   // Get the ICmp opcode
6486   ICmpInst::Predicate Pred = ICI.getPredicate();
6487
6488   // Figure out the interval that is being checked.  For example, a comparison
6489   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6490   // Compute this interval based on the constants involved and the signedness of
6491   // the compare/divide.  This computes a half-open interval, keeping track of
6492   // whether either value in the interval overflows.  After analysis each
6493   // overflow variable is set to 0 if it's corresponding bound variable is valid
6494   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6495   int LoOverflow = 0, HiOverflow = 0;
6496   ConstantInt *LoBound = 0, *HiBound = 0;
6497   
6498   if (!DivIsSigned) {  // udiv
6499     // e.g. X/5 op 3  --> [15, 20)
6500     LoBound = Prod;
6501     HiOverflow = LoOverflow = ProdOV;
6502     if (!HiOverflow)
6503       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6504   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6505     if (CmpRHSV == 0) {       // (X / pos) op 0
6506       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6507       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6508       HiBound = DivRHS;
6509     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6510       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6511       HiOverflow = LoOverflow = ProdOV;
6512       if (!HiOverflow)
6513         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6514     } else {                       // (X / pos) op neg
6515       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6516       HiBound = AddOne(Prod);
6517       LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6518       if (!LoOverflow) {
6519         ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6520         LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6521                                      true) ? -1 : 0;
6522        }
6523     }
6524   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6525     if (CmpRHSV == 0) {       // (X / neg) op 0
6526       // e.g. X/-5 op 0  --> [-4, 5)
6527       LoBound = AddOne(DivRHS);
6528       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6529       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6530         HiOverflow = 1;            // [INTMIN+1, overflow)
6531         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6532       }
6533     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6534       // e.g. X/-5 op 3  --> [-19, -14)
6535       HiBound = AddOne(Prod);
6536       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6537       if (!LoOverflow)
6538         LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6539     } else {                       // (X / neg) op neg
6540       LoBound = Prod;       // e.g. X/-5 op -3  --> [15, 20)
6541       LoOverflow = HiOverflow = ProdOV;
6542       if (!HiOverflow)
6543         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6544     }
6545     
6546     // Dividing by a negative swaps the condition.  LT <-> GT
6547     Pred = ICmpInst::getSwappedPredicate(Pred);
6548   }
6549
6550   Value *X = DivI->getOperand(0);
6551   switch (Pred) {
6552   default: assert(0 && "Unhandled icmp opcode!");
6553   case ICmpInst::ICMP_EQ:
6554     if (LoOverflow && HiOverflow)
6555       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6556     else if (HiOverflow)
6557       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6558                           ICmpInst::ICMP_UGE, X, LoBound);
6559     else if (LoOverflow)
6560       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6561                           ICmpInst::ICMP_ULT, X, HiBound);
6562     else
6563       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6564   case ICmpInst::ICMP_NE:
6565     if (LoOverflow && HiOverflow)
6566       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6567     else if (HiOverflow)
6568       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6569                           ICmpInst::ICMP_ULT, X, LoBound);
6570     else if (LoOverflow)
6571       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6572                           ICmpInst::ICMP_UGE, X, HiBound);
6573     else
6574       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6575   case ICmpInst::ICMP_ULT:
6576   case ICmpInst::ICMP_SLT:
6577     if (LoOverflow == +1)   // Low bound is greater than input range.
6578       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6579     if (LoOverflow == -1)   // Low bound is less than input range.
6580       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6581     return new ICmpInst(Pred, X, LoBound);
6582   case ICmpInst::ICMP_UGT:
6583   case ICmpInst::ICMP_SGT:
6584     if (HiOverflow == +1)       // High bound greater than input range.
6585       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6586     else if (HiOverflow == -1)  // High bound less than input range.
6587       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6588     if (Pred == ICmpInst::ICMP_UGT)
6589       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6590     else
6591       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6592   }
6593 }
6594
6595
6596 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6597 ///
6598 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6599                                                           Instruction *LHSI,
6600                                                           ConstantInt *RHS) {
6601   const APInt &RHSV = RHS->getValue();
6602   
6603   switch (LHSI->getOpcode()) {
6604   case Instruction::Trunc:
6605     if (ICI.isEquality() && LHSI->hasOneUse()) {
6606       // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6607       // of the high bits truncated out of x are known.
6608       unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6609              SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6610       APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6611       APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6612       ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6613       
6614       // If all the high bits are known, we can do this xform.
6615       if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6616         // Pull in the high bits from known-ones set.
6617         APInt NewRHS(RHS->getValue());
6618         NewRHS.zext(SrcBits);
6619         NewRHS |= KnownOne;
6620         return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6621                             ConstantInt::get(NewRHS));
6622       }
6623     }
6624     break;
6625       
6626   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6627     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6628       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6629       // fold the xor.
6630       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6631           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6632         Value *CompareVal = LHSI->getOperand(0);
6633         
6634         // If the sign bit of the XorCST is not set, there is no change to
6635         // the operation, just stop using the Xor.
6636         if (!XorCST->getValue().isNegative()) {
6637           ICI.setOperand(0, CompareVal);
6638           AddToWorkList(LHSI);
6639           return &ICI;
6640         }
6641         
6642         // Was the old condition true if the operand is positive?
6643         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6644         
6645         // If so, the new one isn't.
6646         isTrueIfPositive ^= true;
6647         
6648         if (isTrueIfPositive)
6649           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6650         else
6651           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6652       }
6653
6654       if (LHSI->hasOneUse()) {
6655         // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6656         if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6657           const APInt &SignBit = XorCST->getValue();
6658           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6659                                          ? ICI.getUnsignedPredicate()
6660                                          : ICI.getSignedPredicate();
6661           return new ICmpInst(Pred, LHSI->getOperand(0),
6662                               ConstantInt::get(RHSV ^ SignBit));
6663         }
6664
6665         // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6666         if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6667           const APInt &NotSignBit = XorCST->getValue();
6668           ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6669                                          ? ICI.getUnsignedPredicate()
6670                                          : ICI.getSignedPredicate();
6671           Pred = ICI.getSwappedPredicate(Pred);
6672           return new ICmpInst(Pred, LHSI->getOperand(0),
6673                               ConstantInt::get(RHSV ^ NotSignBit));
6674         }
6675       }
6676     }
6677     break;
6678   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6679     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6680         LHSI->getOperand(0)->hasOneUse()) {
6681       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6682       
6683       // If the LHS is an AND of a truncating cast, we can widen the
6684       // and/compare to be the input width without changing the value
6685       // produced, eliminating a cast.
6686       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6687         // We can do this transformation if either the AND constant does not
6688         // have its sign bit set or if it is an equality comparison. 
6689         // Extending a relational comparison when we're checking the sign
6690         // bit would not work.
6691         if (Cast->hasOneUse() &&
6692             (ICI.isEquality() ||
6693              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6694           uint32_t BitWidth = 
6695             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6696           APInt NewCST = AndCST->getValue();
6697           NewCST.zext(BitWidth);
6698           APInt NewCI = RHSV;
6699           NewCI.zext(BitWidth);
6700           Instruction *NewAnd = 
6701             BinaryOperator::CreateAnd(Cast->getOperand(0),
6702                                       ConstantInt::get(NewCST),LHSI->getName());
6703           InsertNewInstBefore(NewAnd, ICI);
6704           return new ICmpInst(ICI.getPredicate(), NewAnd,
6705                               ConstantInt::get(NewCI));
6706         }
6707       }
6708       
6709       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6710       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6711       // happens a LOT in code produced by the C front-end, for bitfield
6712       // access.
6713       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6714       if (Shift && !Shift->isShift())
6715         Shift = 0;
6716       
6717       ConstantInt *ShAmt;
6718       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6719       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6720       const Type *AndTy = AndCST->getType();          // Type of the and.
6721       
6722       // We can fold this as long as we can't shift unknown bits
6723       // into the mask.  This can only happen with signed shift
6724       // rights, as they sign-extend.
6725       if (ShAmt) {
6726         bool CanFold = Shift->isLogicalShift();
6727         if (!CanFold) {
6728           // To test for the bad case of the signed shr, see if any
6729           // of the bits shifted in could be tested after the mask.
6730           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6731           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6732           
6733           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6734           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6735                AndCST->getValue()) == 0)
6736             CanFold = true;
6737         }
6738         
6739         if (CanFold) {
6740           Constant *NewCst;
6741           if (Shift->getOpcode() == Instruction::Shl)
6742             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6743           else
6744             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6745           
6746           // Check to see if we are shifting out any of the bits being
6747           // compared.
6748           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6749             // If we shifted bits out, the fold is not going to work out.
6750             // As a special case, check to see if this means that the
6751             // result is always true or false now.
6752             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6753               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6754             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6755               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6756           } else {
6757             ICI.setOperand(1, NewCst);
6758             Constant *NewAndCST;
6759             if (Shift->getOpcode() == Instruction::Shl)
6760               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6761             else
6762               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6763             LHSI->setOperand(1, NewAndCST);
6764             LHSI->setOperand(0, Shift->getOperand(0));
6765             AddToWorkList(Shift); // Shift is dead.
6766             AddUsesToWorkList(ICI);
6767             return &ICI;
6768           }
6769         }
6770       }
6771       
6772       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6773       // preferable because it allows the C<<Y expression to be hoisted out
6774       // of a loop if Y is invariant and X is not.
6775       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6776           ICI.isEquality() && !Shift->isArithmeticShift() &&
6777           !isa<Constant>(Shift->getOperand(0))) {
6778         // Compute C << Y.
6779         Value *NS;
6780         if (Shift->getOpcode() == Instruction::LShr) {
6781           NS = BinaryOperator::CreateShl(AndCST, 
6782                                          Shift->getOperand(1), "tmp");
6783         } else {
6784           // Insert a logical shift.
6785           NS = BinaryOperator::CreateLShr(AndCST,
6786                                           Shift->getOperand(1), "tmp");
6787         }
6788         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6789         
6790         // Compute X & (C << Y).
6791         Instruction *NewAnd = 
6792           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6793         InsertNewInstBefore(NewAnd, ICI);
6794         
6795         ICI.setOperand(0, NewAnd);
6796         return &ICI;
6797       }
6798     }
6799     break;
6800     
6801   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6802     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6803     if (!ShAmt) break;
6804     
6805     uint32_t TypeBits = RHSV.getBitWidth();
6806     
6807     // Check that the shift amount is in range.  If not, don't perform
6808     // undefined shifts.  When the shift is visited it will be
6809     // simplified.
6810     if (ShAmt->uge(TypeBits))
6811       break;
6812     
6813     if (ICI.isEquality()) {
6814       // If we are comparing against bits always shifted out, the
6815       // comparison cannot succeed.
6816       Constant *Comp =
6817         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6818       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6819         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6820         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6821         return ReplaceInstUsesWith(ICI, Cst);
6822       }
6823       
6824       if (LHSI->hasOneUse()) {
6825         // Otherwise strength reduce the shift into an and.
6826         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6827         Constant *Mask =
6828           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6829         
6830         Instruction *AndI =
6831           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6832                                     Mask, LHSI->getName()+".mask");
6833         Value *And = InsertNewInstBefore(AndI, ICI);
6834         return new ICmpInst(ICI.getPredicate(), And,
6835                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6836       }
6837     }
6838     
6839     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6840     bool TrueIfSigned = false;
6841     if (LHSI->hasOneUse() &&
6842         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6843       // (X << 31) <s 0  --> (X&1) != 0
6844       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6845                                            (TypeBits-ShAmt->getZExtValue()-1));
6846       Instruction *AndI =
6847         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6848                                   Mask, LHSI->getName()+".mask");
6849       Value *And = InsertNewInstBefore(AndI, ICI);
6850       
6851       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6852                           And, Constant::getNullValue(And->getType()));
6853     }
6854     break;
6855   }
6856     
6857   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6858   case Instruction::AShr: {
6859     // Only handle equality comparisons of shift-by-constant.
6860     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6861     if (!ShAmt || !ICI.isEquality()) break;
6862
6863     // Check that the shift amount is in range.  If not, don't perform
6864     // undefined shifts.  When the shift is visited it will be
6865     // simplified.
6866     uint32_t TypeBits = RHSV.getBitWidth();
6867     if (ShAmt->uge(TypeBits))
6868       break;
6869     
6870     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6871       
6872     // If we are comparing against bits always shifted out, the
6873     // comparison cannot succeed.
6874     APInt Comp = RHSV << ShAmtVal;
6875     if (LHSI->getOpcode() == Instruction::LShr)
6876       Comp = Comp.lshr(ShAmtVal);
6877     else
6878       Comp = Comp.ashr(ShAmtVal);
6879     
6880     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6881       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6882       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6883       return ReplaceInstUsesWith(ICI, Cst);
6884     }
6885     
6886     // Otherwise, check to see if the bits shifted out are known to be zero.
6887     // If so, we can compare against the unshifted value:
6888     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6889     if (LHSI->hasOneUse() &&
6890         MaskedValueIsZero(LHSI->getOperand(0), 
6891                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6892       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6893                           ConstantExpr::getShl(RHS, ShAmt));
6894     }
6895       
6896     if (LHSI->hasOneUse()) {
6897       // Otherwise strength reduce the shift into an and.
6898       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6899       Constant *Mask = ConstantInt::get(Val);
6900       
6901       Instruction *AndI =
6902         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6903                                   Mask, LHSI->getName()+".mask");
6904       Value *And = InsertNewInstBefore(AndI, ICI);
6905       return new ICmpInst(ICI.getPredicate(), And,
6906                           ConstantExpr::getShl(RHS, ShAmt));
6907     }
6908     break;
6909   }
6910     
6911   case Instruction::SDiv:
6912   case Instruction::UDiv:
6913     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6914     // Fold this div into the comparison, producing a range check. 
6915     // Determine, based on the divide type, what the range is being 
6916     // checked.  If there is an overflow on the low or high side, remember 
6917     // it, otherwise compute the range [low, hi) bounding the new value.
6918     // See: InsertRangeTest above for the kinds of replacements possible.
6919     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6920       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6921                                           DivRHS))
6922         return R;
6923     break;
6924
6925   case Instruction::Add:
6926     // Fold: icmp pred (add, X, C1), C2
6927
6928     if (!ICI.isEquality()) {
6929       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6930       if (!LHSC) break;
6931       const APInt &LHSV = LHSC->getValue();
6932
6933       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6934                             .subtract(LHSV);
6935
6936       if (ICI.isSignedPredicate()) {
6937         if (CR.getLower().isSignBit()) {
6938           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6939                               ConstantInt::get(CR.getUpper()));
6940         } else if (CR.getUpper().isSignBit()) {
6941           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6942                               ConstantInt::get(CR.getLower()));
6943         }
6944       } else {
6945         if (CR.getLower().isMinValue()) {
6946           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6947                               ConstantInt::get(CR.getUpper()));
6948         } else if (CR.getUpper().isMinValue()) {
6949           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6950                               ConstantInt::get(CR.getLower()));
6951         }
6952       }
6953     }
6954     break;
6955   }
6956   
6957   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6958   if (ICI.isEquality()) {
6959     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6960     
6961     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6962     // the second operand is a constant, simplify a bit.
6963     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6964       switch (BO->getOpcode()) {
6965       case Instruction::SRem:
6966         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6967         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6968           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6969           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6970             Instruction *NewRem =
6971               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6972                                          BO->getName());
6973             InsertNewInstBefore(NewRem, ICI);
6974             return new ICmpInst(ICI.getPredicate(), NewRem, 
6975                                 Constant::getNullValue(BO->getType()));
6976           }
6977         }
6978         break;
6979       case Instruction::Add:
6980         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6981         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6982           if (BO->hasOneUse())
6983             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6984                                 Subtract(RHS, BOp1C));
6985         } else if (RHSV == 0) {
6986           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6987           // efficiently invertible, or if the add has just this one use.
6988           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6989           
6990           if (Value *NegVal = dyn_castNegVal(BOp1))
6991             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6992           else if (Value *NegVal = dyn_castNegVal(BOp0))
6993             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6994           else if (BO->hasOneUse()) {
6995             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6996             InsertNewInstBefore(Neg, ICI);
6997             Neg->takeName(BO);
6998             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6999           }
7000         }
7001         break;
7002       case Instruction::Xor:
7003         // For the xor case, we can xor two constants together, eliminating
7004         // the explicit xor.
7005         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7006           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
7007                               ConstantExpr::getXor(RHS, BOC));
7008         
7009         // FALLTHROUGH
7010       case Instruction::Sub:
7011         // Replace (([sub|xor] A, B) != 0) with (A != B)
7012         if (RHSV == 0)
7013           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7014                               BO->getOperand(1));
7015         break;
7016         
7017       case Instruction::Or:
7018         // If bits are being or'd in that are not present in the constant we
7019         // are comparing against, then the comparison could never succeed!
7020         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7021           Constant *NotCI = ConstantExpr::getNot(RHS);
7022           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7023             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
7024                                                              isICMP_NE));
7025         }
7026         break;
7027         
7028       case Instruction::And:
7029         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7030           // If bits are being compared against that are and'd out, then the
7031           // comparison can never succeed!
7032           if ((RHSV & ~BOC->getValue()) != 0)
7033             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
7034                                                              isICMP_NE));
7035           
7036           // If we have ((X & C) == C), turn it into ((X & C) != 0).
7037           if (RHS == BOC && RHSV.isPowerOf2())
7038             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7039                                 ICmpInst::ICMP_NE, LHSI,
7040                                 Constant::getNullValue(RHS->getType()));
7041           
7042           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7043           if (BOC->getValue().isSignBit()) {
7044             Value *X = BO->getOperand(0);
7045             Constant *Zero = Constant::getNullValue(X->getType());
7046             ICmpInst::Predicate pred = isICMP_NE ? 
7047               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7048             return new ICmpInst(pred, X, Zero);
7049           }
7050           
7051           // ((X & ~7) == 0) --> X < 8
7052           if (RHSV == 0 && isHighOnes(BOC)) {
7053             Value *X = BO->getOperand(0);
7054             Constant *NegX = ConstantExpr::getNeg(BOC);
7055             ICmpInst::Predicate pred = isICMP_NE ? 
7056               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7057             return new ICmpInst(pred, X, NegX);
7058           }
7059         }
7060       default: break;
7061       }
7062     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7063       // Handle icmp {eq|ne} <intrinsic>, intcst.
7064       if (II->getIntrinsicID() == Intrinsic::bswap) {
7065         AddToWorkList(II);
7066         ICI.setOperand(0, II->getOperand(1));
7067         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
7068         return &ICI;
7069       }
7070     }
7071   }
7072   return 0;
7073 }
7074
7075 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7076 /// We only handle extending casts so far.
7077 ///
7078 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7079   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7080   Value *LHSCIOp        = LHSCI->getOperand(0);
7081   const Type *SrcTy     = LHSCIOp->getType();
7082   const Type *DestTy    = LHSCI->getType();
7083   Value *RHSCIOp;
7084
7085   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
7086   // integer type is the same size as the pointer type.
7087   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7088       getTargetData().getPointerSizeInBits() == 
7089          cast<IntegerType>(DestTy)->getBitWidth()) {
7090     Value *RHSOp = 0;
7091     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7092       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7093     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7094       RHSOp = RHSC->getOperand(0);
7095       // If the pointer types don't match, insert a bitcast.
7096       if (LHSCIOp->getType() != RHSOp->getType())
7097         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7098     }
7099
7100     if (RHSOp)
7101       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7102   }
7103   
7104   // The code below only handles extension cast instructions, so far.
7105   // Enforce this.
7106   if (LHSCI->getOpcode() != Instruction::ZExt &&
7107       LHSCI->getOpcode() != Instruction::SExt)
7108     return 0;
7109
7110   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7111   bool isSignedCmp = ICI.isSignedPredicate();
7112
7113   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7114     // Not an extension from the same type?
7115     RHSCIOp = CI->getOperand(0);
7116     if (RHSCIOp->getType() != LHSCIOp->getType()) 
7117       return 0;
7118     
7119     // If the signedness of the two casts doesn't agree (i.e. one is a sext
7120     // and the other is a zext), then we can't handle this.
7121     if (CI->getOpcode() != LHSCI->getOpcode())
7122       return 0;
7123
7124     // Deal with equality cases early.
7125     if (ICI.isEquality())
7126       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7127
7128     // A signed comparison of sign extended values simplifies into a
7129     // signed comparison.
7130     if (isSignedCmp && isSignedExt)
7131       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7132
7133     // The other three cases all fold into an unsigned comparison.
7134     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7135   }
7136
7137   // If we aren't dealing with a constant on the RHS, exit early
7138   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7139   if (!CI)
7140     return 0;
7141
7142   // Compute the constant that would happen if we truncated to SrcTy then
7143   // reextended to DestTy.
7144   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7145   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
7146
7147   // If the re-extended constant didn't change...
7148   if (Res2 == CI) {
7149     // Make sure that sign of the Cmp and the sign of the Cast are the same.
7150     // For example, we might have:
7151     //    %A = sext short %X to uint
7152     //    %B = icmp ugt uint %A, 1330
7153     // It is incorrect to transform this into 
7154     //    %B = icmp ugt short %X, 1330 
7155     // because %A may have negative value. 
7156     //
7157     // However, we allow this when the compare is EQ/NE, because they are
7158     // signless.
7159     if (isSignedExt == isSignedCmp || ICI.isEquality())
7160       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7161     return 0;
7162   }
7163
7164   // The re-extended constant changed so the constant cannot be represented 
7165   // in the shorter type. Consequently, we cannot emit a simple comparison.
7166
7167   // First, handle some easy cases. We know the result cannot be equal at this
7168   // point so handle the ICI.isEquality() cases
7169   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7170     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
7171   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7172     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
7173
7174   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7175   // should have been folded away previously and not enter in here.
7176   Value *Result;
7177   if (isSignedCmp) {
7178     // We're performing a signed comparison.
7179     if (cast<ConstantInt>(CI)->getValue().isNegative())
7180       Result = ConstantInt::getFalse();          // X < (small) --> false
7181     else
7182       Result = ConstantInt::getTrue();           // X < (large) --> true
7183   } else {
7184     // We're performing an unsigned comparison.
7185     if (isSignedExt) {
7186       // We're performing an unsigned comp with a sign extended value.
7187       // This is true if the input is >= 0. [aka >s -1]
7188       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
7189       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
7190                                    NegOne, ICI.getName()), ICI);
7191     } else {
7192       // Unsigned extend & unsigned compare -> always true.
7193       Result = ConstantInt::getTrue();
7194     }
7195   }
7196
7197   // Finally, return the value computed.
7198   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7199       ICI.getPredicate() == ICmpInst::ICMP_SLT)
7200     return ReplaceInstUsesWith(ICI, Result);
7201
7202   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
7203           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7204          "ICmp should be folded!");
7205   if (Constant *CI = dyn_cast<Constant>(Result))
7206     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7207   return BinaryOperator::CreateNot(Result);
7208 }
7209
7210 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7211   return commonShiftTransforms(I);
7212 }
7213
7214 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7215   return commonShiftTransforms(I);
7216 }
7217
7218 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7219   if (Instruction *R = commonShiftTransforms(I))
7220     return R;
7221   
7222   Value *Op0 = I.getOperand(0);
7223   
7224   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
7225   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7226     if (CSI->isAllOnesValue())
7227       return ReplaceInstUsesWith(I, CSI);
7228   
7229   // See if we can turn a signed shr into an unsigned shr.
7230   if (!isa<VectorType>(I.getType())) {
7231     if (MaskedValueIsZero(Op0,
7232                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
7233       return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7234
7235     // Arithmetic shifting an all-sign-bit value is a no-op.
7236     unsigned NumSignBits = ComputeNumSignBits(Op0);
7237     if (NumSignBits == Op0->getType()->getPrimitiveSizeInBits())
7238       return ReplaceInstUsesWith(I, Op0);
7239   }
7240
7241   return 0;
7242 }
7243
7244 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7245   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7246   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7247
7248   // shl X, 0 == X and shr X, 0 == X
7249   // shl 0, X == 0 and shr 0, X == 0
7250   if (Op1 == Constant::getNullValue(Op1->getType()) ||
7251       Op0 == Constant::getNullValue(Op0->getType()))
7252     return ReplaceInstUsesWith(I, Op0);
7253   
7254   if (isa<UndefValue>(Op0)) {            
7255     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7256       return ReplaceInstUsesWith(I, Op0);
7257     else                                    // undef << X -> 0, undef >>u X -> 0
7258       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7259   }
7260   if (isa<UndefValue>(Op1)) {
7261     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
7262       return ReplaceInstUsesWith(I, Op0);          
7263     else                                     // X << undef, X >>u undef -> 0
7264       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7265   }
7266
7267   // See if we can fold away this shift.
7268   if (!isa<VectorType>(I.getType()) && SimplifyDemandedInstructionBits(I))
7269     return &I;
7270
7271   // Try to fold constant and into select arguments.
7272   if (isa<Constant>(Op0))
7273     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7274       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7275         return R;
7276
7277   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7278     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7279       return Res;
7280   return 0;
7281 }
7282
7283 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7284                                                BinaryOperator &I) {
7285   bool isLeftShift = I.getOpcode() == Instruction::Shl;
7286
7287   // See if we can simplify any instructions used by the instruction whose sole 
7288   // purpose is to compute bits we don't care about.
7289   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7290   
7291   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7292   // of a signed value.
7293   //
7294   if (Op1->uge(TypeBits)) {
7295     if (I.getOpcode() != Instruction::AShr)
7296       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7297     else {
7298       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7299       return &I;
7300     }
7301   }
7302   
7303   // ((X*C1) << C2) == (X * (C1 << C2))
7304   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7305     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7306       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7307         return BinaryOperator::CreateMul(BO->getOperand(0),
7308                                          ConstantExpr::getShl(BOOp, Op1));
7309   
7310   // Try to fold constant and into select arguments.
7311   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7312     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7313       return R;
7314   if (isa<PHINode>(Op0))
7315     if (Instruction *NV = FoldOpIntoPhi(I))
7316       return NV;
7317   
7318   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7319   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7320     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7321     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7322     // place.  Don't try to do this transformation in this case.  Also, we
7323     // require that the input operand is a shift-by-constant so that we have
7324     // confidence that the shifts will get folded together.  We could do this
7325     // xform in more cases, but it is unlikely to be profitable.
7326     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7327         isa<ConstantInt>(TrOp->getOperand(1))) {
7328       // Okay, we'll do this xform.  Make the shift of shift.
7329       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7330       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7331                                                 I.getName());
7332       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7333
7334       // For logical shifts, the truncation has the effect of making the high
7335       // part of the register be zeros.  Emulate this by inserting an AND to
7336       // clear the top bits as needed.  This 'and' will usually be zapped by
7337       // other xforms later if dead.
7338       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7339       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7340       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7341       
7342       // The mask we constructed says what the trunc would do if occurring
7343       // between the shifts.  We want to know the effect *after* the second
7344       // shift.  We know that it is a logical shift by a constant, so adjust the
7345       // mask as appropriate.
7346       if (I.getOpcode() == Instruction::Shl)
7347         MaskV <<= Op1->getZExtValue();
7348       else {
7349         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7350         MaskV = MaskV.lshr(Op1->getZExtValue());
7351       }
7352
7353       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7354                                                    TI->getName());
7355       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7356
7357       // Return the value truncated to the interesting size.
7358       return new TruncInst(And, I.getType());
7359     }
7360   }
7361   
7362   if (Op0->hasOneUse()) {
7363     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7364       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7365       Value *V1, *V2;
7366       ConstantInt *CC;
7367       switch (Op0BO->getOpcode()) {
7368         default: break;
7369         case Instruction::Add:
7370         case Instruction::And:
7371         case Instruction::Or:
7372         case Instruction::Xor: {
7373           // These operators commute.
7374           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7375           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7376               match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7377             Instruction *YS = BinaryOperator::CreateShl(
7378                                             Op0BO->getOperand(0), Op1,
7379                                             Op0BO->getName());
7380             InsertNewInstBefore(YS, I); // (Y << C)
7381             Instruction *X = 
7382               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7383                                      Op0BO->getOperand(1)->getName());
7384             InsertNewInstBefore(X, I);  // (X + (Y << C))
7385             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7386             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7387                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7388           }
7389           
7390           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7391           Value *Op0BOOp1 = Op0BO->getOperand(1);
7392           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7393               match(Op0BOOp1, 
7394                     m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7395                           m_ConstantInt(CC))) &&
7396               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7397             Instruction *YS = BinaryOperator::CreateShl(
7398                                                      Op0BO->getOperand(0), Op1,
7399                                                      Op0BO->getName());
7400             InsertNewInstBefore(YS, I); // (Y << C)
7401             Instruction *XM =
7402               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7403                                         V1->getName()+".mask");
7404             InsertNewInstBefore(XM, I); // X & (CC << C)
7405             
7406             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7407           }
7408         }
7409           
7410         // FALL THROUGH.
7411         case Instruction::Sub: {
7412           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7413           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7414               match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7415             Instruction *YS = BinaryOperator::CreateShl(
7416                                                      Op0BO->getOperand(1), Op1,
7417                                                      Op0BO->getName());
7418             InsertNewInstBefore(YS, I); // (Y << C)
7419             Instruction *X =
7420               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7421                                      Op0BO->getOperand(0)->getName());
7422             InsertNewInstBefore(X, I);  // (X + (Y << C))
7423             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7424             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7425                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7426           }
7427           
7428           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7429           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7430               match(Op0BO->getOperand(0),
7431                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7432                           m_ConstantInt(CC))) && V2 == Op1 &&
7433               cast<BinaryOperator>(Op0BO->getOperand(0))
7434                   ->getOperand(0)->hasOneUse()) {
7435             Instruction *YS = BinaryOperator::CreateShl(
7436                                                      Op0BO->getOperand(1), Op1,
7437                                                      Op0BO->getName());
7438             InsertNewInstBefore(YS, I); // (Y << C)
7439             Instruction *XM =
7440               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7441                                         V1->getName()+".mask");
7442             InsertNewInstBefore(XM, I); // X & (CC << C)
7443             
7444             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7445           }
7446           
7447           break;
7448         }
7449       }
7450       
7451       
7452       // If the operand is an bitwise operator with a constant RHS, and the
7453       // shift is the only use, we can pull it out of the shift.
7454       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7455         bool isValid = true;     // Valid only for And, Or, Xor
7456         bool highBitSet = false; // Transform if high bit of constant set?
7457         
7458         switch (Op0BO->getOpcode()) {
7459           default: isValid = false; break;   // Do not perform transform!
7460           case Instruction::Add:
7461             isValid = isLeftShift;
7462             break;
7463           case Instruction::Or:
7464           case Instruction::Xor:
7465             highBitSet = false;
7466             break;
7467           case Instruction::And:
7468             highBitSet = true;
7469             break;
7470         }
7471         
7472         // If this is a signed shift right, and the high bit is modified
7473         // by the logical operation, do not perform the transformation.
7474         // The highBitSet boolean indicates the value of the high bit of
7475         // the constant which would cause it to be modified for this
7476         // operation.
7477         //
7478         if (isValid && I.getOpcode() == Instruction::AShr)
7479           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7480         
7481         if (isValid) {
7482           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7483           
7484           Instruction *NewShift =
7485             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7486           InsertNewInstBefore(NewShift, I);
7487           NewShift->takeName(Op0BO);
7488           
7489           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7490                                         NewRHS);
7491         }
7492       }
7493     }
7494   }
7495   
7496   // Find out if this is a shift of a shift by a constant.
7497   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7498   if (ShiftOp && !ShiftOp->isShift())
7499     ShiftOp = 0;
7500   
7501   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7502     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7503     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7504     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7505     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7506     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7507     Value *X = ShiftOp->getOperand(0);
7508     
7509     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7510     
7511     const IntegerType *Ty = cast<IntegerType>(I.getType());
7512     
7513     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7514     if (I.getOpcode() == ShiftOp->getOpcode()) {
7515       // If this is oversized composite shift, then unsigned shifts get 0, ashr
7516       // saturates.
7517       if (AmtSum >= TypeBits) {
7518         if (I.getOpcode() != Instruction::AShr)
7519           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7520         AmtSum = TypeBits-1;  // Saturate to 31 for i32 ashr.
7521       }
7522       
7523       return BinaryOperator::Create(I.getOpcode(), X,
7524                                     ConstantInt::get(Ty, AmtSum));
7525     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7526                I.getOpcode() == Instruction::AShr) {
7527       if (AmtSum >= TypeBits)
7528         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7529       
7530       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7531       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7532     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7533                I.getOpcode() == Instruction::LShr) {
7534       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7535       if (AmtSum >= TypeBits)
7536         AmtSum = TypeBits-1;
7537       
7538       Instruction *Shift =
7539         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7540       InsertNewInstBefore(Shift, I);
7541
7542       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7543       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7544     }
7545     
7546     // Okay, if we get here, one shift must be left, and the other shift must be
7547     // right.  See if the amounts are equal.
7548     if (ShiftAmt1 == ShiftAmt2) {
7549       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7550       if (I.getOpcode() == Instruction::Shl) {
7551         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7552         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7553       }
7554       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7555       if (I.getOpcode() == Instruction::LShr) {
7556         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7557         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7558       }
7559       // We can simplify ((X << C) >>s C) into a trunc + sext.
7560       // NOTE: we could do this for any C, but that would make 'unusual' integer
7561       // types.  For now, just stick to ones well-supported by the code
7562       // generators.
7563       const Type *SExtType = 0;
7564       switch (Ty->getBitWidth() - ShiftAmt1) {
7565       case 1  :
7566       case 8  :
7567       case 16 :
7568       case 32 :
7569       case 64 :
7570       case 128:
7571         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7572         break;
7573       default: break;
7574       }
7575       if (SExtType) {
7576         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7577         InsertNewInstBefore(NewTrunc, I);
7578         return new SExtInst(NewTrunc, Ty);
7579       }
7580       // Otherwise, we can't handle it yet.
7581     } else if (ShiftAmt1 < ShiftAmt2) {
7582       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7583       
7584       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7585       if (I.getOpcode() == Instruction::Shl) {
7586         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7587                ShiftOp->getOpcode() == Instruction::AShr);
7588         Instruction *Shift =
7589           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7590         InsertNewInstBefore(Shift, I);
7591         
7592         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7593         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7594       }
7595       
7596       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7597       if (I.getOpcode() == Instruction::LShr) {
7598         assert(ShiftOp->getOpcode() == Instruction::Shl);
7599         Instruction *Shift =
7600           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7601         InsertNewInstBefore(Shift, I);
7602         
7603         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7604         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7605       }
7606       
7607       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7608     } else {
7609       assert(ShiftAmt2 < ShiftAmt1);
7610       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7611
7612       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7613       if (I.getOpcode() == Instruction::Shl) {
7614         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7615                ShiftOp->getOpcode() == Instruction::AShr);
7616         Instruction *Shift =
7617           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7618                                  ConstantInt::get(Ty, ShiftDiff));
7619         InsertNewInstBefore(Shift, I);
7620         
7621         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7622         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7623       }
7624       
7625       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7626       if (I.getOpcode() == Instruction::LShr) {
7627         assert(ShiftOp->getOpcode() == Instruction::Shl);
7628         Instruction *Shift =
7629           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7630         InsertNewInstBefore(Shift, I);
7631         
7632         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7633         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7634       }
7635       
7636       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7637     }
7638   }
7639   return 0;
7640 }
7641
7642
7643 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7644 /// expression.  If so, decompose it, returning some value X, such that Val is
7645 /// X*Scale+Offset.
7646 ///
7647 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7648                                         int &Offset) {
7649   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7650   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7651     Offset = CI->getZExtValue();
7652     Scale  = 0;
7653     return ConstantInt::get(Type::Int32Ty, 0);
7654   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7655     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7656       if (I->getOpcode() == Instruction::Shl) {
7657         // This is a value scaled by '1 << the shift amt'.
7658         Scale = 1U << RHS->getZExtValue();
7659         Offset = 0;
7660         return I->getOperand(0);
7661       } else if (I->getOpcode() == Instruction::Mul) {
7662         // This value is scaled by 'RHS'.
7663         Scale = RHS->getZExtValue();
7664         Offset = 0;
7665         return I->getOperand(0);
7666       } else if (I->getOpcode() == Instruction::Add) {
7667         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7668         // where C1 is divisible by C2.
7669         unsigned SubScale;
7670         Value *SubVal = 
7671           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7672         Offset += RHS->getZExtValue();
7673         Scale = SubScale;
7674         return SubVal;
7675       }
7676     }
7677   }
7678
7679   // Otherwise, we can't look past this.
7680   Scale = 1;
7681   Offset = 0;
7682   return Val;
7683 }
7684
7685
7686 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7687 /// try to eliminate the cast by moving the type information into the alloc.
7688 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7689                                                    AllocationInst &AI) {
7690   const PointerType *PTy = cast<PointerType>(CI.getType());
7691   
7692   // Remove any uses of AI that are dead.
7693   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7694   
7695   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7696     Instruction *User = cast<Instruction>(*UI++);
7697     if (isInstructionTriviallyDead(User)) {
7698       while (UI != E && *UI == User)
7699         ++UI; // If this instruction uses AI more than once, don't break UI.
7700       
7701       ++NumDeadInst;
7702       DOUT << "IC: DCE: " << *User;
7703       EraseInstFromFunction(*User);
7704     }
7705   }
7706   
7707   // Get the type really allocated and the type casted to.
7708   const Type *AllocElTy = AI.getAllocatedType();
7709   const Type *CastElTy = PTy->getElementType();
7710   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7711
7712   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7713   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7714   if (CastElTyAlign < AllocElTyAlign) return 0;
7715
7716   // If the allocation has multiple uses, only promote it if we are strictly
7717   // increasing the alignment of the resultant allocation.  If we keep it the
7718   // same, we open the door to infinite loops of various kinds.  (A reference
7719   // from a dbg.declare doesn't count as a use for this purpose.)
7720   if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7721       CastElTyAlign == AllocElTyAlign) return 0;
7722
7723   uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7724   uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7725   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7726
7727   // See if we can satisfy the modulus by pulling a scale out of the array
7728   // size argument.
7729   unsigned ArraySizeScale;
7730   int ArrayOffset;
7731   Value *NumElements = // See if the array size is a decomposable linear expr.
7732     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7733  
7734   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7735   // do the xform.
7736   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7737       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7738
7739   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7740   Value *Amt = 0;
7741   if (Scale == 1) {
7742     Amt = NumElements;
7743   } else {
7744     // If the allocation size is constant, form a constant mul expression
7745     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7746     if (isa<ConstantInt>(NumElements))
7747       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7748     // otherwise multiply the amount and the number of elements
7749     else {
7750       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7751       Amt = InsertNewInstBefore(Tmp, AI);
7752     }
7753   }
7754   
7755   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7756     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7757     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7758     Amt = InsertNewInstBefore(Tmp, AI);
7759   }
7760   
7761   AllocationInst *New;
7762   if (isa<MallocInst>(AI))
7763     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7764   else
7765     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7766   InsertNewInstBefore(New, AI);
7767   New->takeName(&AI);
7768   
7769   // If the allocation has one real use plus a dbg.declare, just remove the
7770   // declare.
7771   if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7772     EraseInstFromFunction(*DI);
7773   }
7774   // If the allocation has multiple real uses, insert a cast and change all
7775   // things that used it to use the new cast.  This will also hack on CI, but it
7776   // will die soon.
7777   else if (!AI.hasOneUse()) {
7778     AddUsesToWorkList(AI);
7779     // New is the allocation instruction, pointer typed. AI is the original
7780     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7781     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7782     InsertNewInstBefore(NewCast, AI);
7783     AI.replaceAllUsesWith(NewCast);
7784   }
7785   return ReplaceInstUsesWith(CI, New);
7786 }
7787
7788 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7789 /// and return it as type Ty without inserting any new casts and without
7790 /// changing the computed value.  This is used by code that tries to decide
7791 /// whether promoting or shrinking integer operations to wider or smaller types
7792 /// will allow us to eliminate a truncate or extend.
7793 ///
7794 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7795 /// extension operation if Ty is larger.
7796 ///
7797 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7798 /// should return true if trunc(V) can be computed by computing V in the smaller
7799 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7800 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7801 /// efficiently truncated.
7802 ///
7803 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7804 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7805 /// the final result.
7806 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7807                                               unsigned CastOpc,
7808                                               int &NumCastsRemoved){
7809   // We can always evaluate constants in another type.
7810   if (isa<ConstantInt>(V))
7811     return true;
7812   
7813   Instruction *I = dyn_cast<Instruction>(V);
7814   if (!I) return false;
7815   
7816   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7817   
7818   // If this is an extension or truncate, we can often eliminate it.
7819   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7820     // If this is a cast from the destination type, we can trivially eliminate
7821     // it, and this will remove a cast overall.
7822     if (I->getOperand(0)->getType() == Ty) {
7823       // If the first operand is itself a cast, and is eliminable, do not count
7824       // this as an eliminable cast.  We would prefer to eliminate those two
7825       // casts first.
7826       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7827         ++NumCastsRemoved;
7828       return true;
7829     }
7830   }
7831
7832   // We can't extend or shrink something that has multiple uses: doing so would
7833   // require duplicating the instruction in general, which isn't profitable.
7834   if (!I->hasOneUse()) return false;
7835
7836   unsigned Opc = I->getOpcode();
7837   switch (Opc) {
7838   case Instruction::Add:
7839   case Instruction::Sub:
7840   case Instruction::Mul:
7841   case Instruction::And:
7842   case Instruction::Or:
7843   case Instruction::Xor:
7844     // These operators can all arbitrarily be extended or truncated.
7845     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7846                                       NumCastsRemoved) &&
7847            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7848                                       NumCastsRemoved);
7849
7850   case Instruction::Shl:
7851     // If we are truncating the result of this SHL, and if it's a shift of a
7852     // constant amount, we can always perform a SHL in a smaller type.
7853     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7854       uint32_t BitWidth = Ty->getBitWidth();
7855       if (BitWidth < OrigTy->getBitWidth() && 
7856           CI->getLimitedValue(BitWidth) < BitWidth)
7857         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7858                                           NumCastsRemoved);
7859     }
7860     break;
7861   case Instruction::LShr:
7862     // If this is a truncate of a logical shr, we can truncate it to a smaller
7863     // lshr iff we know that the bits we would otherwise be shifting in are
7864     // already zeros.
7865     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7866       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7867       uint32_t BitWidth = Ty->getBitWidth();
7868       if (BitWidth < OrigBitWidth &&
7869           MaskedValueIsZero(I->getOperand(0),
7870             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7871           CI->getLimitedValue(BitWidth) < BitWidth) {
7872         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7873                                           NumCastsRemoved);
7874       }
7875     }
7876     break;
7877   case Instruction::ZExt:
7878   case Instruction::SExt:
7879   case Instruction::Trunc:
7880     // If this is the same kind of case as our original (e.g. zext+zext), we
7881     // can safely replace it.  Note that replacing it does not reduce the number
7882     // of casts in the input.
7883     if (Opc == CastOpc)
7884       return true;
7885
7886     // sext (zext ty1), ty2 -> zext ty2
7887     if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7888       return true;
7889     break;
7890   case Instruction::Select: {
7891     SelectInst *SI = cast<SelectInst>(I);
7892     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7893                                       NumCastsRemoved) &&
7894            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7895                                       NumCastsRemoved);
7896   }
7897   case Instruction::PHI: {
7898     // We can change a phi if we can change all operands.
7899     PHINode *PN = cast<PHINode>(I);
7900     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7901       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7902                                       NumCastsRemoved))
7903         return false;
7904     return true;
7905   }
7906   default:
7907     // TODO: Can handle more cases here.
7908     break;
7909   }
7910   
7911   return false;
7912 }
7913
7914 /// EvaluateInDifferentType - Given an expression that 
7915 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7916 /// evaluate the expression.
7917 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7918                                              bool isSigned) {
7919   if (Constant *C = dyn_cast<Constant>(V))
7920     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7921
7922   // Otherwise, it must be an instruction.
7923   Instruction *I = cast<Instruction>(V);
7924   Instruction *Res = 0;
7925   unsigned Opc = I->getOpcode();
7926   switch (Opc) {
7927   case Instruction::Add:
7928   case Instruction::Sub:
7929   case Instruction::Mul:
7930   case Instruction::And:
7931   case Instruction::Or:
7932   case Instruction::Xor:
7933   case Instruction::AShr:
7934   case Instruction::LShr:
7935   case Instruction::Shl: {
7936     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7937     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7938     Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7939     break;
7940   }    
7941   case Instruction::Trunc:
7942   case Instruction::ZExt:
7943   case Instruction::SExt:
7944     // If the source type of the cast is the type we're trying for then we can
7945     // just return the source.  There's no need to insert it because it is not
7946     // new.
7947     if (I->getOperand(0)->getType() == Ty)
7948       return I->getOperand(0);
7949     
7950     // Otherwise, must be the same type of cast, so just reinsert a new one.
7951     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7952                            Ty);
7953     break;
7954   case Instruction::Select: {
7955     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7956     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7957     Res = SelectInst::Create(I->getOperand(0), True, False);
7958     break;
7959   }
7960   case Instruction::PHI: {
7961     PHINode *OPN = cast<PHINode>(I);
7962     PHINode *NPN = PHINode::Create(Ty);
7963     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7964       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7965       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7966     }
7967     Res = NPN;
7968     break;
7969   }
7970   default: 
7971     // TODO: Can handle more cases here.
7972     assert(0 && "Unreachable!");
7973     break;
7974   }
7975   
7976   Res->takeName(I);
7977   return InsertNewInstBefore(Res, *I);
7978 }
7979
7980 /// @brief Implement the transforms common to all CastInst visitors.
7981 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7982   Value *Src = CI.getOperand(0);
7983
7984   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7985   // eliminate it now.
7986   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7987     if (Instruction::CastOps opc = 
7988         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7989       // The first cast (CSrc) is eliminable so we need to fix up or replace
7990       // the second cast (CI). CSrc will then have a good chance of being dead.
7991       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7992     }
7993   }
7994
7995   // If we are casting a select then fold the cast into the select
7996   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7997     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7998       return NV;
7999
8000   // If we are casting a PHI then fold the cast into the PHI
8001   if (isa<PHINode>(Src))
8002     if (Instruction *NV = FoldOpIntoPhi(CI))
8003       return NV;
8004   
8005   return 0;
8006 }
8007
8008 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8009 /// or not there is a sequence of GEP indices into the type that will land us at
8010 /// the specified offset.  If so, fill them into NewIndices and return the
8011 /// resultant element type, otherwise return null.
8012 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
8013                                        SmallVectorImpl<Value*> &NewIndices,
8014                                        const TargetData *TD) {
8015   if (!Ty->isSized()) return 0;
8016   
8017   // Start with the index over the outer type.  Note that the type size
8018   // might be zero (even if the offset isn't zero) if the indexed type
8019   // is something like [0 x {int, int}]
8020   const Type *IntPtrTy = TD->getIntPtrType();
8021   int64_t FirstIdx = 0;
8022   if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8023     FirstIdx = Offset/TySize;
8024     Offset -= FirstIdx*TySize;
8025     
8026     // Handle hosts where % returns negative instead of values [0..TySize).
8027     if (Offset < 0) {
8028       --FirstIdx;
8029       Offset += TySize;
8030       assert(Offset >= 0);
8031     }
8032     assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8033   }
8034   
8035   NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8036     
8037   // Index into the types.  If we fail, set OrigBase to null.
8038   while (Offset) {
8039     // Indexing into tail padding between struct/array elements.
8040     if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8041       return 0;
8042     
8043     if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8044       const StructLayout *SL = TD->getStructLayout(STy);
8045       assert(Offset < (int64_t)SL->getSizeInBytes() &&
8046              "Offset must stay within the indexed type");
8047       
8048       unsigned Elt = SL->getElementContainingOffset(Offset);
8049       NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
8050       
8051       Offset -= SL->getElementOffset(Elt);
8052       Ty = STy->getElementType(Elt);
8053     } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8054       uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8055       assert(EltSize && "Cannot index into a zero-sized array");
8056       NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8057       Offset %= EltSize;
8058       Ty = AT->getElementType();
8059     } else {
8060       // Otherwise, we can't index into the middle of this atomic type, bail.
8061       return 0;
8062     }
8063   }
8064   
8065   return Ty;
8066 }
8067
8068 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8069 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8070   Value *Src = CI.getOperand(0);
8071   
8072   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8073     // If casting the result of a getelementptr instruction with no offset, turn
8074     // this into a cast of the original pointer!
8075     if (GEP->hasAllZeroIndices()) {
8076       // Changing the cast operand is usually not a good idea but it is safe
8077       // here because the pointer operand is being replaced with another 
8078       // pointer operand so the opcode doesn't need to change.
8079       AddToWorkList(GEP);
8080       CI.setOperand(0, GEP->getOperand(0));
8081       return &CI;
8082     }
8083     
8084     // If the GEP has a single use, and the base pointer is a bitcast, and the
8085     // GEP computes a constant offset, see if we can convert these three
8086     // instructions into fewer.  This typically happens with unions and other
8087     // non-type-safe code.
8088     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8089       if (GEP->hasAllConstantIndices()) {
8090         // We are guaranteed to get a constant from EmitGEPOffset.
8091         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8092         int64_t Offset = OffsetV->getSExtValue();
8093         
8094         // Get the base pointer input of the bitcast, and the type it points to.
8095         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8096         const Type *GEPIdxTy =
8097           cast<PointerType>(OrigBase->getType())->getElementType();
8098         SmallVector<Value*, 8> NewIndices;
8099         if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
8100           // If we were able to index down into an element, create the GEP
8101           // and bitcast the result.  This eliminates one bitcast, potentially
8102           // two.
8103           Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
8104                                                         NewIndices.begin(),
8105                                                         NewIndices.end(), "");
8106           InsertNewInstBefore(NGEP, CI);
8107           NGEP->takeName(GEP);
8108           
8109           if (isa<BitCastInst>(CI))
8110             return new BitCastInst(NGEP, CI.getType());
8111           assert(isa<PtrToIntInst>(CI));
8112           return new PtrToIntInst(NGEP, CI.getType());
8113         }
8114       }      
8115     }
8116   }
8117     
8118   return commonCastTransforms(CI);
8119 }
8120
8121 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8122 /// type like i42.  We don't want to introduce operations on random non-legal
8123 /// integer types where they don't already exist in the code.  In the future,
8124 /// we should consider making this based off target-data, so that 32-bit targets
8125 /// won't get i64 operations etc.
8126 static bool isSafeIntegerType(const Type *Ty) {
8127   switch (Ty->getPrimitiveSizeInBits()) {
8128   case 8:
8129   case 16:
8130   case 32:
8131   case 64:
8132     return true;
8133   default: 
8134     return false;
8135   }
8136 }
8137
8138 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8139 /// integer types. This function implements the common transforms for all those
8140 /// cases.
8141 /// @brief Implement the transforms common to CastInst with integer operands
8142 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8143   if (Instruction *Result = commonCastTransforms(CI))
8144     return Result;
8145
8146   Value *Src = CI.getOperand(0);
8147   const Type *SrcTy = Src->getType();
8148   const Type *DestTy = CI.getType();
8149   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
8150   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
8151
8152   // See if we can simplify any instructions used by the LHS whose sole 
8153   // purpose is to compute bits we don't care about.
8154   if (SimplifyDemandedInstructionBits(CI))
8155     return &CI;
8156
8157   // If the source isn't an instruction or has more than one use then we
8158   // can't do anything more. 
8159   Instruction *SrcI = dyn_cast<Instruction>(Src);
8160   if (!SrcI || !Src->hasOneUse())
8161     return 0;
8162
8163   // Attempt to propagate the cast into the instruction for int->int casts.
8164   int NumCastsRemoved = 0;
8165   if (!isa<BitCastInst>(CI) &&
8166       // Only do this if the dest type is a simple type, don't convert the
8167       // expression tree to something weird like i93 unless the source is also
8168       // strange.
8169       (isSafeIntegerType(DestTy) || !isSafeIntegerType(SrcI->getType())) &&
8170       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
8171                                  CI.getOpcode(), NumCastsRemoved)) {
8172     // If this cast is a truncate, evaluting in a different type always
8173     // eliminates the cast, so it is always a win.  If this is a zero-extension,
8174     // we need to do an AND to maintain the clear top-part of the computation,
8175     // so we require that the input have eliminated at least one cast.  If this
8176     // is a sign extension, we insert two new casts (to do the extension) so we
8177     // require that two casts have been eliminated.
8178     bool DoXForm = false;
8179     bool JustReplace = false;
8180     switch (CI.getOpcode()) {
8181     default:
8182       // All the others use floating point so we shouldn't actually 
8183       // get here because of the check above.
8184       assert(0 && "Unknown cast type");
8185     case Instruction::Trunc:
8186       DoXForm = true;
8187       break;
8188     case Instruction::ZExt: {
8189       DoXForm = NumCastsRemoved >= 1;
8190       if (!DoXForm && 0) {
8191         // If it's unnecessary to issue an AND to clear the high bits, it's
8192         // always profitable to do this xform.
8193         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8194         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8195         if (MaskedValueIsZero(TryRes, Mask))
8196           return ReplaceInstUsesWith(CI, TryRes);
8197         
8198         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8199           if (TryI->use_empty())
8200             EraseInstFromFunction(*TryI);
8201       }
8202       break;
8203     }
8204     case Instruction::SExt: {
8205       DoXForm = NumCastsRemoved >= 2;
8206       if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8207         // If we do not have to emit the truncate + sext pair, then it's always
8208         // profitable to do this xform.
8209         //
8210         // It's not safe to eliminate the trunc + sext pair if one of the
8211         // eliminated cast is a truncate. e.g.
8212         // t2 = trunc i32 t1 to i16
8213         // t3 = sext i16 t2 to i32
8214         // !=
8215         // i32 t1
8216         Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8217         unsigned NumSignBits = ComputeNumSignBits(TryRes);
8218         if (NumSignBits > (DestBitSize - SrcBitSize))
8219           return ReplaceInstUsesWith(CI, TryRes);
8220         
8221         if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8222           if (TryI->use_empty())
8223             EraseInstFromFunction(*TryI);
8224       }
8225       break;
8226     }
8227     }
8228     
8229     if (DoXForm) {
8230       DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8231            << " cast: " << CI;
8232       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
8233                                            CI.getOpcode() == Instruction::SExt);
8234       if (JustReplace)
8235         // Just replace this cast with the result.
8236         return ReplaceInstUsesWith(CI, Res);
8237
8238       assert(Res->getType() == DestTy);
8239       switch (CI.getOpcode()) {
8240       default: assert(0 && "Unknown cast type!");
8241       case Instruction::Trunc:
8242       case Instruction::BitCast:
8243         // Just replace this cast with the result.
8244         return ReplaceInstUsesWith(CI, Res);
8245       case Instruction::ZExt: {
8246         assert(SrcBitSize < DestBitSize && "Not a zext?");
8247
8248         // If the high bits are already zero, just replace this cast with the
8249         // result.
8250         APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8251         if (MaskedValueIsZero(Res, Mask))
8252           return ReplaceInstUsesWith(CI, Res);
8253
8254         // We need to emit an AND to clear the high bits.
8255         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
8256                                                             SrcBitSize));
8257         return BinaryOperator::CreateAnd(Res, C);
8258       }
8259       case Instruction::SExt: {
8260         // If the high bits are already filled with sign bit, just replace this
8261         // cast with the result.
8262         unsigned NumSignBits = ComputeNumSignBits(Res);
8263         if (NumSignBits > (DestBitSize - SrcBitSize))
8264           return ReplaceInstUsesWith(CI, Res);
8265
8266         // We need to emit a cast to truncate, then a cast to sext.
8267         return CastInst::Create(Instruction::SExt,
8268             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
8269                              CI), DestTy);
8270       }
8271       }
8272     }
8273   }
8274   
8275   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8276   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8277
8278   switch (SrcI->getOpcode()) {
8279   case Instruction::Add:
8280   case Instruction::Mul:
8281   case Instruction::And:
8282   case Instruction::Or:
8283   case Instruction::Xor:
8284     // If we are discarding information, rewrite.
8285     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8286       // Don't insert two casts if they cannot be eliminated.  We allow 
8287       // two casts to be inserted if the sizes are the same.  This could 
8288       // only be converting signedness, which is a noop.
8289       if (DestBitSize == SrcBitSize || 
8290           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8291           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8292         Instruction::CastOps opcode = CI.getOpcode();
8293         Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8294         Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8295         return BinaryOperator::Create(
8296             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8297       }
8298     }
8299
8300     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
8301     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
8302         SrcI->getOpcode() == Instruction::Xor &&
8303         Op1 == ConstantInt::getTrue() &&
8304         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8305       Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8306       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
8307     }
8308     break;
8309   case Instruction::SDiv:
8310   case Instruction::UDiv:
8311   case Instruction::SRem:
8312   case Instruction::URem:
8313     // If we are just changing the sign, rewrite.
8314     if (DestBitSize == SrcBitSize) {
8315       // Don't insert two casts if they cannot be eliminated.  We allow 
8316       // two casts to be inserted if the sizes are the same.  This could 
8317       // only be converting signedness, which is a noop.
8318       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
8319           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8320         Value *Op0c = InsertCastBefore(Instruction::BitCast, 
8321                                        Op0, DestTy, *SrcI);
8322         Value *Op1c = InsertCastBefore(Instruction::BitCast, 
8323                                        Op1, DestTy, *SrcI);
8324         return BinaryOperator::Create(
8325           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8326       }
8327     }
8328     break;
8329
8330   case Instruction::Shl:
8331     // Allow changing the sign of the source operand.  Do not allow 
8332     // changing the size of the shift, UNLESS the shift amount is a 
8333     // constant.  We must not change variable sized shifts to a smaller 
8334     // size, because it is undefined to shift more bits out than exist 
8335     // in the value.
8336     if (DestBitSize == SrcBitSize ||
8337         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8338       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8339           Instruction::BitCast : Instruction::Trunc);
8340       Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8341       Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8342       return BinaryOperator::CreateShl(Op0c, Op1c);
8343     }
8344     break;
8345   case Instruction::AShr:
8346     // If this is a signed shr, and if all bits shifted in are about to be
8347     // truncated off, turn it into an unsigned shr to allow greater
8348     // simplifications.
8349     if (DestBitSize < SrcBitSize &&
8350         isa<ConstantInt>(Op1)) {
8351       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8352       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8353         // Insert the new logical shift right.
8354         return BinaryOperator::CreateLShr(Op0, Op1);
8355       }
8356     }
8357     break;
8358   }
8359   return 0;
8360 }
8361
8362 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8363   if (Instruction *Result = commonIntCastTransforms(CI))
8364     return Result;
8365   
8366   Value *Src = CI.getOperand(0);
8367   const Type *Ty = CI.getType();
8368   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8369   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8370
8371   // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8372   if (DestBitWidth == 1) {
8373     Constant *One = ConstantInt::get(Src->getType(), 1);
8374     Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8375     Value *Zero = Constant::getNullValue(Src->getType());
8376     return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8377   }
8378   
8379   // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8380   ConstantInt *ShAmtV = 0;
8381   Value *ShiftOp = 0;
8382   if (Src->hasOneUse() &&
8383       match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8384     uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8385     
8386     // Get a mask for the bits shifting in.
8387     APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8388     if (MaskedValueIsZero(ShiftOp, Mask)) {
8389       if (ShAmt >= DestBitWidth)        // All zeros.
8390         return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8391       
8392       // Okay, we can shrink this.  Truncate the input, then return a new
8393       // shift.
8394       Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8395       Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8396       return BinaryOperator::CreateLShr(V1, V2);
8397     }
8398   }
8399   
8400   return 0;
8401 }
8402
8403 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8404 /// in order to eliminate the icmp.
8405 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8406                                              bool DoXform) {
8407   // If we are just checking for a icmp eq of a single bit and zext'ing it
8408   // to an integer, then shift the bit to the appropriate place and then
8409   // cast to integer to avoid the comparison.
8410   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8411     const APInt &Op1CV = Op1C->getValue();
8412       
8413     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8414     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8415     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8416         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8417       if (!DoXform) return ICI;
8418
8419       Value *In = ICI->getOperand(0);
8420       Value *Sh = ConstantInt::get(In->getType(),
8421                                    In->getType()->getPrimitiveSizeInBits()-1);
8422       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8423                                                         In->getName()+".lobit"),
8424                                CI);
8425       if (In->getType() != CI.getType())
8426         In = CastInst::CreateIntegerCast(In, CI.getType(),
8427                                          false/*ZExt*/, "tmp", &CI);
8428
8429       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8430         Constant *One = ConstantInt::get(In->getType(), 1);
8431         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8432                                                          In->getName()+".not"),
8433                                  CI);
8434       }
8435
8436       return ReplaceInstUsesWith(CI, In);
8437     }
8438       
8439       
8440       
8441     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8442     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8443     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8444     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8445     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8446     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8447     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8448     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8449     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8450         // This only works for EQ and NE
8451         ICI->isEquality()) {
8452       // If Op1C some other power of two, convert:
8453       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8454       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8455       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8456       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8457         
8458       APInt KnownZeroMask(~KnownZero);
8459       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8460         if (!DoXform) return ICI;
8461
8462         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8463         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8464           // (X&4) == 2 --> false
8465           // (X&4) != 2 --> true
8466           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8467           Res = ConstantExpr::getZExt(Res, CI.getType());
8468           return ReplaceInstUsesWith(CI, Res);
8469         }
8470           
8471         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8472         Value *In = ICI->getOperand(0);
8473         if (ShiftAmt) {
8474           // Perform a logical shr by shiftamt.
8475           // Insert the shift to put the result in the low bit.
8476           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8477                                   ConstantInt::get(In->getType(), ShiftAmt),
8478                                                    In->getName()+".lobit"), CI);
8479         }
8480           
8481         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8482           Constant *One = ConstantInt::get(In->getType(), 1);
8483           In = BinaryOperator::CreateXor(In, One, "tmp");
8484           InsertNewInstBefore(cast<Instruction>(In), CI);
8485         }
8486           
8487         if (CI.getType() == In->getType())
8488           return ReplaceInstUsesWith(CI, In);
8489         else
8490           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8491       }
8492     }
8493   }
8494
8495   return 0;
8496 }
8497
8498 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8499   // If one of the common conversion will work ..
8500   if (Instruction *Result = commonIntCastTransforms(CI))
8501     return Result;
8502
8503   Value *Src = CI.getOperand(0);
8504
8505   // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8506   // types and if the sizes are just right we can convert this into a logical
8507   // 'and' which will be much cheaper than the pair of casts.
8508   if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) {   // A->B->C cast
8509     // Get the sizes of the types involved.  We know that the intermediate type
8510     // will be smaller than A or C, but don't know the relation between A and C.
8511     Value *A = CSrc->getOperand(0);
8512     unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
8513     unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8514     unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8515     // If we're actually extending zero bits, then if
8516     // SrcSize <  DstSize: zext(a & mask)
8517     // SrcSize == DstSize: a & mask
8518     // SrcSize  > DstSize: trunc(a) & mask
8519     if (SrcSize < DstSize) {
8520       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8521       Constant *AndConst = ConstantInt::get(AndValue);
8522       Instruction *And =
8523         BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8524       InsertNewInstBefore(And, CI);
8525       return new ZExtInst(And, CI.getType());
8526     } else if (SrcSize == DstSize) {
8527       APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8528       return BinaryOperator::CreateAnd(A, ConstantInt::get(AndValue));
8529     } else if (SrcSize > DstSize) {
8530       Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8531       InsertNewInstBefore(Trunc, CI);
8532       APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8533       return BinaryOperator::CreateAnd(Trunc, ConstantInt::get(AndValue));
8534     }
8535   }
8536
8537   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8538     return transformZExtICmp(ICI, CI);
8539
8540   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8541   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8542     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8543     // of the (zext icmp) will be transformed.
8544     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8545     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8546     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8547         (transformZExtICmp(LHS, CI, false) ||
8548          transformZExtICmp(RHS, CI, false))) {
8549       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8550       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8551       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8552     }
8553   }
8554
8555   return 0;
8556 }
8557
8558 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8559   if (Instruction *I = commonIntCastTransforms(CI))
8560     return I;
8561   
8562   Value *Src = CI.getOperand(0);
8563   
8564   // Canonicalize sign-extend from i1 to a select.
8565   if (Src->getType() == Type::Int1Ty)
8566     return SelectInst::Create(Src,
8567                               ConstantInt::getAllOnesValue(CI.getType()),
8568                               Constant::getNullValue(CI.getType()));
8569
8570   // See if the value being truncated is already sign extended.  If so, just
8571   // eliminate the trunc/sext pair.
8572   if (getOpcode(Src) == Instruction::Trunc) {
8573     Value *Op = cast<User>(Src)->getOperand(0);
8574     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8575     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8576     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8577     unsigned NumSignBits = ComputeNumSignBits(Op);
8578
8579     if (OpBits == DestBits) {
8580       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8581       // bits, it is already ready.
8582       if (NumSignBits > DestBits-MidBits)
8583         return ReplaceInstUsesWith(CI, Op);
8584     } else if (OpBits < DestBits) {
8585       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8586       // bits, just sext from i32.
8587       if (NumSignBits > OpBits-MidBits)
8588         return new SExtInst(Op, CI.getType(), "tmp");
8589     } else {
8590       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8591       // bits, just truncate to i32.
8592       if (NumSignBits > OpBits-MidBits)
8593         return new TruncInst(Op, CI.getType(), "tmp");
8594     }
8595   }
8596
8597   // If the input is a shl/ashr pair of a same constant, then this is a sign
8598   // extension from a smaller value.  If we could trust arbitrary bitwidth
8599   // integers, we could turn this into a truncate to the smaller bit and then
8600   // use a sext for the whole extension.  Since we don't, look deeper and check
8601   // for a truncate.  If the source and dest are the same type, eliminate the
8602   // trunc and extend and just do shifts.  For example, turn:
8603   //   %a = trunc i32 %i to i8
8604   //   %b = shl i8 %a, 6
8605   //   %c = ashr i8 %b, 6
8606   //   %d = sext i8 %c to i32
8607   // into:
8608   //   %a = shl i32 %i, 30
8609   //   %d = ashr i32 %a, 30
8610   Value *A = 0;
8611   ConstantInt *BA = 0, *CA = 0;
8612   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8613                         m_ConstantInt(CA))) &&
8614       BA == CA && isa<TruncInst>(A)) {
8615     Value *I = cast<TruncInst>(A)->getOperand(0);
8616     if (I->getType() == CI.getType()) {
8617       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8618       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8619       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8620       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8621       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8622                                                         CI.getName()), CI);
8623       return BinaryOperator::CreateAShr(I, ShAmtV);
8624     }
8625   }
8626   
8627   return 0;
8628 }
8629
8630 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8631 /// in the specified FP type without changing its value.
8632 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8633   bool losesInfo;
8634   APFloat F = CFP->getValueAPF();
8635   (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8636   if (!losesInfo)
8637     return ConstantFP::get(F);
8638   return 0;
8639 }
8640
8641 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8642 /// through it until we get the source value.
8643 static Value *LookThroughFPExtensions(Value *V) {
8644   if (Instruction *I = dyn_cast<Instruction>(V))
8645     if (I->getOpcode() == Instruction::FPExt)
8646       return LookThroughFPExtensions(I->getOperand(0));
8647   
8648   // If this value is a constant, return the constant in the smallest FP type
8649   // that can accurately represent it.  This allows us to turn
8650   // (float)((double)X+2.0) into x+2.0f.
8651   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8652     if (CFP->getType() == Type::PPC_FP128Ty)
8653       return V;  // No constant folding of this.
8654     // See if the value can be truncated to float and then reextended.
8655     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8656       return V;
8657     if (CFP->getType() == Type::DoubleTy)
8658       return V;  // Won't shrink.
8659     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8660       return V;
8661     // Don't try to shrink to various long double types.
8662   }
8663   
8664   return V;
8665 }
8666
8667 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8668   if (Instruction *I = commonCastTransforms(CI))
8669     return I;
8670   
8671   // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8672   // smaller than the destination type, we can eliminate the truncate by doing
8673   // the add as the smaller type.  This applies to fadd/fsub/fmul/fdiv as well as
8674   // many builtins (sqrt, etc).
8675   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8676   if (OpI && OpI->hasOneUse()) {
8677     switch (OpI->getOpcode()) {
8678     default: break;
8679     case Instruction::FAdd:
8680     case Instruction::FSub:
8681     case Instruction::FMul:
8682     case Instruction::FDiv:
8683     case Instruction::FRem:
8684       const Type *SrcTy = OpI->getType();
8685       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8686       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8687       if (LHSTrunc->getType() != SrcTy && 
8688           RHSTrunc->getType() != SrcTy) {
8689         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8690         // If the source types were both smaller than the destination type of
8691         // the cast, do this xform.
8692         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8693             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8694           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8695                                       CI.getType(), CI);
8696           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8697                                       CI.getType(), CI);
8698           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8699         }
8700       }
8701       break;  
8702     }
8703   }
8704   return 0;
8705 }
8706
8707 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8708   return commonCastTransforms(CI);
8709 }
8710
8711 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8712   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8713   if (OpI == 0)
8714     return commonCastTransforms(FI);
8715
8716   // fptoui(uitofp(X)) --> X
8717   // fptoui(sitofp(X)) --> X
8718   // This is safe if the intermediate type has enough bits in its mantissa to
8719   // accurately represent all values of X.  For example, do not do this with
8720   // i64->float->i64.  This is also safe for sitofp case, because any negative
8721   // 'X' value would cause an undefined result for the fptoui. 
8722   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8723       OpI->getOperand(0)->getType() == FI.getType() &&
8724       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8725                     OpI->getType()->getFPMantissaWidth())
8726     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8727
8728   return commonCastTransforms(FI);
8729 }
8730
8731 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8732   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8733   if (OpI == 0)
8734     return commonCastTransforms(FI);
8735   
8736   // fptosi(sitofp(X)) --> X
8737   // fptosi(uitofp(X)) --> X
8738   // This is safe if the intermediate type has enough bits in its mantissa to
8739   // accurately represent all values of X.  For example, do not do this with
8740   // i64->float->i64.  This is also safe for sitofp case, because any negative
8741   // 'X' value would cause an undefined result for the fptoui. 
8742   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8743       OpI->getOperand(0)->getType() == FI.getType() &&
8744       (int)FI.getType()->getPrimitiveSizeInBits() <= 
8745                     OpI->getType()->getFPMantissaWidth())
8746     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8747   
8748   return commonCastTransforms(FI);
8749 }
8750
8751 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8752   return commonCastTransforms(CI);
8753 }
8754
8755 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8756   return commonCastTransforms(CI);
8757 }
8758
8759 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8760   // If the destination integer type is smaller than the intptr_t type for
8761   // this target, do a ptrtoint to intptr_t then do a trunc.  This allows the
8762   // trunc to be exposed to other transforms.  Don't do this for extending
8763   // ptrtoint's, because we don't know if the target sign or zero extends its
8764   // pointers.
8765   if (CI.getType()->getPrimitiveSizeInBits() < TD->getPointerSizeInBits()) {
8766     Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8767                                                     TD->getIntPtrType(),
8768                                                     "tmp"), CI);
8769     return new TruncInst(P, CI.getType());
8770   }
8771   
8772   return commonPointerCastTransforms(CI);
8773 }
8774
8775 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8776   // If the source integer type is larger than the intptr_t type for
8777   // this target, do a trunc to the intptr_t type, then inttoptr of it.  This
8778   // allows the trunc to be exposed to other transforms.  Don't do this for
8779   // extending inttoptr's, because we don't know if the target sign or zero
8780   // extends to pointers.
8781   if (CI.getOperand(0)->getType()->getPrimitiveSizeInBits() >
8782       TD->getPointerSizeInBits()) {
8783     Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8784                                                  TD->getIntPtrType(),
8785                                                  "tmp"), CI);
8786     return new IntToPtrInst(P, CI.getType());
8787   }
8788   
8789   if (Instruction *I = commonCastTransforms(CI))
8790     return I;
8791   
8792   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8793   if (!DestPointee->isSized()) return 0;
8794
8795   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8796   ConstantInt *Cst;
8797   Value *X;
8798   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8799                                     m_ConstantInt(Cst)))) {
8800     // If the source and destination operands have the same type, see if this
8801     // is a single-index GEP.
8802     if (X->getType() == CI.getType()) {
8803       // Get the size of the pointee type.
8804       uint64_t Size = TD->getTypeAllocSize(DestPointee);
8805
8806       // Convert the constant to intptr type.
8807       APInt Offset = Cst->getValue();
8808       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8809
8810       // If Offset is evenly divisible by Size, we can do this xform.
8811       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8812         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8813         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8814       }
8815     }
8816     // TODO: Could handle other cases, e.g. where add is indexing into field of
8817     // struct etc.
8818   } else if (CI.getOperand(0)->hasOneUse() &&
8819              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8820     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8821     // "inttoptr+GEP" instead of "add+intptr".
8822     
8823     // Get the size of the pointee type.
8824     uint64_t Size = TD->getTypeAllocSize(DestPointee);
8825     
8826     // Convert the constant to intptr type.
8827     APInt Offset = Cst->getValue();
8828     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8829     
8830     // If Offset is evenly divisible by Size, we can do this xform.
8831     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8832       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8833       
8834       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8835                                                             "tmp"), CI);
8836       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8837     }
8838   }
8839   return 0;
8840 }
8841
8842 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8843   // If the operands are integer typed then apply the integer transforms,
8844   // otherwise just apply the common ones.
8845   Value *Src = CI.getOperand(0);
8846   const Type *SrcTy = Src->getType();
8847   const Type *DestTy = CI.getType();
8848
8849   if (SrcTy->isInteger() && DestTy->isInteger()) {
8850     if (Instruction *Result = commonIntCastTransforms(CI))
8851       return Result;
8852   } else if (isa<PointerType>(SrcTy)) {
8853     if (Instruction *I = commonPointerCastTransforms(CI))
8854       return I;
8855   } else {
8856     if (Instruction *Result = commonCastTransforms(CI))
8857       return Result;
8858   }
8859
8860
8861   // Get rid of casts from one type to the same type. These are useless and can
8862   // be replaced by the operand.
8863   if (DestTy == Src->getType())
8864     return ReplaceInstUsesWith(CI, Src);
8865
8866   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8867     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8868     const Type *DstElTy = DstPTy->getElementType();
8869     const Type *SrcElTy = SrcPTy->getElementType();
8870     
8871     // If the address spaces don't match, don't eliminate the bitcast, which is
8872     // required for changing types.
8873     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8874       return 0;
8875     
8876     // If we are casting a malloc or alloca to a pointer to a type of the same
8877     // size, rewrite the allocation instruction to allocate the "right" type.
8878     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8879       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8880         return V;
8881     
8882     // If the source and destination are pointers, and this cast is equivalent
8883     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8884     // This can enhance SROA and other transforms that want type-safe pointers.
8885     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8886     unsigned NumZeros = 0;
8887     while (SrcElTy != DstElTy && 
8888            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8889            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8890       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8891       ++NumZeros;
8892     }
8893
8894     // If we found a path from the src to dest, create the getelementptr now.
8895     if (SrcElTy == DstElTy) {
8896       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8897       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8898                                        ((Instruction*) NULL));
8899     }
8900   }
8901
8902   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8903     if (SVI->hasOneUse()) {
8904       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8905       // a bitconvert to a vector with the same # elts.
8906       if (isa<VectorType>(DestTy) && 
8907           cast<VectorType>(DestTy)->getNumElements() ==
8908                 SVI->getType()->getNumElements() &&
8909           SVI->getType()->getNumElements() ==
8910             cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8911         CastInst *Tmp;
8912         // If either of the operands is a cast from CI.getType(), then
8913         // evaluating the shuffle in the casted destination's type will allow
8914         // us to eliminate at least one cast.
8915         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8916              Tmp->getOperand(0)->getType() == DestTy) ||
8917             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8918              Tmp->getOperand(0)->getType() == DestTy)) {
8919           Value *LHS = InsertCastBefore(Instruction::BitCast,
8920                                         SVI->getOperand(0), DestTy, CI);
8921           Value *RHS = InsertCastBefore(Instruction::BitCast,
8922                                         SVI->getOperand(1), DestTy, CI);
8923           // Return a new shuffle vector.  Use the same element ID's, as we
8924           // know the vector types match #elts.
8925           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8926         }
8927       }
8928     }
8929   }
8930   return 0;
8931 }
8932
8933 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8934 ///   %C = or %A, %B
8935 ///   %D = select %cond, %C, %A
8936 /// into:
8937 ///   %C = select %cond, %B, 0
8938 ///   %D = or %A, %C
8939 ///
8940 /// Assuming that the specified instruction is an operand to the select, return
8941 /// a bitmask indicating which operands of this instruction are foldable if they
8942 /// equal the other incoming value of the select.
8943 ///
8944 static unsigned GetSelectFoldableOperands(Instruction *I) {
8945   switch (I->getOpcode()) {
8946   case Instruction::Add:
8947   case Instruction::Mul:
8948   case Instruction::And:
8949   case Instruction::Or:
8950   case Instruction::Xor:
8951     return 3;              // Can fold through either operand.
8952   case Instruction::Sub:   // Can only fold on the amount subtracted.
8953   case Instruction::Shl:   // Can only fold on the shift amount.
8954   case Instruction::LShr:
8955   case Instruction::AShr:
8956     return 1;
8957   default:
8958     return 0;              // Cannot fold
8959   }
8960 }
8961
8962 /// GetSelectFoldableConstant - For the same transformation as the previous
8963 /// function, return the identity constant that goes into the select.
8964 static Constant *GetSelectFoldableConstant(Instruction *I) {
8965   switch (I->getOpcode()) {
8966   default: assert(0 && "This cannot happen!"); abort();
8967   case Instruction::Add:
8968   case Instruction::Sub:
8969   case Instruction::Or:
8970   case Instruction::Xor:
8971   case Instruction::Shl:
8972   case Instruction::LShr:
8973   case Instruction::AShr:
8974     return Constant::getNullValue(I->getType());
8975   case Instruction::And:
8976     return Constant::getAllOnesValue(I->getType());
8977   case Instruction::Mul:
8978     return ConstantInt::get(I->getType(), 1);
8979   }
8980 }
8981
8982 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8983 /// have the same opcode and only one use each.  Try to simplify this.
8984 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8985                                           Instruction *FI) {
8986   if (TI->getNumOperands() == 1) {
8987     // If this is a non-volatile load or a cast from the same type,
8988     // merge.
8989     if (TI->isCast()) {
8990       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8991         return 0;
8992     } else {
8993       return 0;  // unknown unary op.
8994     }
8995
8996     // Fold this by inserting a select from the input values.
8997     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8998                                            FI->getOperand(0), SI.getName()+".v");
8999     InsertNewInstBefore(NewSI, SI);
9000     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
9001                             TI->getType());
9002   }
9003
9004   // Only handle binary operators here.
9005   if (!isa<BinaryOperator>(TI))
9006     return 0;
9007
9008   // Figure out if the operations have any operands in common.
9009   Value *MatchOp, *OtherOpT, *OtherOpF;
9010   bool MatchIsOpZero;
9011   if (TI->getOperand(0) == FI->getOperand(0)) {
9012     MatchOp  = TI->getOperand(0);
9013     OtherOpT = TI->getOperand(1);
9014     OtherOpF = FI->getOperand(1);
9015     MatchIsOpZero = true;
9016   } else if (TI->getOperand(1) == FI->getOperand(1)) {
9017     MatchOp  = TI->getOperand(1);
9018     OtherOpT = TI->getOperand(0);
9019     OtherOpF = FI->getOperand(0);
9020     MatchIsOpZero = false;
9021   } else if (!TI->isCommutative()) {
9022     return 0;
9023   } else if (TI->getOperand(0) == FI->getOperand(1)) {
9024     MatchOp  = TI->getOperand(0);
9025     OtherOpT = TI->getOperand(1);
9026     OtherOpF = FI->getOperand(0);
9027     MatchIsOpZero = true;
9028   } else if (TI->getOperand(1) == FI->getOperand(0)) {
9029     MatchOp  = TI->getOperand(1);
9030     OtherOpT = TI->getOperand(0);
9031     OtherOpF = FI->getOperand(1);
9032     MatchIsOpZero = true;
9033   } else {
9034     return 0;
9035   }
9036
9037   // If we reach here, they do have operations in common.
9038   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9039                                          OtherOpF, SI.getName()+".v");
9040   InsertNewInstBefore(NewSI, SI);
9041
9042   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9043     if (MatchIsOpZero)
9044       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9045     else
9046       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9047   }
9048   assert(0 && "Shouldn't get here");
9049   return 0;
9050 }
9051
9052 static bool isSelect01(Constant *C1, Constant *C2) {
9053   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9054   if (!C1I)
9055     return false;
9056   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9057   if (!C2I)
9058     return false;
9059   return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9060 }
9061
9062 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9063 /// facilitate further optimization.
9064 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9065                                             Value *FalseVal) {
9066   // See the comment above GetSelectFoldableOperands for a description of the
9067   // transformation we are doing here.
9068   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9069     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9070         !isa<Constant>(FalseVal)) {
9071       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9072         unsigned OpToFold = 0;
9073         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9074           OpToFold = 1;
9075         } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9076           OpToFold = 2;
9077         }
9078
9079         if (OpToFold) {
9080           Constant *C = GetSelectFoldableConstant(TVI);
9081           Value *OOp = TVI->getOperand(2-OpToFold);
9082           // Avoid creating select between 2 constants unless it's selecting
9083           // between 0 and 1.
9084           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9085             Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9086             InsertNewInstBefore(NewSel, SI);
9087             NewSel->takeName(TVI);
9088             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9089               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9090             assert(0 && "Unknown instruction!!");
9091           }
9092         }
9093       }
9094     }
9095   }
9096
9097   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9098     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9099         !isa<Constant>(TrueVal)) {
9100       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9101         unsigned OpToFold = 0;
9102         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9103           OpToFold = 1;
9104         } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9105           OpToFold = 2;
9106         }
9107
9108         if (OpToFold) {
9109           Constant *C = GetSelectFoldableConstant(FVI);
9110           Value *OOp = FVI->getOperand(2-OpToFold);
9111           // Avoid creating select between 2 constants unless it's selecting
9112           // between 0 and 1.
9113           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9114             Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9115             InsertNewInstBefore(NewSel, SI);
9116             NewSel->takeName(FVI);
9117             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9118               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9119             assert(0 && "Unknown instruction!!");
9120           }
9121         }
9122       }
9123     }
9124   }
9125
9126   return 0;
9127 }
9128
9129 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9130 /// ICmpInst as its first operand.
9131 ///
9132 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9133                                                    ICmpInst *ICI) {
9134   bool Changed = false;
9135   ICmpInst::Predicate Pred = ICI->getPredicate();
9136   Value *CmpLHS = ICI->getOperand(0);
9137   Value *CmpRHS = ICI->getOperand(1);
9138   Value *TrueVal = SI.getTrueValue();
9139   Value *FalseVal = SI.getFalseValue();
9140
9141   // Check cases where the comparison is with a constant that
9142   // can be adjusted to fit the min/max idiom. We may edit ICI in
9143   // place here, so make sure the select is the only user.
9144   if (ICI->hasOneUse())
9145     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9146       switch (Pred) {
9147       default: break;
9148       case ICmpInst::ICMP_ULT:
9149       case ICmpInst::ICMP_SLT: {
9150         // X < MIN ? T : F  -->  F
9151         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9152           return ReplaceInstUsesWith(SI, FalseVal);
9153         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
9154         Constant *AdjustedRHS = SubOne(CI);
9155         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9156             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9157           Pred = ICmpInst::getSwappedPredicate(Pred);
9158           CmpRHS = AdjustedRHS;
9159           std::swap(FalseVal, TrueVal);
9160           ICI->setPredicate(Pred);
9161           ICI->setOperand(1, CmpRHS);
9162           SI.setOperand(1, TrueVal);
9163           SI.setOperand(2, FalseVal);
9164           Changed = true;
9165         }
9166         break;
9167       }
9168       case ICmpInst::ICMP_UGT:
9169       case ICmpInst::ICMP_SGT: {
9170         // X > MAX ? T : F  -->  F
9171         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9172           return ReplaceInstUsesWith(SI, FalseVal);
9173         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
9174         Constant *AdjustedRHS = AddOne(CI);
9175         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9176             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9177           Pred = ICmpInst::getSwappedPredicate(Pred);
9178           CmpRHS = AdjustedRHS;
9179           std::swap(FalseVal, TrueVal);
9180           ICI->setPredicate(Pred);
9181           ICI->setOperand(1, CmpRHS);
9182           SI.setOperand(1, TrueVal);
9183           SI.setOperand(2, FalseVal);
9184           Changed = true;
9185         }
9186         break;
9187       }
9188       }
9189
9190       // (x <s 0) ? -1 : 0 -> ashr x, 31   -> all ones if signed
9191       // (x >s -1) ? -1 : 0 -> ashr x, 31  -> all ones if not signed
9192       CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9193       if (match(TrueVal, m_ConstantInt<-1>()) &&
9194           match(FalseVal, m_ConstantInt<0>()))
9195         Pred = ICI->getPredicate();
9196       else if (match(TrueVal, m_ConstantInt<0>()) &&
9197                match(FalseVal, m_ConstantInt<-1>()))
9198         Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9199       
9200       if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9201         // If we are just checking for a icmp eq of a single bit and zext'ing it
9202         // to an integer, then shift the bit to the appropriate place and then
9203         // cast to integer to avoid the comparison.
9204         const APInt &Op1CV = CI->getValue();
9205     
9206         // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
9207         // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
9208         if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9209             (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9210           Value *In = ICI->getOperand(0);
9211           Value *Sh = ConstantInt::get(In->getType(),
9212                                        In->getType()->getPrimitiveSizeInBits()-1);
9213           In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9214                                                           In->getName()+".lobit"),
9215                                    *ICI);
9216           if (In->getType() != SI.getType())
9217             In = CastInst::CreateIntegerCast(In, SI.getType(),
9218                                              true/*SExt*/, "tmp", ICI);
9219     
9220           if (Pred == ICmpInst::ICMP_SGT)
9221             In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9222                                        In->getName()+".not"), *ICI);
9223     
9224           return ReplaceInstUsesWith(SI, In);
9225         }
9226       }
9227     }
9228
9229   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9230     // Transform (X == Y) ? X : Y  -> Y
9231     if (Pred == ICmpInst::ICMP_EQ)
9232       return ReplaceInstUsesWith(SI, FalseVal);
9233     // Transform (X != Y) ? X : Y  -> X
9234     if (Pred == ICmpInst::ICMP_NE)
9235       return ReplaceInstUsesWith(SI, TrueVal);
9236     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9237
9238   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9239     // Transform (X == Y) ? Y : X  -> X
9240     if (Pred == ICmpInst::ICMP_EQ)
9241       return ReplaceInstUsesWith(SI, FalseVal);
9242     // Transform (X != Y) ? Y : X  -> Y
9243     if (Pred == ICmpInst::ICMP_NE)
9244       return ReplaceInstUsesWith(SI, TrueVal);
9245     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9246   }
9247
9248   /// NOTE: if we wanted to, this is where to detect integer ABS
9249
9250   return Changed ? &SI : 0;
9251 }
9252
9253 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9254   Value *CondVal = SI.getCondition();
9255   Value *TrueVal = SI.getTrueValue();
9256   Value *FalseVal = SI.getFalseValue();
9257
9258   // select true, X, Y  -> X
9259   // select false, X, Y -> Y
9260   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9261     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9262
9263   // select C, X, X -> X
9264   if (TrueVal == FalseVal)
9265     return ReplaceInstUsesWith(SI, TrueVal);
9266
9267   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
9268     return ReplaceInstUsesWith(SI, FalseVal);
9269   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
9270     return ReplaceInstUsesWith(SI, TrueVal);
9271   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
9272     if (isa<Constant>(TrueVal))
9273       return ReplaceInstUsesWith(SI, TrueVal);
9274     else
9275       return ReplaceInstUsesWith(SI, FalseVal);
9276   }
9277
9278   if (SI.getType() == Type::Int1Ty) {
9279     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9280       if (C->getZExtValue()) {
9281         // Change: A = select B, true, C --> A = or B, C
9282         return BinaryOperator::CreateOr(CondVal, FalseVal);
9283       } else {
9284         // Change: A = select B, false, C --> A = and !B, C
9285         Value *NotCond =
9286           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9287                                              "not."+CondVal->getName()), SI);
9288         return BinaryOperator::CreateAnd(NotCond, FalseVal);
9289       }
9290     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9291       if (C->getZExtValue() == false) {
9292         // Change: A = select B, C, false --> A = and B, C
9293         return BinaryOperator::CreateAnd(CondVal, TrueVal);
9294       } else {
9295         // Change: A = select B, C, true --> A = or !B, C
9296         Value *NotCond =
9297           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9298                                              "not."+CondVal->getName()), SI);
9299         return BinaryOperator::CreateOr(NotCond, TrueVal);
9300       }
9301     }
9302     
9303     // select a, b, a  -> a&b
9304     // select a, a, b  -> a|b
9305     if (CondVal == TrueVal)
9306       return BinaryOperator::CreateOr(CondVal, FalseVal);
9307     else if (CondVal == FalseVal)
9308       return BinaryOperator::CreateAnd(CondVal, TrueVal);
9309   }
9310
9311   // Selecting between two integer constants?
9312   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9313     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9314       // select C, 1, 0 -> zext C to int
9315       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9316         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9317       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9318         // select C, 0, 1 -> zext !C to int
9319         Value *NotCond =
9320           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9321                                                "not."+CondVal->getName()), SI);
9322         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9323       }
9324
9325       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9326
9327         // (x <s 0) ? -1 : 0 -> ashr x, 31
9328         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9329           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9330             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9331               // The comparison constant and the result are not neccessarily the
9332               // same width. Make an all-ones value by inserting a AShr.
9333               Value *X = IC->getOperand(0);
9334               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
9335               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
9336               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9337                                                         ShAmt, "ones");
9338               InsertNewInstBefore(SRA, SI);
9339
9340               // Then cast to the appropriate width.
9341               return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9342             }
9343           }
9344
9345
9346         // If one of the constants is zero (we know they can't both be) and we
9347         // have an icmp instruction with zero, and we have an 'and' with the
9348         // non-constant value, eliminate this whole mess.  This corresponds to
9349         // cases like this: ((X & 27) ? 27 : 0)
9350         if (TrueValC->isZero() || FalseValC->isZero())
9351           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9352               cast<Constant>(IC->getOperand(1))->isNullValue())
9353             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9354               if (ICA->getOpcode() == Instruction::And &&
9355                   isa<ConstantInt>(ICA->getOperand(1)) &&
9356                   (ICA->getOperand(1) == TrueValC ||
9357                    ICA->getOperand(1) == FalseValC) &&
9358                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9359                 // Okay, now we know that everything is set up, we just don't
9360                 // know whether we have a icmp_ne or icmp_eq and whether the 
9361                 // true or false val is the zero.
9362                 bool ShouldNotVal = !TrueValC->isZero();
9363                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9364                 Value *V = ICA;
9365                 if (ShouldNotVal)
9366                   V = InsertNewInstBefore(BinaryOperator::Create(
9367                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
9368                 return ReplaceInstUsesWith(SI, V);
9369               }
9370       }
9371     }
9372
9373   // See if we are selecting two values based on a comparison of the two values.
9374   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9375     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9376       // Transform (X == Y) ? X : Y  -> Y
9377       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9378         // This is not safe in general for floating point:  
9379         // consider X== -0, Y== +0.
9380         // It becomes safe if either operand is a nonzero constant.
9381         ConstantFP *CFPt, *CFPf;
9382         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9383               !CFPt->getValueAPF().isZero()) ||
9384             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9385              !CFPf->getValueAPF().isZero()))
9386         return ReplaceInstUsesWith(SI, FalseVal);
9387       }
9388       // Transform (X != Y) ? X : Y  -> X
9389       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9390         return ReplaceInstUsesWith(SI, TrueVal);
9391       // NOTE: if we wanted to, this is where to detect MIN/MAX
9392
9393     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9394       // Transform (X == Y) ? Y : X  -> X
9395       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9396         // This is not safe in general for floating point:  
9397         // consider X== -0, Y== +0.
9398         // It becomes safe if either operand is a nonzero constant.
9399         ConstantFP *CFPt, *CFPf;
9400         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9401               !CFPt->getValueAPF().isZero()) ||
9402             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9403              !CFPf->getValueAPF().isZero()))
9404           return ReplaceInstUsesWith(SI, FalseVal);
9405       }
9406       // Transform (X != Y) ? Y : X  -> Y
9407       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9408         return ReplaceInstUsesWith(SI, TrueVal);
9409       // NOTE: if we wanted to, this is where to detect MIN/MAX
9410     }
9411     // NOTE: if we wanted to, this is where to detect ABS
9412   }
9413
9414   // See if we are selecting two values based on a comparison of the two values.
9415   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9416     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9417       return Result;
9418
9419   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9420     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9421       if (TI->hasOneUse() && FI->hasOneUse()) {
9422         Instruction *AddOp = 0, *SubOp = 0;
9423
9424         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9425         if (TI->getOpcode() == FI->getOpcode())
9426           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9427             return IV;
9428
9429         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
9430         // even legal for FP.
9431         if ((TI->getOpcode() == Instruction::Sub &&
9432              FI->getOpcode() == Instruction::Add) ||
9433             (TI->getOpcode() == Instruction::FSub &&
9434              FI->getOpcode() == Instruction::FAdd)) {
9435           AddOp = FI; SubOp = TI;
9436         } else if ((FI->getOpcode() == Instruction::Sub &&
9437                     TI->getOpcode() == Instruction::Add) ||
9438                    (FI->getOpcode() == Instruction::FSub &&
9439                     TI->getOpcode() == Instruction::FAdd)) {
9440           AddOp = TI; SubOp = FI;
9441         }
9442
9443         if (AddOp) {
9444           Value *OtherAddOp = 0;
9445           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9446             OtherAddOp = AddOp->getOperand(1);
9447           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9448             OtherAddOp = AddOp->getOperand(0);
9449           }
9450
9451           if (OtherAddOp) {
9452             // So at this point we know we have (Y -> OtherAddOp):
9453             //        select C, (add X, Y), (sub X, Z)
9454             Value *NegVal;  // Compute -Z
9455             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9456               NegVal = ConstantExpr::getNeg(C);
9457             } else {
9458               NegVal = InsertNewInstBefore(
9459                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9460             }
9461
9462             Value *NewTrueOp = OtherAddOp;
9463             Value *NewFalseOp = NegVal;
9464             if (AddOp != TI)
9465               std::swap(NewTrueOp, NewFalseOp);
9466             Instruction *NewSel =
9467               SelectInst::Create(CondVal, NewTrueOp,
9468                                  NewFalseOp, SI.getName() + ".p");
9469
9470             NewSel = InsertNewInstBefore(NewSel, SI);
9471             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9472           }
9473         }
9474       }
9475
9476   // See if we can fold the select into one of our operands.
9477   if (SI.getType()->isInteger()) {
9478     Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9479     if (FoldI)
9480       return FoldI;
9481   }
9482
9483   if (BinaryOperator::isNot(CondVal)) {
9484     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9485     SI.setOperand(1, FalseVal);
9486     SI.setOperand(2, TrueVal);
9487     return &SI;
9488   }
9489
9490   return 0;
9491 }
9492
9493 /// EnforceKnownAlignment - If the specified pointer points to an object that
9494 /// we control, modify the object's alignment to PrefAlign. This isn't
9495 /// often possible though. If alignment is important, a more reliable approach
9496 /// is to simply align all global variables and allocation instructions to
9497 /// their preferred alignment from the beginning.
9498 ///
9499 static unsigned EnforceKnownAlignment(Value *V,
9500                                       unsigned Align, unsigned PrefAlign) {
9501
9502   User *U = dyn_cast<User>(V);
9503   if (!U) return Align;
9504
9505   switch (getOpcode(U)) {
9506   default: break;
9507   case Instruction::BitCast:
9508     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9509   case Instruction::GetElementPtr: {
9510     // If all indexes are zero, it is just the alignment of the base pointer.
9511     bool AllZeroOperands = true;
9512     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9513       if (!isa<Constant>(*i) ||
9514           !cast<Constant>(*i)->isNullValue()) {
9515         AllZeroOperands = false;
9516         break;
9517       }
9518
9519     if (AllZeroOperands) {
9520       // Treat this like a bitcast.
9521       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9522     }
9523     break;
9524   }
9525   }
9526
9527   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9528     // If there is a large requested alignment and we can, bump up the alignment
9529     // of the global.
9530     if (!GV->isDeclaration()) {
9531       if (GV->getAlignment() >= PrefAlign)
9532         Align = GV->getAlignment();
9533       else {
9534         GV->setAlignment(PrefAlign);
9535         Align = PrefAlign;
9536       }
9537     }
9538   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9539     // If there is a requested alignment and if this is an alloca, round up.  We
9540     // don't do this for malloc, because some systems can't respect the request.
9541     if (isa<AllocaInst>(AI)) {
9542       if (AI->getAlignment() >= PrefAlign)
9543         Align = AI->getAlignment();
9544       else {
9545         AI->setAlignment(PrefAlign);
9546         Align = PrefAlign;
9547       }
9548     }
9549   }
9550
9551   return Align;
9552 }
9553
9554 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9555 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
9556 /// and it is more than the alignment of the ultimate object, see if we can
9557 /// increase the alignment of the ultimate object, making this check succeed.
9558 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9559                                                   unsigned PrefAlign) {
9560   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9561                       sizeof(PrefAlign) * CHAR_BIT;
9562   APInt Mask = APInt::getAllOnesValue(BitWidth);
9563   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9564   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9565   unsigned TrailZ = KnownZero.countTrailingOnes();
9566   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9567
9568   if (PrefAlign > Align)
9569     Align = EnforceKnownAlignment(V, Align, PrefAlign);
9570   
9571     // We don't need to make any adjustment.
9572   return Align;
9573 }
9574
9575 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9576   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9577   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9578   unsigned MinAlign = std::min(DstAlign, SrcAlign);
9579   unsigned CopyAlign = MI->getAlignment();
9580
9581   if (CopyAlign < MinAlign) {
9582     MI->setAlignment(MinAlign);
9583     return MI;
9584   }
9585   
9586   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9587   // load/store.
9588   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9589   if (MemOpLength == 0) return 0;
9590   
9591   // Source and destination pointer types are always "i8*" for intrinsic.  See
9592   // if the size is something we can handle with a single primitive load/store.
9593   // A single load+store correctly handles overlapping memory in the memmove
9594   // case.
9595   unsigned Size = MemOpLength->getZExtValue();
9596   if (Size == 0) return MI;  // Delete this mem transfer.
9597   
9598   if (Size > 8 || (Size&(Size-1)))
9599     return 0;  // If not 1/2/4/8 bytes, exit.
9600   
9601   // Use an integer load+store unless we can find something better.
9602   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9603   
9604   // Memcpy forces the use of i8* for the source and destination.  That means
9605   // that if you're using memcpy to move one double around, you'll get a cast
9606   // from double* to i8*.  We'd much rather use a double load+store rather than
9607   // an i64 load+store, here because this improves the odds that the source or
9608   // dest address will be promotable.  See if we can find a better type than the
9609   // integer datatype.
9610   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9611     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9612     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9613       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9614       // down through these levels if so.
9615       while (!SrcETy->isSingleValueType()) {
9616         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9617           if (STy->getNumElements() == 1)
9618             SrcETy = STy->getElementType(0);
9619           else
9620             break;
9621         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9622           if (ATy->getNumElements() == 1)
9623             SrcETy = ATy->getElementType();
9624           else
9625             break;
9626         } else
9627           break;
9628       }
9629       
9630       if (SrcETy->isSingleValueType())
9631         NewPtrTy = PointerType::getUnqual(SrcETy);
9632     }
9633   }
9634   
9635   
9636   // If the memcpy/memmove provides better alignment info than we can
9637   // infer, use it.
9638   SrcAlign = std::max(SrcAlign, CopyAlign);
9639   DstAlign = std::max(DstAlign, CopyAlign);
9640   
9641   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9642   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9643   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9644   InsertNewInstBefore(L, *MI);
9645   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9646
9647   // Set the size of the copy to 0, it will be deleted on the next iteration.
9648   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9649   return MI;
9650 }
9651
9652 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9653   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9654   if (MI->getAlignment() < Alignment) {
9655     MI->setAlignment(Alignment);
9656     return MI;
9657   }
9658   
9659   // Extract the length and alignment and fill if they are constant.
9660   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9661   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9662   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9663     return 0;
9664   uint64_t Len = LenC->getZExtValue();
9665   Alignment = MI->getAlignment();
9666   
9667   // If the length is zero, this is a no-op
9668   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9669   
9670   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9671   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9672     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9673     
9674     Value *Dest = MI->getDest();
9675     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9676
9677     // Alignment 0 is identity for alignment 1 for memset, but not store.
9678     if (Alignment == 0) Alignment = 1;
9679     
9680     // Extract the fill value and store.
9681     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9682     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9683                                       Alignment), *MI);
9684     
9685     // Set the size of the copy to 0, it will be deleted on the next iteration.
9686     MI->setLength(Constant::getNullValue(LenC->getType()));
9687     return MI;
9688   }
9689
9690   return 0;
9691 }
9692
9693
9694 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9695 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9696 /// the heavy lifting.
9697 ///
9698 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9699   // If the caller function is nounwind, mark the call as nounwind, even if the
9700   // callee isn't.
9701   if (CI.getParent()->getParent()->doesNotThrow() &&
9702       !CI.doesNotThrow()) {
9703     CI.setDoesNotThrow();
9704     return &CI;
9705   }
9706   
9707   
9708   
9709   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9710   if (!II) return visitCallSite(&CI);
9711   
9712   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9713   // visitCallSite.
9714   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9715     bool Changed = false;
9716
9717     // memmove/cpy/set of zero bytes is a noop.
9718     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9719       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9720
9721       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9722         if (CI->getZExtValue() == 1) {
9723           // Replace the instruction with just byte operations.  We would
9724           // transform other cases to loads/stores, but we don't know if
9725           // alignment is sufficient.
9726         }
9727     }
9728
9729     // If we have a memmove and the source operation is a constant global,
9730     // then the source and dest pointers can't alias, so we can change this
9731     // into a call to memcpy.
9732     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9733       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9734         if (GVSrc->isConstant()) {
9735           Module *M = CI.getParent()->getParent()->getParent();
9736           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9737           const Type *Tys[1];
9738           Tys[0] = CI.getOperand(3)->getType();
9739           CI.setOperand(0, 
9740                         Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9741           Changed = true;
9742         }
9743
9744       // memmove(x,x,size) -> noop.
9745       if (MMI->getSource() == MMI->getDest())
9746         return EraseInstFromFunction(CI);
9747     }
9748
9749     // If we can determine a pointer alignment that is bigger than currently
9750     // set, update the alignment.
9751     if (isa<MemTransferInst>(MI)) {
9752       if (Instruction *I = SimplifyMemTransfer(MI))
9753         return I;
9754     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9755       if (Instruction *I = SimplifyMemSet(MSI))
9756         return I;
9757     }
9758           
9759     if (Changed) return II;
9760   }
9761   
9762   switch (II->getIntrinsicID()) {
9763   default: break;
9764   case Intrinsic::bswap:
9765     // bswap(bswap(x)) -> x
9766     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9767       if (Operand->getIntrinsicID() == Intrinsic::bswap)
9768         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9769     break;
9770   case Intrinsic::ppc_altivec_lvx:
9771   case Intrinsic::ppc_altivec_lvxl:
9772   case Intrinsic::x86_sse_loadu_ps:
9773   case Intrinsic::x86_sse2_loadu_pd:
9774   case Intrinsic::x86_sse2_loadu_dq:
9775     // Turn PPC lvx     -> load if the pointer is known aligned.
9776     // Turn X86 loadups -> load if the pointer is known aligned.
9777     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9778       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9779                                        PointerType::getUnqual(II->getType()),
9780                                        CI);
9781       return new LoadInst(Ptr);
9782     }
9783     break;
9784   case Intrinsic::ppc_altivec_stvx:
9785   case Intrinsic::ppc_altivec_stvxl:
9786     // Turn stvx -> store if the pointer is known aligned.
9787     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9788       const Type *OpPtrTy = 
9789         PointerType::getUnqual(II->getOperand(1)->getType());
9790       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9791       return new StoreInst(II->getOperand(1), Ptr);
9792     }
9793     break;
9794   case Intrinsic::x86_sse_storeu_ps:
9795   case Intrinsic::x86_sse2_storeu_pd:
9796   case Intrinsic::x86_sse2_storeu_dq:
9797     // Turn X86 storeu -> store if the pointer is known aligned.
9798     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9799       const Type *OpPtrTy = 
9800         PointerType::getUnqual(II->getOperand(2)->getType());
9801       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9802       return new StoreInst(II->getOperand(2), Ptr);
9803     }
9804     break;
9805     
9806   case Intrinsic::x86_sse_cvttss2si: {
9807     // These intrinsics only demands the 0th element of its input vector.  If
9808     // we can simplify the input based on that, do so now.
9809     unsigned VWidth =
9810       cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9811     APInt DemandedElts(VWidth, 1);
9812     APInt UndefElts(VWidth, 0);
9813     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9814                                               UndefElts)) {
9815       II->setOperand(1, V);
9816       return II;
9817     }
9818     break;
9819   }
9820     
9821   case Intrinsic::ppc_altivec_vperm:
9822     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9823     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9824       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9825       
9826       // Check that all of the elements are integer constants or undefs.
9827       bool AllEltsOk = true;
9828       for (unsigned i = 0; i != 16; ++i) {
9829         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9830             !isa<UndefValue>(Mask->getOperand(i))) {
9831           AllEltsOk = false;
9832           break;
9833         }
9834       }
9835       
9836       if (AllEltsOk) {
9837         // Cast the input vectors to byte vectors.
9838         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9839         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9840         Value *Result = UndefValue::get(Op0->getType());
9841         
9842         // Only extract each element once.
9843         Value *ExtractedElts[32];
9844         memset(ExtractedElts, 0, sizeof(ExtractedElts));
9845         
9846         for (unsigned i = 0; i != 16; ++i) {
9847           if (isa<UndefValue>(Mask->getOperand(i)))
9848             continue;
9849           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9850           Idx &= 31;  // Match the hardware behavior.
9851           
9852           if (ExtractedElts[Idx] == 0) {
9853             Instruction *Elt = 
9854               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9855             InsertNewInstBefore(Elt, CI);
9856             ExtractedElts[Idx] = Elt;
9857           }
9858         
9859           // Insert this value into the result vector.
9860           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9861                                              i, "tmp");
9862           InsertNewInstBefore(cast<Instruction>(Result), CI);
9863         }
9864         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9865       }
9866     }
9867     break;
9868
9869   case Intrinsic::stackrestore: {
9870     // If the save is right next to the restore, remove the restore.  This can
9871     // happen when variable allocas are DCE'd.
9872     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9873       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9874         BasicBlock::iterator BI = SS;
9875         if (&*++BI == II)
9876           return EraseInstFromFunction(CI);
9877       }
9878     }
9879     
9880     // Scan down this block to see if there is another stack restore in the
9881     // same block without an intervening call/alloca.
9882     BasicBlock::iterator BI = II;
9883     TerminatorInst *TI = II->getParent()->getTerminator();
9884     bool CannotRemove = false;
9885     for (++BI; &*BI != TI; ++BI) {
9886       if (isa<AllocaInst>(BI)) {
9887         CannotRemove = true;
9888         break;
9889       }
9890       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9891         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9892           // If there is a stackrestore below this one, remove this one.
9893           if (II->getIntrinsicID() == Intrinsic::stackrestore)
9894             return EraseInstFromFunction(CI);
9895           // Otherwise, ignore the intrinsic.
9896         } else {
9897           // If we found a non-intrinsic call, we can't remove the stack
9898           // restore.
9899           CannotRemove = true;
9900           break;
9901         }
9902       }
9903     }
9904     
9905     // If the stack restore is in a return/unwind block and if there are no
9906     // allocas or calls between the restore and the return, nuke the restore.
9907     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9908       return EraseInstFromFunction(CI);
9909     break;
9910   }
9911   }
9912
9913   return visitCallSite(II);
9914 }
9915
9916 // InvokeInst simplification
9917 //
9918 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9919   return visitCallSite(&II);
9920 }
9921
9922 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9923 /// passed through the varargs area, we can eliminate the use of the cast.
9924 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9925                                          const CastInst * const CI,
9926                                          const TargetData * const TD,
9927                                          const int ix) {
9928   if (!CI->isLosslessCast())
9929     return false;
9930
9931   // The size of ByVal arguments is derived from the type, so we
9932   // can't change to a type with a different size.  If the size were
9933   // passed explicitly we could avoid this check.
9934   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9935     return true;
9936
9937   const Type* SrcTy = 
9938             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9939   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9940   if (!SrcTy->isSized() || !DstTy->isSized())
9941     return false;
9942   if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9943     return false;
9944   return true;
9945 }
9946
9947 // visitCallSite - Improvements for call and invoke instructions.
9948 //
9949 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9950   bool Changed = false;
9951
9952   // If the callee is a constexpr cast of a function, attempt to move the cast
9953   // to the arguments of the call/invoke.
9954   if (transformConstExprCastCall(CS)) return 0;
9955
9956   Value *Callee = CS.getCalledValue();
9957
9958   if (Function *CalleeF = dyn_cast<Function>(Callee))
9959     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9960       Instruction *OldCall = CS.getInstruction();
9961       // If the call and callee calling conventions don't match, this call must
9962       // be unreachable, as the call is undefined.
9963       new StoreInst(ConstantInt::getTrue(),
9964                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9965                                     OldCall);
9966       if (!OldCall->use_empty())
9967         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9968       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9969         return EraseInstFromFunction(*OldCall);
9970       return 0;
9971     }
9972
9973   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9974     // This instruction is not reachable, just remove it.  We insert a store to
9975     // undef so that we know that this code is not reachable, despite the fact
9976     // that we can't modify the CFG here.
9977     new StoreInst(ConstantInt::getTrue(),
9978                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9979                   CS.getInstruction());
9980
9981     if (!CS.getInstruction()->use_empty())
9982       CS.getInstruction()->
9983         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9984
9985     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9986       // Don't break the CFG, insert a dummy cond branch.
9987       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9988                          ConstantInt::getTrue(), II);
9989     }
9990     return EraseInstFromFunction(*CS.getInstruction());
9991   }
9992
9993   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9994     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9995       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9996         return transformCallThroughTrampoline(CS);
9997
9998   const PointerType *PTy = cast<PointerType>(Callee->getType());
9999   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10000   if (FTy->isVarArg()) {
10001     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10002     // See if we can optimize any arguments passed through the varargs area of
10003     // the call.
10004     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10005            E = CS.arg_end(); I != E; ++I, ++ix) {
10006       CastInst *CI = dyn_cast<CastInst>(*I);
10007       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10008         *I = CI->getOperand(0);
10009         Changed = true;
10010       }
10011     }
10012   }
10013
10014   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10015     // Inline asm calls cannot throw - mark them 'nounwind'.
10016     CS.setDoesNotThrow();
10017     Changed = true;
10018   }
10019
10020   return Changed ? CS.getInstruction() : 0;
10021 }
10022
10023 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10024 // attempt to move the cast to the arguments of the call/invoke.
10025 //
10026 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10027   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10028   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10029   if (CE->getOpcode() != Instruction::BitCast || 
10030       !isa<Function>(CE->getOperand(0)))
10031     return false;
10032   Function *Callee = cast<Function>(CE->getOperand(0));
10033   Instruction *Caller = CS.getInstruction();
10034   const AttrListPtr &CallerPAL = CS.getAttributes();
10035
10036   // Okay, this is a cast from a function to a different type.  Unless doing so
10037   // would cause a type conversion of one of our arguments, change this call to
10038   // be a direct call with arguments casted to the appropriate types.
10039   //
10040   const FunctionType *FT = Callee->getFunctionType();
10041   const Type *OldRetTy = Caller->getType();
10042   const Type *NewRetTy = FT->getReturnType();
10043
10044   if (isa<StructType>(NewRetTy))
10045     return false; // TODO: Handle multiple return values.
10046
10047   // Check to see if we are changing the return type...
10048   if (OldRetTy != NewRetTy) {
10049     if (Callee->isDeclaration() &&
10050         // Conversion is ok if changing from one pointer type to another or from
10051         // a pointer to an integer of the same size.
10052         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10053           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10054       return false;   // Cannot transform this return value.
10055
10056     if (!Caller->use_empty() &&
10057         // void -> non-void is handled specially
10058         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10059       return false;   // Cannot transform this return value.
10060
10061     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10062       Attributes RAttrs = CallerPAL.getRetAttributes();
10063       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10064         return false;   // Attribute not compatible with transformed value.
10065     }
10066
10067     // If the callsite is an invoke instruction, and the return value is used by
10068     // a PHI node in a successor, we cannot change the return type of the call
10069     // because there is no place to put the cast instruction (without breaking
10070     // the critical edge).  Bail out in this case.
10071     if (!Caller->use_empty())
10072       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10073         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10074              UI != E; ++UI)
10075           if (PHINode *PN = dyn_cast<PHINode>(*UI))
10076             if (PN->getParent() == II->getNormalDest() ||
10077                 PN->getParent() == II->getUnwindDest())
10078               return false;
10079   }
10080
10081   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10082   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10083
10084   CallSite::arg_iterator AI = CS.arg_begin();
10085   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10086     const Type *ParamTy = FT->getParamType(i);
10087     const Type *ActTy = (*AI)->getType();
10088
10089     if (!CastInst::isCastable(ActTy, ParamTy))
10090       return false;   // Cannot transform this parameter value.
10091
10092     if (CallerPAL.getParamAttributes(i + 1) 
10093         & Attribute::typeIncompatible(ParamTy))
10094       return false;   // Attribute not compatible with transformed value.
10095
10096     // Converting from one pointer type to another or between a pointer and an
10097     // integer of the same size is safe even if we do not have a body.
10098     bool isConvertible = ActTy == ParamTy ||
10099       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10100        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10101     if (Callee->isDeclaration() && !isConvertible) return false;
10102   }
10103
10104   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10105       Callee->isDeclaration())
10106     return false;   // Do not delete arguments unless we have a function body.
10107
10108   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10109       !CallerPAL.isEmpty())
10110     // In this case we have more arguments than the new function type, but we
10111     // won't be dropping them.  Check that these extra arguments have attributes
10112     // that are compatible with being a vararg call argument.
10113     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10114       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10115         break;
10116       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10117       if (PAttrs & Attribute::VarArgsIncompatible)
10118         return false;
10119     }
10120
10121   // Okay, we decided that this is a safe thing to do: go ahead and start
10122   // inserting cast instructions as necessary...
10123   std::vector<Value*> Args;
10124   Args.reserve(NumActualArgs);
10125   SmallVector<AttributeWithIndex, 8> attrVec;
10126   attrVec.reserve(NumCommonArgs);
10127
10128   // Get any return attributes.
10129   Attributes RAttrs = CallerPAL.getRetAttributes();
10130
10131   // If the return value is not being used, the type may not be compatible
10132   // with the existing attributes.  Wipe out any problematic attributes.
10133   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10134
10135   // Add the new return attributes.
10136   if (RAttrs)
10137     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10138
10139   AI = CS.arg_begin();
10140   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10141     const Type *ParamTy = FT->getParamType(i);
10142     if ((*AI)->getType() == ParamTy) {
10143       Args.push_back(*AI);
10144     } else {
10145       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10146           false, ParamTy, false);
10147       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10148       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10149     }
10150
10151     // Add any parameter attributes.
10152     if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10153       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10154   }
10155
10156   // If the function takes more arguments than the call was taking, add them
10157   // now...
10158   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10159     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10160
10161   // If we are removing arguments to the function, emit an obnoxious warning...
10162   if (FT->getNumParams() < NumActualArgs) {
10163     if (!FT->isVarArg()) {
10164       cerr << "WARNING: While resolving call to function '"
10165            << Callee->getName() << "' arguments were dropped!\n";
10166     } else {
10167       // Add all of the arguments in their promoted form to the arg list...
10168       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10169         const Type *PTy = getPromotedType((*AI)->getType());
10170         if (PTy != (*AI)->getType()) {
10171           // Must promote to pass through va_arg area!
10172           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
10173                                                                 PTy, false);
10174           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10175           InsertNewInstBefore(Cast, *Caller);
10176           Args.push_back(Cast);
10177         } else {
10178           Args.push_back(*AI);
10179         }
10180
10181         // Add any parameter attributes.
10182         if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10183           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10184       }
10185     }
10186   }
10187
10188   if (Attributes FnAttrs =  CallerPAL.getFnAttributes())
10189     attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10190
10191   if (NewRetTy == Type::VoidTy)
10192     Caller->setName("");   // Void type should not have a name.
10193
10194   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10195
10196   Instruction *NC;
10197   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10198     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10199                             Args.begin(), Args.end(),
10200                             Caller->getName(), Caller);
10201     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10202     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10203   } else {
10204     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10205                           Caller->getName(), Caller);
10206     CallInst *CI = cast<CallInst>(Caller);
10207     if (CI->isTailCall())
10208       cast<CallInst>(NC)->setTailCall();
10209     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10210     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10211   }
10212
10213   // Insert a cast of the return type as necessary.
10214   Value *NV = NC;
10215   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10216     if (NV->getType() != Type::VoidTy) {
10217       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
10218                                                             OldRetTy, false);
10219       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10220
10221       // If this is an invoke instruction, we should insert it after the first
10222       // non-phi, instruction in the normal successor block.
10223       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10224         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10225         InsertNewInstBefore(NC, *I);
10226       } else {
10227         // Otherwise, it's a call, just insert cast right after the call instr
10228         InsertNewInstBefore(NC, *Caller);
10229       }
10230       AddUsersToWorkList(*Caller);
10231     } else {
10232       NV = UndefValue::get(Caller->getType());
10233     }
10234   }
10235
10236   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10237     Caller->replaceAllUsesWith(NV);
10238   Caller->eraseFromParent();
10239   RemoveFromWorkList(Caller);
10240   return true;
10241 }
10242
10243 // transformCallThroughTrampoline - Turn a call to a function created by the
10244 // init_trampoline intrinsic into a direct call to the underlying function.
10245 //
10246 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10247   Value *Callee = CS.getCalledValue();
10248   const PointerType *PTy = cast<PointerType>(Callee->getType());
10249   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10250   const AttrListPtr &Attrs = CS.getAttributes();
10251
10252   // If the call already has the 'nest' attribute somewhere then give up -
10253   // otherwise 'nest' would occur twice after splicing in the chain.
10254   if (Attrs.hasAttrSomewhere(Attribute::Nest))
10255     return 0;
10256
10257   IntrinsicInst *Tramp =
10258     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10259
10260   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10261   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10262   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10263
10264   const AttrListPtr &NestAttrs = NestF->getAttributes();
10265   if (!NestAttrs.isEmpty()) {
10266     unsigned NestIdx = 1;
10267     const Type *NestTy = 0;
10268     Attributes NestAttr = Attribute::None;
10269
10270     // Look for a parameter marked with the 'nest' attribute.
10271     for (FunctionType::param_iterator I = NestFTy->param_begin(),
10272          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10273       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10274         // Record the parameter type and any other attributes.
10275         NestTy = *I;
10276         NestAttr = NestAttrs.getParamAttributes(NestIdx);
10277         break;
10278       }
10279
10280     if (NestTy) {
10281       Instruction *Caller = CS.getInstruction();
10282       std::vector<Value*> NewArgs;
10283       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10284
10285       SmallVector<AttributeWithIndex, 8> NewAttrs;
10286       NewAttrs.reserve(Attrs.getNumSlots() + 1);
10287
10288       // Insert the nest argument into the call argument list, which may
10289       // mean appending it.  Likewise for attributes.
10290
10291       // Add any result attributes.
10292       if (Attributes Attr = Attrs.getRetAttributes())
10293         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10294
10295       {
10296         unsigned Idx = 1;
10297         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10298         do {
10299           if (Idx == NestIdx) {
10300             // Add the chain argument and attributes.
10301             Value *NestVal = Tramp->getOperand(3);
10302             if (NestVal->getType() != NestTy)
10303               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10304             NewArgs.push_back(NestVal);
10305             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10306           }
10307
10308           if (I == E)
10309             break;
10310
10311           // Add the original argument and attributes.
10312           NewArgs.push_back(*I);
10313           if (Attributes Attr = Attrs.getParamAttributes(Idx))
10314             NewAttrs.push_back
10315               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10316
10317           ++Idx, ++I;
10318         } while (1);
10319       }
10320
10321       // Add any function attributes.
10322       if (Attributes Attr = Attrs.getFnAttributes())
10323         NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10324
10325       // The trampoline may have been bitcast to a bogus type (FTy).
10326       // Handle this by synthesizing a new function type, equal to FTy
10327       // with the chain parameter inserted.
10328
10329       std::vector<const Type*> NewTypes;
10330       NewTypes.reserve(FTy->getNumParams()+1);
10331
10332       // Insert the chain's type into the list of parameter types, which may
10333       // mean appending it.
10334       {
10335         unsigned Idx = 1;
10336         FunctionType::param_iterator I = FTy->param_begin(),
10337           E = FTy->param_end();
10338
10339         do {
10340           if (Idx == NestIdx)
10341             // Add the chain's type.
10342             NewTypes.push_back(NestTy);
10343
10344           if (I == E)
10345             break;
10346
10347           // Add the original type.
10348           NewTypes.push_back(*I);
10349
10350           ++Idx, ++I;
10351         } while (1);
10352       }
10353
10354       // Replace the trampoline call with a direct call.  Let the generic
10355       // code sort out any function type mismatches.
10356       FunctionType *NewFTy =
10357         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
10358       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
10359         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
10360       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10361
10362       Instruction *NewCaller;
10363       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10364         NewCaller = InvokeInst::Create(NewCallee,
10365                                        II->getNormalDest(), II->getUnwindDest(),
10366                                        NewArgs.begin(), NewArgs.end(),
10367                                        Caller->getName(), Caller);
10368         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10369         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10370       } else {
10371         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10372                                      Caller->getName(), Caller);
10373         if (cast<CallInst>(Caller)->isTailCall())
10374           cast<CallInst>(NewCaller)->setTailCall();
10375         cast<CallInst>(NewCaller)->
10376           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10377         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10378       }
10379       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10380         Caller->replaceAllUsesWith(NewCaller);
10381       Caller->eraseFromParent();
10382       RemoveFromWorkList(Caller);
10383       return 0;
10384     }
10385   }
10386
10387   // Replace the trampoline call with a direct call.  Since there is no 'nest'
10388   // parameter, there is no need to adjust the argument list.  Let the generic
10389   // code sort out any function type mismatches.
10390   Constant *NewCallee =
10391     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10392   CS.setCalledFunction(NewCallee);
10393   return CS.getInstruction();
10394 }
10395
10396 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10397 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10398 /// and a single binop.
10399 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10400   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10401   assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10402   unsigned Opc = FirstInst->getOpcode();
10403   Value *LHSVal = FirstInst->getOperand(0);
10404   Value *RHSVal = FirstInst->getOperand(1);
10405     
10406   const Type *LHSType = LHSVal->getType();
10407   const Type *RHSType = RHSVal->getType();
10408   
10409   // Scan to see if all operands are the same opcode, all have one use, and all
10410   // kill their operands (i.e. the operands have one use).
10411   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10412     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10413     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10414         // Verify type of the LHS matches so we don't fold cmp's of different
10415         // types or GEP's with different index types.
10416         I->getOperand(0)->getType() != LHSType ||
10417         I->getOperand(1)->getType() != RHSType)
10418       return 0;
10419
10420     // If they are CmpInst instructions, check their predicates
10421     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10422       if (cast<CmpInst>(I)->getPredicate() !=
10423           cast<CmpInst>(FirstInst)->getPredicate())
10424         return 0;
10425     
10426     // Keep track of which operand needs a phi node.
10427     if (I->getOperand(0) != LHSVal) LHSVal = 0;
10428     if (I->getOperand(1) != RHSVal) RHSVal = 0;
10429   }
10430   
10431   // Otherwise, this is safe to transform!
10432   
10433   Value *InLHS = FirstInst->getOperand(0);
10434   Value *InRHS = FirstInst->getOperand(1);
10435   PHINode *NewLHS = 0, *NewRHS = 0;
10436   if (LHSVal == 0) {
10437     NewLHS = PHINode::Create(LHSType,
10438                              FirstInst->getOperand(0)->getName() + ".pn");
10439     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10440     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10441     InsertNewInstBefore(NewLHS, PN);
10442     LHSVal = NewLHS;
10443   }
10444   
10445   if (RHSVal == 0) {
10446     NewRHS = PHINode::Create(RHSType,
10447                              FirstInst->getOperand(1)->getName() + ".pn");
10448     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10449     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10450     InsertNewInstBefore(NewRHS, PN);
10451     RHSVal = NewRHS;
10452   }
10453   
10454   // Add all operands to the new PHIs.
10455   if (NewLHS || NewRHS) {
10456     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10457       Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10458       if (NewLHS) {
10459         Value *NewInLHS = InInst->getOperand(0);
10460         NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10461       }
10462       if (NewRHS) {
10463         Value *NewInRHS = InInst->getOperand(1);
10464         NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10465       }
10466     }
10467   }
10468     
10469   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10470     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10471   CmpInst *CIOp = cast<CmpInst>(FirstInst);
10472   return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10473                          RHSVal);
10474 }
10475
10476 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10477   GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10478   
10479   SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(), 
10480                                         FirstInst->op_end());
10481   // This is true if all GEP bases are allocas and if all indices into them are
10482   // constants.
10483   bool AllBasePointersAreAllocas = true;
10484   
10485   // Scan to see if all operands are the same opcode, all have one use, and all
10486   // kill their operands (i.e. the operands have one use).
10487   for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10488     GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10489     if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10490       GEP->getNumOperands() != FirstInst->getNumOperands())
10491       return 0;
10492
10493     // Keep track of whether or not all GEPs are of alloca pointers.
10494     if (AllBasePointersAreAllocas &&
10495         (!isa<AllocaInst>(GEP->getOperand(0)) ||
10496          !GEP->hasAllConstantIndices()))
10497       AllBasePointersAreAllocas = false;
10498     
10499     // Compare the operand lists.
10500     for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10501       if (FirstInst->getOperand(op) == GEP->getOperand(op))
10502         continue;
10503       
10504       // Don't merge two GEPs when two operands differ (introducing phi nodes)
10505       // if one of the PHIs has a constant for the index.  The index may be
10506       // substantially cheaper to compute for the constants, so making it a
10507       // variable index could pessimize the path.  This also handles the case
10508       // for struct indices, which must always be constant.
10509       if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10510           isa<ConstantInt>(GEP->getOperand(op)))
10511         return 0;
10512       
10513       if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10514         return 0;
10515       FixedOperands[op] = 0;  // Needs a PHI.
10516     }
10517   }
10518   
10519   // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10520   // bother doing this transformation.  At best, this will just save a bit of
10521   // offset calculation, but all the predecessors will have to materialize the
10522   // stack address into a register anyway.  We'd actually rather *clone* the
10523   // load up into the predecessors so that we have a load of a gep of an alloca,
10524   // which can usually all be folded into the load.
10525   if (AllBasePointersAreAllocas)
10526     return 0;
10527   
10528   // Otherwise, this is safe to transform.  Insert PHI nodes for each operand
10529   // that is variable.
10530   SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10531   
10532   bool HasAnyPHIs = false;
10533   for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10534     if (FixedOperands[i]) continue;  // operand doesn't need a phi.
10535     Value *FirstOp = FirstInst->getOperand(i);
10536     PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10537                                      FirstOp->getName()+".pn");
10538     InsertNewInstBefore(NewPN, PN);
10539     
10540     NewPN->reserveOperandSpace(e);
10541     NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10542     OperandPhis[i] = NewPN;
10543     FixedOperands[i] = NewPN;
10544     HasAnyPHIs = true;
10545   }
10546
10547   
10548   // Add all operands to the new PHIs.
10549   if (HasAnyPHIs) {
10550     for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10551       GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10552       BasicBlock *InBB = PN.getIncomingBlock(i);
10553       
10554       for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10555         if (PHINode *OpPhi = OperandPhis[op])
10556           OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10557     }
10558   }
10559   
10560   Value *Base = FixedOperands[0];
10561   return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10562                                    FixedOperands.end());
10563 }
10564
10565
10566 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10567 /// sink the load out of the block that defines it.  This means that it must be
10568 /// obvious the value of the load is not changed from the point of the load to
10569 /// the end of the block it is in.
10570 ///
10571 /// Finally, it is safe, but not profitable, to sink a load targetting a
10572 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
10573 /// to a register.
10574 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10575   BasicBlock::iterator BBI = L, E = L->getParent()->end();
10576   
10577   for (++BBI; BBI != E; ++BBI)
10578     if (BBI->mayWriteToMemory())
10579       return false;
10580   
10581   // Check for non-address taken alloca.  If not address-taken already, it isn't
10582   // profitable to do this xform.
10583   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10584     bool isAddressTaken = false;
10585     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10586          UI != E; ++UI) {
10587       if (isa<LoadInst>(UI)) continue;
10588       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10589         // If storing TO the alloca, then the address isn't taken.
10590         if (SI->getOperand(1) == AI) continue;
10591       }
10592       isAddressTaken = true;
10593       break;
10594     }
10595     
10596     if (!isAddressTaken && AI->isStaticAlloca())
10597       return false;
10598   }
10599   
10600   // If this load is a load from a GEP with a constant offset from an alloca,
10601   // then we don't want to sink it.  In its present form, it will be
10602   // load [constant stack offset].  Sinking it will cause us to have to
10603   // materialize the stack addresses in each predecessor in a register only to
10604   // do a shared load from register in the successor.
10605   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10606     if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10607       if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10608         return false;
10609   
10610   return true;
10611 }
10612
10613
10614 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10615 // operator and they all are only used by the PHI, PHI together their
10616 // inputs, and do the operation once, to the result of the PHI.
10617 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10618   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10619
10620   // Scan the instruction, looking for input operations that can be folded away.
10621   // If all input operands to the phi are the same instruction (e.g. a cast from
10622   // the same type or "+42") we can pull the operation through the PHI, reducing
10623   // code size and simplifying code.
10624   Constant *ConstantOp = 0;
10625   const Type *CastSrcTy = 0;
10626   bool isVolatile = false;
10627   if (isa<CastInst>(FirstInst)) {
10628     CastSrcTy = FirstInst->getOperand(0)->getType();
10629   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10630     // Can fold binop, compare or shift here if the RHS is a constant, 
10631     // otherwise call FoldPHIArgBinOpIntoPHI.
10632     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10633     if (ConstantOp == 0)
10634       return FoldPHIArgBinOpIntoPHI(PN);
10635   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10636     isVolatile = LI->isVolatile();
10637     // We can't sink the load if the loaded value could be modified between the
10638     // load and the PHI.
10639     if (LI->getParent() != PN.getIncomingBlock(0) ||
10640         !isSafeAndProfitableToSinkLoad(LI))
10641       return 0;
10642     
10643     // If the PHI is of volatile loads and the load block has multiple
10644     // successors, sinking it would remove a load of the volatile value from
10645     // the path through the other successor.
10646     if (isVolatile &&
10647         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10648       return 0;
10649     
10650   } else if (isa<GetElementPtrInst>(FirstInst)) {
10651     return FoldPHIArgGEPIntoPHI(PN);
10652   } else {
10653     return 0;  // Cannot fold this operation.
10654   }
10655
10656   // Check to see if all arguments are the same operation.
10657   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10658     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10659     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10660     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10661       return 0;
10662     if (CastSrcTy) {
10663       if (I->getOperand(0)->getType() != CastSrcTy)
10664         return 0;  // Cast operation must match.
10665     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10666       // We can't sink the load if the loaded value could be modified between 
10667       // the load and the PHI.
10668       if (LI->isVolatile() != isVolatile ||
10669           LI->getParent() != PN.getIncomingBlock(i) ||
10670           !isSafeAndProfitableToSinkLoad(LI))
10671         return 0;
10672       
10673       // If the PHI is of volatile loads and the load block has multiple
10674       // successors, sinking it would remove a load of the volatile value from
10675       // the path through the other successor.
10676       if (isVolatile &&
10677           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10678         return 0;
10679       
10680     } else if (I->getOperand(1) != ConstantOp) {
10681       return 0;
10682     }
10683   }
10684
10685   // Okay, they are all the same operation.  Create a new PHI node of the
10686   // correct type, and PHI together all of the LHS's of the instructions.
10687   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10688                                    PN.getName()+".in");
10689   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10690
10691   Value *InVal = FirstInst->getOperand(0);
10692   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10693
10694   // Add all operands to the new PHI.
10695   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10696     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10697     if (NewInVal != InVal)
10698       InVal = 0;
10699     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10700   }
10701
10702   Value *PhiVal;
10703   if (InVal) {
10704     // The new PHI unions all of the same values together.  This is really
10705     // common, so we handle it intelligently here for compile-time speed.
10706     PhiVal = InVal;
10707     delete NewPN;
10708   } else {
10709     InsertNewInstBefore(NewPN, PN);
10710     PhiVal = NewPN;
10711   }
10712
10713   // Insert and return the new operation.
10714   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10715     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10716   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10717     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10718   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10719     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
10720                            PhiVal, ConstantOp);
10721   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10722   
10723   // If this was a volatile load that we are merging, make sure to loop through
10724   // and mark all the input loads as non-volatile.  If we don't do this, we will
10725   // insert a new volatile load and the old ones will not be deletable.
10726   if (isVolatile)
10727     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10728       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10729   
10730   return new LoadInst(PhiVal, "", isVolatile);
10731 }
10732
10733 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10734 /// that is dead.
10735 static bool DeadPHICycle(PHINode *PN,
10736                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10737   if (PN->use_empty()) return true;
10738   if (!PN->hasOneUse()) return false;
10739
10740   // Remember this node, and if we find the cycle, return.
10741   if (!PotentiallyDeadPHIs.insert(PN))
10742     return true;
10743   
10744   // Don't scan crazily complex things.
10745   if (PotentiallyDeadPHIs.size() == 16)
10746     return false;
10747
10748   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10749     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10750
10751   return false;
10752 }
10753
10754 /// PHIsEqualValue - Return true if this phi node is always equal to
10755 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10756 ///   z = some value; x = phi (y, z); y = phi (x, z)
10757 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10758                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10759   // See if we already saw this PHI node.
10760   if (!ValueEqualPHIs.insert(PN))
10761     return true;
10762   
10763   // Don't scan crazily complex things.
10764   if (ValueEqualPHIs.size() == 16)
10765     return false;
10766  
10767   // Scan the operands to see if they are either phi nodes or are equal to
10768   // the value.
10769   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10770     Value *Op = PN->getIncomingValue(i);
10771     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10772       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10773         return false;
10774     } else if (Op != NonPhiInVal)
10775       return false;
10776   }
10777   
10778   return true;
10779 }
10780
10781
10782 // PHINode simplification
10783 //
10784 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10785   // If LCSSA is around, don't mess with Phi nodes
10786   if (MustPreserveLCSSA) return 0;
10787   
10788   if (Value *V = PN.hasConstantValue())
10789     return ReplaceInstUsesWith(PN, V);
10790
10791   // If all PHI operands are the same operation, pull them through the PHI,
10792   // reducing code size.
10793   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10794       isa<Instruction>(PN.getIncomingValue(1)) &&
10795       cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10796       cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10797       // FIXME: The hasOneUse check will fail for PHIs that use the value more
10798       // than themselves more than once.
10799       PN.getIncomingValue(0)->hasOneUse())
10800     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10801       return Result;
10802
10803   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10804   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10805   // PHI)... break the cycle.
10806   if (PN.hasOneUse()) {
10807     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10808     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10809       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10810       PotentiallyDeadPHIs.insert(&PN);
10811       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10812         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10813     }
10814    
10815     // If this phi has a single use, and if that use just computes a value for
10816     // the next iteration of a loop, delete the phi.  This occurs with unused
10817     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10818     // common case here is good because the only other things that catch this
10819     // are induction variable analysis (sometimes) and ADCE, which is only run
10820     // late.
10821     if (PHIUser->hasOneUse() &&
10822         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10823         PHIUser->use_back() == &PN) {
10824       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10825     }
10826   }
10827
10828   // We sometimes end up with phi cycles that non-obviously end up being the
10829   // same value, for example:
10830   //   z = some value; x = phi (y, z); y = phi (x, z)
10831   // where the phi nodes don't necessarily need to be in the same block.  Do a
10832   // quick check to see if the PHI node only contains a single non-phi value, if
10833   // so, scan to see if the phi cycle is actually equal to that value.
10834   {
10835     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10836     // Scan for the first non-phi operand.
10837     while (InValNo != NumOperandVals && 
10838            isa<PHINode>(PN.getIncomingValue(InValNo)))
10839       ++InValNo;
10840
10841     if (InValNo != NumOperandVals) {
10842       Value *NonPhiInVal = PN.getOperand(InValNo);
10843       
10844       // Scan the rest of the operands to see if there are any conflicts, if so
10845       // there is no need to recursively scan other phis.
10846       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10847         Value *OpVal = PN.getIncomingValue(InValNo);
10848         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10849           break;
10850       }
10851       
10852       // If we scanned over all operands, then we have one unique value plus
10853       // phi values.  Scan PHI nodes to see if they all merge in each other or
10854       // the value.
10855       if (InValNo == NumOperandVals) {
10856         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10857         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10858           return ReplaceInstUsesWith(PN, NonPhiInVal);
10859       }
10860     }
10861   }
10862   return 0;
10863 }
10864
10865 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10866                                    Instruction *InsertPoint,
10867                                    InstCombiner *IC) {
10868   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10869   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10870   // We must cast correctly to the pointer type. Ensure that we
10871   // sign extend the integer value if it is smaller as this is
10872   // used for address computation.
10873   Instruction::CastOps opcode = 
10874      (VTySize < PtrSize ? Instruction::SExt :
10875       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10876   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10877 }
10878
10879
10880 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10881   Value *PtrOp = GEP.getOperand(0);
10882   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10883   // If so, eliminate the noop.
10884   if (GEP.getNumOperands() == 1)
10885     return ReplaceInstUsesWith(GEP, PtrOp);
10886
10887   if (isa<UndefValue>(GEP.getOperand(0)))
10888     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10889
10890   bool HasZeroPointerIndex = false;
10891   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10892     HasZeroPointerIndex = C->isNullValue();
10893
10894   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10895     return ReplaceInstUsesWith(GEP, PtrOp);
10896
10897   // Eliminate unneeded casts for indices.
10898   bool MadeChange = false;
10899   
10900   gep_type_iterator GTI = gep_type_begin(GEP);
10901   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10902        i != e; ++i, ++GTI) {
10903     if (isa<SequentialType>(*GTI)) {
10904       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10905         if (CI->getOpcode() == Instruction::ZExt ||
10906             CI->getOpcode() == Instruction::SExt) {
10907           const Type *SrcTy = CI->getOperand(0)->getType();
10908           // We can eliminate a cast from i32 to i64 iff the target 
10909           // is a 32-bit pointer target.
10910           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10911             MadeChange = true;
10912             *i = CI->getOperand(0);
10913           }
10914         }
10915       }
10916       // If we are using a wider index than needed for this platform, shrink it
10917       // to what we need.  If narrower, sign-extend it to what we need.
10918       // If the incoming value needs a cast instruction,
10919       // insert it.  This explicit cast can make subsequent optimizations more
10920       // obvious.
10921       Value *Op = *i;
10922       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10923         if (Constant *C = dyn_cast<Constant>(Op)) {
10924           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10925           MadeChange = true;
10926         } else {
10927           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10928                                 GEP);
10929           *i = Op;
10930           MadeChange = true;
10931         }
10932       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10933         if (Constant *C = dyn_cast<Constant>(Op)) {
10934           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10935           MadeChange = true;
10936         } else {
10937           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10938                                 GEP);
10939           *i = Op;
10940           MadeChange = true;
10941         }
10942       }
10943     }
10944   }
10945   if (MadeChange) return &GEP;
10946
10947   // Combine Indices - If the source pointer to this getelementptr instruction
10948   // is a getelementptr instruction, combine the indices of the two
10949   // getelementptr instructions into a single instruction.
10950   //
10951   SmallVector<Value*, 8> SrcGEPOperands;
10952   if (User *Src = dyn_castGetElementPtr(PtrOp))
10953     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10954
10955   if (!SrcGEPOperands.empty()) {
10956     // Note that if our source is a gep chain itself that we wait for that
10957     // chain to be resolved before we perform this transformation.  This
10958     // avoids us creating a TON of code in some cases.
10959     //
10960     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10961         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10962       return 0;   // Wait until our source is folded to completion.
10963
10964     SmallVector<Value*, 8> Indices;
10965
10966     // Find out whether the last index in the source GEP is a sequential idx.
10967     bool EndsWithSequential = false;
10968     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10969            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10970       EndsWithSequential = !isa<StructType>(*I);
10971
10972     // Can we combine the two pointer arithmetics offsets?
10973     if (EndsWithSequential) {
10974       // Replace: gep (gep %P, long B), long A, ...
10975       // With:    T = long A+B; gep %P, T, ...
10976       //
10977       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10978       if (SO1 == Constant::getNullValue(SO1->getType())) {
10979         Sum = GO1;
10980       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10981         Sum = SO1;
10982       } else {
10983         // If they aren't the same type, convert both to an integer of the
10984         // target's pointer size.
10985         if (SO1->getType() != GO1->getType()) {
10986           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10987             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10988           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10989             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10990           } else {
10991             unsigned PS = TD->getPointerSizeInBits();
10992             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10993               // Convert GO1 to SO1's type.
10994               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10995
10996             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10997               // Convert SO1 to GO1's type.
10998               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10999             } else {
11000               const Type *PT = TD->getIntPtrType();
11001               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11002               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11003             }
11004           }
11005         }
11006         if (isa<Constant>(SO1) && isa<Constant>(GO1))
11007           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
11008         else {
11009           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11010           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11011         }
11012       }
11013
11014       // Recycle the GEP we already have if possible.
11015       if (SrcGEPOperands.size() == 2) {
11016         GEP.setOperand(0, SrcGEPOperands[0]);
11017         GEP.setOperand(1, Sum);
11018         return &GEP;
11019       } else {
11020         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11021                        SrcGEPOperands.end()-1);
11022         Indices.push_back(Sum);
11023         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11024       }
11025     } else if (isa<Constant>(*GEP.idx_begin()) &&
11026                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11027                SrcGEPOperands.size() != 1) {
11028       // Otherwise we can do the fold if the first index of the GEP is a zero
11029       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11030                      SrcGEPOperands.end());
11031       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11032     }
11033
11034     if (!Indices.empty())
11035       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11036                                        Indices.end(), GEP.getName());
11037
11038   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11039     // GEP of global variable.  If all of the indices for this GEP are
11040     // constants, we can promote this to a constexpr instead of an instruction.
11041
11042     // Scan for nonconstants...
11043     SmallVector<Constant*, 8> Indices;
11044     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11045     for (; I != E && isa<Constant>(*I); ++I)
11046       Indices.push_back(cast<Constant>(*I));
11047
11048     if (I == E) {  // If they are all constants...
11049       Constant *CE = ConstantExpr::getGetElementPtr(GV,
11050                                                     &Indices[0],Indices.size());
11051
11052       // Replace all uses of the GEP with the new constexpr...
11053       return ReplaceInstUsesWith(GEP, CE);
11054     }
11055   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
11056     if (!isa<PointerType>(X->getType())) {
11057       // Not interesting.  Source pointer must be a cast from pointer.
11058     } else if (HasZeroPointerIndex) {
11059       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11060       // into     : GEP [10 x i8]* X, i32 0, ...
11061       //
11062       // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11063       //           into     : GEP i8* X, ...
11064       // 
11065       // This occurs when the program declares an array extern like "int X[];"
11066       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11067       const PointerType *XTy = cast<PointerType>(X->getType());
11068       if (const ArrayType *CATy =
11069           dyn_cast<ArrayType>(CPTy->getElementType())) {
11070         // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11071         if (CATy->getElementType() == XTy->getElementType()) {
11072           // -> GEP i8* X, ...
11073           SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11074           return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11075                                            GEP.getName());
11076         } else if (const ArrayType *XATy =
11077                  dyn_cast<ArrayType>(XTy->getElementType())) {
11078           // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11079           if (CATy->getElementType() == XATy->getElementType()) {
11080             // -> GEP [10 x i8]* X, i32 0, ...
11081             // At this point, we know that the cast source type is a pointer
11082             // to an array of the same type as the destination pointer
11083             // array.  Because the array type is never stepped over (there
11084             // is a leading zero) we can fold the cast into this GEP.
11085             GEP.setOperand(0, X);
11086             return &GEP;
11087           }
11088         }
11089       }
11090     } else if (GEP.getNumOperands() == 2) {
11091       // Transform things like:
11092       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11093       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11094       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11095       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11096       if (isa<ArrayType>(SrcElTy) &&
11097           TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11098           TD->getTypeAllocSize(ResElTy)) {
11099         Value *Idx[2];
11100         Idx[0] = Constant::getNullValue(Type::Int32Ty);
11101         Idx[1] = GEP.getOperand(1);
11102         Value *V = InsertNewInstBefore(
11103                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11104         // V and GEP are both pointer types --> BitCast
11105         return new BitCastInst(V, GEP.getType());
11106       }
11107       
11108       // Transform things like:
11109       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11110       //   (where tmp = 8*tmp2) into:
11111       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11112       
11113       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11114         uint64_t ArrayEltSize =
11115             TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11116         
11117         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
11118         // allow either a mul, shift, or constant here.
11119         Value *NewIdx = 0;
11120         ConstantInt *Scale = 0;
11121         if (ArrayEltSize == 1) {
11122           NewIdx = GEP.getOperand(1);
11123           Scale = ConstantInt::get(NewIdx->getType(), 1);
11124         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11125           NewIdx = ConstantInt::get(CI->getType(), 1);
11126           Scale = CI;
11127         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11128           if (Inst->getOpcode() == Instruction::Shl &&
11129               isa<ConstantInt>(Inst->getOperand(1))) {
11130             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11131             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11132             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
11133             NewIdx = Inst->getOperand(0);
11134           } else if (Inst->getOpcode() == Instruction::Mul &&
11135                      isa<ConstantInt>(Inst->getOperand(1))) {
11136             Scale = cast<ConstantInt>(Inst->getOperand(1));
11137             NewIdx = Inst->getOperand(0);
11138           }
11139         }
11140         
11141         // If the index will be to exactly the right offset with the scale taken
11142         // out, perform the transformation. Note, we don't know whether Scale is
11143         // signed or not. We'll use unsigned version of division/modulo
11144         // operation after making sure Scale doesn't have the sign bit set.
11145         if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11146             Scale->getZExtValue() % ArrayEltSize == 0) {
11147           Scale = ConstantInt::get(Scale->getType(),
11148                                    Scale->getZExtValue() / ArrayEltSize);
11149           if (Scale->getZExtValue() != 1) {
11150             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11151                                                        false /*ZExt*/);
11152             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11153             NewIdx = InsertNewInstBefore(Sc, GEP);
11154           }
11155
11156           // Insert the new GEP instruction.
11157           Value *Idx[2];
11158           Idx[0] = Constant::getNullValue(Type::Int32Ty);
11159           Idx[1] = NewIdx;
11160           Instruction *NewGEP =
11161             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11162           NewGEP = InsertNewInstBefore(NewGEP, GEP);
11163           // The NewGEP must be pointer typed, so must the old one -> BitCast
11164           return new BitCastInst(NewGEP, GEP.getType());
11165         }
11166       }
11167     }
11168   }
11169   
11170   /// See if we can simplify:
11171   ///   X = bitcast A to B*
11172   ///   Y = gep X, <...constant indices...>
11173   /// into a gep of the original struct.  This is important for SROA and alias
11174   /// analysis of unions.  If "A" is also a bitcast, wait for A/X to be merged.
11175   if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11176     if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11177       // Determine how much the GEP moves the pointer.  We are guaranteed to get
11178       // a constant back from EmitGEPOffset.
11179       ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11180       int64_t Offset = OffsetV->getSExtValue();
11181       
11182       // If this GEP instruction doesn't move the pointer, just replace the GEP
11183       // with a bitcast of the real input to the dest type.
11184       if (Offset == 0) {
11185         // If the bitcast is of an allocation, and the allocation will be
11186         // converted to match the type of the cast, don't touch this.
11187         if (isa<AllocationInst>(BCI->getOperand(0))) {
11188           // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11189           if (Instruction *I = visitBitCast(*BCI)) {
11190             if (I != BCI) {
11191               I->takeName(BCI);
11192               BCI->getParent()->getInstList().insert(BCI, I);
11193               ReplaceInstUsesWith(*BCI, I);
11194             }
11195             return &GEP;
11196           }
11197         }
11198         return new BitCastInst(BCI->getOperand(0), GEP.getType());
11199       }
11200       
11201       // Otherwise, if the offset is non-zero, we need to find out if there is a
11202       // field at Offset in 'A's type.  If so, we can pull the cast through the
11203       // GEP.
11204       SmallVector<Value*, 8> NewIndices;
11205       const Type *InTy =
11206         cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11207       if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
11208         Instruction *NGEP =
11209            GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11210                                      NewIndices.end());
11211         if (NGEP->getType() == GEP.getType()) return NGEP;
11212         InsertNewInstBefore(NGEP, GEP);
11213         NGEP->takeName(&GEP);
11214         return new BitCastInst(NGEP, GEP.getType());
11215       }
11216     }
11217   }    
11218     
11219   return 0;
11220 }
11221
11222 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11223   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11224   if (AI.isArrayAllocation()) {  // Check C != 1
11225     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11226       const Type *NewTy = 
11227         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11228       AllocationInst *New = 0;
11229
11230       // Create and insert the replacement instruction...
11231       if (isa<MallocInst>(AI))
11232         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11233       else {
11234         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11235         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11236       }
11237
11238       InsertNewInstBefore(New, AI);
11239
11240       // Scan to the end of the allocation instructions, to skip over a block of
11241       // allocas if possible...also skip interleaved debug info
11242       //
11243       BasicBlock::iterator It = New;
11244       while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11245
11246       // Now that I is pointing to the first non-allocation-inst in the block,
11247       // insert our getelementptr instruction...
11248       //
11249       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
11250       Value *Idx[2];
11251       Idx[0] = NullIdx;
11252       Idx[1] = NullIdx;
11253       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11254                                            New->getName()+".sub", It);
11255
11256       // Now make everything use the getelementptr instead of the original
11257       // allocation.
11258       return ReplaceInstUsesWith(AI, V);
11259     } else if (isa<UndefValue>(AI.getArraySize())) {
11260       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11261     }
11262   }
11263
11264   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11265     // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11266     // Note that we only do this for alloca's, because malloc should allocate
11267     // and return a unique pointer, even for a zero byte allocation.
11268     if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11269       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11270
11271     // If the alignment is 0 (unspecified), assign it the preferred alignment.
11272     if (AI.getAlignment() == 0)
11273       AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11274   }
11275
11276   return 0;
11277 }
11278
11279 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11280   Value *Op = FI.getOperand(0);
11281
11282   // free undef -> unreachable.
11283   if (isa<UndefValue>(Op)) {
11284     // Insert a new store to null because we cannot modify the CFG here.
11285     new StoreInst(ConstantInt::getTrue(),
11286                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
11287     return EraseInstFromFunction(FI);
11288   }
11289   
11290   // If we have 'free null' delete the instruction.  This can happen in stl code
11291   // when lots of inlining happens.
11292   if (isa<ConstantPointerNull>(Op))
11293     return EraseInstFromFunction(FI);
11294   
11295   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11296   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11297     FI.setOperand(0, CI->getOperand(0));
11298     return &FI;
11299   }
11300   
11301   // Change free (gep X, 0,0,0,0) into free(X)
11302   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11303     if (GEPI->hasAllZeroIndices()) {
11304       AddToWorkList(GEPI);
11305       FI.setOperand(0, GEPI->getOperand(0));
11306       return &FI;
11307     }
11308   }
11309   
11310   // Change free(malloc) into nothing, if the malloc has a single use.
11311   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11312     if (MI->hasOneUse()) {
11313       EraseInstFromFunction(FI);
11314       return EraseInstFromFunction(*MI);
11315     }
11316
11317   return 0;
11318 }
11319
11320
11321 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11322 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11323                                         const TargetData *TD) {
11324   User *CI = cast<User>(LI.getOperand(0));
11325   Value *CastOp = CI->getOperand(0);
11326
11327   if (TD) {
11328     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11329       // Instead of loading constant c string, use corresponding integer value
11330       // directly if string length is small enough.
11331       std::string Str;
11332       if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11333         unsigned len = Str.length();
11334         const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11335         unsigned numBits = Ty->getPrimitiveSizeInBits();
11336         // Replace LI with immediate integer store.
11337         if ((numBits >> 3) == len + 1) {
11338           APInt StrVal(numBits, 0);
11339           APInt SingleChar(numBits, 0);
11340           if (TD->isLittleEndian()) {
11341             for (signed i = len-1; i >= 0; i--) {
11342               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11343               StrVal = (StrVal << 8) | SingleChar;
11344             }
11345           } else {
11346             for (unsigned i = 0; i < len; i++) {
11347               SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11348               StrVal = (StrVal << 8) | SingleChar;
11349             }
11350             // Append NULL at the end.
11351             SingleChar = 0;
11352             StrVal = (StrVal << 8) | SingleChar;
11353           }
11354           Value *NL = ConstantInt::get(StrVal);
11355           return IC.ReplaceInstUsesWith(LI, NL);
11356         }
11357       }
11358     }
11359   }
11360
11361   const PointerType *DestTy = cast<PointerType>(CI->getType());
11362   const Type *DestPTy = DestTy->getElementType();
11363   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11364
11365     // If the address spaces don't match, don't eliminate the cast.
11366     if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11367       return 0;
11368
11369     const Type *SrcPTy = SrcTy->getElementType();
11370
11371     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
11372          isa<VectorType>(DestPTy)) {
11373       // If the source is an array, the code below will not succeed.  Check to
11374       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11375       // constants.
11376       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11377         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11378           if (ASrcTy->getNumElements() != 0) {
11379             Value *Idxs[2];
11380             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11381             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11382             SrcTy = cast<PointerType>(CastOp->getType());
11383             SrcPTy = SrcTy->getElementType();
11384           }
11385
11386       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
11387             isa<VectorType>(SrcPTy)) &&
11388           // Do not allow turning this into a load of an integer, which is then
11389           // casted to a pointer, this pessimizes pointer analysis a lot.
11390           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11391           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11392                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11393
11394         // Okay, we are casting from one integer or pointer type to another of
11395         // the same size.  Instead of casting the pointer before the load, cast
11396         // the result of the loaded value.
11397         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11398                                                              CI->getName(),
11399                                                          LI.isVolatile()),LI);
11400         // Now cast the result of the load.
11401         return new BitCastInst(NewLoad, LI.getType());
11402       }
11403     }
11404   }
11405   return 0;
11406 }
11407
11408 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
11409 /// from this value cannot trap.  If it is not obviously safe to load from the
11410 /// specified pointer, we do a quick local scan of the basic block containing
11411 /// ScanFrom, to determine if the address is already accessed.
11412 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
11413   // If it is an alloca it is always safe to load from.
11414   if (isa<AllocaInst>(V)) return true;
11415
11416   // If it is a global variable it is mostly safe to load from.
11417   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
11418     // Don't try to evaluate aliases.  External weak GV can be null.
11419     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
11420
11421   // Otherwise, be a little bit agressive by scanning the local block where we
11422   // want to check to see if the pointer is already being loaded or stored
11423   // from/to.  If so, the previous load or store would have already trapped,
11424   // so there is no harm doing an extra load (also, CSE will later eliminate
11425   // the load entirely).
11426   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
11427
11428   while (BBI != E) {
11429     --BBI;
11430
11431     // If we see a free or a call (which might do a free) the pointer could be
11432     // marked invalid.
11433     if (isa<FreeInst>(BBI) || 
11434         (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)))
11435       return false;
11436     
11437     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11438       if (LI->getOperand(0) == V) return true;
11439     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
11440       if (SI->getOperand(1) == V) return true;
11441     }
11442
11443   }
11444   return false;
11445 }
11446
11447 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11448   Value *Op = LI.getOperand(0);
11449
11450   // Attempt to improve the alignment.
11451   unsigned KnownAlign =
11452     GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11453   if (KnownAlign >
11454       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11455                                 LI.getAlignment()))
11456     LI.setAlignment(KnownAlign);
11457
11458   // load (cast X) --> cast (load X) iff safe
11459   if (isa<CastInst>(Op))
11460     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11461       return Res;
11462
11463   // None of the following transforms are legal for volatile loads.
11464   if (LI.isVolatile()) return 0;
11465   
11466   // Do really simple store-to-load forwarding and load CSE, to catch cases
11467   // where there are several consequtive memory accesses to the same location,
11468   // separated by a few arithmetic operations.
11469   BasicBlock::iterator BBI = &LI;
11470   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11471     return ReplaceInstUsesWith(LI, AvailableVal);
11472
11473   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11474     const Value *GEPI0 = GEPI->getOperand(0);
11475     // TODO: Consider a target hook for valid address spaces for this xform.
11476     if (isa<ConstantPointerNull>(GEPI0) &&
11477         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11478       // Insert a new store to null instruction before the load to indicate
11479       // that this code is not reachable.  We do this instead of inserting
11480       // an unreachable instruction directly because we cannot modify the
11481       // CFG.
11482       new StoreInst(UndefValue::get(LI.getType()),
11483                     Constant::getNullValue(Op->getType()), &LI);
11484       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11485     }
11486   } 
11487
11488   if (Constant *C = dyn_cast<Constant>(Op)) {
11489     // load null/undef -> undef
11490     // TODO: Consider a target hook for valid address spaces for this xform.
11491     if (isa<UndefValue>(C) || (C->isNullValue() && 
11492         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11493       // Insert a new store to null instruction before the load to indicate that
11494       // this code is not reachable.  We do this instead of inserting an
11495       // unreachable instruction directly because we cannot modify the CFG.
11496       new StoreInst(UndefValue::get(LI.getType()),
11497                     Constant::getNullValue(Op->getType()), &LI);
11498       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11499     }
11500
11501     // Instcombine load (constant global) into the value loaded.
11502     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11503       if (GV->isConstant() && GV->hasDefinitiveInitializer())
11504         return ReplaceInstUsesWith(LI, GV->getInitializer());
11505
11506     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11507     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11508       if (CE->getOpcode() == Instruction::GetElementPtr) {
11509         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11510           if (GV->isConstant() && GV->hasDefinitiveInitializer())
11511             if (Constant *V = 
11512                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11513               return ReplaceInstUsesWith(LI, V);
11514         if (CE->getOperand(0)->isNullValue()) {
11515           // Insert a new store to null instruction before the load to indicate
11516           // that this code is not reachable.  We do this instead of inserting
11517           // an unreachable instruction directly because we cannot modify the
11518           // CFG.
11519           new StoreInst(UndefValue::get(LI.getType()),
11520                         Constant::getNullValue(Op->getType()), &LI);
11521           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11522         }
11523
11524       } else if (CE->isCast()) {
11525         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11526           return Res;
11527       }
11528     }
11529   }
11530     
11531   // If this load comes from anywhere in a constant global, and if the global
11532   // is all undef or zero, we know what it loads.
11533   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11534     if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11535       if (GV->getInitializer()->isNullValue())
11536         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11537       else if (isa<UndefValue>(GV->getInitializer()))
11538         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11539     }
11540   }
11541
11542   if (Op->hasOneUse()) {
11543     // Change select and PHI nodes to select values instead of addresses: this
11544     // helps alias analysis out a lot, allows many others simplifications, and
11545     // exposes redundancy in the code.
11546     //
11547     // Note that we cannot do the transformation unless we know that the
11548     // introduced loads cannot trap!  Something like this is valid as long as
11549     // the condition is always false: load (select bool %C, int* null, int* %G),
11550     // but it would not be valid if we transformed it to load from null
11551     // unconditionally.
11552     //
11553     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11554       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
11555       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11556           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11557         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11558                                      SI->getOperand(1)->getName()+".val"), LI);
11559         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11560                                      SI->getOperand(2)->getName()+".val"), LI);
11561         return SelectInst::Create(SI->getCondition(), V1, V2);
11562       }
11563
11564       // load (select (cond, null, P)) -> load P
11565       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11566         if (C->isNullValue()) {
11567           LI.setOperand(0, SI->getOperand(2));
11568           return &LI;
11569         }
11570
11571       // load (select (cond, P, null)) -> load P
11572       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11573         if (C->isNullValue()) {
11574           LI.setOperand(0, SI->getOperand(1));
11575           return &LI;
11576         }
11577     }
11578   }
11579   return 0;
11580 }
11581
11582 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11583 /// when possible.  This makes it generally easy to do alias analysis and/or
11584 /// SROA/mem2reg of the memory object.
11585 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11586   User *CI = cast<User>(SI.getOperand(1));
11587   Value *CastOp = CI->getOperand(0);
11588
11589   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11590   const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11591   if (SrcTy == 0) return 0;
11592   
11593   const Type *SrcPTy = SrcTy->getElementType();
11594
11595   if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11596     return 0;
11597   
11598   /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11599   /// to its first element.  This allows us to handle things like:
11600   ///   store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11601   /// on 32-bit hosts.
11602   SmallVector<Value*, 4> NewGEPIndices;
11603   
11604   // If the source is an array, the code below will not succeed.  Check to
11605   // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
11606   // constants.
11607   if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11608     // Index through pointer.
11609     Constant *Zero = Constant::getNullValue(Type::Int32Ty);
11610     NewGEPIndices.push_back(Zero);
11611     
11612     while (1) {
11613       if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11614         if (!STy->getNumElements()) /* Struct can be empty {} */
11615           break;
11616         NewGEPIndices.push_back(Zero);
11617         SrcPTy = STy->getElementType(0);
11618       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11619         NewGEPIndices.push_back(Zero);
11620         SrcPTy = ATy->getElementType();
11621       } else {
11622         break;
11623       }
11624     }
11625     
11626     SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11627   }
11628
11629   if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11630     return 0;
11631   
11632   // If the pointers point into different address spaces or if they point to
11633   // values with different sizes, we can't do the transformation.
11634   if (SrcTy->getAddressSpace() != 
11635         cast<PointerType>(CI->getType())->getAddressSpace() ||
11636       IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11637       IC.getTargetData().getTypeSizeInBits(DestPTy))
11638     return 0;
11639
11640   // Okay, we are casting from one integer or pointer type to another of
11641   // the same size.  Instead of casting the pointer before 
11642   // the store, cast the value to be stored.
11643   Value *NewCast;
11644   Value *SIOp0 = SI.getOperand(0);
11645   Instruction::CastOps opcode = Instruction::BitCast;
11646   const Type* CastSrcTy = SIOp0->getType();
11647   const Type* CastDstTy = SrcPTy;
11648   if (isa<PointerType>(CastDstTy)) {
11649     if (CastSrcTy->isInteger())
11650       opcode = Instruction::IntToPtr;
11651   } else if (isa<IntegerType>(CastDstTy)) {
11652     if (isa<PointerType>(SIOp0->getType()))
11653       opcode = Instruction::PtrToInt;
11654   }
11655   
11656   // SIOp0 is a pointer to aggregate and this is a store to the first field,
11657   // emit a GEP to index into its first field.
11658   if (!NewGEPIndices.empty()) {
11659     if (Constant *C = dyn_cast<Constant>(CastOp))
11660       CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0], 
11661                                               NewGEPIndices.size());
11662     else
11663       CastOp = IC.InsertNewInstBefore(
11664               GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11665                                         NewGEPIndices.end()), SI);
11666   }
11667   
11668   if (Constant *C = dyn_cast<Constant>(SIOp0))
11669     NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11670   else
11671     NewCast = IC.InsertNewInstBefore(
11672       CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
11673       SI);
11674   return new StoreInst(NewCast, CastOp);
11675 }
11676
11677 /// equivalentAddressValues - Test if A and B will obviously have the same
11678 /// value. This includes recognizing that %t0 and %t1 will have the same
11679 /// value in code like this:
11680 ///   %t0 = getelementptr \@a, 0, 3
11681 ///   store i32 0, i32* %t0
11682 ///   %t1 = getelementptr \@a, 0, 3
11683 ///   %t2 = load i32* %t1
11684 ///
11685 static bool equivalentAddressValues(Value *A, Value *B) {
11686   // Test if the values are trivially equivalent.
11687   if (A == B) return true;
11688   
11689   // Test if the values come form identical arithmetic instructions.
11690   if (isa<BinaryOperator>(A) ||
11691       isa<CastInst>(A) ||
11692       isa<PHINode>(A) ||
11693       isa<GetElementPtrInst>(A))
11694     if (Instruction *BI = dyn_cast<Instruction>(B))
11695       if (cast<Instruction>(A)->isIdenticalTo(BI))
11696         return true;
11697   
11698   // Otherwise they may not be equivalent.
11699   return false;
11700 }
11701
11702 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11703 // return the llvm.dbg.declare.
11704 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11705   if (!V->hasNUses(2))
11706     return 0;
11707   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11708        UI != E; ++UI) {
11709     if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11710       return DI;
11711     if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11712       if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11713         return DI;
11714       }
11715   }
11716   return 0;
11717 }
11718
11719 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11720   Value *Val = SI.getOperand(0);
11721   Value *Ptr = SI.getOperand(1);
11722
11723   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
11724     EraseInstFromFunction(SI);
11725     ++NumCombined;
11726     return 0;
11727   }
11728   
11729   // If the RHS is an alloca with a single use, zapify the store, making the
11730   // alloca dead.
11731   // If the RHS is an alloca with a two uses, the other one being a 
11732   // llvm.dbg.declare, zapify the store and the declare, making the
11733   // alloca dead.  We must do this to prevent declare's from affecting
11734   // codegen.
11735   if (!SI.isVolatile()) {
11736     if (Ptr->hasOneUse()) {
11737       if (isa<AllocaInst>(Ptr)) {
11738         EraseInstFromFunction(SI);
11739         ++NumCombined;
11740         return 0;
11741       }
11742       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11743         if (isa<AllocaInst>(GEP->getOperand(0))) {
11744           if (GEP->getOperand(0)->hasOneUse()) {
11745             EraseInstFromFunction(SI);
11746             ++NumCombined;
11747             return 0;
11748           }
11749           if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11750             EraseInstFromFunction(*DI);
11751             EraseInstFromFunction(SI);
11752             ++NumCombined;
11753             return 0;
11754           }
11755         }
11756       }
11757     }
11758     if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11759       EraseInstFromFunction(*DI);
11760       EraseInstFromFunction(SI);
11761       ++NumCombined;
11762       return 0;
11763     }
11764   }
11765
11766   // Attempt to improve the alignment.
11767   unsigned KnownAlign =
11768     GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11769   if (KnownAlign >
11770       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11771                                 SI.getAlignment()))
11772     SI.setAlignment(KnownAlign);
11773
11774   // Do really simple DSE, to catch cases where there are several consecutive
11775   // stores to the same location, separated by a few arithmetic operations. This
11776   // situation often occurs with bitfield accesses.
11777   BasicBlock::iterator BBI = &SI;
11778   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11779        --ScanInsts) {
11780     --BBI;
11781     // Don't count debug info directives, lest they affect codegen,
11782     // and we skip pointer-to-pointer bitcasts, which are NOPs.
11783     // It is necessary for correctness to skip those that feed into a
11784     // llvm.dbg.declare, as these are not present when debugging is off.
11785     if (isa<DbgInfoIntrinsic>(BBI) ||
11786         (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11787       ScanInsts++;
11788       continue;
11789     }    
11790     
11791     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11792       // Prev store isn't volatile, and stores to the same location?
11793       if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11794                                                           SI.getOperand(1))) {
11795         ++NumDeadStore;
11796         ++BBI;
11797         EraseInstFromFunction(*PrevSI);
11798         continue;
11799       }
11800       break;
11801     }
11802     
11803     // If this is a load, we have to stop.  However, if the loaded value is from
11804     // the pointer we're loading and is producing the pointer we're storing,
11805     // then *this* store is dead (X = load P; store X -> P).
11806     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11807       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11808           !SI.isVolatile()) {
11809         EraseInstFromFunction(SI);
11810         ++NumCombined;
11811         return 0;
11812       }
11813       // Otherwise, this is a load from some other location.  Stores before it
11814       // may not be dead.
11815       break;
11816     }
11817     
11818     // Don't skip over loads or things that can modify memory.
11819     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11820       break;
11821   }
11822   
11823   
11824   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
11825
11826   // store X, null    -> turns into 'unreachable' in SimplifyCFG
11827   if (isa<ConstantPointerNull>(Ptr) &&
11828       cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11829     if (!isa<UndefValue>(Val)) {
11830       SI.setOperand(0, UndefValue::get(Val->getType()));
11831       if (Instruction *U = dyn_cast<Instruction>(Val))
11832         AddToWorkList(U);  // Dropped a use.
11833       ++NumCombined;
11834     }
11835     return 0;  // Do not modify these!
11836   }
11837
11838   // store undef, Ptr -> noop
11839   if (isa<UndefValue>(Val)) {
11840     EraseInstFromFunction(SI);
11841     ++NumCombined;
11842     return 0;
11843   }
11844
11845   // If the pointer destination is a cast, see if we can fold the cast into the
11846   // source instead.
11847   if (isa<CastInst>(Ptr))
11848     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11849       return Res;
11850   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11851     if (CE->isCast())
11852       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11853         return Res;
11854
11855   
11856   // If this store is the last instruction in the basic block (possibly
11857   // excepting debug info instructions and the pointer bitcasts that feed
11858   // into them), and if the block ends with an unconditional branch, try
11859   // to move it to the successor block.
11860   BBI = &SI; 
11861   do {
11862     ++BBI;
11863   } while (isa<DbgInfoIntrinsic>(BBI) ||
11864            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11865   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11866     if (BI->isUnconditional())
11867       if (SimplifyStoreAtEndOfBlock(SI))
11868         return 0;  // xform done!
11869   
11870   return 0;
11871 }
11872
11873 /// SimplifyStoreAtEndOfBlock - Turn things like:
11874 ///   if () { *P = v1; } else { *P = v2 }
11875 /// into a phi node with a store in the successor.
11876 ///
11877 /// Simplify things like:
11878 ///   *P = v1; if () { *P = v2; }
11879 /// into a phi node with a store in the successor.
11880 ///
11881 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11882   BasicBlock *StoreBB = SI.getParent();
11883   
11884   // Check to see if the successor block has exactly two incoming edges.  If
11885   // so, see if the other predecessor contains a store to the same location.
11886   // if so, insert a PHI node (if needed) and move the stores down.
11887   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11888   
11889   // Determine whether Dest has exactly two predecessors and, if so, compute
11890   // the other predecessor.
11891   pred_iterator PI = pred_begin(DestBB);
11892   BasicBlock *OtherBB = 0;
11893   if (*PI != StoreBB)
11894     OtherBB = *PI;
11895   ++PI;
11896   if (PI == pred_end(DestBB))
11897     return false;
11898   
11899   if (*PI != StoreBB) {
11900     if (OtherBB)
11901       return false;
11902     OtherBB = *PI;
11903   }
11904   if (++PI != pred_end(DestBB))
11905     return false;
11906
11907   // Bail out if all the relevant blocks aren't distinct (this can happen,
11908   // for example, if SI is in an infinite loop)
11909   if (StoreBB == DestBB || OtherBB == DestBB)
11910     return false;
11911
11912   // Verify that the other block ends in a branch and is not otherwise empty.
11913   BasicBlock::iterator BBI = OtherBB->getTerminator();
11914   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11915   if (!OtherBr || BBI == OtherBB->begin())
11916     return false;
11917   
11918   // If the other block ends in an unconditional branch, check for the 'if then
11919   // else' case.  there is an instruction before the branch.
11920   StoreInst *OtherStore = 0;
11921   if (OtherBr->isUnconditional()) {
11922     --BBI;
11923     // Skip over debugging info.
11924     while (isa<DbgInfoIntrinsic>(BBI) ||
11925            (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11926       if (BBI==OtherBB->begin())
11927         return false;
11928       --BBI;
11929     }
11930     // If this isn't a store, or isn't a store to the same location, bail out.
11931     OtherStore = dyn_cast<StoreInst>(BBI);
11932     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11933       return false;
11934   } else {
11935     // Otherwise, the other block ended with a conditional branch. If one of the
11936     // destinations is StoreBB, then we have the if/then case.
11937     if (OtherBr->getSuccessor(0) != StoreBB && 
11938         OtherBr->getSuccessor(1) != StoreBB)
11939       return false;
11940     
11941     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11942     // if/then triangle.  See if there is a store to the same ptr as SI that
11943     // lives in OtherBB.
11944     for (;; --BBI) {
11945       // Check to see if we find the matching store.
11946       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11947         if (OtherStore->getOperand(1) != SI.getOperand(1))
11948           return false;
11949         break;
11950       }
11951       // If we find something that may be using or overwriting the stored
11952       // value, or if we run out of instructions, we can't do the xform.
11953       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11954           BBI == OtherBB->begin())
11955         return false;
11956     }
11957     
11958     // In order to eliminate the store in OtherBr, we have to
11959     // make sure nothing reads or overwrites the stored value in
11960     // StoreBB.
11961     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11962       // FIXME: This should really be AA driven.
11963       if (I->mayReadFromMemory() || I->mayWriteToMemory())
11964         return false;
11965     }
11966   }
11967   
11968   // Insert a PHI node now if we need it.
11969   Value *MergedVal = OtherStore->getOperand(0);
11970   if (MergedVal != SI.getOperand(0)) {
11971     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11972     PN->reserveOperandSpace(2);
11973     PN->addIncoming(SI.getOperand(0), SI.getParent());
11974     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11975     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11976   }
11977   
11978   // Advance to a place where it is safe to insert the new store and
11979   // insert it.
11980   BBI = DestBB->getFirstNonPHI();
11981   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11982                                     OtherStore->isVolatile()), *BBI);
11983   
11984   // Nuke the old stores.
11985   EraseInstFromFunction(SI);
11986   EraseInstFromFunction(*OtherStore);
11987   ++NumCombined;
11988   return true;
11989 }
11990
11991
11992 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11993   // Change br (not X), label True, label False to: br X, label False, True
11994   Value *X = 0;
11995   BasicBlock *TrueDest;
11996   BasicBlock *FalseDest;
11997   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11998       !isa<Constant>(X)) {
11999     // Swap Destinations and condition...
12000     BI.setCondition(X);
12001     BI.setSuccessor(0, FalseDest);
12002     BI.setSuccessor(1, TrueDest);
12003     return &BI;
12004   }
12005
12006   // Cannonicalize fcmp_one -> fcmp_oeq
12007   FCmpInst::Predicate FPred; Value *Y;
12008   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
12009                              TrueDest, FalseDest)))
12010     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12011          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12012       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12013       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12014       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
12015       NewSCC->takeName(I);
12016       // Swap Destinations and condition...
12017       BI.setCondition(NewSCC);
12018       BI.setSuccessor(0, FalseDest);
12019       BI.setSuccessor(1, TrueDest);
12020       RemoveFromWorkList(I);
12021       I->eraseFromParent();
12022       AddToWorkList(NewSCC);
12023       return &BI;
12024     }
12025
12026   // Cannonicalize icmp_ne -> icmp_eq
12027   ICmpInst::Predicate IPred;
12028   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12029                       TrueDest, FalseDest)))
12030     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
12031          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12032          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12033       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12034       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12035       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
12036       NewSCC->takeName(I);
12037       // Swap Destinations and condition...
12038       BI.setCondition(NewSCC);
12039       BI.setSuccessor(0, FalseDest);
12040       BI.setSuccessor(1, TrueDest);
12041       RemoveFromWorkList(I);
12042       I->eraseFromParent();;
12043       AddToWorkList(NewSCC);
12044       return &BI;
12045     }
12046
12047   return 0;
12048 }
12049
12050 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12051   Value *Cond = SI.getCondition();
12052   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12053     if (I->getOpcode() == Instruction::Add)
12054       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12055         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12056         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12057           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12058                                                 AddRHS));
12059         SI.setOperand(0, I->getOperand(0));
12060         AddToWorkList(I);
12061         return &SI;
12062       }
12063   }
12064   return 0;
12065 }
12066
12067 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12068   Value *Agg = EV.getAggregateOperand();
12069
12070   if (!EV.hasIndices())
12071     return ReplaceInstUsesWith(EV, Agg);
12072
12073   if (Constant *C = dyn_cast<Constant>(Agg)) {
12074     if (isa<UndefValue>(C))
12075       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12076       
12077     if (isa<ConstantAggregateZero>(C))
12078       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12079
12080     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12081       // Extract the element indexed by the first index out of the constant
12082       Value *V = C->getOperand(*EV.idx_begin());
12083       if (EV.getNumIndices() > 1)
12084         // Extract the remaining indices out of the constant indexed by the
12085         // first index
12086         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12087       else
12088         return ReplaceInstUsesWith(EV, V);
12089     }
12090     return 0; // Can't handle other constants
12091   } 
12092   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12093     // We're extracting from an insertvalue instruction, compare the indices
12094     const unsigned *exti, *exte, *insi, *inse;
12095     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12096          exte = EV.idx_end(), inse = IV->idx_end();
12097          exti != exte && insi != inse;
12098          ++exti, ++insi) {
12099       if (*insi != *exti)
12100         // The insert and extract both reference distinctly different elements.
12101         // This means the extract is not influenced by the insert, and we can
12102         // replace the aggregate operand of the extract with the aggregate
12103         // operand of the insert. i.e., replace
12104         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12105         // %E = extractvalue { i32, { i32 } } %I, 0
12106         // with
12107         // %E = extractvalue { i32, { i32 } } %A, 0
12108         return ExtractValueInst::Create(IV->getAggregateOperand(),
12109                                         EV.idx_begin(), EV.idx_end());
12110     }
12111     if (exti == exte && insi == inse)
12112       // Both iterators are at the end: Index lists are identical. Replace
12113       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12114       // %C = extractvalue { i32, { i32 } } %B, 1, 0
12115       // with "i32 42"
12116       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12117     if (exti == exte) {
12118       // The extract list is a prefix of the insert list. i.e. replace
12119       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12120       // %E = extractvalue { i32, { i32 } } %I, 1
12121       // with
12122       // %X = extractvalue { i32, { i32 } } %A, 1
12123       // %E = insertvalue { i32 } %X, i32 42, 0
12124       // by switching the order of the insert and extract (though the
12125       // insertvalue should be left in, since it may have other uses).
12126       Value *NewEV = InsertNewInstBefore(
12127         ExtractValueInst::Create(IV->getAggregateOperand(),
12128                                  EV.idx_begin(), EV.idx_end()),
12129         EV);
12130       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12131                                      insi, inse);
12132     }
12133     if (insi == inse)
12134       // The insert list is a prefix of the extract list
12135       // We can simply remove the common indices from the extract and make it
12136       // operate on the inserted value instead of the insertvalue result.
12137       // i.e., replace
12138       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12139       // %E = extractvalue { i32, { i32 } } %I, 1, 0
12140       // with
12141       // %E extractvalue { i32 } { i32 42 }, 0
12142       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
12143                                       exti, exte);
12144   }
12145   // Can't simplify extracts from other values. Note that nested extracts are
12146   // already simplified implicitely by the above (extract ( extract (insert) )
12147   // will be translated into extract ( insert ( extract ) ) first and then just
12148   // the value inserted, if appropriate).
12149   return 0;
12150 }
12151
12152 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12153 /// is to leave as a vector operation.
12154 static bool CheapToScalarize(Value *V, bool isConstant) {
12155   if (isa<ConstantAggregateZero>(V)) 
12156     return true;
12157   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12158     if (isConstant) return true;
12159     // If all elts are the same, we can extract.
12160     Constant *Op0 = C->getOperand(0);
12161     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12162       if (C->getOperand(i) != Op0)
12163         return false;
12164     return true;
12165   }
12166   Instruction *I = dyn_cast<Instruction>(V);
12167   if (!I) return false;
12168   
12169   // Insert element gets simplified to the inserted element or is deleted if
12170   // this is constant idx extract element and its a constant idx insertelt.
12171   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12172       isa<ConstantInt>(I->getOperand(2)))
12173     return true;
12174   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12175     return true;
12176   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12177     if (BO->hasOneUse() &&
12178         (CheapToScalarize(BO->getOperand(0), isConstant) ||
12179          CheapToScalarize(BO->getOperand(1), isConstant)))
12180       return true;
12181   if (CmpInst *CI = dyn_cast<CmpInst>(I))
12182     if (CI->hasOneUse() &&
12183         (CheapToScalarize(CI->getOperand(0), isConstant) ||
12184          CheapToScalarize(CI->getOperand(1), isConstant)))
12185       return true;
12186   
12187   return false;
12188 }
12189
12190 /// Read and decode a shufflevector mask.
12191 ///
12192 /// It turns undef elements into values that are larger than the number of
12193 /// elements in the input.
12194 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12195   unsigned NElts = SVI->getType()->getNumElements();
12196   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12197     return std::vector<unsigned>(NElts, 0);
12198   if (isa<UndefValue>(SVI->getOperand(2)))
12199     return std::vector<unsigned>(NElts, 2*NElts);
12200
12201   std::vector<unsigned> Result;
12202   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12203   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12204     if (isa<UndefValue>(*i))
12205       Result.push_back(NElts*2);  // undef -> 8
12206     else
12207       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12208   return Result;
12209 }
12210
12211 /// FindScalarElement - Given a vector and an element number, see if the scalar
12212 /// value is already around as a register, for example if it were inserted then
12213 /// extracted from the vector.
12214 static Value *FindScalarElement(Value *V, unsigned EltNo) {
12215   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12216   const VectorType *PTy = cast<VectorType>(V->getType());
12217   unsigned Width = PTy->getNumElements();
12218   if (EltNo >= Width)  // Out of range access.
12219     return UndefValue::get(PTy->getElementType());
12220   
12221   if (isa<UndefValue>(V))
12222     return UndefValue::get(PTy->getElementType());
12223   else if (isa<ConstantAggregateZero>(V))
12224     return Constant::getNullValue(PTy->getElementType());
12225   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12226     return CP->getOperand(EltNo);
12227   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12228     // If this is an insert to a variable element, we don't know what it is.
12229     if (!isa<ConstantInt>(III->getOperand(2))) 
12230       return 0;
12231     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12232     
12233     // If this is an insert to the element we are looking for, return the
12234     // inserted value.
12235     if (EltNo == IIElt) 
12236       return III->getOperand(1);
12237     
12238     // Otherwise, the insertelement doesn't modify the value, recurse on its
12239     // vector input.
12240     return FindScalarElement(III->getOperand(0), EltNo);
12241   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12242     unsigned LHSWidth =
12243       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12244     unsigned InEl = getShuffleMask(SVI)[EltNo];
12245     if (InEl < LHSWidth)
12246       return FindScalarElement(SVI->getOperand(0), InEl);
12247     else if (InEl < LHSWidth*2)
12248       return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
12249     else
12250       return UndefValue::get(PTy->getElementType());
12251   }
12252   
12253   // Otherwise, we don't know.
12254   return 0;
12255 }
12256
12257 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12258   // If vector val is undef, replace extract with scalar undef.
12259   if (isa<UndefValue>(EI.getOperand(0)))
12260     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12261
12262   // If vector val is constant 0, replace extract with scalar 0.
12263   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12264     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12265   
12266   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12267     // If vector val is constant with all elements the same, replace EI with
12268     // that element. When the elements are not identical, we cannot replace yet
12269     // (we do that below, but only when the index is constant).
12270     Constant *op0 = C->getOperand(0);
12271     for (unsigned i = 1; i < C->getNumOperands(); ++i)
12272       if (C->getOperand(i) != op0) {
12273         op0 = 0; 
12274         break;
12275       }
12276     if (op0)
12277       return ReplaceInstUsesWith(EI, op0);
12278   }
12279   
12280   // If extracting a specified index from the vector, see if we can recursively
12281   // find a previously computed scalar that was inserted into the vector.
12282   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12283     unsigned IndexVal = IdxC->getZExtValue();
12284     unsigned VectorWidth = 
12285       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12286       
12287     // If this is extracting an invalid index, turn this into undef, to avoid
12288     // crashing the code below.
12289     if (IndexVal >= VectorWidth)
12290       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12291     
12292     // This instruction only demands the single element from the input vector.
12293     // If the input vector has a single use, simplify it based on this use
12294     // property.
12295     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12296       APInt UndefElts(VectorWidth, 0);
12297       APInt DemandedMask(VectorWidth, 1 << IndexVal);
12298       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12299                                                 DemandedMask, UndefElts)) {
12300         EI.setOperand(0, V);
12301         return &EI;
12302       }
12303     }
12304     
12305     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
12306       return ReplaceInstUsesWith(EI, Elt);
12307     
12308     // If the this extractelement is directly using a bitcast from a vector of
12309     // the same number of elements, see if we can find the source element from
12310     // it.  In this case, we will end up needing to bitcast the scalars.
12311     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12312       if (const VectorType *VT = 
12313               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12314         if (VT->getNumElements() == VectorWidth)
12315           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
12316             return new BitCastInst(Elt, EI.getType());
12317     }
12318   }
12319   
12320   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12321     if (I->hasOneUse()) {
12322       // Push extractelement into predecessor operation if legal and
12323       // profitable to do so
12324       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12325         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12326         if (CheapToScalarize(BO, isConstantElt)) {
12327           ExtractElementInst *newEI0 = 
12328             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12329                                    EI.getName()+".lhs");
12330           ExtractElementInst *newEI1 =
12331             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12332                                    EI.getName()+".rhs");
12333           InsertNewInstBefore(newEI0, EI);
12334           InsertNewInstBefore(newEI1, EI);
12335           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12336         }
12337       } else if (isa<LoadInst>(I)) {
12338         unsigned AS = 
12339           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12340         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12341                                          PointerType::get(EI.getType(), AS),EI);
12342         GetElementPtrInst *GEP =
12343           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12344         InsertNewInstBefore(GEP, EI);
12345         return new LoadInst(GEP);
12346       }
12347     }
12348     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12349       // Extracting the inserted element?
12350       if (IE->getOperand(2) == EI.getOperand(1))
12351         return ReplaceInstUsesWith(EI, IE->getOperand(1));
12352       // If the inserted and extracted elements are constants, they must not
12353       // be the same value, extract from the pre-inserted value instead.
12354       if (isa<Constant>(IE->getOperand(2)) &&
12355           isa<Constant>(EI.getOperand(1))) {
12356         AddUsesToWorkList(EI);
12357         EI.setOperand(0, IE->getOperand(0));
12358         return &EI;
12359       }
12360     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12361       // If this is extracting an element from a shufflevector, figure out where
12362       // it came from and extract from the appropriate input element instead.
12363       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12364         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12365         Value *Src;
12366         unsigned LHSWidth =
12367           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12368
12369         if (SrcIdx < LHSWidth)
12370           Src = SVI->getOperand(0);
12371         else if (SrcIdx < LHSWidth*2) {
12372           SrcIdx -= LHSWidth;
12373           Src = SVI->getOperand(1);
12374         } else {
12375           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12376         }
12377         return new ExtractElementInst(Src, SrcIdx);
12378       }
12379     }
12380   }
12381   return 0;
12382 }
12383
12384 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12385 /// elements from either LHS or RHS, return the shuffle mask and true. 
12386 /// Otherwise, return false.
12387 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12388                                          std::vector<Constant*> &Mask) {
12389   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12390          "Invalid CollectSingleShuffleElements");
12391   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12392
12393   if (isa<UndefValue>(V)) {
12394     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12395     return true;
12396   } else if (V == LHS) {
12397     for (unsigned i = 0; i != NumElts; ++i)
12398       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12399     return true;
12400   } else if (V == RHS) {
12401     for (unsigned i = 0; i != NumElts; ++i)
12402       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
12403     return true;
12404   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12405     // If this is an insert of an extract from some other vector, include it.
12406     Value *VecOp    = IEI->getOperand(0);
12407     Value *ScalarOp = IEI->getOperand(1);
12408     Value *IdxOp    = IEI->getOperand(2);
12409     
12410     if (!isa<ConstantInt>(IdxOp))
12411       return false;
12412     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12413     
12414     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
12415       // Okay, we can handle this if the vector we are insertinting into is
12416       // transitively ok.
12417       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12418         // If so, update the mask to reflect the inserted undef.
12419         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
12420         return true;
12421       }      
12422     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12423       if (isa<ConstantInt>(EI->getOperand(1)) &&
12424           EI->getOperand(0)->getType() == V->getType()) {
12425         unsigned ExtractedIdx =
12426           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12427         
12428         // This must be extracting from either LHS or RHS.
12429         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12430           // Okay, we can handle this if the vector we are insertinting into is
12431           // transitively ok.
12432           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
12433             // If so, update the mask to reflect the inserted value.
12434             if (EI->getOperand(0) == LHS) {
12435               Mask[InsertedIdx % NumElts] = 
12436                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12437             } else {
12438               assert(EI->getOperand(0) == RHS);
12439               Mask[InsertedIdx % NumElts] = 
12440                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
12441               
12442             }
12443             return true;
12444           }
12445         }
12446       }
12447     }
12448   }
12449   // TODO: Handle shufflevector here!
12450   
12451   return false;
12452 }
12453
12454 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12455 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
12456 /// that computes V and the LHS value of the shuffle.
12457 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12458                                      Value *&RHS) {
12459   assert(isa<VectorType>(V->getType()) && 
12460          (RHS == 0 || V->getType() == RHS->getType()) &&
12461          "Invalid shuffle!");
12462   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12463
12464   if (isa<UndefValue>(V)) {
12465     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
12466     return V;
12467   } else if (isa<ConstantAggregateZero>(V)) {
12468     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
12469     return V;
12470   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12471     // If this is an insert of an extract from some other vector, include it.
12472     Value *VecOp    = IEI->getOperand(0);
12473     Value *ScalarOp = IEI->getOperand(1);
12474     Value *IdxOp    = IEI->getOperand(2);
12475     
12476     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12477       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12478           EI->getOperand(0)->getType() == V->getType()) {
12479         unsigned ExtractedIdx =
12480           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12481         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12482         
12483         // Either the extracted from or inserted into vector must be RHSVec,
12484         // otherwise we'd end up with a shuffle of three inputs.
12485         if (EI->getOperand(0) == RHS || RHS == 0) {
12486           RHS = EI->getOperand(0);
12487           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
12488           Mask[InsertedIdx % NumElts] = 
12489             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
12490           return V;
12491         }
12492         
12493         if (VecOp == RHS) {
12494           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
12495           // Everything but the extracted element is replaced with the RHS.
12496           for (unsigned i = 0; i != NumElts; ++i) {
12497             if (i != InsertedIdx)
12498               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
12499           }
12500           return V;
12501         }
12502         
12503         // If this insertelement is a chain that comes from exactly these two
12504         // vectors, return the vector and the effective shuffle.
12505         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
12506           return EI->getOperand(0);
12507         
12508       }
12509     }
12510   }
12511   // TODO: Handle shufflevector here!
12512   
12513   // Otherwise, can't do anything fancy.  Return an identity vector.
12514   for (unsigned i = 0; i != NumElts; ++i)
12515     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
12516   return V;
12517 }
12518
12519 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12520   Value *VecOp    = IE.getOperand(0);
12521   Value *ScalarOp = IE.getOperand(1);
12522   Value *IdxOp    = IE.getOperand(2);
12523   
12524   // Inserting an undef or into an undefined place, remove this.
12525   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12526     ReplaceInstUsesWith(IE, VecOp);
12527   
12528   // If the inserted element was extracted from some other vector, and if the 
12529   // indexes are constant, try to turn this into a shufflevector operation.
12530   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12531     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12532         EI->getOperand(0)->getType() == IE.getType()) {
12533       unsigned NumVectorElts = IE.getType()->getNumElements();
12534       unsigned ExtractedIdx =
12535         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12536       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12537       
12538       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12539         return ReplaceInstUsesWith(IE, VecOp);
12540       
12541       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
12542         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12543       
12544       // If we are extracting a value from a vector, then inserting it right
12545       // back into the same place, just use the input vector.
12546       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12547         return ReplaceInstUsesWith(IE, VecOp);      
12548       
12549       // We could theoretically do this for ANY input.  However, doing so could
12550       // turn chains of insertelement instructions into a chain of shufflevector
12551       // instructions, and right now we do not merge shufflevectors.  As such,
12552       // only do this in a situation where it is clear that there is benefit.
12553       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12554         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
12555         // the values of VecOp, except then one read from EIOp0.
12556         // Build a new shuffle mask.
12557         std::vector<Constant*> Mask;
12558         if (isa<UndefValue>(VecOp))
12559           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12560         else {
12561           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12562           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12563                                                        NumVectorElts));
12564         } 
12565         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12566         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12567                                      ConstantVector::get(Mask));
12568       }
12569       
12570       // If this insertelement isn't used by some other insertelement, turn it
12571       // (and any insertelements it points to), into one big shuffle.
12572       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12573         std::vector<Constant*> Mask;
12574         Value *RHS = 0;
12575         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12576         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12577         // We now have a shuffle of LHS, RHS, Mask.
12578         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12579       }
12580     }
12581   }
12582
12583   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12584   APInt UndefElts(VWidth, 0);
12585   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12586   if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12587     return &IE;
12588
12589   return 0;
12590 }
12591
12592
12593 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12594   Value *LHS = SVI.getOperand(0);
12595   Value *RHS = SVI.getOperand(1);
12596   std::vector<unsigned> Mask = getShuffleMask(&SVI);
12597
12598   bool MadeChange = false;
12599
12600   // Undefined shuffle mask -> undefined value.
12601   if (isa<UndefValue>(SVI.getOperand(2)))
12602     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12603
12604   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12605
12606   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12607     return 0;
12608
12609   APInt UndefElts(VWidth, 0);
12610   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12611   if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12612     LHS = SVI.getOperand(0);
12613     RHS = SVI.getOperand(1);
12614     MadeChange = true;
12615   }
12616   
12617   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
12618   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12619   if (LHS == RHS || isa<UndefValue>(LHS)) {
12620     if (isa<UndefValue>(LHS) && LHS == RHS) {
12621       // shuffle(undef,undef,mask) -> undef.
12622       return ReplaceInstUsesWith(SVI, LHS);
12623     }
12624     
12625     // Remap any references to RHS to use LHS.
12626     std::vector<Constant*> Elts;
12627     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12628       if (Mask[i] >= 2*e)
12629         Elts.push_back(UndefValue::get(Type::Int32Ty));
12630       else {
12631         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12632             (Mask[i] <  e && isa<UndefValue>(LHS))) {
12633           Mask[i] = 2*e;     // Turn into undef.
12634           Elts.push_back(UndefValue::get(Type::Int32Ty));
12635         } else {
12636           Mask[i] = Mask[i] % e;  // Force to LHS.
12637           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12638         }
12639       }
12640     }
12641     SVI.setOperand(0, SVI.getOperand(1));
12642     SVI.setOperand(1, UndefValue::get(RHS->getType()));
12643     SVI.setOperand(2, ConstantVector::get(Elts));
12644     LHS = SVI.getOperand(0);
12645     RHS = SVI.getOperand(1);
12646     MadeChange = true;
12647   }
12648   
12649   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12650   bool isLHSID = true, isRHSID = true;
12651     
12652   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12653     if (Mask[i] >= e*2) continue;  // Ignore undef values.
12654     // Is this an identity shuffle of the LHS value?
12655     isLHSID &= (Mask[i] == i);
12656       
12657     // Is this an identity shuffle of the RHS value?
12658     isRHSID &= (Mask[i]-e == i);
12659   }
12660
12661   // Eliminate identity shuffles.
12662   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12663   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12664   
12665   // If the LHS is a shufflevector itself, see if we can combine it with this
12666   // one without producing an unusual shuffle.  Here we are really conservative:
12667   // we are absolutely afraid of producing a shuffle mask not in the input
12668   // program, because the code gen may not be smart enough to turn a merged
12669   // shuffle into two specific shuffles: it may produce worse code.  As such,
12670   // we only merge two shuffles if the result is one of the two input shuffle
12671   // masks.  In this case, merging the shuffles just removes one instruction,
12672   // which we know is safe.  This is good for things like turning:
12673   // (splat(splat)) -> splat.
12674   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12675     if (isa<UndefValue>(RHS)) {
12676       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12677
12678       std::vector<unsigned> NewMask;
12679       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12680         if (Mask[i] >= 2*e)
12681           NewMask.push_back(2*e);
12682         else
12683           NewMask.push_back(LHSMask[Mask[i]]);
12684       
12685       // If the result mask is equal to the src shuffle or this shuffle mask, do
12686       // the replacement.
12687       if (NewMask == LHSMask || NewMask == Mask) {
12688         unsigned LHSInNElts =
12689           cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12690         std::vector<Constant*> Elts;
12691         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12692           if (NewMask[i] >= LHSInNElts*2) {
12693             Elts.push_back(UndefValue::get(Type::Int32Ty));
12694           } else {
12695             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12696           }
12697         }
12698         return new ShuffleVectorInst(LHSSVI->getOperand(0),
12699                                      LHSSVI->getOperand(1),
12700                                      ConstantVector::get(Elts));
12701       }
12702     }
12703   }
12704
12705   return MadeChange ? &SVI : 0;
12706 }
12707
12708
12709
12710
12711 /// TryToSinkInstruction - Try to move the specified instruction from its
12712 /// current block into the beginning of DestBlock, which can only happen if it's
12713 /// safe to move the instruction past all of the instructions between it and the
12714 /// end of its block.
12715 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12716   assert(I->hasOneUse() && "Invariants didn't hold!");
12717
12718   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12719   if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12720     return false;
12721
12722   // Do not sink alloca instructions out of the entry block.
12723   if (isa<AllocaInst>(I) && I->getParent() ==
12724         &DestBlock->getParent()->getEntryBlock())
12725     return false;
12726
12727   // We can only sink load instructions if there is nothing between the load and
12728   // the end of block that could change the value.
12729   if (I->mayReadFromMemory()) {
12730     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12731          Scan != E; ++Scan)
12732       if (Scan->mayWriteToMemory())
12733         return false;
12734   }
12735
12736   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12737
12738   CopyPrecedingStopPoint(I, InsertPos);
12739   I->moveBefore(InsertPos);
12740   ++NumSunkInst;
12741   return true;
12742 }
12743
12744
12745 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12746 /// all reachable code to the worklist.
12747 ///
12748 /// This has a couple of tricks to make the code faster and more powerful.  In
12749 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12750 /// them to the worklist (this significantly speeds up instcombine on code where
12751 /// many instructions are dead or constant).  Additionally, if we find a branch
12752 /// whose condition is a known constant, we only visit the reachable successors.
12753 ///
12754 static void AddReachableCodeToWorklist(BasicBlock *BB, 
12755                                        SmallPtrSet<BasicBlock*, 64> &Visited,
12756                                        InstCombiner &IC,
12757                                        const TargetData *TD) {
12758   SmallVector<BasicBlock*, 256> Worklist;
12759   Worklist.push_back(BB);
12760
12761   while (!Worklist.empty()) {
12762     BB = Worklist.back();
12763     Worklist.pop_back();
12764     
12765     // We have now visited this block!  If we've already been here, ignore it.
12766     if (!Visited.insert(BB)) continue;
12767
12768     DbgInfoIntrinsic *DBI_Prev = NULL;
12769     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12770       Instruction *Inst = BBI++;
12771       
12772       // DCE instruction if trivially dead.
12773       if (isInstructionTriviallyDead(Inst)) {
12774         ++NumDeadInst;
12775         DOUT << "IC: DCE: " << *Inst;
12776         Inst->eraseFromParent();
12777         continue;
12778       }
12779       
12780       // ConstantProp instruction if trivially constant.
12781       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12782         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12783         Inst->replaceAllUsesWith(C);
12784         ++NumConstProp;
12785         Inst->eraseFromParent();
12786         continue;
12787       }
12788      
12789       // If there are two consecutive llvm.dbg.stoppoint calls then
12790       // it is likely that the optimizer deleted code in between these
12791       // two intrinsics. 
12792       DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12793       if (DBI_Next) {
12794         if (DBI_Prev
12795             && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12796             && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12797           IC.RemoveFromWorkList(DBI_Prev);
12798           DBI_Prev->eraseFromParent();
12799         }
12800         DBI_Prev = DBI_Next;
12801       } else {
12802         DBI_Prev = 0;
12803       }
12804
12805       IC.AddToWorkList(Inst);
12806     }
12807
12808     // Recursively visit successors.  If this is a branch or switch on a
12809     // constant, only visit the reachable successor.
12810     TerminatorInst *TI = BB->getTerminator();
12811     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12812       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12813         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12814         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12815         Worklist.push_back(ReachableBB);
12816         continue;
12817       }
12818     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12819       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12820         // See if this is an explicit destination.
12821         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12822           if (SI->getCaseValue(i) == Cond) {
12823             BasicBlock *ReachableBB = SI->getSuccessor(i);
12824             Worklist.push_back(ReachableBB);
12825             continue;
12826           }
12827         
12828         // Otherwise it is the default destination.
12829         Worklist.push_back(SI->getSuccessor(0));
12830         continue;
12831       }
12832     }
12833     
12834     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12835       Worklist.push_back(TI->getSuccessor(i));
12836   }
12837 }
12838
12839 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12840   bool Changed = false;
12841   TD = &getAnalysis<TargetData>();
12842   
12843   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12844              << F.getNameStr() << "\n");
12845
12846   {
12847     // Do a depth-first traversal of the function, populate the worklist with
12848     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
12849     // track of which blocks we visit.
12850     SmallPtrSet<BasicBlock*, 64> Visited;
12851     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12852
12853     // Do a quick scan over the function.  If we find any blocks that are
12854     // unreachable, remove any instructions inside of them.  This prevents
12855     // the instcombine code from having to deal with some bad special cases.
12856     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12857       if (!Visited.count(BB)) {
12858         Instruction *Term = BB->getTerminator();
12859         while (Term != BB->begin()) {   // Remove instrs bottom-up
12860           BasicBlock::iterator I = Term; --I;
12861
12862           DOUT << "IC: DCE: " << *I;
12863           // A debug intrinsic shouldn't force another iteration if we weren't
12864           // going to do one without it.
12865           if (!isa<DbgInfoIntrinsic>(I)) {
12866             ++NumDeadInst;
12867             Changed = true;
12868           }
12869           if (!I->use_empty())
12870             I->replaceAllUsesWith(UndefValue::get(I->getType()));
12871           I->eraseFromParent();
12872         }
12873       }
12874   }
12875
12876   while (!Worklist.empty()) {
12877     Instruction *I = RemoveOneFromWorkList();
12878     if (I == 0) continue;  // skip null values.
12879
12880     // Check to see if we can DCE the instruction.
12881     if (isInstructionTriviallyDead(I)) {
12882       // Add operands to the worklist.
12883       if (I->getNumOperands() < 4)
12884         AddUsesToWorkList(*I);
12885       ++NumDeadInst;
12886
12887       DOUT << "IC: DCE: " << *I;
12888
12889       I->eraseFromParent();
12890       RemoveFromWorkList(I);
12891       Changed = true;
12892       continue;
12893     }
12894
12895     // Instruction isn't dead, see if we can constant propagate it.
12896     if (Constant *C = ConstantFoldInstruction(I, TD)) {
12897       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12898
12899       // Add operands to the worklist.
12900       AddUsesToWorkList(*I);
12901       ReplaceInstUsesWith(*I, C);
12902
12903       ++NumConstProp;
12904       I->eraseFromParent();
12905       RemoveFromWorkList(I);
12906       Changed = true;
12907       continue;
12908     }
12909
12910     if (TD &&
12911         (I->getType()->getTypeID() == Type::VoidTyID ||
12912          I->isTrapping())) {
12913       // See if we can constant fold its operands.
12914       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12915         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12916           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12917             if (NewC != CE) {
12918               i->set(NewC);
12919               Changed = true;
12920             }
12921     }
12922
12923     // See if we can trivially sink this instruction to a successor basic block.
12924     if (I->hasOneUse()) {
12925       BasicBlock *BB = I->getParent();
12926       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12927       if (UserParent != BB) {
12928         bool UserIsSuccessor = false;
12929         // See if the user is one of our successors.
12930         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12931           if (*SI == UserParent) {
12932             UserIsSuccessor = true;
12933             break;
12934           }
12935
12936         // If the user is one of our immediate successors, and if that successor
12937         // only has us as a predecessors (we'd have to split the critical edge
12938         // otherwise), we can keep going.
12939         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12940             next(pred_begin(UserParent)) == pred_end(UserParent))
12941           // Okay, the CFG is simple enough, try to sink this instruction.
12942           Changed |= TryToSinkInstruction(I, UserParent);
12943       }
12944     }
12945
12946     // Now that we have an instruction, try combining it to simplify it...
12947 #ifndef NDEBUG
12948     std::string OrigI;
12949 #endif
12950     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12951     if (Instruction *Result = visit(*I)) {
12952       ++NumCombined;
12953       // Should we replace the old instruction with a new one?
12954       if (Result != I) {
12955         DOUT << "IC: Old = " << *I
12956              << "    New = " << *Result;
12957
12958         // Everything uses the new instruction now.
12959         I->replaceAllUsesWith(Result);
12960
12961         // Push the new instruction and any users onto the worklist.
12962         AddToWorkList(Result);
12963         AddUsersToWorkList(*Result);
12964
12965         // Move the name to the new instruction first.
12966         Result->takeName(I);
12967
12968         // Insert the new instruction into the basic block...
12969         BasicBlock *InstParent = I->getParent();
12970         BasicBlock::iterator InsertPos = I;
12971
12972         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
12973           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12974             ++InsertPos;
12975
12976         InstParent->getInstList().insert(InsertPos, Result);
12977
12978         // Make sure that we reprocess all operands now that we reduced their
12979         // use counts.
12980         AddUsesToWorkList(*I);
12981
12982         // Instructions can end up on the worklist more than once.  Make sure
12983         // we do not process an instruction that has been deleted.
12984         RemoveFromWorkList(I);
12985
12986         // Erase the old instruction.
12987         InstParent->getInstList().erase(I);
12988       } else {
12989 #ifndef NDEBUG
12990         DOUT << "IC: Mod = " << OrigI
12991              << "    New = " << *I;
12992 #endif
12993
12994         // If the instruction was modified, it's possible that it is now dead.
12995         // if so, remove it.
12996         if (isInstructionTriviallyDead(I)) {
12997           // Make sure we process all operands now that we are reducing their
12998           // use counts.
12999           AddUsesToWorkList(*I);
13000
13001           // Instructions may end up in the worklist more than once.  Erase all
13002           // occurrences of this instruction.
13003           RemoveFromWorkList(I);
13004           I->eraseFromParent();
13005         } else {
13006           AddToWorkList(I);
13007           AddUsersToWorkList(*I);
13008         }
13009       }
13010       Changed = true;
13011     }
13012   }
13013
13014   assert(WorklistMap.empty() && "Worklist empty, but map not?");
13015     
13016   // Do an explicit clear, this shrinks the map if needed.
13017   WorklistMap.clear();
13018   return Changed;
13019 }
13020
13021
13022 bool InstCombiner::runOnFunction(Function &F) {
13023   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13024   
13025   bool EverMadeChange = false;
13026
13027   // Iterate while there is work to do.
13028   unsigned Iteration = 0;
13029   while (DoOneIteration(F, Iteration++))
13030     EverMadeChange = true;
13031   return EverMadeChange;
13032 }
13033
13034 FunctionPass *llvm::createInstructionCombiningPass() {
13035   return new InstCombiner();
13036 }