Switch over Transforms/Scalar to use the STATISTIC macro. For each statistic
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add int %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %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. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All SetCC 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/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62 STATISTIC(NumSunkInst , "Number of instructions sunk");
63
64 namespace {
65   class VISIBILITY_HIDDEN InstCombiner
66     : public FunctionPass,
67       public InstVisitor<InstCombiner, Instruction*> {
68     // Worklist of all of the instructions that need to be simplified.
69     std::vector<Instruction*> WorkList;
70     TargetData *TD;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(Value &I) {
77       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78            UI != UE; ++UI)
79         WorkList.push_back(cast<Instruction>(*UI));
80     }
81
82     /// AddUsesToWorkList - When an instruction is simplified, add operands to
83     /// the work lists because they might get more simplified now.
84     ///
85     void AddUsesToWorkList(Instruction &I) {
86       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88           WorkList.push_back(Op);
89     }
90     
91     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92     /// dead.  Add all of its operands to the worklist, turning them into
93     /// undef's to reduce the number of uses of those instructions.
94     ///
95     /// Return the specified operand before it is turned into an undef.
96     ///
97     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98       Value *R = I.getOperand(op);
99       
100       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102           WorkList.push_back(Op);
103           // Set the operand to undef to drop the use.
104           I.setOperand(i, UndefValue::get(Op->getType()));
105         }
106       
107       return R;
108     }
109
110     // removeFromWorkList - remove all instances of I from the worklist.
111     void removeFromWorkList(Instruction *I);
112   public:
113     virtual bool runOnFunction(Function &F);
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<TargetData>();
117       AU.addPreservedID(LCSSAID);
118       AU.setPreservesCFG();
119     }
120
121     TargetData &getTargetData() const { return *TD; }
122
123     // Visitation implementation - Implement instruction combining for different
124     // instruction types.  The semantics are as follows:
125     // Return Value:
126     //    null        - No change was made
127     //     I          - Change was made, I is still valid, I may be dead though
128     //   otherwise    - Change was made, replace I with returned instruction
129     //
130     Instruction *visitAdd(BinaryOperator &I);
131     Instruction *visitSub(BinaryOperator &I);
132     Instruction *visitMul(BinaryOperator &I);
133     Instruction *visitURem(BinaryOperator &I);
134     Instruction *visitSRem(BinaryOperator &I);
135     Instruction *visitFRem(BinaryOperator &I);
136     Instruction *commonRemTransforms(BinaryOperator &I);
137     Instruction *commonIRemTransforms(BinaryOperator &I);
138     Instruction *commonDivTransforms(BinaryOperator &I);
139     Instruction *commonIDivTransforms(BinaryOperator &I);
140     Instruction *visitUDiv(BinaryOperator &I);
141     Instruction *visitSDiv(BinaryOperator &I);
142     Instruction *visitFDiv(BinaryOperator &I);
143     Instruction *visitAnd(BinaryOperator &I);
144     Instruction *visitOr (BinaryOperator &I);
145     Instruction *visitXor(BinaryOperator &I);
146     Instruction *visitSetCondInst(SetCondInst &I);
147     Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
148
149     Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
150                               Instruction::BinaryOps Cond, Instruction &I);
151     Instruction *visitShiftInst(ShiftInst &I);
152     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
153                                      ShiftInst &I);
154     Instruction *commonCastTransforms(CastInst &CI);
155     Instruction *commonIntCastTransforms(CastInst &CI);
156     Instruction *visitTrunc(CastInst &CI);
157     Instruction *visitZExt(CastInst &CI);
158     Instruction *visitSExt(CastInst &CI);
159     Instruction *visitFPTrunc(CastInst &CI);
160     Instruction *visitFPExt(CastInst &CI);
161     Instruction *visitFPToUI(CastInst &CI);
162     Instruction *visitFPToSI(CastInst &CI);
163     Instruction *visitUIToFP(CastInst &CI);
164     Instruction *visitSIToFP(CastInst &CI);
165     Instruction *visitPtrToInt(CastInst &CI);
166     Instruction *visitIntToPtr(CastInst &CI);
167     Instruction *visitBitCast(CastInst &CI);
168     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
169                                 Instruction *FI);
170     Instruction *visitSelectInst(SelectInst &CI);
171     Instruction *visitCallInst(CallInst &CI);
172     Instruction *visitInvokeInst(InvokeInst &II);
173     Instruction *visitPHINode(PHINode &PN);
174     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
175     Instruction *visitAllocationInst(AllocationInst &AI);
176     Instruction *visitFreeInst(FreeInst &FI);
177     Instruction *visitLoadInst(LoadInst &LI);
178     Instruction *visitStoreInst(StoreInst &SI);
179     Instruction *visitBranchInst(BranchInst &BI);
180     Instruction *visitSwitchInst(SwitchInst &SI);
181     Instruction *visitInsertElementInst(InsertElementInst &IE);
182     Instruction *visitExtractElementInst(ExtractElementInst &EI);
183     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
184
185     // visitInstruction - Specify what to return for unhandled instructions...
186     Instruction *visitInstruction(Instruction &I) { return 0; }
187
188   private:
189     Instruction *visitCallSite(CallSite CS);
190     bool transformConstExprCastCall(CallSite CS);
191
192   public:
193     // InsertNewInstBefore - insert an instruction New before instruction Old
194     // in the program.  Add the new instruction to the worklist.
195     //
196     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
197       assert(New && New->getParent() == 0 &&
198              "New instruction already inserted into a basic block!");
199       BasicBlock *BB = Old.getParent();
200       BB->getInstList().insert(&Old, New);  // Insert inst
201       WorkList.push_back(New);              // Add to worklist
202       return New;
203     }
204
205     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
206     /// This also adds the cast to the worklist.  Finally, this returns the
207     /// cast.
208     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
209                             Instruction &Pos) {
210       if (V->getType() == Ty) return V;
211
212       if (Constant *CV = dyn_cast<Constant>(V))
213         return ConstantExpr::getCast(opc, CV, Ty);
214       
215       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
216       WorkList.push_back(C);
217       return C;
218     }
219
220     // ReplaceInstUsesWith - This method is to be used when an instruction is
221     // found to be dead, replacable with another preexisting expression.  Here
222     // we add all uses of I to the worklist, replace all uses of I with the new
223     // value, then return I, so that the inst combiner will know that I was
224     // modified.
225     //
226     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
227       AddUsersToWorkList(I);         // Add all modified instrs to worklist
228       if (&I != V) {
229         I.replaceAllUsesWith(V);
230         return &I;
231       } else {
232         // If we are replacing the instruction with itself, this must be in a
233         // segment of unreachable code, so just clobber the instruction.
234         I.replaceAllUsesWith(UndefValue::get(I.getType()));
235         return &I;
236       }
237     }
238
239     // UpdateValueUsesWith - This method is to be used when an value is
240     // found to be replacable with another preexisting expression or was
241     // updated.  Here we add all uses of I to the worklist, replace all uses of
242     // I with the new value (unless the instruction was just updated), then
243     // return true, so that the inst combiner will know that I was modified.
244     //
245     bool UpdateValueUsesWith(Value *Old, Value *New) {
246       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
247       if (Old != New)
248         Old->replaceAllUsesWith(New);
249       if (Instruction *I = dyn_cast<Instruction>(Old))
250         WorkList.push_back(I);
251       if (Instruction *I = dyn_cast<Instruction>(New))
252         WorkList.push_back(I);
253       return true;
254     }
255     
256     // EraseInstFromFunction - When dealing with an instruction that has side
257     // effects or produces a void value, we can't rely on DCE to delete the
258     // instruction.  Instead, visit methods should return the value returned by
259     // this function.
260     Instruction *EraseInstFromFunction(Instruction &I) {
261       assert(I.use_empty() && "Cannot erase instruction that is used!");
262       AddUsesToWorkList(I);
263       removeFromWorkList(&I);
264       I.eraseFromParent();
265       return 0;  // Don't do anything with FI
266     }
267
268   private:
269     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
270     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
271     /// casts that are known to not do anything...
272     ///
273     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
274                                    Value *V, const Type *DestTy,
275                                    Instruction *InsertBefore);
276
277     // SimplifyCommutative - This performs a few simplifications for commutative
278     // operators.
279     bool SimplifyCommutative(BinaryOperator &I);
280
281     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
282                               uint64_t &KnownZero, uint64_t &KnownOne,
283                               unsigned Depth = 0);
284
285     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
286                                       uint64_t &UndefElts, unsigned Depth = 0);
287       
288     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
289     // PHI node as operand #0, see if we can fold the instruction into the PHI
290     // (which is only possible if all operands to the PHI are constants).
291     Instruction *FoldOpIntoPhi(Instruction &I);
292
293     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
294     // operator and they all are only used by the PHI, PHI together their
295     // inputs, and do the operation once, to the result of the PHI.
296     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
297     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
298     
299     
300     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
301                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
302     
303     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
304                               bool isSub, Instruction &I);
305     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
306                                  bool Inside, Instruction &IB);
307     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
308     Instruction *MatchBSwap(BinaryOperator &I);
309
310     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
311   };
312
313   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
314 }
315
316 // getComplexity:  Assign a complexity or rank value to LLVM Values...
317 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
318 static unsigned getComplexity(Value *V) {
319   if (isa<Instruction>(V)) {
320     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
321       return 3;
322     return 4;
323   }
324   if (isa<Argument>(V)) return 3;
325   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
326 }
327
328 // isOnlyUse - Return true if this instruction will be deleted if we stop using
329 // it.
330 static bool isOnlyUse(Value *V) {
331   return V->hasOneUse() || isa<Constant>(V);
332 }
333
334 // getPromotedType - Return the specified type promoted as it would be to pass
335 // though a va_arg area...
336 static const Type *getPromotedType(const Type *Ty) {
337   switch (Ty->getTypeID()) {
338   case Type::SByteTyID:
339   case Type::ShortTyID:  return Type::IntTy;
340   case Type::UByteTyID:
341   case Type::UShortTyID: return Type::UIntTy;
342   case Type::FloatTyID:  return Type::DoubleTy;
343   default:               return Ty;
344   }
345 }
346
347 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
348 /// expression bitcast,  return the operand value, otherwise return null.
349 static Value *getBitCastOperand(Value *V) {
350   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
351     return I->getOperand(0);
352   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
353     if (CE->getOpcode() == Instruction::BitCast)
354       return CE->getOperand(0);
355   return 0;
356 }
357
358 /// This function is a wrapper around CastInst::isEliminableCastPair. It
359 /// simply extracts arguments and returns what that function returns.
360 /// @Determine if it is valid to eliminate a Convert pair
361 static Instruction::CastOps 
362 isEliminableCastPair(
363   const CastInst *CI, ///< The first cast instruction
364   unsigned opcode,       ///< The opcode of the second cast instruction
365   const Type *DstTy,     ///< The target type for the second cast instruction
366   TargetData *TD         ///< The target data for pointer size
367 ) {
368   
369   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
370   const Type *MidTy = CI->getType();                  // B from above
371
372   // Get the opcodes of the two Cast instructions
373   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
374   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
375
376   return Instruction::CastOps(
377       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
378                                      DstTy, TD->getIntPtrType()));
379 }
380
381 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
382 /// in any code being generated.  It does not require codegen if V is simple
383 /// enough or if the cast can be folded into other casts.
384 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
385   if (V->getType() == Ty || isa<Constant>(V)) return false;
386   
387   // If this is a noop cast, it isn't real codegen.
388   if (V->getType()->canLosslesslyBitCastTo(Ty))
389     return false;
390
391   // If this is another cast that can be eliminated, it isn't codegen either.
392   if (const CastInst *CI = dyn_cast<CastInst>(V))
393     if (isEliminableCastPair(CI, CastInst::getCastOpcode(
394             V, V->getType()->isSigned(), Ty, Ty->isSigned()), Ty, TD)) 
395       return false;
396   return true;
397 }
398
399 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
400 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
401 /// casts that are known to not do anything...
402 ///
403 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
404                                              Value *V, const Type *DestTy,
405                                              Instruction *InsertBefore) {
406   if (V->getType() == DestTy) return V;
407   if (Constant *C = dyn_cast<Constant>(V))
408     return ConstantExpr::getCast(opcode, C, DestTy);
409   
410   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
411 }
412
413 // SimplifyCommutative - This performs a few simplifications for commutative
414 // operators:
415 //
416 //  1. Order operands such that they are listed from right (least complex) to
417 //     left (most complex).  This puts constants before unary operators before
418 //     binary operators.
419 //
420 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
421 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
422 //
423 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
424   bool Changed = false;
425   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
426     Changed = !I.swapOperands();
427
428   if (!I.isAssociative()) return Changed;
429   Instruction::BinaryOps Opcode = I.getOpcode();
430   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
431     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
432       if (isa<Constant>(I.getOperand(1))) {
433         Constant *Folded = ConstantExpr::get(I.getOpcode(),
434                                              cast<Constant>(I.getOperand(1)),
435                                              cast<Constant>(Op->getOperand(1)));
436         I.setOperand(0, Op->getOperand(0));
437         I.setOperand(1, Folded);
438         return true;
439       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
440         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
441             isOnlyUse(Op) && isOnlyUse(Op1)) {
442           Constant *C1 = cast<Constant>(Op->getOperand(1));
443           Constant *C2 = cast<Constant>(Op1->getOperand(1));
444
445           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
446           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
447           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
448                                                     Op1->getOperand(0),
449                                                     Op1->getName(), &I);
450           WorkList.push_back(New);
451           I.setOperand(0, New);
452           I.setOperand(1, Folded);
453           return true;
454         }
455     }
456   return Changed;
457 }
458
459 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
460 // if the LHS is a constant zero (which is the 'negate' form).
461 //
462 static inline Value *dyn_castNegVal(Value *V) {
463   if (BinaryOperator::isNeg(V))
464     return BinaryOperator::getNegArgument(V);
465
466   // Constants can be considered to be negated values if they can be folded.
467   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
468     return ConstantExpr::getNeg(C);
469   return 0;
470 }
471
472 static inline Value *dyn_castNotVal(Value *V) {
473   if (BinaryOperator::isNot(V))
474     return BinaryOperator::getNotArgument(V);
475
476   // Constants can be considered to be not'ed values...
477   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
478     return ConstantExpr::getNot(C);
479   return 0;
480 }
481
482 // dyn_castFoldableMul - If this value is a multiply that can be folded into
483 // other computations (because it has a constant operand), return the
484 // non-constant operand of the multiply, and set CST to point to the multiplier.
485 // Otherwise, return null.
486 //
487 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
488   if (V->hasOneUse() && V->getType()->isInteger())
489     if (Instruction *I = dyn_cast<Instruction>(V)) {
490       if (I->getOpcode() == Instruction::Mul)
491         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
492           return I->getOperand(0);
493       if (I->getOpcode() == Instruction::Shl)
494         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
495           // The multiplier is really 1 << CST.
496           Constant *One = ConstantInt::get(V->getType(), 1);
497           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
498           return I->getOperand(0);
499         }
500     }
501   return 0;
502 }
503
504 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
505 /// expression, return it.
506 static User *dyn_castGetElementPtr(Value *V) {
507   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
508   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
509     if (CE->getOpcode() == Instruction::GetElementPtr)
510       return cast<User>(V);
511   return false;
512 }
513
514 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
515 static ConstantInt *AddOne(ConstantInt *C) {
516   return cast<ConstantInt>(ConstantExpr::getAdd(C,
517                                          ConstantInt::get(C->getType(), 1)));
518 }
519 static ConstantInt *SubOne(ConstantInt *C) {
520   return cast<ConstantInt>(ConstantExpr::getSub(C,
521                                          ConstantInt::get(C->getType(), 1)));
522 }
523
524 /// GetConstantInType - Return a ConstantInt with the specified type and value.
525 ///
526 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
527   if (Ty->isUnsigned()) 
528     return ConstantInt::get(Ty, Val);
529   else if (Ty->getTypeID() == Type::BoolTyID)
530     return ConstantBool::get(Val);
531   int64_t SVal = Val;
532   SVal <<= 64-Ty->getPrimitiveSizeInBits();
533   SVal >>= 64-Ty->getPrimitiveSizeInBits();
534   return ConstantInt::get(Ty, SVal);
535 }
536
537
538 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
539 /// known to be either zero or one and return them in the KnownZero/KnownOne
540 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
541 /// processing.
542 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
543                               uint64_t &KnownOne, unsigned Depth = 0) {
544   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
545   // we cannot optimize based on the assumption that it is zero without changing
546   // it to be an explicit zero.  If we don't change it to zero, other code could
547   // optimized based on the contradictory assumption that it is non-zero.
548   // Because instcombine aggressively folds operations with undef args anyway,
549   // this won't lose us code quality.
550   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
551     // We know all of the bits for a constant!
552     KnownOne = CI->getZExtValue() & Mask;
553     KnownZero = ~KnownOne & Mask;
554     return;
555   }
556
557   KnownZero = KnownOne = 0;   // Don't know anything.
558   if (Depth == 6 || Mask == 0)
559     return;  // Limit search depth.
560
561   uint64_t KnownZero2, KnownOne2;
562   Instruction *I = dyn_cast<Instruction>(V);
563   if (!I) return;
564
565   Mask &= V->getType()->getIntegralTypeMask();
566   
567   switch (I->getOpcode()) {
568   case Instruction::And:
569     // If either the LHS or the RHS are Zero, the result is zero.
570     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
571     Mask &= ~KnownZero;
572     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
573     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
574     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
575     
576     // Output known-1 bits are only known if set in both the LHS & RHS.
577     KnownOne &= KnownOne2;
578     // Output known-0 are known to be clear if zero in either the LHS | RHS.
579     KnownZero |= KnownZero2;
580     return;
581   case Instruction::Or:
582     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
583     Mask &= ~KnownOne;
584     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
585     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
586     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
587     
588     // Output known-0 bits are only known if clear in both the LHS & RHS.
589     KnownZero &= KnownZero2;
590     // Output known-1 are known to be set if set in either the LHS | RHS.
591     KnownOne |= KnownOne2;
592     return;
593   case Instruction::Xor: {
594     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
595     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
596     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
597     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
598     
599     // Output known-0 bits are known if clear or set in both the LHS & RHS.
600     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
601     // Output known-1 are known to be set if set in only one of the LHS, RHS.
602     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
603     KnownZero = KnownZeroOut;
604     return;
605   }
606   case Instruction::Select:
607     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
608     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
609     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
610     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
611
612     // Only known if known in both the LHS and RHS.
613     KnownOne &= KnownOne2;
614     KnownZero &= KnownZero2;
615     return;
616   case Instruction::FPTrunc:
617   case Instruction::FPExt:
618   case Instruction::FPToUI:
619   case Instruction::FPToSI:
620   case Instruction::SIToFP:
621   case Instruction::PtrToInt:
622   case Instruction::UIToFP:
623   case Instruction::IntToPtr:
624     return; // Can't work with floating point or pointers
625   case Instruction::Trunc: 
626     // All these have integer operands
627     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
628     return;
629   case Instruction::BitCast: {
630     const Type *SrcTy = I->getOperand(0)->getType();
631     if (SrcTy->isIntegral()) {
632       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
633       return;
634     }
635     break;
636   }
637   case Instruction::ZExt:  {
638     // Compute the bits in the result that are not present in the input.
639     const Type *SrcTy = I->getOperand(0)->getType();
640     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
641     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
642       
643     Mask &= SrcTy->getIntegralTypeMask();
644     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
645     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
646     // The top bits are known to be zero.
647     KnownZero |= NewBits;
648     return;
649   }
650   case Instruction::SExt: {
651     // Compute the bits in the result that are not present in the input.
652     const Type *SrcTy = I->getOperand(0)->getType();
653     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
654     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
655       
656     Mask &= SrcTy->getIntegralTypeMask();
657     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
658     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
659
660     // If the sign bit of the input is known set or clear, then we know the
661     // top bits of the result.
662     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
663     if (KnownZero & InSignBit) {          // Input sign bit known zero
664       KnownZero |= NewBits;
665       KnownOne &= ~NewBits;
666     } else if (KnownOne & InSignBit) {    // Input sign bit known set
667       KnownOne |= NewBits;
668       KnownZero &= ~NewBits;
669     } else {                              // Input sign bit unknown
670       KnownZero &= ~NewBits;
671       KnownOne &= ~NewBits;
672     }
673     return;
674   }
675   case Instruction::Shl:
676     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
677     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
678       uint64_t ShiftAmt = SA->getZExtValue();
679       Mask >>= ShiftAmt;
680       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
681       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
682       KnownZero <<= ShiftAmt;
683       KnownOne  <<= ShiftAmt;
684       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
685       return;
686     }
687     break;
688   case Instruction::LShr:
689     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
690     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
691       // Compute the new bits that are at the top now.
692       uint64_t ShiftAmt = SA->getZExtValue();
693       uint64_t HighBits = (1ULL << ShiftAmt)-1;
694       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
695       
696       // Unsigned shift right.
697       Mask <<= ShiftAmt;
698       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
699       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
700       KnownZero >>= ShiftAmt;
701       KnownOne  >>= ShiftAmt;
702       KnownZero |= HighBits;  // high bits known zero.
703       return;
704     }
705     break;
706   case Instruction::AShr:
707     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
708     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
709       // Compute the new bits that are at the top now.
710       uint64_t ShiftAmt = SA->getZExtValue();
711       uint64_t HighBits = (1ULL << ShiftAmt)-1;
712       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
713       
714       // Signed shift right.
715       Mask <<= ShiftAmt;
716       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
717       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
718       KnownZero >>= ShiftAmt;
719       KnownOne  >>= ShiftAmt;
720         
721       // Handle the sign bits.
722       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
723       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
724         
725       if (KnownZero & SignBit) {       // New bits are known zero.
726         KnownZero |= HighBits;
727       } else if (KnownOne & SignBit) { // New bits are known one.
728         KnownOne |= HighBits;
729       }
730       return;
731     }
732     break;
733   }
734 }
735
736 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
737 /// this predicate to simplify operations downstream.  Mask is known to be zero
738 /// for bits that V cannot have.
739 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
740   uint64_t KnownZero, KnownOne;
741   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
742   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
743   return (KnownZero & Mask) == Mask;
744 }
745
746 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
747 /// specified instruction is a constant integer.  If so, check to see if there
748 /// are any bits set in the constant that are not demanded.  If so, shrink the
749 /// constant and return true.
750 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
751                                    uint64_t Demanded) {
752   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
753   if (!OpC) return false;
754
755   // If there are no bits set that aren't demanded, nothing to do.
756   if ((~Demanded & OpC->getZExtValue()) == 0)
757     return false;
758
759   // This is producing any bits that are not needed, shrink the RHS.
760   uint64_t Val = Demanded & OpC->getZExtValue();
761   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
762   return true;
763 }
764
765 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
766 // set of known zero and one bits, compute the maximum and minimum values that
767 // could have the specified known zero and known one bits, returning them in
768 // min/max.
769 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
770                                                    uint64_t KnownZero,
771                                                    uint64_t KnownOne,
772                                                    int64_t &Min, int64_t &Max) {
773   uint64_t TypeBits = Ty->getIntegralTypeMask();
774   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
775
776   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
777   
778   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
779   // bit if it is unknown.
780   Min = KnownOne;
781   Max = KnownOne|UnknownBits;
782   
783   if (SignBit & UnknownBits) { // Sign bit is unknown
784     Min |= SignBit;
785     Max &= ~SignBit;
786   }
787   
788   // Sign extend the min/max values.
789   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
790   Min = (Min << ShAmt) >> ShAmt;
791   Max = (Max << ShAmt) >> ShAmt;
792 }
793
794 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
795 // a set of known zero and one bits, compute the maximum and minimum values that
796 // could have the specified known zero and known one bits, returning them in
797 // min/max.
798 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
799                                                      uint64_t KnownZero,
800                                                      uint64_t KnownOne,
801                                                      uint64_t &Min,
802                                                      uint64_t &Max) {
803   uint64_t TypeBits = Ty->getIntegralTypeMask();
804   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
805   
806   // The minimum value is when the unknown bits are all zeros.
807   Min = KnownOne;
808   // The maximum value is when the unknown bits are all ones.
809   Max = KnownOne|UnknownBits;
810 }
811
812
813 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
814 /// DemandedMask bits of the result of V are ever used downstream.  If we can
815 /// use this information to simplify V, do so and return true.  Otherwise,
816 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
817 /// the expression (used to simplify the caller).  The KnownZero/One bits may
818 /// only be accurate for those bits in the DemandedMask.
819 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
820                                         uint64_t &KnownZero, uint64_t &KnownOne,
821                                         unsigned Depth) {
822   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
823     // We know all of the bits for a constant!
824     KnownOne = CI->getZExtValue() & DemandedMask;
825     KnownZero = ~KnownOne & DemandedMask;
826     return false;
827   }
828   
829   KnownZero = KnownOne = 0;
830   if (!V->hasOneUse()) {    // Other users may use these bits.
831     if (Depth != 0) {       // Not at the root.
832       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
833       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
834       return false;
835     }
836     // If this is the root being simplified, allow it to have multiple uses,
837     // just set the DemandedMask to all bits.
838     DemandedMask = V->getType()->getIntegralTypeMask();
839   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
840     if (V != UndefValue::get(V->getType()))
841       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
842     return false;
843   } else if (Depth == 6) {        // Limit search depth.
844     return false;
845   }
846   
847   Instruction *I = dyn_cast<Instruction>(V);
848   if (!I) return false;        // Only analyze instructions.
849
850   DemandedMask &= V->getType()->getIntegralTypeMask();
851   
852   uint64_t KnownZero2 = 0, KnownOne2 = 0;
853   switch (I->getOpcode()) {
854   default: break;
855   case Instruction::And:
856     // If either the LHS or the RHS are Zero, the result is zero.
857     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
858                              KnownZero, KnownOne, Depth+1))
859       return true;
860     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
861
862     // If something is known zero on the RHS, the bits aren't demanded on the
863     // LHS.
864     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
865                              KnownZero2, KnownOne2, Depth+1))
866       return true;
867     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
868
869     // If all of the demanded bits are known 1 on one side, return the other.
870     // These bits cannot contribute to the result of the 'and'.
871     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
872       return UpdateValueUsesWith(I, I->getOperand(0));
873     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
874       return UpdateValueUsesWith(I, I->getOperand(1));
875     
876     // If all of the demanded bits in the inputs are known zeros, return zero.
877     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
878       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
879       
880     // If the RHS is a constant, see if we can simplify it.
881     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
882       return UpdateValueUsesWith(I, I);
883       
884     // Output known-1 bits are only known if set in both the LHS & RHS.
885     KnownOne &= KnownOne2;
886     // Output known-0 are known to be clear if zero in either the LHS | RHS.
887     KnownZero |= KnownZero2;
888     break;
889   case Instruction::Or:
890     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
891                              KnownZero, KnownOne, Depth+1))
892       return true;
893     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
894     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
895                              KnownZero2, KnownOne2, Depth+1))
896       return true;
897     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
898     
899     // If all of the demanded bits are known zero on one side, return the other.
900     // These bits cannot contribute to the result of the 'or'.
901     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
902       return UpdateValueUsesWith(I, I->getOperand(0));
903     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
904       return UpdateValueUsesWith(I, I->getOperand(1));
905
906     // If all of the potentially set bits on one side are known to be set on
907     // the other side, just use the 'other' side.
908     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
909         (DemandedMask & (~KnownZero)))
910       return UpdateValueUsesWith(I, I->getOperand(0));
911     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
912         (DemandedMask & (~KnownZero2)))
913       return UpdateValueUsesWith(I, I->getOperand(1));
914         
915     // If the RHS is a constant, see if we can simplify it.
916     if (ShrinkDemandedConstant(I, 1, DemandedMask))
917       return UpdateValueUsesWith(I, I);
918           
919     // Output known-0 bits are only known if clear in both the LHS & RHS.
920     KnownZero &= KnownZero2;
921     // Output known-1 are known to be set if set in either the LHS | RHS.
922     KnownOne |= KnownOne2;
923     break;
924   case Instruction::Xor: {
925     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
926                              KnownZero, KnownOne, Depth+1))
927       return true;
928     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
929     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
930                              KnownZero2, KnownOne2, Depth+1))
931       return true;
932     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
933     
934     // If all of the demanded bits are known zero on one side, return the other.
935     // These bits cannot contribute to the result of the 'xor'.
936     if ((DemandedMask & KnownZero) == DemandedMask)
937       return UpdateValueUsesWith(I, I->getOperand(0));
938     if ((DemandedMask & KnownZero2) == DemandedMask)
939       return UpdateValueUsesWith(I, I->getOperand(1));
940     
941     // Output known-0 bits are known if clear or set in both the LHS & RHS.
942     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
943     // Output known-1 are known to be set if set in only one of the LHS, RHS.
944     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
945     
946     // If all of the demanded bits are known to be zero on one side or the
947     // other, turn this into an *inclusive* or.
948     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
949     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
950       Instruction *Or =
951         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
952                                  I->getName());
953       InsertNewInstBefore(Or, *I);
954       return UpdateValueUsesWith(I, Or);
955     }
956     
957     // If all of the demanded bits on one side are known, and all of the set
958     // bits on that side are also known to be set on the other side, turn this
959     // into an AND, as we know the bits will be cleared.
960     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
961     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
962       if ((KnownOne & KnownOne2) == KnownOne) {
963         Constant *AndC = GetConstantInType(I->getType(), 
964                                            ~KnownOne & DemandedMask);
965         Instruction *And = 
966           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
967         InsertNewInstBefore(And, *I);
968         return UpdateValueUsesWith(I, And);
969       }
970     }
971     
972     // If the RHS is a constant, see if we can simplify it.
973     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
974     if (ShrinkDemandedConstant(I, 1, DemandedMask))
975       return UpdateValueUsesWith(I, I);
976     
977     KnownZero = KnownZeroOut;
978     KnownOne  = KnownOneOut;
979     break;
980   }
981   case Instruction::Select:
982     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
983                              KnownZero, KnownOne, Depth+1))
984       return true;
985     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
986                              KnownZero2, KnownOne2, Depth+1))
987       return true;
988     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
989     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
990     
991     // If the operands are constants, see if we can simplify them.
992     if (ShrinkDemandedConstant(I, 1, DemandedMask))
993       return UpdateValueUsesWith(I, I);
994     if (ShrinkDemandedConstant(I, 2, DemandedMask))
995       return UpdateValueUsesWith(I, I);
996     
997     // Only known if known in both the LHS and RHS.
998     KnownOne &= KnownOne2;
999     KnownZero &= KnownZero2;
1000     break;
1001   case Instruction::Trunc:
1002     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1003                              KnownZero, KnownOne, Depth+1))
1004       return true;
1005     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1006     break;
1007   case Instruction::BitCast:
1008     if (!I->getOperand(0)->getType()->isIntegral())
1009       return false;
1010       
1011     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1012                              KnownZero, KnownOne, Depth+1))
1013       return true;
1014     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1015     break;
1016   case Instruction::ZExt: {
1017     // Compute the bits in the result that are not present in the input.
1018     const Type *SrcTy = I->getOperand(0)->getType();
1019     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1020     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1021     
1022     DemandedMask &= SrcTy->getIntegralTypeMask();
1023     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1024                              KnownZero, KnownOne, Depth+1))
1025       return true;
1026     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1027     // The top bits are known to be zero.
1028     KnownZero |= NewBits;
1029     break;
1030   }
1031   case Instruction::SExt: {
1032     // Compute the bits in the result that are not present in the input.
1033     const Type *SrcTy = I->getOperand(0)->getType();
1034     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1035     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1036     
1037     // Get the sign bit for the source type
1038     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1039     int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1040
1041     // If any of the sign extended bits are demanded, we know that the sign
1042     // bit is demanded.
1043     if (NewBits & DemandedMask)
1044       InputDemandedBits |= InSignBit;
1045       
1046     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1047                              KnownZero, KnownOne, Depth+1))
1048       return true;
1049     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1050       
1051     // If the sign bit of the input is known set or clear, then we know the
1052     // top bits of the result.
1053
1054     // If the input sign bit is known zero, or if the NewBits are not demanded
1055     // convert this into a zero extension.
1056     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1057       // Convert to ZExt cast
1058       CastInst *NewCast = CastInst::create(
1059         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1060       return UpdateValueUsesWith(I, NewCast);
1061     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1062       KnownOne |= NewBits;
1063       KnownZero &= ~NewBits;
1064     } else {                              // Input sign bit unknown
1065       KnownZero &= ~NewBits;
1066       KnownOne &= ~NewBits;
1067     }
1068     break;
1069   }
1070   case Instruction::Add:
1071     // If there is a constant on the RHS, there are a variety of xformations
1072     // we can do.
1073     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1074       // If null, this should be simplified elsewhere.  Some of the xforms here
1075       // won't work if the RHS is zero.
1076       if (RHS->isNullValue())
1077         break;
1078       
1079       // Figure out what the input bits are.  If the top bits of the and result
1080       // are not demanded, then the add doesn't demand them from its input
1081       // either.
1082       
1083       // Shift the demanded mask up so that it's at the top of the uint64_t.
1084       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1085       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1086       
1087       // If the top bit of the output is demanded, demand everything from the
1088       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1089       uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1090
1091       // Find information about known zero/one bits in the input.
1092       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1093                                KnownZero2, KnownOne2, Depth+1))
1094         return true;
1095
1096       // If the RHS of the add has bits set that can't affect the input, reduce
1097       // the constant.
1098       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1099         return UpdateValueUsesWith(I, I);
1100       
1101       // Avoid excess work.
1102       if (KnownZero2 == 0 && KnownOne2 == 0)
1103         break;
1104       
1105       // Turn it into OR if input bits are zero.
1106       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1107         Instruction *Or =
1108           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1109                                    I->getName());
1110         InsertNewInstBefore(Or, *I);
1111         return UpdateValueUsesWith(I, Or);
1112       }
1113       
1114       // We can say something about the output known-zero and known-one bits,
1115       // depending on potential carries from the input constant and the
1116       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1117       // bits set and the RHS constant is 0x01001, then we know we have a known
1118       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1119       
1120       // To compute this, we first compute the potential carry bits.  These are
1121       // the bits which may be modified.  I'm not aware of a better way to do
1122       // this scan.
1123       uint64_t RHSVal = RHS->getZExtValue();
1124       
1125       bool CarryIn = false;
1126       uint64_t CarryBits = 0;
1127       uint64_t CurBit = 1;
1128       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1129         // Record the current carry in.
1130         if (CarryIn) CarryBits |= CurBit;
1131         
1132         bool CarryOut;
1133         
1134         // This bit has a carry out unless it is "zero + zero" or
1135         // "zero + anything" with no carry in.
1136         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1137           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1138         } else if (!CarryIn &&
1139                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1140           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1141         } else {
1142           // Otherwise, we have to assume we have a carry out.
1143           CarryOut = true;
1144         }
1145         
1146         // This stage's carry out becomes the next stage's carry-in.
1147         CarryIn = CarryOut;
1148       }
1149       
1150       // Now that we know which bits have carries, compute the known-1/0 sets.
1151       
1152       // Bits are known one if they are known zero in one operand and one in the
1153       // other, and there is no input carry.
1154       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1155       
1156       // Bits are known zero if they are known zero in both operands and there
1157       // is no input carry.
1158       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1159     }
1160     break;
1161   case Instruction::Shl:
1162     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163       uint64_t ShiftAmt = SA->getZExtValue();
1164       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1165                                KnownZero, KnownOne, Depth+1))
1166         return true;
1167       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1168       KnownZero <<= ShiftAmt;
1169       KnownOne  <<= ShiftAmt;
1170       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1171     }
1172     break;
1173   case Instruction::LShr:
1174     // For a logical shift right
1175     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1176       unsigned ShiftAmt = SA->getZExtValue();
1177       
1178       // Compute the new bits that are at the top now.
1179       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1180       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1181       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1182       // Unsigned shift right.
1183       if (SimplifyDemandedBits(I->getOperand(0),
1184                               (DemandedMask << ShiftAmt) & TypeMask,
1185                                KnownZero, KnownOne, Depth+1))
1186         return true;
1187       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1188       KnownZero &= TypeMask;
1189       KnownOne  &= TypeMask;
1190       KnownZero >>= ShiftAmt;
1191       KnownOne  >>= ShiftAmt;
1192       KnownZero |= HighBits;  // high bits known zero.
1193     }
1194     break;
1195   case Instruction::AShr:
1196     // If this is an arithmetic shift right and only the low-bit is set, we can
1197     // always convert this into a logical shr, even if the shift amount is
1198     // variable.  The low bit of the shift cannot be an input sign bit unless
1199     // the shift amount is >= the size of the datatype, which is undefined.
1200     if (DemandedMask == 1) {
1201       // Perform the logical shift right.
1202       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1203                                     I->getOperand(1), I->getName());
1204       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1205       return UpdateValueUsesWith(I, NewVal);
1206     }    
1207     
1208     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1209       unsigned ShiftAmt = SA->getZExtValue();
1210       
1211       // Compute the new bits that are at the top now.
1212       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1213       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1214       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1215       // Signed shift right.
1216       if (SimplifyDemandedBits(I->getOperand(0),
1217                                (DemandedMask << ShiftAmt) & TypeMask,
1218                                KnownZero, KnownOne, Depth+1))
1219         return true;
1220       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1221       KnownZero &= TypeMask;
1222       KnownOne  &= TypeMask;
1223       KnownZero >>= ShiftAmt;
1224       KnownOne  >>= ShiftAmt;
1225         
1226       // Handle the sign bits.
1227       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1228       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1229         
1230       // If the input sign bit is known to be zero, or if none of the top bits
1231       // are demanded, turn this into an unsigned shift right.
1232       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1233         // Perform the logical shift right.
1234         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1235                                       SA, I->getName());
1236         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1237         return UpdateValueUsesWith(I, NewVal);
1238       } else if (KnownOne & SignBit) { // New bits are known one.
1239         KnownOne |= HighBits;
1240       }
1241     }
1242     break;
1243   }
1244   
1245   // If the client is only demanding bits that we know, return the known
1246   // constant.
1247   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1248     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1249   return false;
1250 }  
1251
1252
1253 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1254 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1255 /// actually used by the caller.  This method analyzes which elements of the
1256 /// operand are undef and returns that information in UndefElts.
1257 ///
1258 /// If the information about demanded elements can be used to simplify the
1259 /// operation, the operation is simplified, then the resultant value is
1260 /// returned.  This returns null if no change was made.
1261 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1262                                                 uint64_t &UndefElts,
1263                                                 unsigned Depth) {
1264   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1265   assert(VWidth <= 64 && "Vector too wide to analyze!");
1266   uint64_t EltMask = ~0ULL >> (64-VWidth);
1267   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1268          "Invalid DemandedElts!");
1269
1270   if (isa<UndefValue>(V)) {
1271     // If the entire vector is undefined, just return this info.
1272     UndefElts = EltMask;
1273     return 0;
1274   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1275     UndefElts = EltMask;
1276     return UndefValue::get(V->getType());
1277   }
1278   
1279   UndefElts = 0;
1280   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1281     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1282     Constant *Undef = UndefValue::get(EltTy);
1283
1284     std::vector<Constant*> Elts;
1285     for (unsigned i = 0; i != VWidth; ++i)
1286       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1287         Elts.push_back(Undef);
1288         UndefElts |= (1ULL << i);
1289       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1290         Elts.push_back(Undef);
1291         UndefElts |= (1ULL << i);
1292       } else {                               // Otherwise, defined.
1293         Elts.push_back(CP->getOperand(i));
1294       }
1295         
1296     // If we changed the constant, return it.
1297     Constant *NewCP = ConstantPacked::get(Elts);
1298     return NewCP != CP ? NewCP : 0;
1299   } else if (isa<ConstantAggregateZero>(V)) {
1300     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1301     // set to undef.
1302     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1303     Constant *Zero = Constant::getNullValue(EltTy);
1304     Constant *Undef = UndefValue::get(EltTy);
1305     std::vector<Constant*> Elts;
1306     for (unsigned i = 0; i != VWidth; ++i)
1307       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1308     UndefElts = DemandedElts ^ EltMask;
1309     return ConstantPacked::get(Elts);
1310   }
1311   
1312   if (!V->hasOneUse()) {    // Other users may use these bits.
1313     if (Depth != 0) {       // Not at the root.
1314       // TODO: Just compute the UndefElts information recursively.
1315       return false;
1316     }
1317     return false;
1318   } else if (Depth == 10) {        // Limit search depth.
1319     return false;
1320   }
1321   
1322   Instruction *I = dyn_cast<Instruction>(V);
1323   if (!I) return false;        // Only analyze instructions.
1324   
1325   bool MadeChange = false;
1326   uint64_t UndefElts2;
1327   Value *TmpV;
1328   switch (I->getOpcode()) {
1329   default: break;
1330     
1331   case Instruction::InsertElement: {
1332     // If this is a variable index, we don't know which element it overwrites.
1333     // demand exactly the same input as we produce.
1334     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1335     if (Idx == 0) {
1336       // Note that we can't propagate undef elt info, because we don't know
1337       // which elt is getting updated.
1338       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1339                                         UndefElts2, Depth+1);
1340       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1341       break;
1342     }
1343     
1344     // If this is inserting an element that isn't demanded, remove this
1345     // insertelement.
1346     unsigned IdxNo = Idx->getZExtValue();
1347     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1348       return AddSoonDeadInstToWorklist(*I, 0);
1349     
1350     // Otherwise, the element inserted overwrites whatever was there, so the
1351     // input demanded set is simpler than the output set.
1352     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1353                                       DemandedElts & ~(1ULL << IdxNo),
1354                                       UndefElts, Depth+1);
1355     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1356
1357     // The inserted element is defined.
1358     UndefElts |= 1ULL << IdxNo;
1359     break;
1360   }
1361     
1362   case Instruction::And:
1363   case Instruction::Or:
1364   case Instruction::Xor:
1365   case Instruction::Add:
1366   case Instruction::Sub:
1367   case Instruction::Mul:
1368     // div/rem demand all inputs, because they don't want divide by zero.
1369     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1370                                       UndefElts, Depth+1);
1371     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1372     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1373                                       UndefElts2, Depth+1);
1374     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1375       
1376     // Output elements are undefined if both are undefined.  Consider things
1377     // like undef&0.  The result is known zero, not undef.
1378     UndefElts &= UndefElts2;
1379     break;
1380     
1381   case Instruction::Call: {
1382     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1383     if (!II) break;
1384     switch (II->getIntrinsicID()) {
1385     default: break;
1386       
1387     // Binary vector operations that work column-wise.  A dest element is a
1388     // function of the corresponding input elements from the two inputs.
1389     case Intrinsic::x86_sse_sub_ss:
1390     case Intrinsic::x86_sse_mul_ss:
1391     case Intrinsic::x86_sse_min_ss:
1392     case Intrinsic::x86_sse_max_ss:
1393     case Intrinsic::x86_sse2_sub_sd:
1394     case Intrinsic::x86_sse2_mul_sd:
1395     case Intrinsic::x86_sse2_min_sd:
1396     case Intrinsic::x86_sse2_max_sd:
1397       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1398                                         UndefElts, Depth+1);
1399       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1400       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1401                                         UndefElts2, Depth+1);
1402       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1403
1404       // If only the low elt is demanded and this is a scalarizable intrinsic,
1405       // scalarize it now.
1406       if (DemandedElts == 1) {
1407         switch (II->getIntrinsicID()) {
1408         default: break;
1409         case Intrinsic::x86_sse_sub_ss:
1410         case Intrinsic::x86_sse_mul_ss:
1411         case Intrinsic::x86_sse2_sub_sd:
1412         case Intrinsic::x86_sse2_mul_sd:
1413           // TODO: Lower MIN/MAX/ABS/etc
1414           Value *LHS = II->getOperand(1);
1415           Value *RHS = II->getOperand(2);
1416           // Extract the element as scalars.
1417           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1418           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1419           
1420           switch (II->getIntrinsicID()) {
1421           default: assert(0 && "Case stmts out of sync!");
1422           case Intrinsic::x86_sse_sub_ss:
1423           case Intrinsic::x86_sse2_sub_sd:
1424             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1425                                                         II->getName()), *II);
1426             break;
1427           case Intrinsic::x86_sse_mul_ss:
1428           case Intrinsic::x86_sse2_mul_sd:
1429             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1430                                                          II->getName()), *II);
1431             break;
1432           }
1433           
1434           Instruction *New =
1435             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1436                                   II->getName());
1437           InsertNewInstBefore(New, *II);
1438           AddSoonDeadInstToWorklist(*II, 0);
1439           return New;
1440         }            
1441       }
1442         
1443       // Output elements are undefined if both are undefined.  Consider things
1444       // like undef&0.  The result is known zero, not undef.
1445       UndefElts &= UndefElts2;
1446       break;
1447     }
1448     break;
1449   }
1450   }
1451   return MadeChange ? I : 0;
1452 }
1453
1454 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1455 // true when both operands are equal...
1456 //
1457 static bool isTrueWhenEqual(Instruction &I) {
1458   return I.getOpcode() == Instruction::SetEQ ||
1459          I.getOpcode() == Instruction::SetGE ||
1460          I.getOpcode() == Instruction::SetLE;
1461 }
1462
1463 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1464 /// function is designed to check a chain of associative operators for a
1465 /// potential to apply a certain optimization.  Since the optimization may be
1466 /// applicable if the expression was reassociated, this checks the chain, then
1467 /// reassociates the expression as necessary to expose the optimization
1468 /// opportunity.  This makes use of a special Functor, which must define
1469 /// 'shouldApply' and 'apply' methods.
1470 ///
1471 template<typename Functor>
1472 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1473   unsigned Opcode = Root.getOpcode();
1474   Value *LHS = Root.getOperand(0);
1475
1476   // Quick check, see if the immediate LHS matches...
1477   if (F.shouldApply(LHS))
1478     return F.apply(Root);
1479
1480   // Otherwise, if the LHS is not of the same opcode as the root, return.
1481   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1482   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1483     // Should we apply this transform to the RHS?
1484     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1485
1486     // If not to the RHS, check to see if we should apply to the LHS...
1487     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1488       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1489       ShouldApply = true;
1490     }
1491
1492     // If the functor wants to apply the optimization to the RHS of LHSI,
1493     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1494     if (ShouldApply) {
1495       BasicBlock *BB = Root.getParent();
1496
1497       // Now all of the instructions are in the current basic block, go ahead
1498       // and perform the reassociation.
1499       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1500
1501       // First move the selected RHS to the LHS of the root...
1502       Root.setOperand(0, LHSI->getOperand(1));
1503
1504       // Make what used to be the LHS of the root be the user of the root...
1505       Value *ExtraOperand = TmpLHSI->getOperand(1);
1506       if (&Root == TmpLHSI) {
1507         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1508         return 0;
1509       }
1510       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1511       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1512       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1513       BasicBlock::iterator ARI = &Root; ++ARI;
1514       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1515       ARI = Root;
1516
1517       // Now propagate the ExtraOperand down the chain of instructions until we
1518       // get to LHSI.
1519       while (TmpLHSI != LHSI) {
1520         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1521         // Move the instruction to immediately before the chain we are
1522         // constructing to avoid breaking dominance properties.
1523         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1524         BB->getInstList().insert(ARI, NextLHSI);
1525         ARI = NextLHSI;
1526
1527         Value *NextOp = NextLHSI->getOperand(1);
1528         NextLHSI->setOperand(1, ExtraOperand);
1529         TmpLHSI = NextLHSI;
1530         ExtraOperand = NextOp;
1531       }
1532
1533       // Now that the instructions are reassociated, have the functor perform
1534       // the transformation...
1535       return F.apply(Root);
1536     }
1537
1538     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1539   }
1540   return 0;
1541 }
1542
1543
1544 // AddRHS - Implements: X + X --> X << 1
1545 struct AddRHS {
1546   Value *RHS;
1547   AddRHS(Value *rhs) : RHS(rhs) {}
1548   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1549   Instruction *apply(BinaryOperator &Add) const {
1550     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1551                          ConstantInt::get(Type::UByteTy, 1));
1552   }
1553 };
1554
1555 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1556 //                 iff C1&C2 == 0
1557 struct AddMaskingAnd {
1558   Constant *C2;
1559   AddMaskingAnd(Constant *c) : C2(c) {}
1560   bool shouldApply(Value *LHS) const {
1561     ConstantInt *C1;
1562     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1563            ConstantExpr::getAnd(C1, C2)->isNullValue();
1564   }
1565   Instruction *apply(BinaryOperator &Add) const {
1566     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1567   }
1568 };
1569
1570 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1571                                              InstCombiner *IC) {
1572   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1573     if (Constant *SOC = dyn_cast<Constant>(SO))
1574       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1575
1576     return IC->InsertNewInstBefore(CastInst::create(
1577           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1578   }
1579
1580   // Figure out if the constant is the left or the right argument.
1581   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1582   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1583
1584   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1585     if (ConstIsRHS)
1586       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1587     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1588   }
1589
1590   Value *Op0 = SO, *Op1 = ConstOperand;
1591   if (!ConstIsRHS)
1592     std::swap(Op0, Op1);
1593   Instruction *New;
1594   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1595     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1596   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1597     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1598   else {
1599     assert(0 && "Unknown binary instruction type!");
1600     abort();
1601   }
1602   return IC->InsertNewInstBefore(New, I);
1603 }
1604
1605 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1606 // constant as the other operand, try to fold the binary operator into the
1607 // select arguments.  This also works for Cast instructions, which obviously do
1608 // not have a second operand.
1609 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1610                                      InstCombiner *IC) {
1611   // Don't modify shared select instructions
1612   if (!SI->hasOneUse()) return 0;
1613   Value *TV = SI->getOperand(1);
1614   Value *FV = SI->getOperand(2);
1615
1616   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1617     // Bool selects with constant operands can be folded to logical ops.
1618     if (SI->getType() == Type::BoolTy) return 0;
1619
1620     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1621     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1622
1623     return new SelectInst(SI->getCondition(), SelectTrueVal,
1624                           SelectFalseVal);
1625   }
1626   return 0;
1627 }
1628
1629
1630 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1631 /// node as operand #0, see if we can fold the instruction into the PHI (which
1632 /// is only possible if all operands to the PHI are constants).
1633 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1634   PHINode *PN = cast<PHINode>(I.getOperand(0));
1635   unsigned NumPHIValues = PN->getNumIncomingValues();
1636   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1637
1638   // Check to see if all of the operands of the PHI are constants.  If there is
1639   // one non-constant value, remember the BB it is.  If there is more than one
1640   // bail out.
1641   BasicBlock *NonConstBB = 0;
1642   for (unsigned i = 0; i != NumPHIValues; ++i)
1643     if (!isa<Constant>(PN->getIncomingValue(i))) {
1644       if (NonConstBB) return 0;  // More than one non-const value.
1645       NonConstBB = PN->getIncomingBlock(i);
1646       
1647       // If the incoming non-constant value is in I's block, we have an infinite
1648       // loop.
1649       if (NonConstBB == I.getParent())
1650         return 0;
1651     }
1652   
1653   // If there is exactly one non-constant value, we can insert a copy of the
1654   // operation in that block.  However, if this is a critical edge, we would be
1655   // inserting the computation one some other paths (e.g. inside a loop).  Only
1656   // do this if the pred block is unconditionally branching into the phi block.
1657   if (NonConstBB) {
1658     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1659     if (!BI || !BI->isUnconditional()) return 0;
1660   }
1661
1662   // Okay, we can do the transformation: create the new PHI node.
1663   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1664   I.setName("");
1665   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1666   InsertNewInstBefore(NewPN, *PN);
1667
1668   // Next, add all of the operands to the PHI.
1669   if (I.getNumOperands() == 2) {
1670     Constant *C = cast<Constant>(I.getOperand(1));
1671     for (unsigned i = 0; i != NumPHIValues; ++i) {
1672       Value *InV;
1673       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1674         InV = ConstantExpr::get(I.getOpcode(), InC, C);
1675       } else {
1676         assert(PN->getIncomingBlock(i) == NonConstBB);
1677         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1678           InV = BinaryOperator::create(BO->getOpcode(),
1679                                        PN->getIncomingValue(i), C, "phitmp",
1680                                        NonConstBB->getTerminator());
1681         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1682           InV = new ShiftInst(SI->getOpcode(),
1683                               PN->getIncomingValue(i), C, "phitmp",
1684                               NonConstBB->getTerminator());
1685         else
1686           assert(0 && "Unknown binop!");
1687         
1688         WorkList.push_back(cast<Instruction>(InV));
1689       }
1690       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1691     }
1692   } else { 
1693     CastInst *CI = cast<CastInst>(&I);
1694     const Type *RetTy = CI->getType();
1695     for (unsigned i = 0; i != NumPHIValues; ++i) {
1696       Value *InV;
1697       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1698         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1699       } else {
1700         assert(PN->getIncomingBlock(i) == NonConstBB);
1701         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1702                                I.getType(), "phitmp", 
1703                                NonConstBB->getTerminator());
1704         WorkList.push_back(cast<Instruction>(InV));
1705       }
1706       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1707     }
1708   }
1709   return ReplaceInstUsesWith(I, NewPN);
1710 }
1711
1712 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1713   bool Changed = SimplifyCommutative(I);
1714   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1715
1716   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1717     // X + undef -> undef
1718     if (isa<UndefValue>(RHS))
1719       return ReplaceInstUsesWith(I, RHS);
1720
1721     // X + 0 --> X
1722     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1723       if (RHSC->isNullValue())
1724         return ReplaceInstUsesWith(I, LHS);
1725     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1726       if (CFP->isExactlyValue(-0.0))
1727         return ReplaceInstUsesWith(I, LHS);
1728     }
1729
1730     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1731       // X + (signbit) --> X ^ signbit
1732       uint64_t Val = CI->getZExtValue();
1733       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1734         return BinaryOperator::createXor(LHS, RHS);
1735       
1736       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1737       // (X & 254)+1 -> (X&254)|1
1738       uint64_t KnownZero, KnownOne;
1739       if (!isa<PackedType>(I.getType()) &&
1740           SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1741                                KnownZero, KnownOne))
1742         return &I;
1743     }
1744
1745     if (isa<PHINode>(LHS))
1746       if (Instruction *NV = FoldOpIntoPhi(I))
1747         return NV;
1748     
1749     ConstantInt *XorRHS = 0;
1750     Value *XorLHS = 0;
1751     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1752       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1753       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1754       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1755       
1756       uint64_t C0080Val = 1ULL << 31;
1757       int64_t CFF80Val = -C0080Val;
1758       unsigned Size = 32;
1759       do {
1760         if (TySizeBits > Size) {
1761           bool Found = false;
1762           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1763           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1764           if (RHSSExt == CFF80Val) {
1765             if (XorRHS->getZExtValue() == C0080Val)
1766               Found = true;
1767           } else if (RHSZExt == C0080Val) {
1768             if (XorRHS->getSExtValue() == CFF80Val)
1769               Found = true;
1770           }
1771           if (Found) {
1772             // This is a sign extend if the top bits are known zero.
1773             uint64_t Mask = ~0ULL;
1774             Mask <<= 64-(TySizeBits-Size);
1775             Mask &= XorLHS->getType()->getIntegralTypeMask();
1776             if (!MaskedValueIsZero(XorLHS, Mask))
1777               Size = 0;  // Not a sign ext, but can't be any others either.
1778             goto FoundSExt;
1779           }
1780         }
1781         Size >>= 1;
1782         C0080Val >>= Size;
1783         CFF80Val >>= Size;
1784       } while (Size >= 8);
1785       
1786 FoundSExt:
1787       const Type *MiddleType = 0;
1788       switch (Size) {
1789       default: break;
1790       case 32: MiddleType = Type::IntTy; break;
1791       case 16: MiddleType = Type::ShortTy; break;
1792       case 8:  MiddleType = Type::SByteTy; break;
1793       }
1794       if (MiddleType) {
1795         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1796         InsertNewInstBefore(NewTrunc, I);
1797         return new SExtInst(NewTrunc, I.getType());
1798       }
1799     }
1800   }
1801
1802   // X + X --> X << 1
1803   if (I.getType()->isInteger()) {
1804     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1805
1806     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1807       if (RHSI->getOpcode() == Instruction::Sub)
1808         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1809           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1810     }
1811     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1812       if (LHSI->getOpcode() == Instruction::Sub)
1813         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1814           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1815     }
1816   }
1817
1818   // -A + B  -->  B - A
1819   if (Value *V = dyn_castNegVal(LHS))
1820     return BinaryOperator::createSub(RHS, V);
1821
1822   // A + -B  -->  A - B
1823   if (!isa<Constant>(RHS))
1824     if (Value *V = dyn_castNegVal(RHS))
1825       return BinaryOperator::createSub(LHS, V);
1826
1827
1828   ConstantInt *C2;
1829   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1830     if (X == RHS)   // X*C + X --> X * (C+1)
1831       return BinaryOperator::createMul(RHS, AddOne(C2));
1832
1833     // X*C1 + X*C2 --> X * (C1+C2)
1834     ConstantInt *C1;
1835     if (X == dyn_castFoldableMul(RHS, C1))
1836       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1837   }
1838
1839   // X + X*C --> X * (C+1)
1840   if (dyn_castFoldableMul(RHS, C2) == LHS)
1841     return BinaryOperator::createMul(LHS, AddOne(C2));
1842
1843
1844   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1845   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1846     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1847
1848   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1849     Value *X = 0;
1850     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1851       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1852       return BinaryOperator::createSub(C, X);
1853     }
1854
1855     // (X & FF00) + xx00  -> (X+xx00) & FF00
1856     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1857       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1858       if (Anded == CRHS) {
1859         // See if all bits from the first bit set in the Add RHS up are included
1860         // in the mask.  First, get the rightmost bit.
1861         uint64_t AddRHSV = CRHS->getZExtValue();
1862
1863         // Form a mask of all bits from the lowest bit added through the top.
1864         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1865         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1866
1867         // See if the and mask includes all of these bits.
1868         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1869
1870         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1871           // Okay, the xform is safe.  Insert the new add pronto.
1872           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1873                                                             LHS->getName()), I);
1874           return BinaryOperator::createAnd(NewAdd, C2);
1875         }
1876       }
1877     }
1878
1879     // Try to fold constant add into select arguments.
1880     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1881       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1882         return R;
1883   }
1884
1885   // add (cast *A to intptrtype) B -> 
1886   //   cast (GEP (cast *A to sbyte*) B) -> 
1887   //     intptrtype
1888   {
1889     CastInst *CI = dyn_cast<CastInst>(LHS);
1890     Value *Other = RHS;
1891     if (!CI) {
1892       CI = dyn_cast<CastInst>(RHS);
1893       Other = LHS;
1894     }
1895     if (CI && CI->getType()->isSized() && 
1896         (CI->getType()->getPrimitiveSize() == 
1897          TD->getIntPtrType()->getPrimitiveSize()) 
1898         && isa<PointerType>(CI->getOperand(0)->getType())) {
1899       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1900                                    PointerType::get(Type::SByteTy), I);
1901       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1902       return new PtrToIntInst(I2, CI->getType());
1903     }
1904   }
1905
1906   return Changed ? &I : 0;
1907 }
1908
1909 // isSignBit - Return true if the value represented by the constant only has the
1910 // highest order bit set.
1911 static bool isSignBit(ConstantInt *CI) {
1912   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1913   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1914 }
1915
1916 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1917 ///
1918 static Value *RemoveNoopCast(Value *V) {
1919   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1920     const Type *CTy = CI->getType();
1921     const Type *OpTy = CI->getOperand(0)->getType();
1922     if (CTy->isInteger() && OpTy->isInteger()) {
1923       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1924         return RemoveNoopCast(CI->getOperand(0));
1925     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1926       return RemoveNoopCast(CI->getOperand(0));
1927   }
1928   return V;
1929 }
1930
1931 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1932   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1933
1934   if (Op0 == Op1)         // sub X, X  -> 0
1935     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1936
1937   // If this is a 'B = x-(-A)', change to B = x+A...
1938   if (Value *V = dyn_castNegVal(Op1))
1939     return BinaryOperator::createAdd(Op0, V);
1940
1941   if (isa<UndefValue>(Op0))
1942     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1943   if (isa<UndefValue>(Op1))
1944     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1945
1946   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1947     // Replace (-1 - A) with (~A)...
1948     if (C->isAllOnesValue())
1949       return BinaryOperator::createNot(Op1);
1950
1951     // C - ~X == X + (1+C)
1952     Value *X = 0;
1953     if (match(Op1, m_Not(m_Value(X))))
1954       return BinaryOperator::createAdd(X,
1955                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1956     // -((uint)X >> 31) -> ((int)X >> 31)
1957     // -((int)X >> 31) -> ((uint)X >> 31)
1958     if (C->isNullValue()) {
1959       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1960       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1961         if (SI->getOpcode() == Instruction::LShr) {
1962           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1963             // Check to see if we are shifting out everything but the sign bit.
1964             if (CU->getZExtValue() == 
1965                 SI->getType()->getPrimitiveSizeInBits()-1) {
1966               // Ok, the transformation is safe.  Insert AShr.
1967               return new ShiftInst(Instruction::AShr, SI->getOperand(0),
1968                                     CU, SI->getName());
1969             }
1970           }
1971         }
1972         else if (SI->getOpcode() == Instruction::AShr) {
1973           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1974             // Check to see if we are shifting out everything but the sign bit.
1975             if (CU->getZExtValue() == 
1976                 SI->getType()->getPrimitiveSizeInBits()-1) {
1977               // Ok, the transformation is safe.  Insert LShr.
1978               return new ShiftInst(Instruction::LShr, SI->getOperand(0),
1979                                     CU, SI->getName());
1980             }
1981           }
1982         } 
1983     }
1984
1985     // Try to fold constant sub into select arguments.
1986     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1987       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1988         return R;
1989
1990     if (isa<PHINode>(Op0))
1991       if (Instruction *NV = FoldOpIntoPhi(I))
1992         return NV;
1993   }
1994
1995   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1996     if (Op1I->getOpcode() == Instruction::Add &&
1997         !Op0->getType()->isFPOrFPVector()) {
1998       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
1999         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2000       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2001         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2002       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2003         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2004           // C1-(X+C2) --> (C1-C2)-X
2005           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2006                                            Op1I->getOperand(0));
2007       }
2008     }
2009
2010     if (Op1I->hasOneUse()) {
2011       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2012       // is not used by anyone else...
2013       //
2014       if (Op1I->getOpcode() == Instruction::Sub &&
2015           !Op1I->getType()->isFPOrFPVector()) {
2016         // Swap the two operands of the subexpr...
2017         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2018         Op1I->setOperand(0, IIOp1);
2019         Op1I->setOperand(1, IIOp0);
2020
2021         // Create the new top level add instruction...
2022         return BinaryOperator::createAdd(Op0, Op1);
2023       }
2024
2025       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2026       //
2027       if (Op1I->getOpcode() == Instruction::And &&
2028           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2029         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2030
2031         Value *NewNot =
2032           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2033         return BinaryOperator::createAnd(Op0, NewNot);
2034       }
2035
2036       // 0 - (X sdiv C)  -> (X sdiv -C)
2037       if (Op1I->getOpcode() == Instruction::SDiv)
2038         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2039           if (CSI->isNullValue())
2040             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2041               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2042                                                ConstantExpr::getNeg(DivRHS));
2043
2044       // X - X*C --> X * (1-C)
2045       ConstantInt *C2 = 0;
2046       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2047         Constant *CP1 =
2048           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2049         return BinaryOperator::createMul(Op0, CP1);
2050       }
2051     }
2052   }
2053
2054   if (!Op0->getType()->isFPOrFPVector())
2055     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2056       if (Op0I->getOpcode() == Instruction::Add) {
2057         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2058           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2059         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2060           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2061       } else if (Op0I->getOpcode() == Instruction::Sub) {
2062         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2063           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2064       }
2065
2066   ConstantInt *C1;
2067   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2068     if (X == Op1) { // X*C - X --> X * (C-1)
2069       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2070       return BinaryOperator::createMul(Op1, CP1);
2071     }
2072
2073     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2074     if (X == dyn_castFoldableMul(Op1, C2))
2075       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2076   }
2077   return 0;
2078 }
2079
2080 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2081 /// really just returns true if the most significant (sign) bit is set.
2082 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2083   if (RHS->getType()->isSigned()) {
2084     // True if source is LHS < 0 or LHS <= -1
2085     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2086            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2087   } else {
2088     ConstantInt *RHSC = cast<ConstantInt>(RHS);
2089     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2090     // the size of the integer type.
2091     if (Opcode == Instruction::SetGE)
2092       return RHSC->getZExtValue() ==
2093         1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2094     if (Opcode == Instruction::SetGT)
2095       return RHSC->getZExtValue() ==
2096         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2097   }
2098   return false;
2099 }
2100
2101 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2102   bool Changed = SimplifyCommutative(I);
2103   Value *Op0 = I.getOperand(0);
2104
2105   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2106     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2107
2108   // Simplify mul instructions with a constant RHS...
2109   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2110     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2111
2112       // ((X << C1)*C2) == (X * (C2 << C1))
2113       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2114         if (SI->getOpcode() == Instruction::Shl)
2115           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2116             return BinaryOperator::createMul(SI->getOperand(0),
2117                                              ConstantExpr::getShl(CI, ShOp));
2118
2119       if (CI->isNullValue())
2120         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2121       if (CI->equalsInt(1))                  // X * 1  == X
2122         return ReplaceInstUsesWith(I, Op0);
2123       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2124         return BinaryOperator::createNeg(Op0, I.getName());
2125
2126       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2127       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2128         uint64_t C = Log2_64(Val);
2129         return new ShiftInst(Instruction::Shl, Op0,
2130                              ConstantInt::get(Type::UByteTy, C));
2131       }
2132     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2133       if (Op1F->isNullValue())
2134         return ReplaceInstUsesWith(I, Op1);
2135
2136       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2137       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2138       if (Op1F->getValue() == 1.0)
2139         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2140     }
2141     
2142     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2143       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2144           isa<ConstantInt>(Op0I->getOperand(1))) {
2145         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2146         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2147                                                      Op1, "tmp");
2148         InsertNewInstBefore(Add, I);
2149         Value *C1C2 = ConstantExpr::getMul(Op1, 
2150                                            cast<Constant>(Op0I->getOperand(1)));
2151         return BinaryOperator::createAdd(Add, C1C2);
2152         
2153       }
2154
2155     // Try to fold constant mul into select arguments.
2156     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2157       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2158         return R;
2159
2160     if (isa<PHINode>(Op0))
2161       if (Instruction *NV = FoldOpIntoPhi(I))
2162         return NV;
2163   }
2164
2165   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2166     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2167       return BinaryOperator::createMul(Op0v, Op1v);
2168
2169   // If one of the operands of the multiply is a cast from a boolean value, then
2170   // we know the bool is either zero or one, so this is a 'masking' multiply.
2171   // See if we can simplify things based on how the boolean was originally
2172   // formed.
2173   CastInst *BoolCast = 0;
2174   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2175     if (CI->getOperand(0)->getType() == Type::BoolTy)
2176       BoolCast = CI;
2177   if (!BoolCast)
2178     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2179       if (CI->getOperand(0)->getType() == Type::BoolTy)
2180         BoolCast = CI;
2181   if (BoolCast) {
2182     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2183       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2184       const Type *SCOpTy = SCIOp0->getType();
2185
2186       // If the setcc is true iff the sign bit of X is set, then convert this
2187       // multiply into a shift/and combination.
2188       if (isa<ConstantInt>(SCIOp1) &&
2189           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2190         // Shift the X value right to turn it into "all signbits".
2191         Constant *Amt = ConstantInt::get(Type::UByteTy,
2192                                           SCOpTy->getPrimitiveSizeInBits()-1);
2193         Value *V =
2194           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2195                                             BoolCast->getOperand(0)->getName()+
2196                                             ".mask"), I);
2197
2198         // If the multiply type is not the same as the source type, sign extend
2199         // or truncate to the multiply type.
2200         if (I.getType() != V->getType()) {
2201           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2202           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2203           Instruction::CastOps opcode = 
2204             (SrcBits == DstBits ? Instruction::BitCast : 
2205              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2206           V = InsertCastBefore(opcode, V, I.getType(), I);
2207         }
2208
2209         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2210         return BinaryOperator::createAnd(V, OtherOp);
2211       }
2212     }
2213   }
2214
2215   return Changed ? &I : 0;
2216 }
2217
2218 /// This function implements the transforms on div instructions that work
2219 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2220 /// used by the visitors to those instructions.
2221 /// @brief Transforms common to all three div instructions
2222 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2223   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2224
2225   // undef / X -> 0
2226   if (isa<UndefValue>(Op0))
2227     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2228
2229   // X / undef -> undef
2230   if (isa<UndefValue>(Op1))
2231     return ReplaceInstUsesWith(I, Op1);
2232
2233   // Handle cases involving: div X, (select Cond, Y, Z)
2234   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2235     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2236     // same basic block, then we replace the select with Y, and the condition 
2237     // of the select with false (if the cond value is in the same BB).  If the
2238     // select has uses other than the div, this allows them to be simplified
2239     // also. Note that div X, Y is just as good as div X, 0 (undef)
2240     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2241       if (ST->isNullValue()) {
2242         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2243         if (CondI && CondI->getParent() == I.getParent())
2244           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2245         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2246           I.setOperand(1, SI->getOperand(2));
2247         else
2248           UpdateValueUsesWith(SI, SI->getOperand(2));
2249         return &I;
2250       }
2251
2252     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2253     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2254       if (ST->isNullValue()) {
2255         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2256         if (CondI && CondI->getParent() == I.getParent())
2257           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2258         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2259           I.setOperand(1, SI->getOperand(1));
2260         else
2261           UpdateValueUsesWith(SI, SI->getOperand(1));
2262         return &I;
2263       }
2264   }
2265
2266   return 0;
2267 }
2268
2269 /// This function implements the transforms common to both integer division
2270 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2271 /// division instructions.
2272 /// @brief Common integer divide transforms
2273 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2274   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2275
2276   if (Instruction *Common = commonDivTransforms(I))
2277     return Common;
2278
2279   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2280     // div X, 1 == X
2281     if (RHS->equalsInt(1))
2282       return ReplaceInstUsesWith(I, Op0);
2283
2284     // (X / C1) / C2  -> X / (C1*C2)
2285     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2286       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2287         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2288           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2289                                         ConstantExpr::getMul(RHS, LHSRHS));
2290         }
2291
2292     if (!RHS->isNullValue()) { // avoid X udiv 0
2293       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2294         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2295           return R;
2296       if (isa<PHINode>(Op0))
2297         if (Instruction *NV = FoldOpIntoPhi(I))
2298           return NV;
2299     }
2300   }
2301
2302   // 0 / X == 0, we don't need to preserve faults!
2303   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2304     if (LHS->equalsInt(0))
2305       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2306
2307   return 0;
2308 }
2309
2310 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2311   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2312
2313   // Handle the integer div common cases
2314   if (Instruction *Common = commonIDivTransforms(I))
2315     return Common;
2316
2317   // X udiv C^2 -> X >> C
2318   // Check to see if this is an unsigned division with an exact power of 2,
2319   // if so, convert to a right shift.
2320   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2321     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2322       if (isPowerOf2_64(Val)) {
2323         uint64_t ShiftAmt = Log2_64(Val);
2324         return new ShiftInst(Instruction::LShr, Op0, 
2325                               ConstantInt::get(Type::UByteTy, ShiftAmt));
2326       }
2327   }
2328
2329   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2330   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2331     if (RHSI->getOpcode() == Instruction::Shl &&
2332         isa<ConstantInt>(RHSI->getOperand(0))) {
2333       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2334       if (isPowerOf2_64(C1)) {
2335         Value *N = RHSI->getOperand(1);
2336         const Type *NTy = N->getType();
2337         if (uint64_t C2 = Log2_64(C1)) {
2338           Constant *C2V = ConstantInt::get(NTy, C2);
2339           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2340         }
2341         return new ShiftInst(Instruction::LShr, Op0, N);
2342       }
2343     }
2344   }
2345   
2346   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2347   // where C1&C2 are powers of two.
2348   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2349     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2350       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2351         if (!STO->isNullValue() && !STO->isNullValue()) {
2352           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2353           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2354             // Compute the shift amounts
2355             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2356             // Construct the "on true" case of the select
2357             Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2358             Instruction *TSI = 
2359               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2360             TSI = InsertNewInstBefore(TSI, I);
2361     
2362             // Construct the "on false" case of the select
2363             Constant *FC = ConstantInt::get(Type::UByteTy, FSA); 
2364             Instruction *FSI = 
2365               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2366             FSI = InsertNewInstBefore(FSI, I);
2367
2368             // construct the select instruction and return it.
2369             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2370           }
2371         }
2372   }
2373   return 0;
2374 }
2375
2376 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2377   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2378
2379   // Handle the integer div common cases
2380   if (Instruction *Common = commonIDivTransforms(I))
2381     return Common;
2382
2383   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2384     // sdiv X, -1 == -X
2385     if (RHS->isAllOnesValue())
2386       return BinaryOperator::createNeg(Op0);
2387
2388     // -X/C -> X/-C
2389     if (Value *LHSNeg = dyn_castNegVal(Op0))
2390       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2391   }
2392
2393   // If the sign bits of both operands are zero (i.e. we can prove they are
2394   // unsigned inputs), turn this into a udiv.
2395   if (I.getType()->isInteger()) {
2396     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2397     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2398       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2399     }
2400   }      
2401   
2402   return 0;
2403 }
2404
2405 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2406   return commonDivTransforms(I);
2407 }
2408
2409 /// GetFactor - If we can prove that the specified value is at least a multiple
2410 /// of some factor, return that factor.
2411 static Constant *GetFactor(Value *V) {
2412   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2413     return CI;
2414   
2415   // Unless we can be tricky, we know this is a multiple of 1.
2416   Constant *Result = ConstantInt::get(V->getType(), 1);
2417   
2418   Instruction *I = dyn_cast<Instruction>(V);
2419   if (!I) return Result;
2420   
2421   if (I->getOpcode() == Instruction::Mul) {
2422     // Handle multiplies by a constant, etc.
2423     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2424                                 GetFactor(I->getOperand(1)));
2425   } else if (I->getOpcode() == Instruction::Shl) {
2426     // (X<<C) -> X * (1 << C)
2427     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2428       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2429       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2430     }
2431   } else if (I->getOpcode() == Instruction::And) {
2432     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2433       // X & 0xFFF0 is known to be a multiple of 16.
2434       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2435       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2436         return ConstantExpr::getShl(Result, 
2437                                     ConstantInt::get(Type::UByteTy, Zeros));
2438     }
2439   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2440     // Only handle int->int casts.
2441     if (!CI->isIntegerCast())
2442       return Result;
2443     Value *Op = CI->getOperand(0);
2444     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2445   }    
2446   return Result;
2447 }
2448
2449 /// This function implements the transforms on rem instructions that work
2450 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2451 /// is used by the visitors to those instructions.
2452 /// @brief Transforms common to all three rem instructions
2453 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2454   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2455
2456   // 0 % X == 0, we don't need to preserve faults!
2457   if (Constant *LHS = dyn_cast<Constant>(Op0))
2458     if (LHS->isNullValue())
2459       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460
2461   if (isa<UndefValue>(Op0))              // undef % X -> 0
2462     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2463   if (isa<UndefValue>(Op1))
2464     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2465
2466   // Handle cases involving: rem X, (select Cond, Y, Z)
2467   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2468     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2469     // the same basic block, then we replace the select with Y, and the
2470     // condition of the select with false (if the cond value is in the same
2471     // BB).  If the select has uses other than the div, this allows them to be
2472     // simplified also.
2473     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2474       if (ST->isNullValue()) {
2475         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2476         if (CondI && CondI->getParent() == I.getParent())
2477           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2478         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2479           I.setOperand(1, SI->getOperand(2));
2480         else
2481           UpdateValueUsesWith(SI, SI->getOperand(2));
2482         return &I;
2483       }
2484     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2485     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2486       if (ST->isNullValue()) {
2487         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2488         if (CondI && CondI->getParent() == I.getParent())
2489           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2490         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2491           I.setOperand(1, SI->getOperand(1));
2492         else
2493           UpdateValueUsesWith(SI, SI->getOperand(1));
2494         return &I;
2495       }
2496   }
2497
2498   return 0;
2499 }
2500
2501 /// This function implements the transforms common to both integer remainder
2502 /// instructions (urem and srem). It is called by the visitors to those integer
2503 /// remainder instructions.
2504 /// @brief Common integer remainder transforms
2505 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2506   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508   if (Instruction *common = commonRemTransforms(I))
2509     return common;
2510
2511   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2512     // X % 0 == undef, we don't need to preserve faults!
2513     if (RHS->equalsInt(0))
2514       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2515     
2516     if (RHS->equalsInt(1))  // X % 1 == 0
2517       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2518
2519     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2520       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2521         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2522           return R;
2523       } else if (isa<PHINode>(Op0I)) {
2524         if (Instruction *NV = FoldOpIntoPhi(I))
2525           return NV;
2526       }
2527       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2528       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2529         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2530     }
2531   }
2532
2533   return 0;
2534 }
2535
2536 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2537   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539   if (Instruction *common = commonIRemTransforms(I))
2540     return common;
2541   
2542   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2543     // X urem C^2 -> X and C
2544     // Check to see if this is an unsigned remainder with an exact power of 2,
2545     // if so, convert to a bitwise and.
2546     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2547       if (isPowerOf2_64(C->getZExtValue()))
2548         return BinaryOperator::createAnd(Op0, SubOne(C));
2549   }
2550
2551   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2552     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2553     if (RHSI->getOpcode() == Instruction::Shl &&
2554         isa<ConstantInt>(RHSI->getOperand(0))) {
2555       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2556       if (isPowerOf2_64(C1)) {
2557         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2558         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2559                                                                    "tmp"), I);
2560         return BinaryOperator::createAnd(Op0, Add);
2561       }
2562     }
2563   }
2564
2565   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2566   // where C1&C2 are powers of two.
2567   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2568     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2569       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2570         // STO == 0 and SFO == 0 handled above.
2571         if (isPowerOf2_64(STO->getZExtValue()) && 
2572             isPowerOf2_64(SFO->getZExtValue())) {
2573           Value *TrueAnd = InsertNewInstBefore(
2574             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2575           Value *FalseAnd = InsertNewInstBefore(
2576             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2577           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2578         }
2579       }
2580   }
2581   
2582   return 0;
2583 }
2584
2585 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2586   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2587
2588   if (Instruction *common = commonIRemTransforms(I))
2589     return common;
2590   
2591   if (Value *RHSNeg = dyn_castNegVal(Op1))
2592     if (!isa<ConstantInt>(RHSNeg) || 
2593         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2594       // X % -Y -> X % Y
2595       AddUsesToWorkList(I);
2596       I.setOperand(1, RHSNeg);
2597       return &I;
2598     }
2599  
2600   // If the top bits of both operands are zero (i.e. we can prove they are
2601   // unsigned inputs), turn this into a urem.
2602   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2603   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2604     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2605     return BinaryOperator::createURem(Op0, Op1, I.getName());
2606   }
2607
2608   return 0;
2609 }
2610
2611 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2612   return commonRemTransforms(I);
2613 }
2614
2615 // isMaxValueMinusOne - return true if this is Max-1
2616 static bool isMaxValueMinusOne(const ConstantInt *C) {
2617   if (C->getType()->isUnsigned()) 
2618     return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2619
2620   // Calculate 0111111111..11111
2621   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2622   int64_t Val = INT64_MAX;             // All ones
2623   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2624   return C->getSExtValue() == Val-1;
2625 }
2626
2627 // isMinValuePlusOne - return true if this is Min+1
2628 static bool isMinValuePlusOne(const ConstantInt *C) {
2629   if (C->getType()->isUnsigned())
2630     return C->getZExtValue() == 1;
2631
2632   // Calculate 1111111111000000000000
2633   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2634   int64_t Val = -1;                    // All ones
2635   Val <<= TypeBits-1;                  // Shift over to the right spot
2636   return C->getSExtValue() == Val+1;
2637 }
2638
2639 // isOneBitSet - Return true if there is exactly one bit set in the specified
2640 // constant.
2641 static bool isOneBitSet(const ConstantInt *CI) {
2642   uint64_t V = CI->getZExtValue();
2643   return V && (V & (V-1)) == 0;
2644 }
2645
2646 #if 0   // Currently unused
2647 // isLowOnes - Return true if the constant is of the form 0+1+.
2648 static bool isLowOnes(const ConstantInt *CI) {
2649   uint64_t V = CI->getZExtValue();
2650
2651   // There won't be bits set in parts that the type doesn't contain.
2652   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2653
2654   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2655   return U && V && (U & V) == 0;
2656 }
2657 #endif
2658
2659 // isHighOnes - Return true if the constant is of the form 1+0+.
2660 // This is the same as lowones(~X).
2661 static bool isHighOnes(const ConstantInt *CI) {
2662   uint64_t V = ~CI->getZExtValue();
2663   if (~V == 0) return false;  // 0's does not match "1+"
2664
2665   // There won't be bits set in parts that the type doesn't contain.
2666   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2667
2668   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2669   return U && V && (U & V) == 0;
2670 }
2671
2672
2673 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
2674 /// are carefully arranged to allow folding of expressions such as:
2675 ///
2676 ///      (A < B) | (A > B) --> (A != B)
2677 ///
2678 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2679 /// represents that the comparison is true if A == B, and bit value '1' is true
2680 /// if A < B.
2681 ///
2682 static unsigned getSetCondCode(const SetCondInst *SCI) {
2683   switch (SCI->getOpcode()) {
2684     // False -> 0
2685   case Instruction::SetGT: return 1;
2686   case Instruction::SetEQ: return 2;
2687   case Instruction::SetGE: return 3;
2688   case Instruction::SetLT: return 4;
2689   case Instruction::SetNE: return 5;
2690   case Instruction::SetLE: return 6;
2691     // True -> 7
2692   default:
2693     assert(0 && "Invalid SetCC opcode!");
2694     return 0;
2695   }
2696 }
2697
2698 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2699 /// opcode and two operands into either a constant true or false, or a brand new
2700 /// SetCC instruction.
2701 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2702   switch (Opcode) {
2703   case 0: return ConstantBool::getFalse();
2704   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2705   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2706   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2707   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2708   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2709   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2710   case 7: return ConstantBool::getTrue();
2711   default: assert(0 && "Illegal SetCCCode!"); return 0;
2712   }
2713 }
2714
2715 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2716 namespace {
2717 struct FoldSetCCLogical {
2718   InstCombiner &IC;
2719   Value *LHS, *RHS;
2720   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2721     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2722   bool shouldApply(Value *V) const {
2723     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2724       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2725               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2726     return false;
2727   }
2728   Instruction *apply(BinaryOperator &Log) const {
2729     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2730     if (SCI->getOperand(0) != LHS) {
2731       assert(SCI->getOperand(1) == LHS);
2732       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
2733     }
2734
2735     unsigned LHSCode = getSetCondCode(SCI);
2736     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2737     unsigned Code;
2738     switch (Log.getOpcode()) {
2739     case Instruction::And: Code = LHSCode & RHSCode; break;
2740     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2741     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2742     default: assert(0 && "Illegal logical opcode!"); return 0;
2743     }
2744
2745     Value *RV = getSetCCValue(Code, LHS, RHS);
2746     if (Instruction *I = dyn_cast<Instruction>(RV))
2747       return I;
2748     // Otherwise, it's a constant boolean value...
2749     return IC.ReplaceInstUsesWith(Log, RV);
2750   }
2751 };
2752 } // end anonymous namespace
2753
2754 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2755 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2756 // guaranteed to be either a shift instruction or a binary operator.
2757 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2758                                     ConstantIntegral *OpRHS,
2759                                     ConstantIntegral *AndRHS,
2760                                     BinaryOperator &TheAnd) {
2761   Value *X = Op->getOperand(0);
2762   Constant *Together = 0;
2763   if (!isa<ShiftInst>(Op))
2764     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2765
2766   switch (Op->getOpcode()) {
2767   case Instruction::Xor:
2768     if (Op->hasOneUse()) {
2769       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2770       std::string OpName = Op->getName(); Op->setName("");
2771       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2772       InsertNewInstBefore(And, TheAnd);
2773       return BinaryOperator::createXor(And, Together);
2774     }
2775     break;
2776   case Instruction::Or:
2777     if (Together == AndRHS) // (X | C) & C --> C
2778       return ReplaceInstUsesWith(TheAnd, AndRHS);
2779
2780     if (Op->hasOneUse() && Together != OpRHS) {
2781       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2782       std::string Op0Name = Op->getName(); Op->setName("");
2783       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2784       InsertNewInstBefore(Or, TheAnd);
2785       return BinaryOperator::createAnd(Or, AndRHS);
2786     }
2787     break;
2788   case Instruction::Add:
2789     if (Op->hasOneUse()) {
2790       // Adding a one to a single bit bit-field should be turned into an XOR
2791       // of the bit.  First thing to check is to see if this AND is with a
2792       // single bit constant.
2793       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2794
2795       // Clear bits that are not part of the constant.
2796       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2797
2798       // If there is only one bit set...
2799       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2800         // Ok, at this point, we know that we are masking the result of the
2801         // ADD down to exactly one bit.  If the constant we are adding has
2802         // no bits set below this bit, then we can eliminate the ADD.
2803         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2804
2805         // Check to see if any bits below the one bit set in AndRHSV are set.
2806         if ((AddRHS & (AndRHSV-1)) == 0) {
2807           // If not, the only thing that can effect the output of the AND is
2808           // the bit specified by AndRHSV.  If that bit is set, the effect of
2809           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2810           // no effect.
2811           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2812             TheAnd.setOperand(0, X);
2813             return &TheAnd;
2814           } else {
2815             std::string Name = Op->getName(); Op->setName("");
2816             // Pull the XOR out of the AND.
2817             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2818             InsertNewInstBefore(NewAnd, TheAnd);
2819             return BinaryOperator::createXor(NewAnd, AndRHS);
2820           }
2821         }
2822       }
2823     }
2824     break;
2825
2826   case Instruction::Shl: {
2827     // We know that the AND will not produce any of the bits shifted in, so if
2828     // the anded constant includes them, clear them now!
2829     //
2830     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2831     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2832     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2833
2834     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2835       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2836     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2837       TheAnd.setOperand(1, CI);
2838       return &TheAnd;
2839     }
2840     break;
2841   }
2842   case Instruction::LShr:
2843   {
2844     // We know that the AND will not produce any of the bits shifted in, so if
2845     // the anded constant includes them, clear them now!  This only applies to
2846     // unsigned shifts, because a signed shr may bring in set bits!
2847     //
2848     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2849     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2850     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2851
2852     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2853       return ReplaceInstUsesWith(TheAnd, Op);
2854     } else if (CI != AndRHS) {
2855       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2856       return &TheAnd;
2857     }
2858     break;
2859   }
2860   case Instruction::AShr:
2861     // Signed shr.
2862     // See if this is shifting in some sign extension, then masking it out
2863     // with an and.
2864     if (Op->hasOneUse()) {
2865       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2866       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2867       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2868       if (C == AndRHS) {          // Masking out bits shifted in.
2869         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2870         // Make the argument unsigned.
2871         Value *ShVal = Op->getOperand(0);
2872         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2873                                     OpRHS, Op->getName()), TheAnd);
2874         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2875       }
2876     }
2877     break;
2878   }
2879   return 0;
2880 }
2881
2882
2883 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2884 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2885 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
2886 /// insert new instructions.
2887 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2888                                            bool Inside, Instruction &IB) {
2889   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2890          "Lo is not <= Hi in range emission code!");
2891   if (Inside) {
2892     if (Lo == Hi)  // Trivially false.
2893       return new SetCondInst(Instruction::SetNE, V, V);
2894     if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
2895       return new SetCondInst(Instruction::SetLT, V, Hi);
2896
2897     Constant *AddCST = ConstantExpr::getNeg(Lo);
2898     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2899     InsertNewInstBefore(Add, IB);
2900     // Convert to unsigned for the comparison.
2901     const Type *UnsType = Add->getType()->getUnsignedVersion();
2902     Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
2903     AddCST = ConstantExpr::getAdd(AddCST, Hi);
2904     AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
2905     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2906   }
2907
2908   if (Lo == Hi)  // Trivially true.
2909     return new SetCondInst(Instruction::SetEQ, V, V);
2910
2911   Hi = SubOne(cast<ConstantInt>(Hi));
2912
2913   // V < 0 || V >= Hi ->'V > Hi-1'
2914   if (cast<ConstantIntegral>(Lo)->isMinValue(Lo->getType()->isSigned()))
2915     return new SetCondInst(Instruction::SetGT, V, Hi);
2916
2917   // Emit X-Lo > Hi-Lo-1
2918   Constant *AddCST = ConstantExpr::getNeg(Lo);
2919   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2920   InsertNewInstBefore(Add, IB);
2921   // Convert to unsigned for the comparison.
2922   const Type *UnsType = Add->getType()->getUnsignedVersion();
2923   Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add, UnsType, IB);
2924   AddCST = ConstantExpr::getAdd(AddCST, Hi);
2925   AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
2926   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2927 }
2928
2929 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2930 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2931 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2932 // not, since all 1s are not contiguous.
2933 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2934   uint64_t V = Val->getZExtValue();
2935   if (!isShiftedMask_64(V)) return false;
2936
2937   // look for the first zero bit after the run of ones
2938   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2939   // look for the first non-zero bit
2940   ME = 64-CountLeadingZeros_64(V);
2941   return true;
2942 }
2943
2944
2945
2946 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2947 /// where isSub determines whether the operator is a sub.  If we can fold one of
2948 /// the following xforms:
2949 /// 
2950 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2951 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2952 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2953 ///
2954 /// return (A +/- B).
2955 ///
2956 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2957                                         ConstantIntegral *Mask, bool isSub,
2958                                         Instruction &I) {
2959   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2960   if (!LHSI || LHSI->getNumOperands() != 2 ||
2961       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2962
2963   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2964
2965   switch (LHSI->getOpcode()) {
2966   default: return 0;
2967   case Instruction::And:
2968     if (ConstantExpr::getAnd(N, Mask) == Mask) {
2969       // If the AndRHS is a power of two minus one (0+1+), this is simple.
2970       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
2971         break;
2972
2973       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2974       // part, we don't need any explicit masks to take them out of A.  If that
2975       // is all N is, ignore it.
2976       unsigned MB, ME;
2977       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
2978         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2979         Mask >>= 64-MB+1;
2980         if (MaskedValueIsZero(RHS, Mask))
2981           break;
2982       }
2983     }
2984     return 0;
2985   case Instruction::Or:
2986   case Instruction::Xor:
2987     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2988     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
2989         ConstantExpr::getAnd(N, Mask)->isNullValue())
2990       break;
2991     return 0;
2992   }
2993   
2994   Instruction *New;
2995   if (isSub)
2996     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2997   else
2998     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2999   return InsertNewInstBefore(New, I);
3000 }
3001
3002 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3003   bool Changed = SimplifyCommutative(I);
3004   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3005
3006   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3007     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3008
3009   // and X, X = X
3010   if (Op0 == Op1)
3011     return ReplaceInstUsesWith(I, Op1);
3012
3013   // See if we can simplify any instructions used by the instruction whose sole 
3014   // purpose is to compute bits we don't care about.
3015   uint64_t KnownZero, KnownOne;
3016   if (!isa<PackedType>(I.getType()) &&
3017       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3018                            KnownZero, KnownOne))
3019     return &I;
3020   
3021   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3022     uint64_t AndRHSMask = AndRHS->getZExtValue();
3023     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3024     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3025
3026     // Optimize a variety of ((val OP C1) & C2) combinations...
3027     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3028       Instruction *Op0I = cast<Instruction>(Op0);
3029       Value *Op0LHS = Op0I->getOperand(0);
3030       Value *Op0RHS = Op0I->getOperand(1);
3031       switch (Op0I->getOpcode()) {
3032       case Instruction::Xor:
3033       case Instruction::Or:
3034         // If the mask is only needed on one incoming arm, push it up.
3035         if (Op0I->hasOneUse()) {
3036           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3037             // Not masking anything out for the LHS, move to RHS.
3038             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3039                                                    Op0RHS->getName()+".masked");
3040             InsertNewInstBefore(NewRHS, I);
3041             return BinaryOperator::create(
3042                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3043           }
3044           if (!isa<Constant>(Op0RHS) &&
3045               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3046             // Not masking anything out for the RHS, move to LHS.
3047             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3048                                                    Op0LHS->getName()+".masked");
3049             InsertNewInstBefore(NewLHS, I);
3050             return BinaryOperator::create(
3051                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3052           }
3053         }
3054
3055         break;
3056       case Instruction::Add:
3057         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3058         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3059         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3060         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3061           return BinaryOperator::createAnd(V, AndRHS);
3062         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3063           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3064         break;
3065
3066       case Instruction::Sub:
3067         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3068         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3069         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3070         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3071           return BinaryOperator::createAnd(V, AndRHS);
3072         break;
3073       }
3074
3075       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3076         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3077           return Res;
3078     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3079       // If this is an integer truncation or change from signed-to-unsigned, and
3080       // if the source is an and/or with immediate, transform it.  This
3081       // frequently occurs for bitfield accesses.
3082       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3083         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3084             CastOp->getNumOperands() == 2)
3085           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3086             if (CastOp->getOpcode() == Instruction::And) {
3087               // Change: and (cast (and X, C1) to T), C2
3088               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3089               // This will fold the two constants together, which may allow 
3090               // other simplifications.
3091               Instruction *NewCast = CastInst::createTruncOrBitCast(
3092                 CastOp->getOperand(0), I.getType(), 
3093                 CastOp->getName()+".shrunk");
3094               NewCast = InsertNewInstBefore(NewCast, I);
3095               // trunc_or_bitcast(C1)&C2
3096               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3097               C3 = ConstantExpr::getAnd(C3, AndRHS);
3098               return BinaryOperator::createAnd(NewCast, C3);
3099             } else if (CastOp->getOpcode() == Instruction::Or) {
3100               // Change: and (cast (or X, C1) to T), C2
3101               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3102               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3103               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3104                 return ReplaceInstUsesWith(I, AndRHS);
3105             }
3106       }
3107     }
3108
3109     // Try to fold constant and into select arguments.
3110     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3111       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3112         return R;
3113     if (isa<PHINode>(Op0))
3114       if (Instruction *NV = FoldOpIntoPhi(I))
3115         return NV;
3116   }
3117
3118   Value *Op0NotVal = dyn_castNotVal(Op0);
3119   Value *Op1NotVal = dyn_castNotVal(Op1);
3120
3121   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3122     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3123
3124   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3125   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3126     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3127                                                I.getName()+".demorgan");
3128     InsertNewInstBefore(Or, I);
3129     return BinaryOperator::createNot(Or);
3130   }
3131   
3132   {
3133     Value *A = 0, *B = 0;
3134     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3135       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3136         return ReplaceInstUsesWith(I, Op1);
3137     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3138       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3139         return ReplaceInstUsesWith(I, Op0);
3140     
3141     if (Op0->hasOneUse() &&
3142         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3143       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3144         I.swapOperands();     // Simplify below
3145         std::swap(Op0, Op1);
3146       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3147         cast<BinaryOperator>(Op0)->swapOperands();
3148         I.swapOperands();     // Simplify below
3149         std::swap(Op0, Op1);
3150       }
3151     }
3152     if (Op1->hasOneUse() &&
3153         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3154       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3155         cast<BinaryOperator>(Op1)->swapOperands();
3156         std::swap(A, B);
3157       }
3158       if (A == Op0) {                                // A&(A^B) -> A & ~B
3159         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3160         InsertNewInstBefore(NotB, I);
3161         return BinaryOperator::createAnd(A, NotB);
3162       }
3163     }
3164   }
3165   
3166
3167   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3168     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3169     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3170       return R;
3171
3172     Value *LHSVal, *RHSVal;
3173     ConstantInt *LHSCst, *RHSCst;
3174     Instruction::BinaryOps LHSCC, RHSCC;
3175     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3176       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3177         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
3178             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3179             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3180             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3181           // Ensure that the larger constant is on the RHS.
3182           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3183           SetCondInst *LHS = cast<SetCondInst>(Op0);
3184           if (cast<ConstantBool>(Cmp)->getValue()) {
3185             std::swap(LHS, RHS);
3186             std::swap(LHSCst, RHSCst);
3187             std::swap(LHSCC, RHSCC);
3188           }
3189
3190           // At this point, we know we have have two setcc instructions
3191           // comparing a value against two constants and and'ing the result
3192           // together.  Because of the above check, we know that we only have
3193           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3194           // FoldSetCCLogical check above), that the two constants are not
3195           // equal.
3196           assert(LHSCst != RHSCst && "Compares not folded above?");
3197
3198           switch (LHSCC) {
3199           default: assert(0 && "Unknown integer condition code!");
3200           case Instruction::SetEQ:
3201             switch (RHSCC) {
3202             default: assert(0 && "Unknown integer condition code!");
3203             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
3204             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
3205               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3206             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
3207             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
3208               return ReplaceInstUsesWith(I, LHS);
3209             }
3210           case Instruction::SetNE:
3211             switch (RHSCC) {
3212             default: assert(0 && "Unknown integer condition code!");
3213             case Instruction::SetLT:
3214               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3215                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3216               break;                        // (X != 13 & X < 15) -> no change
3217             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
3218             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
3219               return ReplaceInstUsesWith(I, RHS);
3220             case Instruction::SetNE:
3221               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3222                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3223                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3224                                                       LHSVal->getName()+".off");
3225                 InsertNewInstBefore(Add, I);
3226                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3227                 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3228                                                     UnsType, I);
3229                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3230                 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
3231                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3232               }
3233               break;                        // (X != 13 & X != 15) -> no change
3234             }
3235             break;
3236           case Instruction::SetLT:
3237             switch (RHSCC) {
3238             default: assert(0 && "Unknown integer condition code!");
3239             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
3240             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
3241               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3242             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
3243             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
3244               return ReplaceInstUsesWith(I, LHS);
3245             }
3246           case Instruction::SetGT:
3247             switch (RHSCC) {
3248             default: assert(0 && "Unknown integer condition code!");
3249             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
3250               return ReplaceInstUsesWith(I, LHS);
3251             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
3252               return ReplaceInstUsesWith(I, RHS);
3253             case Instruction::SetNE:
3254               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3255                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3256               break;                        // (X > 13 & X != 15) -> no change
3257             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
3258               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3259             }
3260           }
3261         }
3262   }
3263
3264   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3265   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3266     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3267       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3268         const Type *SrcTy = Op0C->getOperand(0)->getType();
3269         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3270             // Only do this if the casts both really cause code to be generated.
3271             ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3272             ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3273           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3274                                                          Op1C->getOperand(0),
3275                                                          I.getName());
3276           InsertNewInstBefore(NewOp, I);
3277           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3278         }
3279       }
3280     
3281   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3282   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3283     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3284       if (SI0->getOpcode() == SI1->getOpcode() && 
3285           SI0->getOperand(1) == SI1->getOperand(1) &&
3286           (SI0->hasOneUse() || SI1->hasOneUse())) {
3287         Instruction *NewOp =
3288           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3289                                                         SI1->getOperand(0),
3290                                                         SI0->getName()), I);
3291         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3292       }
3293   }
3294
3295   return Changed ? &I : 0;
3296 }
3297
3298 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3299 /// in the result.  If it does, and if the specified byte hasn't been filled in
3300 /// yet, fill it in and return false.
3301 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3302   Instruction *I = dyn_cast<Instruction>(V);
3303   if (I == 0) return true;
3304
3305   // If this is an or instruction, it is an inner node of the bswap.
3306   if (I->getOpcode() == Instruction::Or)
3307     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3308            CollectBSwapParts(I->getOperand(1), ByteValues);
3309   
3310   // If this is a shift by a constant int, and it is "24", then its operand
3311   // defines a byte.  We only handle unsigned types here.
3312   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3313     // Not shifting the entire input by N-1 bytes?
3314     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3315         8*(ByteValues.size()-1))
3316       return true;
3317     
3318     unsigned DestNo;
3319     if (I->getOpcode() == Instruction::Shl) {
3320       // X << 24 defines the top byte with the lowest of the input bytes.
3321       DestNo = ByteValues.size()-1;
3322     } else {
3323       // X >>u 24 defines the low byte with the highest of the input bytes.
3324       DestNo = 0;
3325     }
3326     
3327     // If the destination byte value is already defined, the values are or'd
3328     // together, which isn't a bswap (unless it's an or of the same bits).
3329     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3330       return true;
3331     ByteValues[DestNo] = I->getOperand(0);
3332     return false;
3333   }
3334   
3335   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3336   // don't have this.
3337   Value *Shift = 0, *ShiftLHS = 0;
3338   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3339   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3340       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3341     return true;
3342   Instruction *SI = cast<Instruction>(Shift);
3343
3344   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3345   if (ShiftAmt->getZExtValue() & 7 ||
3346       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3347     return true;
3348   
3349   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3350   unsigned DestByte;
3351   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3352     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3353       break;
3354   // Unknown mask for bswap.
3355   if (DestByte == ByteValues.size()) return true;
3356   
3357   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3358   unsigned SrcByte;
3359   if (SI->getOpcode() == Instruction::Shl)
3360     SrcByte = DestByte - ShiftBytes;
3361   else
3362     SrcByte = DestByte + ShiftBytes;
3363   
3364   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3365   if (SrcByte != ByteValues.size()-DestByte-1)
3366     return true;
3367   
3368   // If the destination byte value is already defined, the values are or'd
3369   // together, which isn't a bswap (unless it's an or of the same bits).
3370   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3371     return true;
3372   ByteValues[DestByte] = SI->getOperand(0);
3373   return false;
3374 }
3375
3376 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3377 /// If so, insert the new bswap intrinsic and return it.
3378 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3379   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3380   if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3381     return 0;
3382   
3383   /// ByteValues - For each byte of the result, we keep track of which value
3384   /// defines each byte.
3385   std::vector<Value*> ByteValues;
3386   ByteValues.resize(I.getType()->getPrimitiveSize());
3387     
3388   // Try to find all the pieces corresponding to the bswap.
3389   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3390       CollectBSwapParts(I.getOperand(1), ByteValues))
3391     return 0;
3392   
3393   // Check to see if all of the bytes come from the same value.
3394   Value *V = ByteValues[0];
3395   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3396   
3397   // Check to make sure that all of the bytes come from the same value.
3398   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3399     if (ByteValues[i] != V)
3400       return 0;
3401     
3402   // If they do then *success* we can turn this into a bswap.  Figure out what
3403   // bswap to make it into.
3404   Module *M = I.getParent()->getParent()->getParent();
3405   const char *FnName = 0;
3406   if (I.getType() == Type::UShortTy)
3407     FnName = "llvm.bswap.i16";
3408   else if (I.getType() == Type::UIntTy)
3409     FnName = "llvm.bswap.i32";
3410   else if (I.getType() == Type::ULongTy)
3411     FnName = "llvm.bswap.i64";
3412   else
3413     assert(0 && "Unknown integer type!");
3414   Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3415   
3416   return new CallInst(F, V);
3417 }
3418
3419
3420 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3421   bool Changed = SimplifyCommutative(I);
3422   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3423
3424   if (isa<UndefValue>(Op1))
3425     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3426                                ConstantIntegral::getAllOnesValue(I.getType()));
3427
3428   // or X, X = X
3429   if (Op0 == Op1)
3430     return ReplaceInstUsesWith(I, Op0);
3431
3432   // See if we can simplify any instructions used by the instruction whose sole 
3433   // purpose is to compute bits we don't care about.
3434   uint64_t KnownZero, KnownOne;
3435   if (!isa<PackedType>(I.getType()) &&
3436       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3437                            KnownZero, KnownOne))
3438     return &I;
3439   
3440   // or X, -1 == -1
3441   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3442     ConstantInt *C1 = 0; Value *X = 0;
3443     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3444     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3445       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3446       Op0->setName("");
3447       InsertNewInstBefore(Or, I);
3448       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3449     }
3450
3451     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3452     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3453       std::string Op0Name = Op0->getName(); Op0->setName("");
3454       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3455       InsertNewInstBefore(Or, I);
3456       return BinaryOperator::createXor(Or,
3457                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3458     }
3459
3460     // Try to fold constant and into select arguments.
3461     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3462       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3463         return R;
3464     if (isa<PHINode>(Op0))
3465       if (Instruction *NV = FoldOpIntoPhi(I))
3466         return NV;
3467   }
3468
3469   Value *A = 0, *B = 0;
3470   ConstantInt *C1 = 0, *C2 = 0;
3471
3472   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3473     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3474       return ReplaceInstUsesWith(I, Op1);
3475   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3476     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3477       return ReplaceInstUsesWith(I, Op0);
3478
3479   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3480   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3481   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3482       match(Op1, m_Or(m_Value(), m_Value())) ||
3483       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3484        match(Op1, m_Shift(m_Value(), m_Value())))) {
3485     if (Instruction *BSwap = MatchBSwap(I))
3486       return BSwap;
3487   }
3488   
3489   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3490   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3491       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3492     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3493     Op0->setName("");
3494     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3495   }
3496
3497   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3498   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3499       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3500     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3501     Op0->setName("");
3502     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3503   }
3504
3505   // (A & C1)|(B & C2)
3506   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3507       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3508
3509     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3510       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3511
3512
3513     // If we have: ((V + N) & C1) | (V & C2)
3514     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3515     // replace with V+N.
3516     if (C1 == ConstantExpr::getNot(C2)) {
3517       Value *V1 = 0, *V2 = 0;
3518       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3519           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3520         // Add commutes, try both ways.
3521         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3522           return ReplaceInstUsesWith(I, A);
3523         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3524           return ReplaceInstUsesWith(I, A);
3525       }
3526       // Or commutes, try both ways.
3527       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3528           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3529         // Add commutes, try both ways.
3530         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3531           return ReplaceInstUsesWith(I, B);
3532         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3533           return ReplaceInstUsesWith(I, B);
3534       }
3535     }
3536   }
3537   
3538   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3539   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3540     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3541       if (SI0->getOpcode() == SI1->getOpcode() && 
3542           SI0->getOperand(1) == SI1->getOperand(1) &&
3543           (SI0->hasOneUse() || SI1->hasOneUse())) {
3544         Instruction *NewOp =
3545         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3546                                                      SI1->getOperand(0),
3547                                                      SI0->getName()), I);
3548         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3549       }
3550   }
3551
3552   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3553     if (A == Op1)   // ~A | A == -1
3554       return ReplaceInstUsesWith(I,
3555                                 ConstantIntegral::getAllOnesValue(I.getType()));
3556   } else {
3557     A = 0;
3558   }
3559   // Note, A is still live here!
3560   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3561     if (Op0 == B)
3562       return ReplaceInstUsesWith(I,
3563                                 ConstantIntegral::getAllOnesValue(I.getType()));
3564
3565     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3566     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3567       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3568                                               I.getName()+".demorgan"), I);
3569       return BinaryOperator::createNot(And);
3570     }
3571   }
3572
3573   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3574   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3575     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3576       return R;
3577
3578     Value *LHSVal, *RHSVal;
3579     ConstantInt *LHSCst, *RHSCst;
3580     Instruction::BinaryOps LHSCC, RHSCC;
3581     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3582       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3583         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
3584             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3585             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3586             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3587           // Ensure that the larger constant is on the RHS.
3588           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3589           SetCondInst *LHS = cast<SetCondInst>(Op0);
3590           if (cast<ConstantBool>(Cmp)->getValue()) {
3591             std::swap(LHS, RHS);
3592             std::swap(LHSCst, RHSCst);
3593             std::swap(LHSCC, RHSCC);
3594           }
3595
3596           // At this point, we know we have have two setcc instructions
3597           // comparing a value against two constants and or'ing the result
3598           // together.  Because of the above check, we know that we only have
3599           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3600           // FoldSetCCLogical check above), that the two constants are not
3601           // equal.
3602           assert(LHSCst != RHSCst && "Compares not folded above?");
3603
3604           switch (LHSCC) {
3605           default: assert(0 && "Unknown integer condition code!");
3606           case Instruction::SetEQ:
3607             switch (RHSCC) {
3608             default: assert(0 && "Unknown integer condition code!");
3609             case Instruction::SetEQ:
3610               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3611                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3612                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3613                                                       LHSVal->getName()+".off");
3614                 InsertNewInstBefore(Add, I);
3615                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3616                 Value *OffsetVal = InsertCastBefore(Instruction::BitCast, Add,
3617                                                     UnsType, I);
3618                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3619                 AddCST = ConstantExpr::getBitCast(AddCST, UnsType);
3620                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3621               }
3622               break;                  // (X == 13 | X == 15) -> no change
3623
3624             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
3625               break;
3626             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
3627             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
3628               return ReplaceInstUsesWith(I, RHS);
3629             }
3630             break;
3631           case Instruction::SetNE:
3632             switch (RHSCC) {
3633             default: assert(0 && "Unknown integer condition code!");
3634             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
3635             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
3636               return ReplaceInstUsesWith(I, LHS);
3637             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
3638             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
3639               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3640             }
3641             break;
3642           case Instruction::SetLT:
3643             switch (RHSCC) {
3644             default: assert(0 && "Unknown integer condition code!");
3645             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
3646               break;
3647             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
3648               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3649             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
3650             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
3651               return ReplaceInstUsesWith(I, RHS);
3652             }
3653             break;
3654           case Instruction::SetGT:
3655             switch (RHSCC) {
3656             default: assert(0 && "Unknown integer condition code!");
3657             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
3658             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
3659               return ReplaceInstUsesWith(I, LHS);
3660             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
3661             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
3662               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3663             }
3664           }
3665         }
3666   }
3667     
3668   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3669   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3670     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3671       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3672         const Type *SrcTy = Op0C->getOperand(0)->getType();
3673         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3674             // Only do this if the casts both really cause code to be generated.
3675             ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3676             ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3677           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3678                                                         Op1C->getOperand(0),
3679                                                         I.getName());
3680           InsertNewInstBefore(NewOp, I);
3681           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3682         }
3683       }
3684       
3685
3686   return Changed ? &I : 0;
3687 }
3688
3689 // XorSelf - Implements: X ^ X --> 0
3690 struct XorSelf {
3691   Value *RHS;
3692   XorSelf(Value *rhs) : RHS(rhs) {}
3693   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3694   Instruction *apply(BinaryOperator &Xor) const {
3695     return &Xor;
3696   }
3697 };
3698
3699
3700 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3701   bool Changed = SimplifyCommutative(I);
3702   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3703
3704   if (isa<UndefValue>(Op1))
3705     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3706
3707   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3708   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3709     assert(Result == &I && "AssociativeOpt didn't work?");
3710     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3711   }
3712   
3713   // See if we can simplify any instructions used by the instruction whose sole 
3714   // purpose is to compute bits we don't care about.
3715   uint64_t KnownZero, KnownOne;
3716   if (!isa<PackedType>(I.getType()) &&
3717       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3718                            KnownZero, KnownOne))
3719     return &I;
3720
3721   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3722     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3723       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3724       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3725         if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3726           return new SetCondInst(SCI->getInverseCondition(),
3727                                  SCI->getOperand(0), SCI->getOperand(1));
3728
3729       // ~(c-X) == X-c-1 == X+(-c-1)
3730       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3731         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3732           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3733           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3734                                               ConstantInt::get(I.getType(), 1));
3735           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3736         }
3737
3738       // ~(~X & Y) --> (X | ~Y)
3739       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3740         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3741         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3742           Instruction *NotY =
3743             BinaryOperator::createNot(Op0I->getOperand(1),
3744                                       Op0I->getOperand(1)->getName()+".not");
3745           InsertNewInstBefore(NotY, I);
3746           return BinaryOperator::createOr(Op0NotVal, NotY);
3747         }
3748       }
3749
3750       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3751         if (Op0I->getOpcode() == Instruction::Add) {
3752           // ~(X-c) --> (-c-1)-X
3753           if (RHS->isAllOnesValue()) {
3754             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3755             return BinaryOperator::createSub(
3756                            ConstantExpr::getSub(NegOp0CI,
3757                                              ConstantInt::get(I.getType(), 1)),
3758                                           Op0I->getOperand(0));
3759           }
3760         } else if (Op0I->getOpcode() == Instruction::Or) {
3761           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3762           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3763             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3764             // Anything in both C1 and C2 is known to be zero, remove it from
3765             // NewRHS.
3766             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3767             NewRHS = ConstantExpr::getAnd(NewRHS, 
3768                                           ConstantExpr::getNot(CommonBits));
3769             WorkList.push_back(Op0I);
3770             I.setOperand(0, Op0I->getOperand(0));
3771             I.setOperand(1, NewRHS);
3772             return &I;
3773           }
3774         }
3775     }
3776
3777     // Try to fold constant and into select arguments.
3778     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3779       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3780         return R;
3781     if (isa<PHINode>(Op0))
3782       if (Instruction *NV = FoldOpIntoPhi(I))
3783         return NV;
3784   }
3785
3786   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3787     if (X == Op1)
3788       return ReplaceInstUsesWith(I,
3789                                 ConstantIntegral::getAllOnesValue(I.getType()));
3790
3791   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3792     if (X == Op0)
3793       return ReplaceInstUsesWith(I,
3794                                 ConstantIntegral::getAllOnesValue(I.getType()));
3795
3796   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3797     if (Op1I->getOpcode() == Instruction::Or) {
3798       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3799         Op1I->swapOperands();
3800         I.swapOperands();
3801         std::swap(Op0, Op1);
3802       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3803         I.swapOperands();     // Simplified below.
3804         std::swap(Op0, Op1);
3805       }
3806     } else if (Op1I->getOpcode() == Instruction::Xor) {
3807       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3808         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3809       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3810         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3811     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3812       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3813         Op1I->swapOperands();
3814       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3815         I.swapOperands();     // Simplified below.
3816         std::swap(Op0, Op1);
3817       }
3818     }
3819
3820   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3821     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3822       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3823         Op0I->swapOperands();
3824       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3825         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3826         InsertNewInstBefore(NotB, I);
3827         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3828       }
3829     } else if (Op0I->getOpcode() == Instruction::Xor) {
3830       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3831         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3832       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3833         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3834     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3835       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3836         Op0I->swapOperands();
3837       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
3838           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
3839         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3840         InsertNewInstBefore(N, I);
3841         return BinaryOperator::createAnd(N, Op1);
3842       }
3843     }
3844
3845   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3846   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3847     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3848       return R;
3849
3850   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3851   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
3852     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3853       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
3854         const Type *SrcTy = Op0C->getOperand(0)->getType();
3855         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3856             // Only do this if the casts both really cause code to be generated.
3857             ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3858             ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3859           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3860                                                          Op1C->getOperand(0),
3861                                                          I.getName());
3862           InsertNewInstBefore(NewOp, I);
3863           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3864         }
3865       }
3866
3867   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
3868   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3869     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3870       if (SI0->getOpcode() == SI1->getOpcode() && 
3871           SI0->getOperand(1) == SI1->getOperand(1) &&
3872           (SI0->hasOneUse() || SI1->hasOneUse())) {
3873         Instruction *NewOp =
3874         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
3875                                                       SI1->getOperand(0),
3876                                                       SI0->getName()), I);
3877         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3878       }
3879   }
3880     
3881   return Changed ? &I : 0;
3882 }
3883
3884 static bool isPositive(ConstantInt *C) {
3885   return C->getSExtValue() >= 0;
3886 }
3887
3888 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3889 /// overflowed for this type.
3890 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3891                             ConstantInt *In2) {
3892   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3893
3894   if (In1->getType()->isUnsigned())
3895     return cast<ConstantInt>(Result)->getZExtValue() <
3896            cast<ConstantInt>(In1)->getZExtValue();
3897   if (isPositive(In1) != isPositive(In2))
3898     return false;
3899   if (isPositive(In1))
3900     return cast<ConstantInt>(Result)->getSExtValue() <
3901            cast<ConstantInt>(In1)->getSExtValue();
3902   return cast<ConstantInt>(Result)->getSExtValue() >
3903          cast<ConstantInt>(In1)->getSExtValue();
3904 }
3905
3906 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3907 /// code necessary to compute the offset from the base pointer (without adding
3908 /// in the base pointer).  Return the result as a signed integer of intptr size.
3909 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3910   TargetData &TD = IC.getTargetData();
3911   gep_type_iterator GTI = gep_type_begin(GEP);
3912   const Type *UIntPtrTy = TD.getIntPtrType();
3913   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3914   Value *Result = Constant::getNullValue(SIntPtrTy);
3915
3916   // Build a mask for high order bits.
3917   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3918
3919   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3920     Value *Op = GEP->getOperand(i);
3921     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3922     Constant *Scale = ConstantInt::get(SIntPtrTy, Size);
3923     if (Constant *OpC = dyn_cast<Constant>(Op)) {
3924       if (!OpC->isNullValue()) {
3925         OpC = ConstantExpr::getIntegerCast(OpC, SIntPtrTy, true /*SExt*/);
3926         Scale = ConstantExpr::getMul(OpC, Scale);
3927         if (Constant *RC = dyn_cast<Constant>(Result))
3928           Result = ConstantExpr::getAdd(RC, Scale);
3929         else {
3930           // Emit an add instruction.
3931           Result = IC.InsertNewInstBefore(
3932              BinaryOperator::createAdd(Result, Scale,
3933                                        GEP->getName()+".offs"), I);
3934         }
3935       }
3936     } else {
3937       // Convert to correct type.
3938       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, SIntPtrTy,
3939                                                Op->getName()+".c"), I);
3940       if (Size != 1)
3941         // We'll let instcombine(mul) convert this to a shl if possible.
3942         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3943                                                     GEP->getName()+".idx"), I);
3944
3945       // Emit an add instruction.
3946       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3947                                                     GEP->getName()+".offs"), I);
3948     }
3949   }
3950   return Result;
3951 }
3952
3953 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3954 /// else.  At this point we know that the GEP is on the LHS of the comparison.
3955 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3956                                         Instruction::BinaryOps Cond,
3957                                         Instruction &I) {
3958   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3959
3960   if (CastInst *CI = dyn_cast<CastInst>(RHS))
3961     if (isa<PointerType>(CI->getOperand(0)->getType()))
3962       RHS = CI->getOperand(0);
3963
3964   Value *PtrBase = GEPLHS->getOperand(0);
3965   if (PtrBase == RHS) {
3966     // As an optimization, we don't actually have to compute the actual value of
3967     // OFFSET if this is a seteq or setne comparison, just return whether each
3968     // index is zero or not.
3969     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3970       Instruction *InVal = 0;
3971       gep_type_iterator GTI = gep_type_begin(GEPLHS);
3972       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3973         bool EmitIt = true;
3974         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3975           if (isa<UndefValue>(C))  // undef index -> undef.
3976             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3977           if (C->isNullValue())
3978             EmitIt = false;
3979           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3980             EmitIt = false;  // This is indexing into a zero sized array?
3981           } else if (isa<ConstantInt>(C))
3982             return ReplaceInstUsesWith(I, // No comparison is needed here.
3983                                  ConstantBool::get(Cond == Instruction::SetNE));
3984         }
3985
3986         if (EmitIt) {
3987           Instruction *Comp =
3988             new SetCondInst(Cond, GEPLHS->getOperand(i),
3989                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3990           if (InVal == 0)
3991             InVal = Comp;
3992           else {
3993             InVal = InsertNewInstBefore(InVal, I);
3994             InsertNewInstBefore(Comp, I);
3995             if (Cond == Instruction::SetNE)   // True if any are unequal
3996               InVal = BinaryOperator::createOr(InVal, Comp);
3997             else                              // True if all are equal
3998               InVal = BinaryOperator::createAnd(InVal, Comp);
3999           }
4000         }
4001       }
4002
4003       if (InVal)
4004         return InVal;
4005       else
4006         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
4007                             ConstantBool::get(Cond == Instruction::SetEQ));
4008     }
4009
4010     // Only lower this if the setcc is the only user of the GEP or if we expect
4011     // the result to fold to a constant!
4012     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4013       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4014       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4015       return new SetCondInst(Cond, Offset,
4016                              Constant::getNullValue(Offset->getType()));
4017     }
4018   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4019     // If the base pointers are different, but the indices are the same, just
4020     // compare the base pointer.
4021     if (PtrBase != GEPRHS->getOperand(0)) {
4022       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4023       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4024                         GEPRHS->getOperand(0)->getType();
4025       if (IndicesTheSame)
4026         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4027           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4028             IndicesTheSame = false;
4029             break;
4030           }
4031
4032       // If all indices are the same, just compare the base pointers.
4033       if (IndicesTheSame)
4034         return new SetCondInst(Cond, GEPLHS->getOperand(0),
4035                                GEPRHS->getOperand(0));
4036
4037       // Otherwise, the base pointers are different and the indices are
4038       // different, bail out.
4039       return 0;
4040     }
4041
4042     // If one of the GEPs has all zero indices, recurse.
4043     bool AllZeros = true;
4044     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4045       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4046           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4047         AllZeros = false;
4048         break;
4049       }
4050     if (AllZeros)
4051       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
4052                           SetCondInst::getSwappedCondition(Cond), I);
4053
4054     // If the other GEP has all zero indices, recurse.
4055     AllZeros = true;
4056     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4057       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4058           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4059         AllZeros = false;
4060         break;
4061       }
4062     if (AllZeros)
4063       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4064
4065     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4066       // If the GEPs only differ by one index, compare it.
4067       unsigned NumDifferences = 0;  // Keep track of # differences.
4068       unsigned DiffOperand = 0;     // The operand that differs.
4069       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4070         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4071           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4072                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4073             // Irreconcilable differences.
4074             NumDifferences = 2;
4075             break;
4076           } else {
4077             if (NumDifferences++) break;
4078             DiffOperand = i;
4079           }
4080         }
4081
4082       if (NumDifferences == 0)   // SAME GEP?
4083         return ReplaceInstUsesWith(I, // No comparison is needed here.
4084                                  ConstantBool::get(Cond == Instruction::SetEQ));
4085       else if (NumDifferences == 1) {
4086         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4087         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4088
4089         // Convert the operands to signed values to make sure to perform a
4090         // signed comparison.
4091         const Type *NewTy = LHSV->getType()->getSignedVersion();
4092         if (LHSV->getType() != NewTy)
4093           LHSV = InsertCastBefore(Instruction::BitCast, LHSV, NewTy, I);
4094         if (RHSV->getType() != NewTy)
4095           RHSV = InsertCastBefore(Instruction::BitCast, RHSV, NewTy, I);
4096         return new SetCondInst(Cond, LHSV, RHSV);
4097       }
4098     }
4099
4100     // Only lower this if the setcc is the only user of the GEP or if we expect
4101     // the result to fold to a constant!
4102     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4103         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4104       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4105       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4106       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4107       return new SetCondInst(Cond, L, R);
4108     }
4109   }
4110   return 0;
4111 }
4112
4113
4114 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
4115   bool Changed = SimplifyCommutative(I);
4116   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4117   const Type *Ty = Op0->getType();
4118
4119   // setcc X, X
4120   if (Op0 == Op1)
4121     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4122
4123   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
4124     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4125
4126   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4127   // addresses never equal each other!  We already know that Op0 != Op1.
4128   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4129        isa<ConstantPointerNull>(Op0)) &&
4130       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4131        isa<ConstantPointerNull>(Op1)))
4132     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4133
4134   // setcc's with boolean values can always be turned into bitwise operations
4135   if (Ty == Type::BoolTy) {
4136     switch (I.getOpcode()) {
4137     default: assert(0 && "Invalid setcc instruction!");
4138     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
4139       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4140       InsertNewInstBefore(Xor, I);
4141       return BinaryOperator::createNot(Xor);
4142     }
4143     case Instruction::SetNE:
4144       return BinaryOperator::createXor(Op0, Op1);
4145
4146     case Instruction::SetGT:
4147       std::swap(Op0, Op1);                   // Change setgt -> setlt
4148       // FALL THROUGH
4149     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
4150       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4151       InsertNewInstBefore(Not, I);
4152       return BinaryOperator::createAnd(Not, Op1);
4153     }
4154     case Instruction::SetGE:
4155       std::swap(Op0, Op1);                   // Change setge -> setle
4156       // FALL THROUGH
4157     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
4158       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4159       InsertNewInstBefore(Not, I);
4160       return BinaryOperator::createOr(Not, Op1);
4161     }
4162     }
4163   }
4164
4165   // See if we are doing a comparison between a constant and an instruction that
4166   // can be folded into the comparison.
4167   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4168     // Check to see if we are comparing against the minimum or maximum value...
4169     if (CI->isMinValue(CI->getType()->isSigned())) {
4170       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
4171         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4172       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
4173         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4174       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
4175         return BinaryOperator::createSetEQ(Op0, Op1);
4176       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
4177         return BinaryOperator::createSetNE(Op0, Op1);
4178
4179     } else if (CI->isMaxValue(CI->getType()->isSigned())) {
4180       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
4181         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4182       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
4183         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4184       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
4185         return BinaryOperator::createSetEQ(Op0, Op1);
4186       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
4187         return BinaryOperator::createSetNE(Op0, Op1);
4188
4189       // Comparing against a value really close to min or max?
4190     } else if (isMinValuePlusOne(CI)) {
4191       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
4192         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4193       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
4194         return BinaryOperator::createSetNE(Op0, SubOne(CI));
4195
4196     } else if (isMaxValueMinusOne(CI)) {
4197       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
4198         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4199       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
4200         return BinaryOperator::createSetNE(Op0, AddOne(CI));
4201     }
4202
4203     // If we still have a setle or setge instruction, turn it into the
4204     // appropriate setlt or setgt instruction.  Since the border cases have
4205     // already been handled above, this requires little checking.
4206     //
4207     if (I.getOpcode() == Instruction::SetLE)
4208       return BinaryOperator::createSetLT(Op0, AddOne(CI));
4209     if (I.getOpcode() == Instruction::SetGE)
4210       return BinaryOperator::createSetGT(Op0, SubOne(CI));
4211
4212     
4213     // See if we can fold the comparison based on bits known to be zero or one
4214     // in the input.
4215     uint64_t KnownZero, KnownOne;
4216     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4217                              KnownZero, KnownOne, 0))
4218       return &I;
4219         
4220     // Given the known and unknown bits, compute a range that the LHS could be
4221     // in.
4222     if (KnownOne | KnownZero) {
4223       if (Ty->isUnsigned()) {   // Unsigned comparison.
4224         uint64_t Min, Max;
4225         uint64_t RHSVal = CI->getZExtValue();
4226         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4227                                                  Min, Max);
4228         switch (I.getOpcode()) {  // LE/GE have been folded already.
4229         default: assert(0 && "Unknown setcc opcode!");
4230         case Instruction::SetEQ:
4231           if (Max < RHSVal || Min > RHSVal)
4232             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4233           break;
4234         case Instruction::SetNE:
4235           if (Max < RHSVal || Min > RHSVal)
4236             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4237           break;
4238         case Instruction::SetLT:
4239           if (Max < RHSVal)
4240             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4241           if (Min > RHSVal)
4242             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4243           break;
4244         case Instruction::SetGT:
4245           if (Min > RHSVal)
4246             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4247           if (Max < RHSVal)
4248             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4249           break;
4250         }
4251       } else {              // Signed comparison.
4252         int64_t Min, Max;
4253         int64_t RHSVal = CI->getSExtValue();
4254         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4255                                                Min, Max);
4256         switch (I.getOpcode()) {  // LE/GE have been folded already.
4257         default: assert(0 && "Unknown setcc opcode!");
4258         case Instruction::SetEQ:
4259           if (Max < RHSVal || Min > RHSVal)
4260             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4261           break;
4262         case Instruction::SetNE:
4263           if (Max < RHSVal || Min > RHSVal)
4264             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4265           break;
4266         case Instruction::SetLT:
4267           if (Max < RHSVal)
4268             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4269           if (Min > RHSVal)
4270             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4271           break;
4272         case Instruction::SetGT:
4273           if (Min > RHSVal)
4274             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4275           if (Max < RHSVal)
4276             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4277           break;
4278         }
4279       }
4280     }
4281           
4282     // Since the RHS is a constantInt (CI), if the left hand side is an 
4283     // instruction, see if that instruction also has constants so that the 
4284     // instruction can be folded into the setcc
4285     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4286       switch (LHSI->getOpcode()) {
4287       case Instruction::And:
4288         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4289             LHSI->getOperand(0)->hasOneUse()) {
4290           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4291
4292           // If an operand is an AND of a truncating cast, we can widen the
4293           // and/compare to be the input width without changing the value
4294           // produced, eliminating a cast.
4295           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4296             // We can do this transformation if either the AND constant does not
4297             // have its sign bit set or if it is an equality comparison. 
4298             // Extending a relational comparison when we're checking the sign
4299             // bit would not work.
4300             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4301                 (I.isEquality() ||
4302                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4303                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4304               ConstantInt *NewCST;
4305               ConstantInt *NewCI;
4306               if (Cast->getOperand(0)->getType()->isSigned()) {
4307                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4308                                            AndCST->getZExtValue());
4309                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4310                                           CI->getZExtValue());
4311               } else {
4312                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4313                                            AndCST->getZExtValue());
4314                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4315                                           CI->getZExtValue());
4316               }
4317               Instruction *NewAnd = 
4318                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4319                                           LHSI->getName());
4320               InsertNewInstBefore(NewAnd, I);
4321               return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4322             }
4323           }
4324           
4325           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4326           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4327           // happens a LOT in code produced by the C front-end, for bitfield
4328           // access.
4329           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4330
4331           // Check to see if there is a noop-cast between the shift and the and.
4332           if (!Shift) {
4333             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4334               if (CI->getOpcode() == Instruction::BitCast)
4335                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4336           }
4337
4338           ConstantInt *ShAmt;
4339           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4340           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4341           const Type *AndTy = AndCST->getType();          // Type of the and.
4342
4343           // We can fold this as long as we can't shift unknown bits
4344           // into the mask.  This can only happen with signed shift
4345           // rights, as they sign-extend.
4346           if (ShAmt) {
4347             bool CanFold = Shift->isLogicalShift();
4348             if (!CanFold) {
4349               // To test for the bad case of the signed shr, see if any
4350               // of the bits shifted in could be tested after the mask.
4351               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4352               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4353
4354               Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4355               Constant *ShVal =
4356                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4357                                      OShAmt);
4358               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4359                 CanFold = true;
4360             }
4361
4362             if (CanFold) {
4363               Constant *NewCst;
4364               if (Shift->getOpcode() == Instruction::Shl)
4365                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4366               else
4367                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4368
4369               // Check to see if we are shifting out any of the bits being
4370               // compared.
4371               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4372                 // If we shifted bits out, the fold is not going to work out.
4373                 // As a special case, check to see if this means that the
4374                 // result is always true or false now.
4375                 if (I.getOpcode() == Instruction::SetEQ)
4376                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4377                 if (I.getOpcode() == Instruction::SetNE)
4378                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4379               } else {
4380                 I.setOperand(1, NewCst);
4381                 Constant *NewAndCST;
4382                 if (Shift->getOpcode() == Instruction::Shl)
4383                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4384                 else
4385                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4386                 LHSI->setOperand(1, NewAndCST);
4387                 if (AndTy == Ty) 
4388                   LHSI->setOperand(0, Shift->getOperand(0));
4389                 else {
4390                   Value *NewCast = InsertCastBefore(Instruction::BitCast,
4391                                                     Shift->getOperand(0), AndTy,
4392                                                     *Shift);
4393                   LHSI->setOperand(0, NewCast);
4394                 }
4395                 WorkList.push_back(Shift); // Shift is dead.
4396                 AddUsesToWorkList(I);
4397                 return &I;
4398               }
4399             }
4400           }
4401           
4402           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4403           // preferable because it allows the C<<Y expression to be hoisted out
4404           // of a loop if Y is invariant and X is not.
4405           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4406               I.isEquality() && !Shift->isArithmeticShift() &&
4407               isa<Instruction>(Shift->getOperand(0))) {
4408             // Compute C << Y.
4409             Value *NS;
4410             if (Shift->getOpcode() == Instruction::LShr) {
4411               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4412                                  "tmp");
4413             } else {
4414               // Insert a logical shift.
4415               NS = new ShiftInst(Instruction::LShr, AndCST,
4416                                  Shift->getOperand(1), "tmp");
4417             }
4418             InsertNewInstBefore(cast<Instruction>(NS), I);
4419
4420             // If C's sign doesn't agree with the and, insert a cast now.
4421             if (NS->getType() != LHSI->getType())
4422               NS = InsertCastBefore(Instruction::BitCast, NS, LHSI->getType(),
4423                                     I);
4424
4425             Value *ShiftOp = Shift->getOperand(0);
4426             if (ShiftOp->getType() != LHSI->getType())
4427               ShiftOp = InsertCastBefore(Instruction::BitCast, ShiftOp, 
4428                                          LHSI->getType(), I);
4429               
4430             // Compute X & (C << Y).
4431             Instruction *NewAnd =
4432               BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4433             InsertNewInstBefore(NewAnd, I);
4434             
4435             I.setOperand(0, NewAnd);
4436             return &I;
4437           }
4438         }
4439         break;
4440
4441       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
4442         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4443           if (I.isEquality()) {
4444             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4445
4446             // Check that the shift amount is in range.  If not, don't perform
4447             // undefined shifts.  When the shift is visited it will be
4448             // simplified.
4449             if (ShAmt->getZExtValue() >= TypeBits)
4450               break;
4451
4452             // If we are comparing against bits always shifted out, the
4453             // comparison cannot succeed.
4454             Constant *Comp =
4455               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4456             if (Comp != CI) {// Comparing against a bit that we know is zero.
4457               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4458               Constant *Cst = ConstantBool::get(IsSetNE);
4459               return ReplaceInstUsesWith(I, Cst);
4460             }
4461
4462             if (LHSI->hasOneUse()) {
4463               // Otherwise strength reduce the shift into an and.
4464               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4465               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4466
4467               Constant *Mask;
4468               if (CI->getType()->isUnsigned()) {
4469                 Mask = ConstantInt::get(CI->getType(), Val);
4470               } else if (ShAmtVal != 0) {
4471                 Mask = ConstantInt::get(CI->getType(), Val);
4472               } else {
4473                 Mask = ConstantInt::getAllOnesValue(CI->getType());
4474               }
4475
4476               Instruction *AndI =
4477                 BinaryOperator::createAnd(LHSI->getOperand(0),
4478                                           Mask, LHSI->getName()+".mask");
4479               Value *And = InsertNewInstBefore(AndI, I);
4480               return new SetCondInst(I.getOpcode(), And,
4481                                      ConstantExpr::getLShr(CI, ShAmt));
4482             }
4483           }
4484         }
4485         break;
4486
4487       case Instruction::LShr:         // (setcc (shr X, ShAmt), CI)
4488       case Instruction::AShr:
4489         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4490           if (I.isEquality()) {
4491             // Check that the shift amount is in range.  If not, don't perform
4492             // undefined shifts.  When the shift is visited it will be
4493             // simplified.
4494             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4495             if (ShAmt->getZExtValue() >= TypeBits)
4496               break;
4497
4498             // If we are comparing against bits always shifted out, the
4499             // comparison cannot succeed.
4500             Constant *Comp;
4501             if (CI->getType()->isUnsigned())
4502               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4503                                            ShAmt);
4504             else
4505               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4506                                            ShAmt);
4507
4508             if (Comp != CI) {// Comparing against a bit that we know is zero.
4509               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4510               Constant *Cst = ConstantBool::get(IsSetNE);
4511               return ReplaceInstUsesWith(I, Cst);
4512             }
4513
4514             if (LHSI->hasOneUse() || CI->isNullValue()) {
4515               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4516
4517               // Otherwise strength reduce the shift into an and.
4518               uint64_t Val = ~0ULL;          // All ones.
4519               Val <<= ShAmtVal;              // Shift over to the right spot.
4520
4521               Constant *Mask;
4522               if (CI->getType()->isUnsigned()) {
4523                 Val &= ~0ULL >> (64-TypeBits);
4524                 Mask = ConstantInt::get(CI->getType(), Val);
4525               } else {
4526                 Mask = ConstantInt::get(CI->getType(), Val);
4527               }
4528
4529               Instruction *AndI =
4530                 BinaryOperator::createAnd(LHSI->getOperand(0),
4531                                           Mask, LHSI->getName()+".mask");
4532               Value *And = InsertNewInstBefore(AndI, I);
4533               return new SetCondInst(I.getOpcode(), And,
4534                                      ConstantExpr::getShl(CI, ShAmt));
4535             }
4536           }
4537         }
4538         break;
4539
4540       case Instruction::SDiv:
4541       case Instruction::UDiv:
4542         // Fold: setcc ([us]div X, C1), C2 -> range test
4543         // Fold this div into the comparison, producing a range check. 
4544         // Determine, based on the divide type, what the range is being 
4545         // checked.  If there is an overflow on the low or high side, remember 
4546         // it, otherwise compute the range [low, hi) bounding the new value.
4547         // See: InsertRangeTest above for the kinds of replacements possible.
4548         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4549           // FIXME: If the operand types don't match the type of the divide 
4550           // then don't attempt this transform. The code below doesn't have the
4551           // logic to deal with a signed divide and an unsigned compare (and
4552           // vice versa). This is because (x /s C1) <s C2  produces different 
4553           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4554           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4555           // work. :(  The if statement below tests that condition and bails 
4556           // if it finds it. 
4557           const Type *DivRHSTy = DivRHS->getType();
4558           unsigned DivOpCode = LHSI->getOpcode();
4559           if (I.isEquality() &&
4560               ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4561                (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4562             break;
4563
4564           // Initialize the variables that will indicate the nature of the
4565           // range check.
4566           bool LoOverflow = false, HiOverflow = false;
4567           ConstantInt *LoBound = 0, *HiBound = 0;
4568
4569           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4570           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4571           // C2 (CI). By solving for X we can turn this into a range check 
4572           // instead of computing a divide. 
4573           ConstantInt *Prod = 
4574             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4575
4576           // Determine if the product overflows by seeing if the product is
4577           // not equal to the divide. Make sure we do the same kind of divide
4578           // as in the LHS instruction that we're folding. 
4579           bool ProdOV = !DivRHS->isNullValue() && 
4580             (DivOpCode == Instruction::SDiv ?  
4581              ConstantExpr::getSDiv(Prod, DivRHS) :
4582               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4583
4584           // Get the SetCC opcode
4585           Instruction::BinaryOps Opcode = I.getOpcode();
4586
4587           if (DivRHS->isNullValue()) {  
4588             // Don't hack on divide by zeros!
4589           } else if (DivOpCode == Instruction::UDiv) {  // udiv
4590             LoBound = Prod;
4591             LoOverflow = ProdOV;
4592             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4593           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4594             if (CI->isNullValue()) {       // (X / pos) op 0
4595               // Can't overflow.
4596               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4597               HiBound = DivRHS;
4598             } else if (isPositive(CI)) {   // (X / pos) op pos
4599               LoBound = Prod;
4600               LoOverflow = ProdOV;
4601               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4602             } else {                       // (X / pos) op neg
4603               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4604               LoOverflow = AddWithOverflow(LoBound, Prod,
4605                                            cast<ConstantInt>(DivRHSH));
4606               HiBound = Prod;
4607               HiOverflow = ProdOV;
4608             }
4609           } else {                         // Divisor is < 0.
4610             if (CI->isNullValue()) {       // (X / neg) op 0
4611               LoBound = AddOne(DivRHS);
4612               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4613               if (HiBound == DivRHS)
4614                 LoBound = 0;               // - INTMIN = INTMIN
4615             } else if (isPositive(CI)) {   // (X / neg) op pos
4616               HiOverflow = LoOverflow = ProdOV;
4617               if (!LoOverflow)
4618                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4619               HiBound = AddOne(Prod);
4620             } else {                       // (X / neg) op neg
4621               LoBound = Prod;
4622               LoOverflow = HiOverflow = ProdOV;
4623               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4624             }
4625
4626             // Dividing by a negate swaps the condition.
4627             Opcode = SetCondInst::getSwappedCondition(Opcode);
4628           }
4629
4630           if (LoBound) {
4631             Value *X = LHSI->getOperand(0);
4632             switch (Opcode) {
4633             default: assert(0 && "Unhandled setcc opcode!");
4634             case Instruction::SetEQ:
4635               if (LoOverflow && HiOverflow)
4636                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4637               else if (HiOverflow)
4638                 return new SetCondInst(Instruction::SetGE, X, LoBound);
4639               else if (LoOverflow)
4640                 return new SetCondInst(Instruction::SetLT, X, HiBound);
4641               else
4642                 return InsertRangeTest(X, LoBound, HiBound, true, I);
4643             case Instruction::SetNE:
4644               if (LoOverflow && HiOverflow)
4645                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4646               else if (HiOverflow)
4647                 return new SetCondInst(Instruction::SetLT, X, LoBound);
4648               else if (LoOverflow)
4649                 return new SetCondInst(Instruction::SetGE, X, HiBound);
4650               else
4651                 return InsertRangeTest(X, LoBound, HiBound, false, I);
4652             case Instruction::SetLT:
4653               if (LoOverflow)
4654                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4655               return new SetCondInst(Instruction::SetLT, X, LoBound);
4656             case Instruction::SetGT:
4657               if (HiOverflow)
4658                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4659               return new SetCondInst(Instruction::SetGE, X, HiBound);
4660             }
4661           }
4662         }
4663         break;
4664       }
4665
4666     // Simplify seteq and setne instructions with integer constant RHS.
4667     if (I.isEquality()) {
4668       bool isSetNE = I.getOpcode() == Instruction::SetNE;
4669
4670       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4671       // the second operand is a constant, simplify a bit.
4672       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4673         switch (BO->getOpcode()) {
4674         case Instruction::SRem:
4675           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4676           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4677               BO->hasOneUse()) {
4678             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4679             if (V > 1 && isPowerOf2_64(V)) {
4680               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4681                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4682               return BinaryOperator::create(I.getOpcode(), NewRem,
4683                 Constant::getNullValue(BO->getType()));
4684             }
4685           }
4686           break;
4687         case Instruction::Add:
4688           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4689           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4690             if (BO->hasOneUse())
4691               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4692                                      ConstantExpr::getSub(CI, BOp1C));
4693           } else if (CI->isNullValue()) {
4694             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4695             // efficiently invertible, or if the add has just this one use.
4696             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4697
4698             if (Value *NegVal = dyn_castNegVal(BOp1))
4699               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4700             else if (Value *NegVal = dyn_castNegVal(BOp0))
4701               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4702             else if (BO->hasOneUse()) {
4703               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4704               BO->setName("");
4705               InsertNewInstBefore(Neg, I);
4706               return new SetCondInst(I.getOpcode(), BOp0, Neg);
4707             }
4708           }
4709           break;
4710         case Instruction::Xor:
4711           // For the xor case, we can xor two constants together, eliminating
4712           // the explicit xor.
4713           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4714             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4715                                   ConstantExpr::getXor(CI, BOC));
4716
4717           // FALLTHROUGH
4718         case Instruction::Sub:
4719           // Replace (([sub|xor] A, B) != 0) with (A != B)
4720           if (CI->isNullValue())
4721             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4722                                    BO->getOperand(1));
4723           break;
4724
4725         case Instruction::Or:
4726           // If bits are being or'd in that are not present in the constant we
4727           // are comparing against, then the comparison could never succeed!
4728           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4729             Constant *NotCI = ConstantExpr::getNot(CI);
4730             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4731               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4732           }
4733           break;
4734
4735         case Instruction::And:
4736           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4737             // If bits are being compared against that are and'd out, then the
4738             // comparison can never succeed!
4739             if (!ConstantExpr::getAnd(CI,
4740                                       ConstantExpr::getNot(BOC))->isNullValue())
4741               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4742
4743             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4744             if (CI == BOC && isOneBitSet(CI))
4745               return new SetCondInst(isSetNE ? Instruction::SetEQ :
4746                                      Instruction::SetNE, Op0,
4747                                      Constant::getNullValue(CI->getType()));
4748
4749             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4750             // to be a signed value as appropriate.
4751             if (isSignBit(BOC)) {
4752               Value *X = BO->getOperand(0);
4753               // If 'X' is not signed, insert a cast now...
4754               if (!BOC->getType()->isSigned()) {
4755                 const Type *DestTy = BOC->getType()->getSignedVersion();
4756                 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
4757               }
4758               return new SetCondInst(isSetNE ? Instruction::SetLT :
4759                                          Instruction::SetGE, X,
4760                                      Constant::getNullValue(X->getType()));
4761             }
4762
4763             // ((X & ~7) == 0) --> X < 8
4764             if (CI->isNullValue() && isHighOnes(BOC)) {
4765               Value *X = BO->getOperand(0);
4766               Constant *NegX = ConstantExpr::getNeg(BOC);
4767
4768               // If 'X' is signed, insert a cast now.
4769               if (NegX->getType()->isSigned()) {
4770                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4771                 X = InsertCastBefore(Instruction::BitCast, X, DestTy, I);
4772                 NegX = ConstantExpr::getBitCast(NegX, DestTy);
4773               }
4774
4775               return new SetCondInst(isSetNE ? Instruction::SetGE :
4776                                      Instruction::SetLT, X, NegX);
4777             }
4778
4779           }
4780         default: break;
4781         }
4782       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
4783         // Handle set{eq|ne} <intrinsic>, intcst.
4784         switch (II->getIntrinsicID()) {
4785         default: break;
4786         case Intrinsic::bswap_i16:   // seteq (bswap(x)), c -> seteq(x,bswap(c))
4787           WorkList.push_back(II);  // Dead?
4788           I.setOperand(0, II->getOperand(1));
4789           I.setOperand(1, ConstantInt::get(Type::UShortTy,
4790                                            ByteSwap_16(CI->getZExtValue())));
4791           return &I;
4792         case Intrinsic::bswap_i32:   // seteq (bswap(x)), c -> seteq(x,bswap(c))
4793           WorkList.push_back(II);  // Dead?
4794           I.setOperand(0, II->getOperand(1));
4795           I.setOperand(1, ConstantInt::get(Type::UIntTy,
4796                                            ByteSwap_32(CI->getZExtValue())));
4797           return &I;
4798         case Intrinsic::bswap_i64:   // seteq (bswap(x)), c -> seteq(x,bswap(c))
4799           WorkList.push_back(II);  // Dead?
4800           I.setOperand(0, II->getOperand(1));
4801           I.setOperand(1, ConstantInt::get(Type::ULongTy,
4802                                            ByteSwap_64(CI->getZExtValue())));
4803           return &I;
4804         }
4805       }
4806     } else {  // Not a SetEQ/SetNE
4807       // If the LHS is a cast from an integral value of the same size,
4808       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4809         Value *CastOp = Cast->getOperand(0);
4810         const Type *SrcTy = CastOp->getType();
4811         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4812         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4813             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4814           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4815                  "Source and destination signednesses should differ!");
4816           if (Cast->getType()->isSigned()) {
4817             // If this is a signed comparison, check for comparisons in the
4818             // vicinity of zero.
4819             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4820               // X < 0  => x > 127
4821               return BinaryOperator::createSetGT(CastOp,
4822                          ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4823             else if (I.getOpcode() == Instruction::SetGT &&
4824                      cast<ConstantInt>(CI)->getSExtValue() == -1)
4825               // X > -1  => x < 128
4826               return BinaryOperator::createSetLT(CastOp,
4827                          ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4828           } else {
4829             ConstantInt *CUI = cast<ConstantInt>(CI);
4830             if (I.getOpcode() == Instruction::SetLT &&
4831                 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4832               // X < 128 => X > -1
4833               return BinaryOperator::createSetGT(CastOp,
4834                                                  ConstantInt::get(SrcTy, -1));
4835             else if (I.getOpcode() == Instruction::SetGT &&
4836                      CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4837               // X > 127 => X < 0
4838               return BinaryOperator::createSetLT(CastOp,
4839                                                  Constant::getNullValue(SrcTy));
4840           }
4841         }
4842       }
4843     }
4844   }
4845
4846   // Handle setcc with constant RHS's that can be integer, FP or pointer.
4847   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4848     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4849       switch (LHSI->getOpcode()) {
4850       case Instruction::GetElementPtr:
4851         if (RHSC->isNullValue()) {
4852           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4853           bool isAllZeros = true;
4854           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4855             if (!isa<Constant>(LHSI->getOperand(i)) ||
4856                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4857               isAllZeros = false;
4858               break;
4859             }
4860           if (isAllZeros)
4861             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4862                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
4863         }
4864         break;
4865
4866       case Instruction::PHI:
4867         if (Instruction *NV = FoldOpIntoPhi(I))
4868           return NV;
4869         break;
4870       case Instruction::Select:
4871         // If either operand of the select is a constant, we can fold the
4872         // comparison into the select arms, which will cause one to be
4873         // constant folded and the select turned into a bitwise or.
4874         Value *Op1 = 0, *Op2 = 0;
4875         if (LHSI->hasOneUse()) {
4876           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4877             // Fold the known value into the constant operand.
4878             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4879             // Insert a new SetCC of the other select operand.
4880             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4881                                                       LHSI->getOperand(2), RHSC,
4882                                                       I.getName()), I);
4883           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4884             // Fold the known value into the constant operand.
4885             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4886             // Insert a new SetCC of the other select operand.
4887             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4888                                                       LHSI->getOperand(1), RHSC,
4889                                                       I.getName()), I);
4890           }
4891         }
4892
4893         if (Op1)
4894           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4895         break;
4896       }
4897   }
4898
4899   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4900   if (User *GEP = dyn_castGetElementPtr(Op0))
4901     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4902       return NI;
4903   if (User *GEP = dyn_castGetElementPtr(Op1))
4904     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4905                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
4906       return NI;
4907
4908   // Test to see if the operands of the setcc are casted versions of other
4909   // values.  If the cast can be stripped off both arguments, we do so now.
4910   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4911     Value *CastOp0 = CI->getOperand(0);
4912     if (CI->isLosslessCast() && I.isEquality() && 
4913         (isa<Constant>(Op1) || isa<CastInst>(Op1))) { 
4914       // We keep moving the cast from the left operand over to the right
4915       // operand, where it can often be eliminated completely.
4916       Op0 = CastOp0;
4917
4918       // If operand #1 is a cast instruction, see if we can eliminate it as
4919       // well.
4920       if (CastInst *CI2 = dyn_cast<CastInst>(Op1)) { 
4921         Value *CI2Op0 = CI2->getOperand(0);
4922         if (CI2Op0->getType()->canLosslesslyBitCastTo(Op0->getType()))
4923           Op1 = CI2Op0;
4924       }
4925
4926       // If Op1 is a constant, we can fold the cast into the constant.
4927       if (Op1->getType() != Op0->getType())
4928         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4929           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
4930         } else {
4931           // Otherwise, cast the RHS right before the setcc
4932           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
4933         }
4934       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4935     }
4936
4937     // Handle the special case of: setcc (cast bool to X), <cst>
4938     // This comes up when you have code like
4939     //   int X = A < B;
4940     //   if (X) ...
4941     // For generality, we handle any zero-extension of any operand comparison
4942     // with a constant or another cast from the same type.
4943     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4944       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4945         return R;
4946   }
4947   
4948   if (I.isEquality()) {
4949     Value *A, *B;
4950     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4951         (A == Op1 || B == Op1)) {
4952       // (A^B) == A  ->  B == 0
4953       Value *OtherVal = A == Op1 ? B : A;
4954       return BinaryOperator::create(I.getOpcode(), OtherVal,
4955                                     Constant::getNullValue(A->getType()));
4956     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4957                (A == Op0 || B == Op0)) {
4958       // A == (A^B)  ->  B == 0
4959       Value *OtherVal = A == Op0 ? B : A;
4960       return BinaryOperator::create(I.getOpcode(), OtherVal,
4961                                     Constant::getNullValue(A->getType()));
4962     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4963       // (A-B) == A  ->  B == 0
4964       return BinaryOperator::create(I.getOpcode(), B,
4965                                     Constant::getNullValue(B->getType()));
4966     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4967       // A == (A-B)  ->  B == 0
4968       return BinaryOperator::create(I.getOpcode(), B,
4969                                     Constant::getNullValue(B->getType()));
4970     }
4971     
4972     Value *C, *D;
4973     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
4974     if (Op0->hasOneUse() && Op1->hasOneUse() &&
4975         match(Op0, m_And(m_Value(A), m_Value(B))) && 
4976         match(Op1, m_And(m_Value(C), m_Value(D)))) {
4977       Value *X = 0, *Y = 0, *Z = 0;
4978       
4979       if (A == C) {
4980         X = B; Y = D; Z = A;
4981       } else if (A == D) {
4982         X = B; Y = C; Z = A;
4983       } else if (B == C) {
4984         X = A; Y = D; Z = B;
4985       } else if (B == D) {
4986         X = A; Y = C; Z = B;
4987       }
4988       
4989       if (X) {   // Build (X^Y) & Z
4990         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
4991         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
4992         I.setOperand(0, Op1);
4993         I.setOperand(1, Constant::getNullValue(Op1->getType()));
4994         return &I;
4995       }
4996     }
4997   }
4998   return Changed ? &I : 0;
4999 }
5000
5001 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
5002 // We only handle extending casts so far.
5003 //
5004 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
5005   const CastInst *LHSCI = cast<CastInst>(SCI.getOperand(0));
5006   Value *LHSCIOp        = LHSCI->getOperand(0);
5007   const Type *SrcTy     = LHSCIOp->getType();
5008   const Type *DestTy    = SCI.getOperand(0)->getType();
5009   Value *RHSCIOp;
5010
5011   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
5012     return 0;
5013
5014   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
5015   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
5016   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
5017
5018   // Is this a sign or zero extension?
5019   bool isSignSrc  = SrcTy->isSigned();
5020   bool isSignDest = DestTy->isSigned();
5021
5022   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
5023     // Not an extension from the same type?
5024     RHSCIOp = CI->getOperand(0);
5025     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
5026   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
5027     // Compute the constant that would happen if we truncated to SrcTy then
5028     // reextended to DestTy.
5029     Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5030     Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5031
5032     if (Res2 == CI) {
5033       // Make sure that src sign and dest sign match. For example,
5034       //
5035       // %A = cast short %X to uint
5036       // %B = setgt uint %A, 1330
5037       //
5038       // It is incorrect to transform this into 
5039       //
5040       // %B = setgt short %X, 1330 
5041       // 
5042       // because %A may have negative value. 
5043       // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5044       // OR operation is EQ/NE.
5045       if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
5046         RHSCIOp = Res1;
5047       else
5048         return 0;
5049     } else {
5050       // If the value cannot be represented in the shorter type, we cannot emit
5051       // a simple comparison.
5052       if (SCI.getOpcode() == Instruction::SetEQ)
5053         return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
5054       if (SCI.getOpcode() == Instruction::SetNE)
5055         return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
5056
5057       // Evaluate the comparison for LT.
5058       Value *Result;
5059       if (DestTy->isSigned()) {
5060         // We're performing a signed comparison.
5061         if (isSignSrc) {
5062           // Signed extend and signed comparison.
5063           if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
5064             Result = ConstantBool::getFalse();
5065           else
5066             Result = ConstantBool::getTrue();           // X < (large) --> true
5067         } else {
5068           // Unsigned extend and signed comparison.
5069           if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5070             Result = ConstantBool::getFalse();
5071           else
5072             Result = ConstantBool::getTrue();
5073         }
5074       } else {
5075         // We're performing an unsigned comparison.
5076         if (!isSignSrc) {
5077           // Unsigned extend & compare -> always true.
5078           Result = ConstantBool::getTrue();
5079         } else {
5080           // We're performing an unsigned comp with a sign extended value.
5081           // This is true if the input is >= 0. [aka >s -1]
5082           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5083           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
5084                                                   NegOne, SCI.getName()), SCI);
5085         }
5086       }
5087
5088       // Finally, return the value computed.
5089       if (SCI.getOpcode() == Instruction::SetLT) {
5090         return ReplaceInstUsesWith(SCI, Result);
5091       } else {
5092         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
5093         if (Constant *CI = dyn_cast<Constant>(Result))
5094           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
5095         else
5096           return BinaryOperator::createNot(Result);
5097       }
5098     }
5099   } else {
5100     return 0;
5101   }
5102
5103   // Okay, just insert a compare of the reduced operands now!
5104   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
5105 }
5106
5107 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5108   assert(I.getOperand(1)->getType() == Type::UByteTy);
5109   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5110   bool isLeftShift = I.getOpcode() == Instruction::Shl;
5111
5112   // shl X, 0 == X and shr X, 0 == X
5113   // shl 0, X == 0 and shr 0, X == 0
5114   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
5115       Op0 == Constant::getNullValue(Op0->getType()))
5116     return ReplaceInstUsesWith(I, Op0);
5117   
5118   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
5119     if (!isLeftShift && I.getType()->isSigned())
5120       return ReplaceInstUsesWith(I, Op0);
5121     else                         // undef << X -> 0   AND  undef >>u X -> 0
5122       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5123   }
5124   if (isa<UndefValue>(Op1)) {
5125     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
5126       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5127     else
5128       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
5129   }
5130
5131   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5132   if (I.getOpcode() == Instruction::AShr)
5133     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5134       if (CSI->isAllOnesValue())
5135         return ReplaceInstUsesWith(I, CSI);
5136
5137   // Try to fold constant and into select arguments.
5138   if (isa<Constant>(Op0))
5139     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5140       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5141         return R;
5142
5143   // See if we can turn a signed shr into an unsigned shr.
5144   if (I.isArithmeticShift()) {
5145     if (MaskedValueIsZero(Op0,
5146                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5147       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5148     }
5149   }
5150
5151   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5152     if (CUI->getType()->isUnsigned())
5153       if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5154         return Res;
5155   return 0;
5156 }
5157
5158 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5159                                                ShiftInst &I) {
5160   bool isLeftShift = I.getOpcode() == Instruction::Shl;
5161   bool isSignedShift = isLeftShift ? Op0->getType()->isSigned() : 
5162                                      I.getOpcode() == Instruction::AShr;
5163   bool isUnsignedShift = !isSignedShift;
5164
5165   // See if we can simplify any instructions used by the instruction whose sole 
5166   // purpose is to compute bits we don't care about.
5167   uint64_t KnownZero, KnownOne;
5168   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5169                            KnownZero, KnownOne))
5170     return &I;
5171   
5172   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5173   // of a signed value.
5174   //
5175   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5176   if (Op1->getZExtValue() >= TypeBits) {
5177     if (isUnsignedShift || isLeftShift)
5178       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5179     else {
5180       I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
5181       return &I;
5182     }
5183   }
5184   
5185   // ((X*C1) << C2) == (X * (C1 << C2))
5186   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5187     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5188       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5189         return BinaryOperator::createMul(BO->getOperand(0),
5190                                          ConstantExpr::getShl(BOOp, Op1));
5191   
5192   // Try to fold constant and into select arguments.
5193   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5194     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5195       return R;
5196   if (isa<PHINode>(Op0))
5197     if (Instruction *NV = FoldOpIntoPhi(I))
5198       return NV;
5199   
5200   if (Op0->hasOneUse()) {
5201     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5202       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5203       Value *V1, *V2;
5204       ConstantInt *CC;
5205       switch (Op0BO->getOpcode()) {
5206         default: break;
5207         case Instruction::Add:
5208         case Instruction::And:
5209         case Instruction::Or:
5210         case Instruction::Xor:
5211           // These operators commute.
5212           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5213           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5214               match(Op0BO->getOperand(1),
5215                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5216             Instruction *YS = new ShiftInst(Instruction::Shl, 
5217                                             Op0BO->getOperand(0), Op1,
5218                                             Op0BO->getName());
5219             InsertNewInstBefore(YS, I); // (Y << C)
5220             Instruction *X = 
5221               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5222                                      Op0BO->getOperand(1)->getName());
5223             InsertNewInstBefore(X, I);  // (X + (Y << C))
5224             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5225             C2 = ConstantExpr::getShl(C2, Op1);
5226             return BinaryOperator::createAnd(X, C2);
5227           }
5228           
5229           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5230           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5231               match(Op0BO->getOperand(1),
5232                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5233                           m_ConstantInt(CC))) && V2 == Op1 &&
5234       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5235             Instruction *YS = new ShiftInst(Instruction::Shl, 
5236                                             Op0BO->getOperand(0), Op1,
5237                                             Op0BO->getName());
5238             InsertNewInstBefore(YS, I); // (Y << C)
5239             Instruction *XM =
5240               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5241                                         V1->getName()+".mask");
5242             InsertNewInstBefore(XM, I); // X & (CC << C)
5243             
5244             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5245           }
5246           
5247           // FALL THROUGH.
5248         case Instruction::Sub:
5249           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5250           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5251               match(Op0BO->getOperand(0),
5252                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5253             Instruction *YS = new ShiftInst(Instruction::Shl, 
5254                                             Op0BO->getOperand(1), Op1,
5255                                             Op0BO->getName());
5256             InsertNewInstBefore(YS, I); // (Y << C)
5257             Instruction *X =
5258               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5259                                      Op0BO->getOperand(0)->getName());
5260             InsertNewInstBefore(X, I);  // (X + (Y << C))
5261             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5262             C2 = ConstantExpr::getShl(C2, Op1);
5263             return BinaryOperator::createAnd(X, C2);
5264           }
5265           
5266           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5267           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5268               match(Op0BO->getOperand(0),
5269                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5270                           m_ConstantInt(CC))) && V2 == Op1 &&
5271               cast<BinaryOperator>(Op0BO->getOperand(0))
5272                   ->getOperand(0)->hasOneUse()) {
5273             Instruction *YS = new ShiftInst(Instruction::Shl, 
5274                                             Op0BO->getOperand(1), Op1,
5275                                             Op0BO->getName());
5276             InsertNewInstBefore(YS, I); // (Y << C)
5277             Instruction *XM =
5278               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5279                                         V1->getName()+".mask");
5280             InsertNewInstBefore(XM, I); // X & (CC << C)
5281             
5282             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5283           }
5284           
5285           break;
5286       }
5287       
5288       
5289       // If the operand is an bitwise operator with a constant RHS, and the
5290       // shift is the only use, we can pull it out of the shift.
5291       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5292         bool isValid = true;     // Valid only for And, Or, Xor
5293         bool highBitSet = false; // Transform if high bit of constant set?
5294         
5295         switch (Op0BO->getOpcode()) {
5296           default: isValid = false; break;   // Do not perform transform!
5297           case Instruction::Add:
5298             isValid = isLeftShift;
5299             break;
5300           case Instruction::Or:
5301           case Instruction::Xor:
5302             highBitSet = false;
5303             break;
5304           case Instruction::And:
5305             highBitSet = true;
5306             break;
5307         }
5308         
5309         // If this is a signed shift right, and the high bit is modified
5310         // by the logical operation, do not perform the transformation.
5311         // The highBitSet boolean indicates the value of the high bit of
5312         // the constant which would cause it to be modified for this
5313         // operation.
5314         //
5315         if (isValid && !isLeftShift && isSignedShift) {
5316           uint64_t Val = Op0C->getZExtValue();
5317           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5318         }
5319         
5320         if (isValid) {
5321           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5322           
5323           Instruction *NewShift =
5324             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5325                           Op0BO->getName());
5326           Op0BO->setName("");
5327           InsertNewInstBefore(NewShift, I);
5328           
5329           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5330                                         NewRHS);
5331         }
5332       }
5333     }
5334   }
5335   
5336   // Find out if this is a shift of a shift by a constant.
5337   ShiftInst *ShiftOp = 0;
5338   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5339     ShiftOp = Op0SI;
5340   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5341     // If this is a noop-integer cast of a shift instruction, use the shift.
5342     if (isa<ShiftInst>(CI->getOperand(0))) {
5343       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5344     }
5345   }
5346   
5347   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5348     // Find the operands and properties of the input shift.  Note that the
5349     // signedness of the input shift may differ from the current shift if there
5350     // is a noop cast between the two.
5351     bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5352     bool isShiftOfSignedShift = isShiftOfLeftShift ? 
5353            ShiftOp->getType()->isSigned() : 
5354            ShiftOp->getOpcode() == Instruction::AShr;
5355     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5356     
5357     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5358
5359     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5360     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5361     
5362     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5363     if (isLeftShift == isShiftOfLeftShift) {
5364       // Do not fold these shifts if the first one is signed and the second one
5365       // is unsigned and this is a right shift.  Further, don't do any folding
5366       // on them.
5367       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5368         return 0;
5369       
5370       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5371       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5372         Amt = Op0->getType()->getPrimitiveSizeInBits();
5373       
5374       Value *Op = ShiftOp->getOperand(0);
5375       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5376                                           ConstantInt::get(Type::UByteTy, Amt));
5377       if (I.getType() == ShiftResult->getType())
5378         return ShiftResult;
5379       InsertNewInstBefore(ShiftResult, I);
5380       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5381     }
5382     
5383     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5384     // signed types, we can only support the (A >> c1) << c2 configuration,
5385     // because it can not turn an arbitrary bit of A into a sign bit.
5386     if (isUnsignedShift || isLeftShift) {
5387       // Calculate bitmask for what gets shifted off the edge.
5388       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5389       if (isLeftShift)
5390         C = ConstantExpr::getShl(C, ShiftAmt1C);
5391       else
5392         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5393       
5394       Value *Op = ShiftOp->getOperand(0);
5395       if (Op->getType() != C->getType())
5396         Op = InsertCastBefore(Instruction::BitCast, Op, I.getType(), I);
5397       
5398       Instruction *Mask =
5399         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5400       InsertNewInstBefore(Mask, I);
5401       
5402       // Figure out what flavor of shift we should use...
5403       if (ShiftAmt1 == ShiftAmt2) {
5404         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5405       } else if (ShiftAmt1 < ShiftAmt2) {
5406         return new ShiftInst(I.getOpcode(), Mask,
5407                          ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5408       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5409         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5410           return new ShiftInst(Instruction::LShr, Mask, 
5411             ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5412         } else {
5413           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5414                     ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5415         }
5416       } else {
5417         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5418         Instruction *Shift =
5419           new ShiftInst(ShiftOp->getOpcode(), Mask,
5420                         ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5421         InsertNewInstBefore(Shift, I);
5422         
5423         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5424         C = ConstantExpr::getShl(C, Op1);
5425         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5426       }
5427     } else {
5428       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5429       // this case, C1 == C2 and C1 is 8, 16, or 32.
5430       if (ShiftAmt1 == ShiftAmt2) {
5431         const Type *SExtType = 0;
5432         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5433         case 8 : SExtType = Type::SByteTy; break;
5434         case 16: SExtType = Type::ShortTy; break;
5435         case 32: SExtType = Type::IntTy; break;
5436         }
5437         
5438         if (SExtType) {
5439           Instruction *NewTrunc = 
5440             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5441           InsertNewInstBefore(NewTrunc, I);
5442           return new SExtInst(NewTrunc, I.getType());
5443         }
5444       }
5445     }
5446   }
5447   return 0;
5448 }
5449
5450
5451 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5452 /// expression.  If so, decompose it, returning some value X, such that Val is
5453 /// X*Scale+Offset.
5454 ///
5455 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5456                                         unsigned &Offset) {
5457   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5458   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5459     if (CI->getType()->isUnsigned()) {
5460       Offset = CI->getZExtValue();
5461       Scale  = 1;
5462       return ConstantInt::get(Type::UIntTy, 0);
5463     }
5464   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5465     if (I->getNumOperands() == 2) {
5466       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5467         if (CUI->getType()->isUnsigned()) {
5468           if (I->getOpcode() == Instruction::Shl) {
5469             // This is a value scaled by '1 << the shift amt'.
5470             Scale = 1U << CUI->getZExtValue();
5471             Offset = 0;
5472             return I->getOperand(0);
5473           } else if (I->getOpcode() == Instruction::Mul) {
5474             // This value is scaled by 'CUI'.
5475             Scale = CUI->getZExtValue();
5476             Offset = 0;
5477             return I->getOperand(0);
5478           } else if (I->getOpcode() == Instruction::Add) {
5479             // We have X+C.  Check to see if we really have (X*C2)+C1, 
5480             // where C1 is divisible by C2.
5481             unsigned SubScale;
5482             Value *SubVal = 
5483               DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5484             Offset += CUI->getZExtValue();
5485             if (SubScale > 1 && (Offset % SubScale == 0)) {
5486               Scale = SubScale;
5487               return SubVal;
5488             }
5489           }
5490         }
5491       }
5492     }
5493   }
5494
5495   // Otherwise, we can't look past this.
5496   Scale = 1;
5497   Offset = 0;
5498   return Val;
5499 }
5500
5501
5502 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5503 /// try to eliminate the cast by moving the type information into the alloc.
5504 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5505                                                    AllocationInst &AI) {
5506   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5507   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5508   
5509   // Remove any uses of AI that are dead.
5510   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5511   std::vector<Instruction*> DeadUsers;
5512   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5513     Instruction *User = cast<Instruction>(*UI++);
5514     if (isInstructionTriviallyDead(User)) {
5515       while (UI != E && *UI == User)
5516         ++UI; // If this instruction uses AI more than once, don't break UI.
5517       
5518       // Add operands to the worklist.
5519       AddUsesToWorkList(*User);
5520       ++NumDeadInst;
5521       DOUT << "IC: DCE: " << *User;
5522       
5523       User->eraseFromParent();
5524       removeFromWorkList(User);
5525     }
5526   }
5527   
5528   // Get the type really allocated and the type casted to.
5529   const Type *AllocElTy = AI.getAllocatedType();
5530   const Type *CastElTy = PTy->getElementType();
5531   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5532
5533   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5534   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5535   if (CastElTyAlign < AllocElTyAlign) return 0;
5536
5537   // If the allocation has multiple uses, only promote it if we are strictly
5538   // increasing the alignment of the resultant allocation.  If we keep it the
5539   // same, we open the door to infinite loops of various kinds.
5540   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5541
5542   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5543   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5544   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5545
5546   // See if we can satisfy the modulus by pulling a scale out of the array
5547   // size argument.
5548   unsigned ArraySizeScale, ArrayOffset;
5549   Value *NumElements = // See if the array size is a decomposable linear expr.
5550     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5551  
5552   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5553   // do the xform.
5554   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5555       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5556
5557   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5558   Value *Amt = 0;
5559   if (Scale == 1) {
5560     Amt = NumElements;
5561   } else {
5562     // If the allocation size is constant, form a constant mul expression
5563     Amt = ConstantInt::get(Type::UIntTy, Scale);
5564     if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5565       Amt = ConstantExpr::getMul(
5566               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5567     // otherwise multiply the amount and the number of elements
5568     else if (Scale != 1) {
5569       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5570       Amt = InsertNewInstBefore(Tmp, AI);
5571     }
5572   }
5573   
5574   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5575     Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5576     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5577     Amt = InsertNewInstBefore(Tmp, AI);
5578   }
5579   
5580   std::string Name = AI.getName(); AI.setName("");
5581   AllocationInst *New;
5582   if (isa<MallocInst>(AI))
5583     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5584   else
5585     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5586   InsertNewInstBefore(New, AI);
5587   
5588   // If the allocation has multiple uses, insert a cast and change all things
5589   // that used it to use the new cast.  This will also hack on CI, but it will
5590   // die soon.
5591   if (!AI.hasOneUse()) {
5592     AddUsesToWorkList(AI);
5593     // New is the allocation instruction, pointer typed. AI is the original
5594     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5595     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5596     InsertNewInstBefore(NewCast, AI);
5597     AI.replaceAllUsesWith(NewCast);
5598   }
5599   return ReplaceInstUsesWith(CI, New);
5600 }
5601
5602 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5603 /// and return it without inserting any new casts.  This is used by code that
5604 /// tries to decide whether promoting or shrinking integer operations to wider
5605 /// or smaller types will allow us to eliminate a truncate or extend.
5606 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5607                                        int &NumCastsRemoved) {
5608   if (isa<Constant>(V)) return true;
5609   
5610   Instruction *I = dyn_cast<Instruction>(V);
5611   if (!I || !I->hasOneUse()) return false;
5612   
5613   switch (I->getOpcode()) {
5614   case Instruction::And:
5615   case Instruction::Or:
5616   case Instruction::Xor:
5617     // These operators can all arbitrarily be extended or truncated.
5618     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5619            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5620   case Instruction::AShr:
5621   case Instruction::LShr:
5622   case Instruction::Shl:
5623     // If this is just a bitcast changing the sign of the operation, we can
5624     // convert if the operand can be converted.
5625     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5626       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5627     break;
5628   case Instruction::Trunc:
5629   case Instruction::ZExt:
5630   case Instruction::SExt:
5631   case Instruction::BitCast:
5632     // If this is a cast from the destination type, we can trivially eliminate
5633     // it, and this will remove a cast overall.
5634     if (I->getOperand(0)->getType() == Ty) {
5635       // If the first operand is itself a cast, and is eliminable, do not count
5636       // this as an eliminable cast.  We would prefer to eliminate those two
5637       // casts first.
5638       if (isa<CastInst>(I->getOperand(0)))
5639         return true;
5640       
5641       ++NumCastsRemoved;
5642       return true;
5643     }
5644     break;
5645   default:
5646     // TODO: Can handle more cases here.
5647     break;
5648   }
5649   
5650   return false;
5651 }
5652
5653 /// EvaluateInDifferentType - Given an expression that 
5654 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5655 /// evaluate the expression.
5656 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5657                                              bool isSigned ) {
5658   if (Constant *C = dyn_cast<Constant>(V))
5659     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5660
5661   // Otherwise, it must be an instruction.
5662   Instruction *I = cast<Instruction>(V);
5663   Instruction *Res = 0;
5664   switch (I->getOpcode()) {
5665   case Instruction::And:
5666   case Instruction::Or:
5667   case Instruction::Xor: {
5668     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5669     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5670     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5671                                  LHS, RHS, I->getName());
5672     break;
5673   }
5674   case Instruction::AShr:
5675   case Instruction::LShr:
5676   case Instruction::Shl: {
5677     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5678     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5679                         I->getOperand(1), I->getName());
5680     break;
5681   }    
5682   case Instruction::Trunc:
5683   case Instruction::ZExt:
5684   case Instruction::SExt:
5685   case Instruction::BitCast:
5686     // If the source type of the cast is the type we're trying for then we can
5687     // just return the source. There's no need to insert it because its not new.
5688     if (I->getOperand(0)->getType() == Ty)
5689       return I->getOperand(0);
5690     
5691     // Some other kind of cast, which shouldn't happen, so just ..
5692     // FALL THROUGH
5693   default: 
5694     // TODO: Can handle more cases here.
5695     assert(0 && "Unreachable!");
5696     break;
5697   }
5698   
5699   return InsertNewInstBefore(Res, *I);
5700 }
5701
5702 /// @brief Implement the transforms common to all CastInst visitors.
5703 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5704   Value *Src = CI.getOperand(0);
5705
5706   // Casting undef to anything results in undef so might as just replace it and
5707   // get rid of the cast.
5708   if (isa<UndefValue>(Src))   // cast undef -> undef
5709     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5710
5711   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5712   // eliminate it now.
5713   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5714     if (Instruction::CastOps opc = 
5715         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5716       // The first cast (CSrc) is eliminable so we need to fix up or replace
5717       // the second cast (CI). CSrc will then have a good chance of being dead.
5718       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5719     }
5720   }
5721
5722   // If casting the result of a getelementptr instruction with no offset, turn
5723   // this into a cast of the original pointer!
5724   //
5725   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5726     bool AllZeroOperands = true;
5727     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5728       if (!isa<Constant>(GEP->getOperand(i)) ||
5729           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5730         AllZeroOperands = false;
5731         break;
5732       }
5733     if (AllZeroOperands) {
5734       // Changing the cast operand is usually not a good idea but it is safe
5735       // here because the pointer operand is being replaced with another 
5736       // pointer operand so the opcode doesn't need to change.
5737       CI.setOperand(0, GEP->getOperand(0));
5738       return &CI;
5739     }
5740   }
5741     
5742   // If we are casting a malloc or alloca to a pointer to a type of the same
5743   // size, rewrite the allocation instruction to allocate the "right" type.
5744   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5745     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5746       return V;
5747
5748   // If we are casting a select then fold the cast into the select
5749   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5750     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5751       return NV;
5752
5753   // If we are casting a PHI then fold the cast into the PHI
5754   if (isa<PHINode>(Src))
5755     if (Instruction *NV = FoldOpIntoPhi(CI))
5756       return NV;
5757   
5758   return 0;
5759 }
5760
5761 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5762 /// integers. This function implements the common transforms for all those
5763 /// cases.
5764 /// @brief Implement the transforms common to CastInst with integer operands
5765 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5766   if (Instruction *Result = commonCastTransforms(CI))
5767     return Result;
5768
5769   Value *Src = CI.getOperand(0);
5770   const Type *SrcTy = Src->getType();
5771   const Type *DestTy = CI.getType();
5772   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
5773   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5774
5775   // See if we can simplify any instructions used by the LHS whose sole 
5776   // purpose is to compute bits we don't care about.
5777   uint64_t KnownZero = 0, KnownOne = 0;
5778   if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
5779                            KnownZero, KnownOne))
5780     return &CI;
5781
5782   // If the source isn't an instruction or has more than one use then we
5783   // can't do anything more. 
5784   if (!isa<Instruction>(Src) || !Src->hasOneUse())
5785     return 0;
5786
5787   // Attempt to propagate the cast into the instruction.
5788   Instruction *SrcI = cast<Instruction>(Src);
5789   int NumCastsRemoved = 0;
5790   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
5791     // If this cast is a truncate, evaluting in a different type always
5792     // eliminates the cast, so it is always a win.  If this is a noop-cast
5793     // this just removes a noop cast which isn't pointful, but simplifies
5794     // the code.  If this is a zero-extension, we need to do an AND to
5795     // maintain the clear top-part of the computation, so we require that
5796     // the input have eliminated at least one cast.  If this is a sign
5797     // extension, we insert two new casts (to do the extension) so we
5798     // require that two casts have been eliminated.
5799     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
5800     if (!DoXForm) {
5801       switch (CI.getOpcode()) {
5802         case Instruction::Trunc:
5803           DoXForm = true;
5804           break;
5805         case Instruction::ZExt:
5806           DoXForm = NumCastsRemoved >= 1;
5807           break;
5808         case Instruction::SExt:
5809           DoXForm = NumCastsRemoved >= 2;
5810           break;
5811         case Instruction::BitCast:
5812           DoXForm = false;
5813           break;
5814         default:
5815           // All the others use floating point so we shouldn't actually 
5816           // get here because of the check above.
5817           assert(!"Unknown cast type .. unreachable");
5818           break;
5819       }
5820     }
5821     
5822     if (DoXForm) {
5823       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
5824                                            CI.getOpcode() == Instruction::SExt);
5825       assert(Res->getType() == DestTy);
5826       switch (CI.getOpcode()) {
5827       default: assert(0 && "Unknown cast type!");
5828       case Instruction::Trunc:
5829       case Instruction::BitCast:
5830         // Just replace this cast with the result.
5831         return ReplaceInstUsesWith(CI, Res);
5832       case Instruction::ZExt: {
5833         // We need to emit an AND to clear the high bits.
5834         assert(SrcBitSize < DestBitSize && "Not a zext?");
5835         Constant *C = 
5836           ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5837         if (DestBitSize < 64)
5838           C = ConstantExpr::getTrunc(C, DestTy);
5839         else {
5840           assert(DestBitSize == 64);
5841           C = ConstantExpr::getBitCast(C, DestTy);
5842         }
5843         return BinaryOperator::createAnd(Res, C);
5844       }
5845       case Instruction::SExt:
5846         // We need to emit a cast to truncate, then a cast to sext.
5847         return CastInst::create(Instruction::SExt,
5848             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
5849                              CI), DestTy);
5850       }
5851     }
5852   }
5853   
5854   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5855   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5856
5857   switch (SrcI->getOpcode()) {
5858   case Instruction::Add:
5859   case Instruction::Mul:
5860   case Instruction::And:
5861   case Instruction::Or:
5862   case Instruction::Xor:
5863     // If we are discarding information, or just changing the sign, 
5864     // rewrite.
5865     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5866       // Don't insert two casts if they cannot be eliminated.  We allow 
5867       // two casts to be inserted if the sizes are the same.  This could 
5868       // only be converting signedness, which is a noop.
5869       if (DestBitSize == SrcBitSize || 
5870           !ValueRequiresCast(Op1, DestTy,TD) ||
5871           !ValueRequiresCast(Op0, DestTy, TD)) {
5872         Instruction::CastOps opcode = CI.getOpcode();
5873         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
5874         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
5875         return BinaryOperator::create(
5876             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5877       }
5878     }
5879
5880     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
5881     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
5882         SrcI->getOpcode() == Instruction::Xor &&
5883         Op1 == ConstantBool::getTrue() &&
5884         (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5885       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
5886       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
5887     }
5888     break;
5889   case Instruction::SDiv:
5890   case Instruction::UDiv:
5891   case Instruction::SRem:
5892   case Instruction::URem:
5893     // If we are just changing the sign, rewrite.
5894     if (DestBitSize == SrcBitSize) {
5895       // Don't insert two casts if they cannot be eliminated.  We allow 
5896       // two casts to be inserted if the sizes are the same.  This could 
5897       // only be converting signedness, which is a noop.
5898       if (!ValueRequiresCast(Op1, DestTy,TD) || 
5899           !ValueRequiresCast(Op0, DestTy, TD)) {
5900         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
5901                                               Op0, DestTy, SrcI);
5902         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
5903                                               Op1, DestTy, SrcI);
5904         return BinaryOperator::create(
5905           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5906       }
5907     }
5908     break;
5909
5910   case Instruction::Shl:
5911     // Allow changing the sign of the source operand.  Do not allow 
5912     // changing the size of the shift, UNLESS the shift amount is a 
5913     // constant.  We must not change variable sized shifts to a smaller 
5914     // size, because it is undefined to shift more bits out than exist 
5915     // in the value.
5916     if (DestBitSize == SrcBitSize ||
5917         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5918       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
5919           Instruction::BitCast : Instruction::Trunc);
5920       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
5921       return new ShiftInst(Instruction::Shl, Op0c, Op1);
5922     }
5923     break;
5924   case Instruction::AShr:
5925     // If this is a signed shr, and if all bits shifted in are about to be
5926     // truncated off, turn it into an unsigned shr to allow greater
5927     // simplifications.
5928     if (DestBitSize < SrcBitSize &&
5929         isa<ConstantInt>(Op1)) {
5930       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5931       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5932         // Insert the new logical shift right.
5933         return new ShiftInst(Instruction::LShr, Op0, Op1);
5934       }
5935     }
5936     break;
5937
5938   case Instruction::SetEQ:
5939   case Instruction::SetNE:
5940     // If we are just checking for a seteq of a single bit and casting it
5941     // to an integer.  If so, shift the bit to the appropriate place then
5942     // cast to integer to avoid the comparison.
5943     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5944       uint64_t Op1CV = Op1C->getZExtValue();
5945       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
5946       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5947       // cast (X == 1) to int --> X        iff X has only the low bit set.
5948       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
5949       // cast (X != 0) to int --> X        iff X has only the low bit set.
5950       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
5951       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
5952       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5953       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5954         // If Op1C some other power of two, convert:
5955         uint64_t KnownZero, KnownOne;
5956         uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5957         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5958         
5959         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
5960           bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5961           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5962             // (X&4) == 2 --> false
5963             // (X&4) != 2 --> true
5964             Constant *Res = ConstantBool::get(isSetNE);
5965             Res = ConstantExpr::getZExt(Res, CI.getType());
5966             return ReplaceInstUsesWith(CI, Res);
5967           }
5968           
5969           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5970           Value *In = Op0;
5971           if (ShiftAmt) {
5972             // Perform a logical shr by shiftamt.
5973             // Insert the shift to put the result in the low bit.
5974             In = InsertNewInstBefore(
5975               new ShiftInst(Instruction::LShr, In,
5976                             ConstantInt::get(Type::UByteTy, ShiftAmt),
5977                             In->getName()+".lobit"), CI);
5978           }
5979           
5980           if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5981             Constant *One = ConstantInt::get(In->getType(), 1);
5982             In = BinaryOperator::createXor(In, One, "tmp");
5983             InsertNewInstBefore(cast<Instruction>(In), CI);
5984           }
5985           
5986           if (CI.getType() == In->getType())
5987             return ReplaceInstUsesWith(CI, In);
5988           else
5989             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
5990         }
5991       }
5992     }
5993     break;
5994   }
5995   return 0;
5996 }
5997
5998 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
5999   if (Instruction *Result = commonIntCastTransforms(CI))
6000     return Result;
6001   
6002   Value *Src = CI.getOperand(0);
6003   const Type *Ty = CI.getType();
6004   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6005   
6006   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6007     switch (SrcI->getOpcode()) {
6008     default: break;
6009     case Instruction::LShr:
6010       // We can shrink lshr to something smaller if we know the bits shifted in
6011       // are already zeros.
6012       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6013         unsigned ShAmt = ShAmtV->getZExtValue();
6014         
6015         // Get a mask for the bits shifting in.
6016         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6017         Value* SrcIOp0 = SrcI->getOperand(0);
6018         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6019           if (ShAmt >= DestBitWidth)        // All zeros.
6020             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6021
6022           // Okay, we can shrink this.  Truncate the input, then return a new
6023           // shift.
6024           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6025           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6026         }
6027       } else {     // This is a variable shr.
6028         
6029         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6030         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6031         // loop-invariant and CSE'd.
6032         if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6033           Value *One = ConstantInt::get(SrcI->getType(), 1);
6034
6035           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6036                                                        SrcI->getOperand(1),
6037                                                        "tmp"), CI);
6038           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6039                                                             SrcI->getOperand(0),
6040                                                             "tmp"), CI);
6041           Value *Zero = Constant::getNullValue(V->getType());
6042           return BinaryOperator::createSetNE(V, Zero);
6043         }
6044       }
6045       break;
6046     }
6047   }
6048   
6049   return 0;
6050 }
6051
6052 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6053   // If one of the common conversion will work ..
6054   if (Instruction *Result = commonIntCastTransforms(CI))
6055     return Result;
6056
6057   Value *Src = CI.getOperand(0);
6058
6059   // If this is a cast of a cast
6060   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6061     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6062     // types and if the sizes are just right we can convert this into a logical
6063     // 'and' which will be much cheaper than the pair of casts.
6064     if (isa<TruncInst>(CSrc)) {
6065       // Get the sizes of the types involved
6066       Value *A = CSrc->getOperand(0);
6067       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6068       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6069       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6070       // If we're actually extending zero bits and the trunc is a no-op
6071       if (MidSize < DstSize && SrcSize == DstSize) {
6072         // Replace both of the casts with an And of the type mask.
6073         uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6074         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6075         Instruction *And = 
6076           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6077         // Unfortunately, if the type changed, we need to cast it back.
6078         if (And->getType() != CI.getType()) {
6079           And->setName(CSrc->getName()+".mask");
6080           InsertNewInstBefore(And, CI);
6081           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6082         }
6083         return And;
6084       }
6085     }
6086   }
6087
6088   return 0;
6089 }
6090
6091 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6092   return commonIntCastTransforms(CI);
6093 }
6094
6095 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6096   return commonCastTransforms(CI);
6097 }
6098
6099 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6100   return commonCastTransforms(CI);
6101 }
6102
6103 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6104   return commonCastTransforms(CI);
6105 }
6106
6107 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6108   return commonCastTransforms(CI);
6109 }
6110
6111 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6112   return commonCastTransforms(CI);
6113 }
6114
6115 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6116   return commonCastTransforms(CI);
6117 }
6118
6119 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6120   return commonCastTransforms(CI);
6121 }
6122
6123 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6124   return commonCastTransforms(CI);
6125 }
6126
6127 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6128
6129   // If the operands are integer typed then apply the integer transforms,
6130   // otherwise just apply the common ones.
6131   Value *Src = CI.getOperand(0);
6132   const Type *SrcTy = Src->getType();
6133   const Type *DestTy = CI.getType();
6134
6135   if (SrcTy->isInteger() && DestTy->isInteger()) {
6136     if (Instruction *Result = commonIntCastTransforms(CI))
6137       return Result;
6138   } else {
6139     if (Instruction *Result = commonCastTransforms(CI))
6140       return Result;
6141   }
6142
6143
6144   // Get rid of casts from one type to the same type. These are useless and can
6145   // be replaced by the operand.
6146   if (DestTy == Src->getType())
6147     return ReplaceInstUsesWith(CI, Src);
6148
6149   // If the source and destination are pointers, and this cast is equivalent to
6150   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6151   // This can enhance SROA and other transforms that want type-safe pointers.
6152   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6153     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6154       const Type *DstElTy = DstPTy->getElementType();
6155       const Type *SrcElTy = SrcPTy->getElementType();
6156       
6157       Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
6158       unsigned NumZeros = 0;
6159       while (SrcElTy != DstElTy && 
6160              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6161              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6162         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6163         ++NumZeros;
6164       }
6165
6166       // If we found a path from the src to dest, create the getelementptr now.
6167       if (SrcElTy == DstElTy) {
6168         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6169         return new GetElementPtrInst(Src, Idxs);
6170       }
6171     }
6172   }
6173
6174   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6175     if (SVI->hasOneUse()) {
6176       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6177       // a bitconvert to a vector with the same # elts.
6178       if (isa<PackedType>(DestTy) && 
6179           cast<PackedType>(DestTy)->getNumElements() == 
6180                 SVI->getType()->getNumElements()) {
6181         CastInst *Tmp;
6182         // If either of the operands is a cast from CI.getType(), then
6183         // evaluating the shuffle in the casted destination's type will allow
6184         // us to eliminate at least one cast.
6185         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6186              Tmp->getOperand(0)->getType() == DestTy) ||
6187             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6188              Tmp->getOperand(0)->getType() == DestTy)) {
6189           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6190                                                SVI->getOperand(0), DestTy, &CI);
6191           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6192                                                SVI->getOperand(1), DestTy, &CI);
6193           // Return a new shuffle vector.  Use the same element ID's, as we
6194           // know the vector types match #elts.
6195           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6196         }
6197       }
6198     }
6199   }
6200   return 0;
6201 }
6202
6203 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6204 ///   %C = or %A, %B
6205 ///   %D = select %cond, %C, %A
6206 /// into:
6207 ///   %C = select %cond, %B, 0
6208 ///   %D = or %A, %C
6209 ///
6210 /// Assuming that the specified instruction is an operand to the select, return
6211 /// a bitmask indicating which operands of this instruction are foldable if they
6212 /// equal the other incoming value of the select.
6213 ///
6214 static unsigned GetSelectFoldableOperands(Instruction *I) {
6215   switch (I->getOpcode()) {
6216   case Instruction::Add:
6217   case Instruction::Mul:
6218   case Instruction::And:
6219   case Instruction::Or:
6220   case Instruction::Xor:
6221     return 3;              // Can fold through either operand.
6222   case Instruction::Sub:   // Can only fold on the amount subtracted.
6223   case Instruction::Shl:   // Can only fold on the shift amount.
6224   case Instruction::LShr:
6225   case Instruction::AShr:
6226     return 1;
6227   default:
6228     return 0;              // Cannot fold
6229   }
6230 }
6231
6232 /// GetSelectFoldableConstant - For the same transformation as the previous
6233 /// function, return the identity constant that goes into the select.
6234 static Constant *GetSelectFoldableConstant(Instruction *I) {
6235   switch (I->getOpcode()) {
6236   default: assert(0 && "This cannot happen!"); abort();
6237   case Instruction::Add:
6238   case Instruction::Sub:
6239   case Instruction::Or:
6240   case Instruction::Xor:
6241     return Constant::getNullValue(I->getType());
6242   case Instruction::Shl:
6243   case Instruction::LShr:
6244   case Instruction::AShr:
6245     return Constant::getNullValue(Type::UByteTy);
6246   case Instruction::And:
6247     return ConstantInt::getAllOnesValue(I->getType());
6248   case Instruction::Mul:
6249     return ConstantInt::get(I->getType(), 1);
6250   }
6251 }
6252
6253 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6254 /// have the same opcode and only one use each.  Try to simplify this.
6255 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6256                                           Instruction *FI) {
6257   if (TI->getNumOperands() == 1) {
6258     // If this is a non-volatile load or a cast from the same type,
6259     // merge.
6260     if (TI->isCast()) {
6261       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6262         return 0;
6263     } else {
6264       return 0;  // unknown unary op.
6265     }
6266
6267     // Fold this by inserting a select from the input values.
6268     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6269                                        FI->getOperand(0), SI.getName()+".v");
6270     InsertNewInstBefore(NewSI, SI);
6271     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6272                             TI->getType());
6273   }
6274
6275   // Only handle binary operators here.
6276   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6277     return 0;
6278
6279   // Figure out if the operations have any operands in common.
6280   Value *MatchOp, *OtherOpT, *OtherOpF;
6281   bool MatchIsOpZero;
6282   if (TI->getOperand(0) == FI->getOperand(0)) {
6283     MatchOp  = TI->getOperand(0);
6284     OtherOpT = TI->getOperand(1);
6285     OtherOpF = FI->getOperand(1);
6286     MatchIsOpZero = true;
6287   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6288     MatchOp  = TI->getOperand(1);
6289     OtherOpT = TI->getOperand(0);
6290     OtherOpF = FI->getOperand(0);
6291     MatchIsOpZero = false;
6292   } else if (!TI->isCommutative()) {
6293     return 0;
6294   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6295     MatchOp  = TI->getOperand(0);
6296     OtherOpT = TI->getOperand(1);
6297     OtherOpF = FI->getOperand(0);
6298     MatchIsOpZero = true;
6299   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6300     MatchOp  = TI->getOperand(1);
6301     OtherOpT = TI->getOperand(0);
6302     OtherOpF = FI->getOperand(1);
6303     MatchIsOpZero = true;
6304   } else {
6305     return 0;
6306   }
6307
6308   // If we reach here, they do have operations in common.
6309   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6310                                      OtherOpF, SI.getName()+".v");
6311   InsertNewInstBefore(NewSI, SI);
6312
6313   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6314     if (MatchIsOpZero)
6315       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6316     else
6317       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6318   } else {
6319     if (MatchIsOpZero)
6320       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6321     else
6322       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6323   }
6324 }
6325
6326 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6327   Value *CondVal = SI.getCondition();
6328   Value *TrueVal = SI.getTrueValue();
6329   Value *FalseVal = SI.getFalseValue();
6330
6331   // select true, X, Y  -> X
6332   // select false, X, Y -> Y
6333   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6334     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6335
6336   // select C, X, X -> X
6337   if (TrueVal == FalseVal)
6338     return ReplaceInstUsesWith(SI, TrueVal);
6339
6340   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6341     return ReplaceInstUsesWith(SI, FalseVal);
6342   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6343     return ReplaceInstUsesWith(SI, TrueVal);
6344   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6345     if (isa<Constant>(TrueVal))
6346       return ReplaceInstUsesWith(SI, TrueVal);
6347     else
6348       return ReplaceInstUsesWith(SI, FalseVal);
6349   }
6350
6351   if (SI.getType() == Type::BoolTy)
6352     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6353       if (C->getValue()) {
6354         // Change: A = select B, true, C --> A = or B, C
6355         return BinaryOperator::createOr(CondVal, FalseVal);
6356       } else {
6357         // Change: A = select B, false, C --> A = and !B, C
6358         Value *NotCond =
6359           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6360                                              "not."+CondVal->getName()), SI);
6361         return BinaryOperator::createAnd(NotCond, FalseVal);
6362       }
6363     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6364       if (C->getValue() == false) {
6365         // Change: A = select B, C, false --> A = and B, C
6366         return BinaryOperator::createAnd(CondVal, TrueVal);
6367       } else {
6368         // Change: A = select B, C, true --> A = or !B, C
6369         Value *NotCond =
6370           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6371                                              "not."+CondVal->getName()), SI);
6372         return BinaryOperator::createOr(NotCond, TrueVal);
6373       }
6374     }
6375
6376   // Selecting between two integer constants?
6377   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6378     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6379       // select C, 1, 0 -> cast C to int
6380       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6381         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6382       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6383         // select C, 0, 1 -> cast !C to int
6384         Value *NotCond =
6385           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6386                                                "not."+CondVal->getName()), SI);
6387         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6388       }
6389
6390       if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6391
6392         // (x <s 0) ? -1 : 0 -> sra x, 31
6393         // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6394         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6395           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6396             bool CanXForm = false;
6397             if (CmpCst->getType()->isSigned())
6398               CanXForm = CmpCst->isNullValue() && 
6399                          IC->getOpcode() == Instruction::SetLT;
6400             else {
6401               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6402               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6403                          IC->getOpcode() == Instruction::SetGT;
6404             }
6405             
6406             if (CanXForm) {
6407               // The comparison constant and the result are not neccessarily the
6408               // same width. Make an all-ones value by inserting a AShr.
6409               Value *X = IC->getOperand(0);
6410               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6411               Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6412               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6413                                                ShAmt, "ones");
6414               InsertNewInstBefore(SRA, SI);
6415               
6416               // Finally, convert to the type of the select RHS.  We figure out
6417               // if this requires a SExt, Trunc or BitCast based on the sizes.
6418               Instruction::CastOps opc = Instruction::BitCast;
6419               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6420               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6421               if (SRASize < SISize)
6422                 opc = Instruction::SExt;
6423               else if (SRASize > SISize)
6424                 opc = Instruction::Trunc;
6425               return CastInst::create(opc, SRA, SI.getType());
6426             }
6427           }
6428
6429
6430         // If one of the constants is zero (we know they can't both be) and we
6431         // have a setcc instruction with zero, and we have an 'and' with the
6432         // non-constant value, eliminate this whole mess.  This corresponds to
6433         // cases like this: ((X & 27) ? 27 : 0)
6434         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6435           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6436               cast<Constant>(IC->getOperand(1))->isNullValue())
6437             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6438               if (ICA->getOpcode() == Instruction::And &&
6439                   isa<ConstantInt>(ICA->getOperand(1)) &&
6440                   (ICA->getOperand(1) == TrueValC ||
6441                    ICA->getOperand(1) == FalseValC) &&
6442                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6443                 // Okay, now we know that everything is set up, we just don't
6444                 // know whether we have a setne or seteq and whether the true or
6445                 // false val is the zero.
6446                 bool ShouldNotVal = !TrueValC->isNullValue();
6447                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6448                 Value *V = ICA;
6449                 if (ShouldNotVal)
6450                   V = InsertNewInstBefore(BinaryOperator::create(
6451                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6452                 return ReplaceInstUsesWith(SI, V);
6453               }
6454       }
6455     }
6456
6457   // See if we are selecting two values based on a comparison of the two values.
6458   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6459     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6460       // Transform (X == Y) ? X : Y  -> Y
6461       if (SCI->getOpcode() == Instruction::SetEQ)
6462         return ReplaceInstUsesWith(SI, FalseVal);
6463       // Transform (X != Y) ? X : Y  -> X
6464       if (SCI->getOpcode() == Instruction::SetNE)
6465         return ReplaceInstUsesWith(SI, TrueVal);
6466       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6467
6468     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6469       // Transform (X == Y) ? Y : X  -> X
6470       if (SCI->getOpcode() == Instruction::SetEQ)
6471         return ReplaceInstUsesWith(SI, FalseVal);
6472       // Transform (X != Y) ? Y : X  -> Y
6473       if (SCI->getOpcode() == Instruction::SetNE)
6474         return ReplaceInstUsesWith(SI, TrueVal);
6475       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6476     }
6477   }
6478
6479   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6480     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6481       if (TI->hasOneUse() && FI->hasOneUse()) {
6482         Instruction *AddOp = 0, *SubOp = 0;
6483
6484         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6485         if (TI->getOpcode() == FI->getOpcode())
6486           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6487             return IV;
6488
6489         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6490         // even legal for FP.
6491         if (TI->getOpcode() == Instruction::Sub &&
6492             FI->getOpcode() == Instruction::Add) {
6493           AddOp = FI; SubOp = TI;
6494         } else if (FI->getOpcode() == Instruction::Sub &&
6495                    TI->getOpcode() == Instruction::Add) {
6496           AddOp = TI; SubOp = FI;
6497         }
6498
6499         if (AddOp) {
6500           Value *OtherAddOp = 0;
6501           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6502             OtherAddOp = AddOp->getOperand(1);
6503           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6504             OtherAddOp = AddOp->getOperand(0);
6505           }
6506
6507           if (OtherAddOp) {
6508             // So at this point we know we have (Y -> OtherAddOp):
6509             //        select C, (add X, Y), (sub X, Z)
6510             Value *NegVal;  // Compute -Z
6511             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6512               NegVal = ConstantExpr::getNeg(C);
6513             } else {
6514               NegVal = InsertNewInstBefore(
6515                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6516             }
6517
6518             Value *NewTrueOp = OtherAddOp;
6519             Value *NewFalseOp = NegVal;
6520             if (AddOp != TI)
6521               std::swap(NewTrueOp, NewFalseOp);
6522             Instruction *NewSel =
6523               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6524
6525             NewSel = InsertNewInstBefore(NewSel, SI);
6526             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6527           }
6528         }
6529       }
6530
6531   // See if we can fold the select into one of our operands.
6532   if (SI.getType()->isInteger()) {
6533     // See the comment above GetSelectFoldableOperands for a description of the
6534     // transformation we are doing here.
6535     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6536       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6537           !isa<Constant>(FalseVal))
6538         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6539           unsigned OpToFold = 0;
6540           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6541             OpToFold = 1;
6542           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6543             OpToFold = 2;
6544           }
6545
6546           if (OpToFold) {
6547             Constant *C = GetSelectFoldableConstant(TVI);
6548             std::string Name = TVI->getName(); TVI->setName("");
6549             Instruction *NewSel =
6550               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6551                              Name);
6552             InsertNewInstBefore(NewSel, SI);
6553             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6554               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6555             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6556               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6557             else {
6558               assert(0 && "Unknown instruction!!");
6559             }
6560           }
6561         }
6562
6563     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6564       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6565           !isa<Constant>(TrueVal))
6566         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6567           unsigned OpToFold = 0;
6568           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6569             OpToFold = 1;
6570           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6571             OpToFold = 2;
6572           }
6573
6574           if (OpToFold) {
6575             Constant *C = GetSelectFoldableConstant(FVI);
6576             std::string Name = FVI->getName(); FVI->setName("");
6577             Instruction *NewSel =
6578               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6579                              Name);
6580             InsertNewInstBefore(NewSel, SI);
6581             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6582               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6583             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6584               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6585             else {
6586               assert(0 && "Unknown instruction!!");
6587             }
6588           }
6589         }
6590   }
6591
6592   if (BinaryOperator::isNot(CondVal)) {
6593     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6594     SI.setOperand(1, FalseVal);
6595     SI.setOperand(2, TrueVal);
6596     return &SI;
6597   }
6598
6599   return 0;
6600 }
6601
6602 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6603 /// determine, return it, otherwise return 0.
6604 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6605   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6606     unsigned Align = GV->getAlignment();
6607     if (Align == 0 && TD) 
6608       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6609     return Align;
6610   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6611     unsigned Align = AI->getAlignment();
6612     if (Align == 0 && TD) {
6613       if (isa<AllocaInst>(AI))
6614         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6615       else if (isa<MallocInst>(AI)) {
6616         // Malloc returns maximally aligned memory.
6617         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6618         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6619         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6620       }
6621     }
6622     return Align;
6623   } else if (isa<BitCastInst>(V) ||
6624              (isa<ConstantExpr>(V) && 
6625               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6626     User *CI = cast<User>(V);
6627     if (isa<PointerType>(CI->getOperand(0)->getType()))
6628       return GetKnownAlignment(CI->getOperand(0), TD);
6629     return 0;
6630   } else if (isa<GetElementPtrInst>(V) ||
6631              (isa<ConstantExpr>(V) && 
6632               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6633     User *GEPI = cast<User>(V);
6634     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6635     if (BaseAlignment == 0) return 0;
6636     
6637     // If all indexes are zero, it is just the alignment of the base pointer.
6638     bool AllZeroOperands = true;
6639     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6640       if (!isa<Constant>(GEPI->getOperand(i)) ||
6641           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6642         AllZeroOperands = false;
6643         break;
6644       }
6645     if (AllZeroOperands)
6646       return BaseAlignment;
6647     
6648     // Otherwise, if the base alignment is >= the alignment we expect for the
6649     // base pointer type, then we know that the resultant pointer is aligned at
6650     // least as much as its type requires.
6651     if (!TD) return 0;
6652
6653     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6654     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6655         <= BaseAlignment) {
6656       const Type *GEPTy = GEPI->getType();
6657       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6658     }
6659     return 0;
6660   }
6661   return 0;
6662 }
6663
6664
6665 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6666 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6667 /// the heavy lifting.
6668 ///
6669 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6670   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6671   if (!II) return visitCallSite(&CI);
6672   
6673   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6674   // visitCallSite.
6675   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6676     bool Changed = false;
6677
6678     // memmove/cpy/set of zero bytes is a noop.
6679     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6680       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6681
6682       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6683         if (CI->getZExtValue() == 1) {
6684           // Replace the instruction with just byte operations.  We would
6685           // transform other cases to loads/stores, but we don't know if
6686           // alignment is sufficient.
6687         }
6688     }
6689
6690     // If we have a memmove and the source operation is a constant global,
6691     // then the source and dest pointers can't alias, so we can change this
6692     // into a call to memcpy.
6693     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6694       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6695         if (GVSrc->isConstant()) {
6696           Module *M = CI.getParent()->getParent()->getParent();
6697           const char *Name;
6698           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6699               Type::UIntTy)
6700             Name = "llvm.memcpy.i32";
6701           else
6702             Name = "llvm.memcpy.i64";
6703           Function *MemCpy = M->getOrInsertFunction(Name,
6704                                      CI.getCalledFunction()->getFunctionType());
6705           CI.setOperand(0, MemCpy);
6706           Changed = true;
6707         }
6708     }
6709
6710     // If we can determine a pointer alignment that is bigger than currently
6711     // set, update the alignment.
6712     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6713       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6714       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6715       unsigned Align = std::min(Alignment1, Alignment2);
6716       if (MI->getAlignment()->getZExtValue() < Align) {
6717         MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6718         Changed = true;
6719       }
6720     } else if (isa<MemSetInst>(MI)) {
6721       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6722       if (MI->getAlignment()->getZExtValue() < Alignment) {
6723         MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6724         Changed = true;
6725       }
6726     }
6727           
6728     if (Changed) return II;
6729   } else {
6730     switch (II->getIntrinsicID()) {
6731     default: break;
6732     case Intrinsic::ppc_altivec_lvx:
6733     case Intrinsic::ppc_altivec_lvxl:
6734     case Intrinsic::x86_sse_loadu_ps:
6735     case Intrinsic::x86_sse2_loadu_pd:
6736     case Intrinsic::x86_sse2_loadu_dq:
6737       // Turn PPC lvx     -> load if the pointer is known aligned.
6738       // Turn X86 loadups -> load if the pointer is known aligned.
6739       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6740         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6741                                       PointerType::get(II->getType()), CI);
6742         return new LoadInst(Ptr);
6743       }
6744       break;
6745     case Intrinsic::ppc_altivec_stvx:
6746     case Intrinsic::ppc_altivec_stvxl:
6747       // Turn stvx -> store if the pointer is known aligned.
6748       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6749         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6750         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
6751                                       OpPtrTy, CI);
6752         return new StoreInst(II->getOperand(1), Ptr);
6753       }
6754       break;
6755     case Intrinsic::x86_sse_storeu_ps:
6756     case Intrinsic::x86_sse2_storeu_pd:
6757     case Intrinsic::x86_sse2_storeu_dq:
6758     case Intrinsic::x86_sse2_storel_dq:
6759       // Turn X86 storeu -> store if the pointer is known aligned.
6760       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6761         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6762         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6763                                       OpPtrTy, CI);
6764         return new StoreInst(II->getOperand(2), Ptr);
6765       }
6766       break;
6767       
6768     case Intrinsic::x86_sse_cvttss2si: {
6769       // These intrinsics only demands the 0th element of its input vector.  If
6770       // we can simplify the input based on that, do so now.
6771       uint64_t UndefElts;
6772       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
6773                                                 UndefElts)) {
6774         II->setOperand(1, V);
6775         return II;
6776       }
6777       break;
6778     }
6779       
6780     case Intrinsic::ppc_altivec_vperm:
6781       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6782       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6783         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6784         
6785         // Check that all of the elements are integer constants or undefs.
6786         bool AllEltsOk = true;
6787         for (unsigned i = 0; i != 16; ++i) {
6788           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
6789               !isa<UndefValue>(Mask->getOperand(i))) {
6790             AllEltsOk = false;
6791             break;
6792           }
6793         }
6794         
6795         if (AllEltsOk) {
6796           // Cast the input vectors to byte vectors.
6797           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
6798                                         II->getOperand(1), Mask->getType(), CI);
6799           Value *Op1 = InsertCastBefore(Instruction::BitCast,
6800                                         II->getOperand(2), Mask->getType(), CI);
6801           Value *Result = UndefValue::get(Op0->getType());
6802           
6803           // Only extract each element once.
6804           Value *ExtractedElts[32];
6805           memset(ExtractedElts, 0, sizeof(ExtractedElts));
6806           
6807           for (unsigned i = 0; i != 16; ++i) {
6808             if (isa<UndefValue>(Mask->getOperand(i)))
6809               continue;
6810             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6811             Idx &= 31;  // Match the hardware behavior.
6812             
6813             if (ExtractedElts[Idx] == 0) {
6814               Instruction *Elt = 
6815                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6816               InsertNewInstBefore(Elt, CI);
6817               ExtractedElts[Idx] = Elt;
6818             }
6819           
6820             // Insert this value into the result vector.
6821             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6822             InsertNewInstBefore(cast<Instruction>(Result), CI);
6823           }
6824           return CastInst::create(Instruction::BitCast, Result, CI.getType());
6825         }
6826       }
6827       break;
6828
6829     case Intrinsic::stackrestore: {
6830       // If the save is right next to the restore, remove the restore.  This can
6831       // happen when variable allocas are DCE'd.
6832       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6833         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6834           BasicBlock::iterator BI = SS;
6835           if (&*++BI == II)
6836             return EraseInstFromFunction(CI);
6837         }
6838       }
6839       
6840       // If the stack restore is in a return/unwind block and if there are no
6841       // allocas or calls between the restore and the return, nuke the restore.
6842       TerminatorInst *TI = II->getParent()->getTerminator();
6843       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6844         BasicBlock::iterator BI = II;
6845         bool CannotRemove = false;
6846         for (++BI; &*BI != TI; ++BI) {
6847           if (isa<AllocaInst>(BI) ||
6848               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6849             CannotRemove = true;
6850             break;
6851           }
6852         }
6853         if (!CannotRemove)
6854           return EraseInstFromFunction(CI);
6855       }
6856       break;
6857     }
6858     }
6859   }
6860
6861   return visitCallSite(II);
6862 }
6863
6864 // InvokeInst simplification
6865 //
6866 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6867   return visitCallSite(&II);
6868 }
6869
6870 // visitCallSite - Improvements for call and invoke instructions.
6871 //
6872 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6873   bool Changed = false;
6874
6875   // If the callee is a constexpr cast of a function, attempt to move the cast
6876   // to the arguments of the call/invoke.
6877   if (transformConstExprCastCall(CS)) return 0;
6878
6879   Value *Callee = CS.getCalledValue();
6880
6881   if (Function *CalleeF = dyn_cast<Function>(Callee))
6882     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6883       Instruction *OldCall = CS.getInstruction();
6884       // If the call and callee calling conventions don't match, this call must
6885       // be unreachable, as the call is undefined.
6886       new StoreInst(ConstantBool::getTrue(),
6887                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6888       if (!OldCall->use_empty())
6889         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6890       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
6891         return EraseInstFromFunction(*OldCall);
6892       return 0;
6893     }
6894
6895   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6896     // This instruction is not reachable, just remove it.  We insert a store to
6897     // undef so that we know that this code is not reachable, despite the fact
6898     // that we can't modify the CFG here.
6899     new StoreInst(ConstantBool::getTrue(),
6900                   UndefValue::get(PointerType::get(Type::BoolTy)),
6901                   CS.getInstruction());
6902
6903     if (!CS.getInstruction()->use_empty())
6904       CS.getInstruction()->
6905         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6906
6907     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6908       // Don't break the CFG, insert a dummy cond branch.
6909       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6910                      ConstantBool::getTrue(), II);
6911     }
6912     return EraseInstFromFunction(*CS.getInstruction());
6913   }
6914
6915   const PointerType *PTy = cast<PointerType>(Callee->getType());
6916   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6917   if (FTy->isVarArg()) {
6918     // See if we can optimize any arguments passed through the varargs area of
6919     // the call.
6920     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6921            E = CS.arg_end(); I != E; ++I)
6922       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6923         // If this cast does not effect the value passed through the varargs
6924         // area, we can eliminate the use of the cast.
6925         Value *Op = CI->getOperand(0);
6926         if (CI->isLosslessCast()) {
6927           *I = Op;
6928           Changed = true;
6929         }
6930       }
6931   }
6932
6933   return Changed ? CS.getInstruction() : 0;
6934 }
6935
6936 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6937 // attempt to move the cast to the arguments of the call/invoke.
6938 //
6939 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6940   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6941   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6942   if (CE->getOpcode() != Instruction::BitCast || 
6943       !isa<Function>(CE->getOperand(0)))
6944     return false;
6945   Function *Callee = cast<Function>(CE->getOperand(0));
6946   Instruction *Caller = CS.getInstruction();
6947
6948   // Okay, this is a cast from a function to a different type.  Unless doing so
6949   // would cause a type conversion of one of our arguments, change this call to
6950   // be a direct call with arguments casted to the appropriate types.
6951   //
6952   const FunctionType *FT = Callee->getFunctionType();
6953   const Type *OldRetTy = Caller->getType();
6954
6955   // Check to see if we are changing the return type...
6956   if (OldRetTy != FT->getReturnType()) {
6957     if (Callee->isExternal() &&
6958         !Caller->use_empty() && 
6959         !(OldRetTy->canLosslesslyBitCastTo(FT->getReturnType()) ||
6960           (isa<PointerType>(FT->getReturnType()) && 
6961            TD->getIntPtrType()->canLosslesslyBitCastTo(OldRetTy)))
6962         )
6963       return false;   // Cannot transform this return value...
6964
6965     // If the callsite is an invoke instruction, and the return value is used by
6966     // a PHI node in a successor, we cannot change the return type of the call
6967     // because there is no place to put the cast instruction (without breaking
6968     // the critical edge).  Bail out in this case.
6969     if (!Caller->use_empty())
6970       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6971         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6972              UI != E; ++UI)
6973           if (PHINode *PN = dyn_cast<PHINode>(*UI))
6974             if (PN->getParent() == II->getNormalDest() ||
6975                 PN->getParent() == II->getUnwindDest())
6976               return false;
6977   }
6978
6979   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6980   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6981
6982   CallSite::arg_iterator AI = CS.arg_begin();
6983   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6984     const Type *ParamTy = FT->getParamType(i);
6985     const Type *ActTy = (*AI)->getType();
6986     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
6987     //Either we can cast directly, or we can upconvert the argument
6988     bool isConvertible = ActTy->canLosslesslyBitCastTo(ParamTy) ||
6989       (ParamTy->isIntegral() && ActTy->isIntegral() &&
6990        ParamTy->isSigned() == ActTy->isSigned() &&
6991        ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6992       (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6993        c->getSExtValue() > 0);
6994     if (Callee->isExternal() && !isConvertible) return false;
6995   }
6996
6997   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6998       Callee->isExternal())
6999     return false;   // Do not delete arguments unless we have a function body...
7000
7001   // Okay, we decided that this is a safe thing to do: go ahead and start
7002   // inserting cast instructions as necessary...
7003   std::vector<Value*> Args;
7004   Args.reserve(NumActualArgs);
7005
7006   AI = CS.arg_begin();
7007   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7008     const Type *ParamTy = FT->getParamType(i);
7009     if ((*AI)->getType() == ParamTy) {
7010       Args.push_back(*AI);
7011     } else {
7012       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7013           (*AI)->getType()->isSigned(), ParamTy, ParamTy->isSigned());
7014       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7015       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7016     }
7017   }
7018
7019   // If the function takes more arguments than the call was taking, add them
7020   // now...
7021   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7022     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7023
7024   // If we are removing arguments to the function, emit an obnoxious warning...
7025   if (FT->getNumParams() < NumActualArgs)
7026     if (!FT->isVarArg()) {
7027       cerr << "WARNING: While resolving call to function '"
7028            << Callee->getName() << "' arguments were dropped!\n";
7029     } else {
7030       // Add all of the arguments in their promoted form to the arg list...
7031       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7032         const Type *PTy = getPromotedType((*AI)->getType());
7033         if (PTy != (*AI)->getType()) {
7034           // Must promote to pass through va_arg area!
7035           Instruction::CastOps opcode = CastInst::getCastOpcode(
7036               *AI, (*AI)->getType()->isSigned(), PTy, PTy->isSigned());
7037           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7038           InsertNewInstBefore(Cast, *Caller);
7039           Args.push_back(Cast);
7040         } else {
7041           Args.push_back(*AI);
7042         }
7043       }
7044     }
7045
7046   if (FT->getReturnType() == Type::VoidTy)
7047     Caller->setName("");   // Void type should not have a name...
7048
7049   Instruction *NC;
7050   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7051     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7052                         Args, Caller->getName(), Caller);
7053     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7054   } else {
7055     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7056     if (cast<CallInst>(Caller)->isTailCall())
7057       cast<CallInst>(NC)->setTailCall();
7058    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7059   }
7060
7061   // Insert a cast of the return type as necessary...
7062   Value *NV = NC;
7063   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7064     if (NV->getType() != Type::VoidTy) {
7065       const Type *CallerTy = Caller->getType();
7066       Instruction::CastOps opcode = CastInst::getCastOpcode(
7067           NC, NC->getType()->isSigned(), CallerTy, CallerTy->isSigned());
7068       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7069
7070       // If this is an invoke instruction, we should insert it after the first
7071       // non-phi, instruction in the normal successor block.
7072       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7073         BasicBlock::iterator I = II->getNormalDest()->begin();
7074         while (isa<PHINode>(I)) ++I;
7075         InsertNewInstBefore(NC, *I);
7076       } else {
7077         // Otherwise, it's a call, just insert cast right after the call instr
7078         InsertNewInstBefore(NC, *Caller);
7079       }
7080       AddUsersToWorkList(*Caller);
7081     } else {
7082       NV = UndefValue::get(Caller->getType());
7083     }
7084   }
7085
7086   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7087     Caller->replaceAllUsesWith(NV);
7088   Caller->getParent()->getInstList().erase(Caller);
7089   removeFromWorkList(Caller);
7090   return true;
7091 }
7092
7093 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7094 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7095 /// and a single binop.
7096 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7097   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7098   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7099          isa<GetElementPtrInst>(FirstInst));
7100   unsigned Opc = FirstInst->getOpcode();
7101   Value *LHSVal = FirstInst->getOperand(0);
7102   Value *RHSVal = FirstInst->getOperand(1);
7103     
7104   const Type *LHSType = LHSVal->getType();
7105   const Type *RHSType = RHSVal->getType();
7106   
7107   // Scan to see if all operands are the same opcode, all have one use, and all
7108   // kill their operands (i.e. the operands have one use).
7109   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7110     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7111     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7112         // Verify type of the LHS matches so we don't fold setcc's of different
7113         // types or GEP's with different index types.
7114         I->getOperand(0)->getType() != LHSType ||
7115         I->getOperand(1)->getType() != RHSType)
7116       return 0;
7117     
7118     // Keep track of which operand needs a phi node.
7119     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7120     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7121   }
7122   
7123   // Otherwise, this is safe to transform, determine if it is profitable.
7124
7125   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7126   // Indexes are often folded into load/store instructions, so we don't want to
7127   // hide them behind a phi.
7128   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7129     return 0;
7130   
7131   Value *InLHS = FirstInst->getOperand(0);
7132   Value *InRHS = FirstInst->getOperand(1);
7133   PHINode *NewLHS = 0, *NewRHS = 0;
7134   if (LHSVal == 0) {
7135     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7136     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7137     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7138     InsertNewInstBefore(NewLHS, PN);
7139     LHSVal = NewLHS;
7140   }
7141   
7142   if (RHSVal == 0) {
7143     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7144     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7145     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7146     InsertNewInstBefore(NewRHS, PN);
7147     RHSVal = NewRHS;
7148   }
7149   
7150   // Add all operands to the new PHIs.
7151   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7152     if (NewLHS) {
7153       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7154       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7155     }
7156     if (NewRHS) {
7157       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7158       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7159     }
7160   }
7161     
7162   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7163     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7164   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7165     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7166   else {
7167     assert(isa<GetElementPtrInst>(FirstInst));
7168     return new GetElementPtrInst(LHSVal, RHSVal);
7169   }
7170 }
7171
7172 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7173 /// of the block that defines it.  This means that it must be obvious the value
7174 /// of the load is not changed from the point of the load to the end of the
7175 /// block it is in.
7176 static bool isSafeToSinkLoad(LoadInst *L) {
7177   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7178   
7179   for (++BBI; BBI != E; ++BBI)
7180     if (BBI->mayWriteToMemory())
7181       return false;
7182   return true;
7183 }
7184
7185
7186 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7187 // operator and they all are only used by the PHI, PHI together their
7188 // inputs, and do the operation once, to the result of the PHI.
7189 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7190   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7191
7192   // Scan the instruction, looking for input operations that can be folded away.
7193   // If all input operands to the phi are the same instruction (e.g. a cast from
7194   // the same type or "+42") we can pull the operation through the PHI, reducing
7195   // code size and simplifying code.
7196   Constant *ConstantOp = 0;
7197   const Type *CastSrcTy = 0;
7198   bool isVolatile = false;
7199   if (isa<CastInst>(FirstInst)) {
7200     CastSrcTy = FirstInst->getOperand(0)->getType();
7201   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
7202     // Can fold binop or shift here if the RHS is a constant, otherwise call
7203     // FoldPHIArgBinOpIntoPHI.
7204     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7205     if (ConstantOp == 0)
7206       return FoldPHIArgBinOpIntoPHI(PN);
7207   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7208     isVolatile = LI->isVolatile();
7209     // We can't sink the load if the loaded value could be modified between the
7210     // load and the PHI.
7211     if (LI->getParent() != PN.getIncomingBlock(0) ||
7212         !isSafeToSinkLoad(LI))
7213       return 0;
7214   } else if (isa<GetElementPtrInst>(FirstInst)) {
7215     if (FirstInst->getNumOperands() == 2)
7216       return FoldPHIArgBinOpIntoPHI(PN);
7217     // Can't handle general GEPs yet.
7218     return 0;
7219   } else {
7220     return 0;  // Cannot fold this operation.
7221   }
7222
7223   // Check to see if all arguments are the same operation.
7224   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7225     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7226     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7227     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
7228       return 0;
7229     if (CastSrcTy) {
7230       if (I->getOperand(0)->getType() != CastSrcTy)
7231         return 0;  // Cast operation must match.
7232     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7233       // We can't sink the load if the loaded value could be modified between the
7234       // load and the PHI.
7235       if (LI->isVolatile() != isVolatile ||
7236           LI->getParent() != PN.getIncomingBlock(i) ||
7237           !isSafeToSinkLoad(LI))
7238         return 0;
7239     } else if (I->getOperand(1) != ConstantOp) {
7240       return 0;
7241     }
7242   }
7243
7244   // Okay, they are all the same operation.  Create a new PHI node of the
7245   // correct type, and PHI together all of the LHS's of the instructions.
7246   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7247                                PN.getName()+".in");
7248   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7249
7250   Value *InVal = FirstInst->getOperand(0);
7251   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7252
7253   // Add all operands to the new PHI.
7254   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7255     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7256     if (NewInVal != InVal)
7257       InVal = 0;
7258     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7259   }
7260
7261   Value *PhiVal;
7262   if (InVal) {
7263     // The new PHI unions all of the same values together.  This is really
7264     // common, so we handle it intelligently here for compile-time speed.
7265     PhiVal = InVal;
7266     delete NewPN;
7267   } else {
7268     InsertNewInstBefore(NewPN, PN);
7269     PhiVal = NewPN;
7270   }
7271
7272   // Insert and return the new operation.
7273   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7274     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7275   else if (isa<LoadInst>(FirstInst))
7276     return new LoadInst(PhiVal, "", isVolatile);
7277   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7278     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7279   else
7280     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7281                          PhiVal, ConstantOp);
7282 }
7283
7284 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7285 /// that is dead.
7286 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7287   if (PN->use_empty()) return true;
7288   if (!PN->hasOneUse()) return false;
7289
7290   // Remember this node, and if we find the cycle, return.
7291   if (!PotentiallyDeadPHIs.insert(PN).second)
7292     return true;
7293
7294   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7295     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7296
7297   return false;
7298 }
7299
7300 // PHINode simplification
7301 //
7302 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7303   // If LCSSA is around, don't mess with Phi nodes
7304   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7305   
7306   if (Value *V = PN.hasConstantValue())
7307     return ReplaceInstUsesWith(PN, V);
7308
7309   // If all PHI operands are the same operation, pull them through the PHI,
7310   // reducing code size.
7311   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7312       PN.getIncomingValue(0)->hasOneUse())
7313     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7314       return Result;
7315
7316   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7317   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7318   // PHI)... break the cycle.
7319   if (PN.hasOneUse())
7320     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7321       std::set<PHINode*> PotentiallyDeadPHIs;
7322       PotentiallyDeadPHIs.insert(&PN);
7323       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7324         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7325     }
7326
7327   return 0;
7328 }
7329
7330 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7331                                    Instruction *InsertPoint,
7332                                    InstCombiner *IC) {
7333   unsigned PtrSize = DTy->getPrimitiveSize();
7334   unsigned VTySize = V->getType()->getPrimitiveSize();
7335   // We must cast correctly to the pointer type. Ensure that we
7336   // sign extend the integer value if it is smaller as this is
7337   // used for address computation.
7338   Instruction::CastOps opcode = 
7339      (VTySize < PtrSize ? Instruction::SExt :
7340       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7341   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7342 }
7343
7344
7345 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7346   Value *PtrOp = GEP.getOperand(0);
7347   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7348   // If so, eliminate the noop.
7349   if (GEP.getNumOperands() == 1)
7350     return ReplaceInstUsesWith(GEP, PtrOp);
7351
7352   if (isa<UndefValue>(GEP.getOperand(0)))
7353     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7354
7355   bool HasZeroPointerIndex = false;
7356   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7357     HasZeroPointerIndex = C->isNullValue();
7358
7359   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7360     return ReplaceInstUsesWith(GEP, PtrOp);
7361
7362   // Eliminate unneeded casts for indices.
7363   bool MadeChange = false;
7364   gep_type_iterator GTI = gep_type_begin(GEP);
7365   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7366     if (isa<SequentialType>(*GTI)) {
7367       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7368         Value *Src = CI->getOperand(0);
7369         const Type *SrcTy = Src->getType();
7370         const Type *DestTy = CI->getType();
7371         if (Src->getType()->isInteger()) {
7372           if (SrcTy->getPrimitiveSizeInBits() ==
7373                        DestTy->getPrimitiveSizeInBits()) {
7374             // We can always eliminate a cast from ulong or long to the other.
7375             // We can always eliminate a cast from uint to int or the other on
7376             // 32-bit pointer platforms.
7377             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7378               MadeChange = true;
7379               GEP.setOperand(i, Src);
7380             }
7381           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7382                      SrcTy->getPrimitiveSize() == 4) {
7383             // We can always eliminate a cast from int to [u]long.  We can
7384             // eliminate a cast from uint to [u]long iff the target is a 32-bit
7385             // pointer target.
7386             if (SrcTy->isSigned() ||
7387                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7388               MadeChange = true;
7389               GEP.setOperand(i, Src);
7390             }
7391           }
7392         }
7393       }
7394       // If we are using a wider index than needed for this platform, shrink it
7395       // to what we need.  If the incoming value needs a cast instruction,
7396       // insert it.  This explicit cast can make subsequent optimizations more
7397       // obvious.
7398       Value *Op = GEP.getOperand(i);
7399       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7400         if (Constant *C = dyn_cast<Constant>(Op)) {
7401           GEP.setOperand(i, ConstantExpr::getTrunc(C,
7402                                      TD->getIntPtrType()->getSignedVersion()));
7403           MadeChange = true;
7404         } else {
7405           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7406                                 GEP);
7407           GEP.setOperand(i, Op);
7408           MadeChange = true;
7409         }
7410
7411       // If this is a constant idx, make sure to canonicalize it to be a signed
7412       // operand, otherwise CSE and other optimizations are pessimized.
7413       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7414         if (CUI->getType()->isUnsigned()) {
7415           GEP.setOperand(i, 
7416             ConstantExpr::getBitCast(CUI, CUI->getType()->getSignedVersion()));
7417           MadeChange = true;
7418         }
7419     }
7420   if (MadeChange) return &GEP;
7421
7422   // Combine Indices - If the source pointer to this getelementptr instruction
7423   // is a getelementptr instruction, combine the indices of the two
7424   // getelementptr instructions into a single instruction.
7425   //
7426   std::vector<Value*> SrcGEPOperands;
7427   if (User *Src = dyn_castGetElementPtr(PtrOp))
7428     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7429
7430   if (!SrcGEPOperands.empty()) {
7431     // Note that if our source is a gep chain itself that we wait for that
7432     // chain to be resolved before we perform this transformation.  This
7433     // avoids us creating a TON of code in some cases.
7434     //
7435     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7436         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7437       return 0;   // Wait until our source is folded to completion.
7438
7439     std::vector<Value *> Indices;
7440
7441     // Find out whether the last index in the source GEP is a sequential idx.
7442     bool EndsWithSequential = false;
7443     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7444            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7445       EndsWithSequential = !isa<StructType>(*I);
7446
7447     // Can we combine the two pointer arithmetics offsets?
7448     if (EndsWithSequential) {
7449       // Replace: gep (gep %P, long B), long A, ...
7450       // With:    T = long A+B; gep %P, T, ...
7451       //
7452       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7453       if (SO1 == Constant::getNullValue(SO1->getType())) {
7454         Sum = GO1;
7455       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7456         Sum = SO1;
7457       } else {
7458         // If they aren't the same type, convert both to an integer of the
7459         // target's pointer size.
7460         if (SO1->getType() != GO1->getType()) {
7461           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7462             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7463           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7464             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7465           } else {
7466             unsigned PS = TD->getPointerSize();
7467             if (SO1->getType()->getPrimitiveSize() == PS) {
7468               // Convert GO1 to SO1's type.
7469               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7470
7471             } else if (GO1->getType()->getPrimitiveSize() == PS) {
7472               // Convert SO1 to GO1's type.
7473               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7474             } else {
7475               const Type *PT = TD->getIntPtrType();
7476               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7477               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7478             }
7479           }
7480         }
7481         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7482           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7483         else {
7484           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7485           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7486         }
7487       }
7488
7489       // Recycle the GEP we already have if possible.
7490       if (SrcGEPOperands.size() == 2) {
7491         GEP.setOperand(0, SrcGEPOperands[0]);
7492         GEP.setOperand(1, Sum);
7493         return &GEP;
7494       } else {
7495         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7496                        SrcGEPOperands.end()-1);
7497         Indices.push_back(Sum);
7498         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7499       }
7500     } else if (isa<Constant>(*GEP.idx_begin()) &&
7501                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7502                SrcGEPOperands.size() != 1) {
7503       // Otherwise we can do the fold if the first index of the GEP is a zero
7504       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7505                      SrcGEPOperands.end());
7506       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7507     }
7508
7509     if (!Indices.empty())
7510       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7511
7512   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7513     // GEP of global variable.  If all of the indices for this GEP are
7514     // constants, we can promote this to a constexpr instead of an instruction.
7515
7516     // Scan for nonconstants...
7517     std::vector<Constant*> Indices;
7518     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7519     for (; I != E && isa<Constant>(*I); ++I)
7520       Indices.push_back(cast<Constant>(*I));
7521
7522     if (I == E) {  // If they are all constants...
7523       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7524
7525       // Replace all uses of the GEP with the new constexpr...
7526       return ReplaceInstUsesWith(GEP, CE);
7527     }
7528   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7529     if (!isa<PointerType>(X->getType())) {
7530       // Not interesting.  Source pointer must be a cast from pointer.
7531     } else if (HasZeroPointerIndex) {
7532       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7533       // into     : GEP [10 x ubyte]* X, long 0, ...
7534       //
7535       // This occurs when the program declares an array extern like "int X[];"
7536       //
7537       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7538       const PointerType *XTy = cast<PointerType>(X->getType());
7539       if (const ArrayType *XATy =
7540           dyn_cast<ArrayType>(XTy->getElementType()))
7541         if (const ArrayType *CATy =
7542             dyn_cast<ArrayType>(CPTy->getElementType()))
7543           if (CATy->getElementType() == XATy->getElementType()) {
7544             // At this point, we know that the cast source type is a pointer
7545             // to an array of the same type as the destination pointer
7546             // array.  Because the array type is never stepped over (there
7547             // is a leading zero) we can fold the cast into this GEP.
7548             GEP.setOperand(0, X);
7549             return &GEP;
7550           }
7551     } else if (GEP.getNumOperands() == 2) {
7552       // Transform things like:
7553       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7554       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7555       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7556       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7557       if (isa<ArrayType>(SrcElTy) &&
7558           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7559           TD->getTypeSize(ResElTy)) {
7560         Value *V = InsertNewInstBefore(
7561                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7562                                      GEP.getOperand(1), GEP.getName()), GEP);
7563         // V and GEP are both pointer types --> BitCast
7564         return new BitCastInst(V, GEP.getType());
7565       }
7566       
7567       // Transform things like:
7568       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7569       //   (where tmp = 8*tmp2) into:
7570       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7571       
7572       if (isa<ArrayType>(SrcElTy) &&
7573           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7574         uint64_t ArrayEltSize =
7575             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7576         
7577         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7578         // allow either a mul, shift, or constant here.
7579         Value *NewIdx = 0;
7580         ConstantInt *Scale = 0;
7581         if (ArrayEltSize == 1) {
7582           NewIdx = GEP.getOperand(1);
7583           Scale = ConstantInt::get(NewIdx->getType(), 1);
7584         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7585           NewIdx = ConstantInt::get(CI->getType(), 1);
7586           Scale = CI;
7587         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7588           if (Inst->getOpcode() == Instruction::Shl &&
7589               isa<ConstantInt>(Inst->getOperand(1))) {
7590             unsigned ShAmt =
7591               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7592             if (Inst->getType()->isSigned())
7593               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7594             else
7595               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7596             NewIdx = Inst->getOperand(0);
7597           } else if (Inst->getOpcode() == Instruction::Mul &&
7598                      isa<ConstantInt>(Inst->getOperand(1))) {
7599             Scale = cast<ConstantInt>(Inst->getOperand(1));
7600             NewIdx = Inst->getOperand(0);
7601           }
7602         }
7603
7604         // If the index will be to exactly the right offset with the scale taken
7605         // out, perform the transformation.
7606         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7607           if (isa<ConstantInt>(Scale))
7608             Scale = ConstantInt::get(Scale->getType(),
7609                                       Scale->getZExtValue() / ArrayEltSize);
7610           if (Scale->getZExtValue() != 1) {
7611             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7612                                                        true /*SExt*/);
7613             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7614             NewIdx = InsertNewInstBefore(Sc, GEP);
7615           }
7616
7617           // Insert the new GEP instruction.
7618           Instruction *NewGEP =
7619             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7620                                   NewIdx, GEP.getName());
7621           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7622           // The NewGEP must be pointer typed, so must the old one -> BitCast
7623           return new BitCastInst(NewGEP, GEP.getType());
7624         }
7625       }
7626     }
7627   }
7628
7629   return 0;
7630 }
7631
7632 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7633   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7634   if (AI.isArrayAllocation())    // Check C != 1
7635     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7636       const Type *NewTy = 
7637         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7638       AllocationInst *New = 0;
7639
7640       // Create and insert the replacement instruction...
7641       if (isa<MallocInst>(AI))
7642         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7643       else {
7644         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7645         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7646       }
7647
7648       InsertNewInstBefore(New, AI);
7649
7650       // Scan to the end of the allocation instructions, to skip over a block of
7651       // allocas if possible...
7652       //
7653       BasicBlock::iterator It = New;
7654       while (isa<AllocationInst>(*It)) ++It;
7655
7656       // Now that I is pointing to the first non-allocation-inst in the block,
7657       // insert our getelementptr instruction...
7658       //
7659       Value *NullIdx = Constant::getNullValue(Type::IntTy);
7660       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7661                                        New->getName()+".sub", It);
7662
7663       // Now make everything use the getelementptr instead of the original
7664       // allocation.
7665       return ReplaceInstUsesWith(AI, V);
7666     } else if (isa<UndefValue>(AI.getArraySize())) {
7667       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7668     }
7669
7670   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7671   // Note that we only do this for alloca's, because malloc should allocate and
7672   // return a unique pointer, even for a zero byte allocation.
7673   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7674       TD->getTypeSize(AI.getAllocatedType()) == 0)
7675     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7676
7677   return 0;
7678 }
7679
7680 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7681   Value *Op = FI.getOperand(0);
7682
7683   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7684   if (CastInst *CI = dyn_cast<CastInst>(Op))
7685     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7686       FI.setOperand(0, CI->getOperand(0));
7687       return &FI;
7688     }
7689
7690   // free undef -> unreachable.
7691   if (isa<UndefValue>(Op)) {
7692     // Insert a new store to null because we cannot modify the CFG here.
7693     new StoreInst(ConstantBool::getTrue(),
7694                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7695     return EraseInstFromFunction(FI);
7696   }
7697
7698   // If we have 'free null' delete the instruction.  This can happen in stl code
7699   // when lots of inlining happens.
7700   if (isa<ConstantPointerNull>(Op))
7701     return EraseInstFromFunction(FI);
7702
7703   return 0;
7704 }
7705
7706
7707 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7708 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7709   User *CI = cast<User>(LI.getOperand(0));
7710   Value *CastOp = CI->getOperand(0);
7711
7712   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7713   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7714     const Type *SrcPTy = SrcTy->getElementType();
7715
7716     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7717         isa<PackedType>(DestPTy)) {
7718       // If the source is an array, the code below will not succeed.  Check to
7719       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7720       // constants.
7721       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7722         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7723           if (ASrcTy->getNumElements() != 0) {
7724             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7725             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7726             SrcTy = cast<PointerType>(CastOp->getType());
7727             SrcPTy = SrcTy->getElementType();
7728           }
7729
7730       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7731            isa<PackedType>(SrcPTy)) &&
7732           // Do not allow turning this into a load of an integer, which is then
7733           // casted to a pointer, this pessimizes pointer analysis a lot.
7734           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7735           IC.getTargetData().getTypeSize(SrcPTy) ==
7736                IC.getTargetData().getTypeSize(DestPTy)) {
7737
7738         // Okay, we are casting from one integer or pointer type to another of
7739         // the same size.  Instead of casting the pointer before the load, cast
7740         // the result of the loaded value.
7741         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7742                                                              CI->getName(),
7743                                                          LI.isVolatile()),LI);
7744         // Now cast the result of the load.
7745         return new BitCastInst(NewLoad, LI.getType());
7746       }
7747     }
7748   }
7749   return 0;
7750 }
7751
7752 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7753 /// from this value cannot trap.  If it is not obviously safe to load from the
7754 /// specified pointer, we do a quick local scan of the basic block containing
7755 /// ScanFrom, to determine if the address is already accessed.
7756 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7757   // If it is an alloca or global variable, it is always safe to load from.
7758   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7759
7760   // Otherwise, be a little bit agressive by scanning the local block where we
7761   // want to check to see if the pointer is already being loaded or stored
7762   // from/to.  If so, the previous load or store would have already trapped,
7763   // so there is no harm doing an extra load (also, CSE will later eliminate
7764   // the load entirely).
7765   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7766
7767   while (BBI != E) {
7768     --BBI;
7769
7770     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7771       if (LI->getOperand(0) == V) return true;
7772     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7773       if (SI->getOperand(1) == V) return true;
7774
7775   }
7776   return false;
7777 }
7778
7779 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7780   Value *Op = LI.getOperand(0);
7781
7782   // load (cast X) --> cast (load X) iff safe
7783   if (isa<CastInst>(Op))
7784     if (Instruction *Res = InstCombineLoadCast(*this, LI))
7785       return Res;
7786
7787   // None of the following transforms are legal for volatile loads.
7788   if (LI.isVolatile()) return 0;
7789   
7790   if (&LI.getParent()->front() != &LI) {
7791     BasicBlock::iterator BBI = &LI; --BBI;
7792     // If the instruction immediately before this is a store to the same
7793     // address, do a simple form of store->load forwarding.
7794     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7795       if (SI->getOperand(1) == LI.getOperand(0))
7796         return ReplaceInstUsesWith(LI, SI->getOperand(0));
7797     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7798       if (LIB->getOperand(0) == LI.getOperand(0))
7799         return ReplaceInstUsesWith(LI, LIB);
7800   }
7801
7802   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7803     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7804         isa<UndefValue>(GEPI->getOperand(0))) {
7805       // Insert a new store to null instruction before the load to indicate
7806       // that this code is not reachable.  We do this instead of inserting
7807       // an unreachable instruction directly because we cannot modify the
7808       // CFG.
7809       new StoreInst(UndefValue::get(LI.getType()),
7810                     Constant::getNullValue(Op->getType()), &LI);
7811       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7812     }
7813
7814   if (Constant *C = dyn_cast<Constant>(Op)) {
7815     // load null/undef -> undef
7816     if ((C->isNullValue() || isa<UndefValue>(C))) {
7817       // Insert a new store to null instruction before the load to indicate that
7818       // this code is not reachable.  We do this instead of inserting an
7819       // unreachable instruction directly because we cannot modify the CFG.
7820       new StoreInst(UndefValue::get(LI.getType()),
7821                     Constant::getNullValue(Op->getType()), &LI);
7822       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7823     }
7824
7825     // Instcombine load (constant global) into the value loaded.
7826     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7827       if (GV->isConstant() && !GV->isExternal())
7828         return ReplaceInstUsesWith(LI, GV->getInitializer());
7829
7830     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7831     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7832       if (CE->getOpcode() == Instruction::GetElementPtr) {
7833         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7834           if (GV->isConstant() && !GV->isExternal())
7835             if (Constant *V = 
7836                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7837               return ReplaceInstUsesWith(LI, V);
7838         if (CE->getOperand(0)->isNullValue()) {
7839           // Insert a new store to null instruction before the load to indicate
7840           // that this code is not reachable.  We do this instead of inserting
7841           // an unreachable instruction directly because we cannot modify the
7842           // CFG.
7843           new StoreInst(UndefValue::get(LI.getType()),
7844                         Constant::getNullValue(Op->getType()), &LI);
7845           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7846         }
7847
7848       } else if (CE->isCast()) {
7849         if (Instruction *Res = InstCombineLoadCast(*this, LI))
7850           return Res;
7851       }
7852   }
7853
7854   if (Op->hasOneUse()) {
7855     // Change select and PHI nodes to select values instead of addresses: this
7856     // helps alias analysis out a lot, allows many others simplifications, and
7857     // exposes redundancy in the code.
7858     //
7859     // Note that we cannot do the transformation unless we know that the
7860     // introduced loads cannot trap!  Something like this is valid as long as
7861     // the condition is always false: load (select bool %C, int* null, int* %G),
7862     // but it would not be valid if we transformed it to load from null
7863     // unconditionally.
7864     //
7865     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7866       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
7867       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7868           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7869         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7870                                      SI->getOperand(1)->getName()+".val"), LI);
7871         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7872                                      SI->getOperand(2)->getName()+".val"), LI);
7873         return new SelectInst(SI->getCondition(), V1, V2);
7874       }
7875
7876       // load (select (cond, null, P)) -> load P
7877       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7878         if (C->isNullValue()) {
7879           LI.setOperand(0, SI->getOperand(2));
7880           return &LI;
7881         }
7882
7883       // load (select (cond, P, null)) -> load P
7884       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7885         if (C->isNullValue()) {
7886           LI.setOperand(0, SI->getOperand(1));
7887           return &LI;
7888         }
7889     }
7890   }
7891   return 0;
7892 }
7893
7894 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7895 /// when possible.
7896 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7897   User *CI = cast<User>(SI.getOperand(1));
7898   Value *CastOp = CI->getOperand(0);
7899
7900   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7901   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7902     const Type *SrcPTy = SrcTy->getElementType();
7903
7904     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7905       // If the source is an array, the code below will not succeed.  Check to
7906       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7907       // constants.
7908       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7909         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7910           if (ASrcTy->getNumElements() != 0) {
7911             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7912             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7913             SrcTy = cast<PointerType>(CastOp->getType());
7914             SrcPTy = SrcTy->getElementType();
7915           }
7916
7917       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7918           IC.getTargetData().getTypeSize(SrcPTy) ==
7919                IC.getTargetData().getTypeSize(DestPTy)) {
7920
7921         // Okay, we are casting from one integer or pointer type to another of
7922         // the same size.  Instead of casting the pointer before the store, cast
7923         // the value to be stored.
7924         Value *NewCast;
7925         Instruction::CastOps opcode = Instruction::BitCast;
7926         Value *SIOp0 = SI.getOperand(0);
7927         if (isa<PointerType>(SrcPTy)) {
7928           if (SIOp0->getType()->isIntegral())
7929             opcode = Instruction::IntToPtr;
7930         } else if (SrcPTy->isIntegral()) {
7931           if (isa<PointerType>(SIOp0->getType()))
7932             opcode = Instruction::PtrToInt;
7933         }
7934         if (Constant *C = dyn_cast<Constant>(SIOp0))
7935           NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
7936         else
7937           NewCast = IC.InsertNewInstBefore(
7938             CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
7939         return new StoreInst(NewCast, CastOp);
7940       }
7941     }
7942   }
7943   return 0;
7944 }
7945
7946 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7947   Value *Val = SI.getOperand(0);
7948   Value *Ptr = SI.getOperand(1);
7949
7950   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
7951     EraseInstFromFunction(SI);
7952     ++NumCombined;
7953     return 0;
7954   }
7955
7956   // Do really simple DSE, to catch cases where there are several consequtive
7957   // stores to the same location, separated by a few arithmetic operations. This
7958   // situation often occurs with bitfield accesses.
7959   BasicBlock::iterator BBI = &SI;
7960   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7961        --ScanInsts) {
7962     --BBI;
7963     
7964     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7965       // Prev store isn't volatile, and stores to the same location?
7966       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7967         ++NumDeadStore;
7968         ++BBI;
7969         EraseInstFromFunction(*PrevSI);
7970         continue;
7971       }
7972       break;
7973     }
7974     
7975     // If this is a load, we have to stop.  However, if the loaded value is from
7976     // the pointer we're loading and is producing the pointer we're storing,
7977     // then *this* store is dead (X = load P; store X -> P).
7978     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7979       if (LI == Val && LI->getOperand(0) == Ptr) {
7980         EraseInstFromFunction(SI);
7981         ++NumCombined;
7982         return 0;
7983       }
7984       // Otherwise, this is a load from some other location.  Stores before it
7985       // may not be dead.
7986       break;
7987     }
7988     
7989     // Don't skip over loads or things that can modify memory.
7990     if (BBI->mayWriteToMemory())
7991       break;
7992   }
7993   
7994   
7995   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
7996
7997   // store X, null    -> turns into 'unreachable' in SimplifyCFG
7998   if (isa<ConstantPointerNull>(Ptr)) {
7999     if (!isa<UndefValue>(Val)) {
8000       SI.setOperand(0, UndefValue::get(Val->getType()));
8001       if (Instruction *U = dyn_cast<Instruction>(Val))
8002         WorkList.push_back(U);  // Dropped a use.
8003       ++NumCombined;
8004     }
8005     return 0;  // Do not modify these!
8006   }
8007
8008   // store undef, Ptr -> noop
8009   if (isa<UndefValue>(Val)) {
8010     EraseInstFromFunction(SI);
8011     ++NumCombined;
8012     return 0;
8013   }
8014
8015   // If the pointer destination is a cast, see if we can fold the cast into the
8016   // source instead.
8017   if (isa<CastInst>(Ptr))
8018     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8019       return Res;
8020   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8021     if (CE->isCast())
8022       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8023         return Res;
8024
8025   
8026   // If this store is the last instruction in the basic block, and if the block
8027   // ends with an unconditional branch, try to move it to the successor block.
8028   BBI = &SI; ++BBI;
8029   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8030     if (BI->isUnconditional()) {
8031       // Check to see if the successor block has exactly two incoming edges.  If
8032       // so, see if the other predecessor contains a store to the same location.
8033       // if so, insert a PHI node (if needed) and move the stores down.
8034       BasicBlock *Dest = BI->getSuccessor(0);
8035
8036       pred_iterator PI = pred_begin(Dest);
8037       BasicBlock *Other = 0;
8038       if (*PI != BI->getParent())
8039         Other = *PI;
8040       ++PI;
8041       if (PI != pred_end(Dest)) {
8042         if (*PI != BI->getParent())
8043           if (Other)
8044             Other = 0;
8045           else
8046             Other = *PI;
8047         if (++PI != pred_end(Dest))
8048           Other = 0;
8049       }
8050       if (Other) {  // If only one other pred...
8051         BBI = Other->getTerminator();
8052         // Make sure this other block ends in an unconditional branch and that
8053         // there is an instruction before the branch.
8054         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8055             BBI != Other->begin()) {
8056           --BBI;
8057           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8058           
8059           // If this instruction is a store to the same location.
8060           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8061             // Okay, we know we can perform this transformation.  Insert a PHI
8062             // node now if we need it.
8063             Value *MergedVal = OtherStore->getOperand(0);
8064             if (MergedVal != SI.getOperand(0)) {
8065               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8066               PN->reserveOperandSpace(2);
8067               PN->addIncoming(SI.getOperand(0), SI.getParent());
8068               PN->addIncoming(OtherStore->getOperand(0), Other);
8069               MergedVal = InsertNewInstBefore(PN, Dest->front());
8070             }
8071             
8072             // Advance to a place where it is safe to insert the new store and
8073             // insert it.
8074             BBI = Dest->begin();
8075             while (isa<PHINode>(BBI)) ++BBI;
8076             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8077                                               OtherStore->isVolatile()), *BBI);
8078
8079             // Nuke the old stores.
8080             EraseInstFromFunction(SI);
8081             EraseInstFromFunction(*OtherStore);
8082             ++NumCombined;
8083             return 0;
8084           }
8085         }
8086       }
8087     }
8088   
8089   return 0;
8090 }
8091
8092
8093 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8094   // Change br (not X), label True, label False to: br X, label False, True
8095   Value *X = 0;
8096   BasicBlock *TrueDest;
8097   BasicBlock *FalseDest;
8098   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8099       !isa<Constant>(X)) {
8100     // Swap Destinations and condition...
8101     BI.setCondition(X);
8102     BI.setSuccessor(0, FalseDest);
8103     BI.setSuccessor(1, TrueDest);
8104     return &BI;
8105   }
8106
8107   // Cannonicalize setne -> seteq
8108   Instruction::BinaryOps Op; Value *Y;
8109   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
8110                       TrueDest, FalseDest)))
8111     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
8112          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
8113       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
8114       std::string Name = I->getName(); I->setName("");
8115       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
8116       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
8117       // Swap Destinations and condition...
8118       BI.setCondition(NewSCC);
8119       BI.setSuccessor(0, FalseDest);
8120       BI.setSuccessor(1, TrueDest);
8121       removeFromWorkList(I);
8122       I->getParent()->getInstList().erase(I);
8123       WorkList.push_back(cast<Instruction>(NewSCC));
8124       return &BI;
8125     }
8126
8127   return 0;
8128 }
8129
8130 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8131   Value *Cond = SI.getCondition();
8132   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8133     if (I->getOpcode() == Instruction::Add)
8134       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8135         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8136         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8137           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8138                                                 AddRHS));
8139         SI.setOperand(0, I->getOperand(0));
8140         WorkList.push_back(I);
8141         return &SI;
8142       }
8143   }
8144   return 0;
8145 }
8146
8147 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8148 /// is to leave as a vector operation.
8149 static bool CheapToScalarize(Value *V, bool isConstant) {
8150   if (isa<ConstantAggregateZero>(V)) 
8151     return true;
8152   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8153     if (isConstant) return true;
8154     // If all elts are the same, we can extract.
8155     Constant *Op0 = C->getOperand(0);
8156     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8157       if (C->getOperand(i) != Op0)
8158         return false;
8159     return true;
8160   }
8161   Instruction *I = dyn_cast<Instruction>(V);
8162   if (!I) return false;
8163   
8164   // Insert element gets simplified to the inserted element or is deleted if
8165   // this is constant idx extract element and its a constant idx insertelt.
8166   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8167       isa<ConstantInt>(I->getOperand(2)))
8168     return true;
8169   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8170     return true;
8171   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8172     if (BO->hasOneUse() &&
8173         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8174          CheapToScalarize(BO->getOperand(1), isConstant)))
8175       return true;
8176   
8177   return false;
8178 }
8179
8180 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8181 /// elements into values that are larger than the #elts in the input.
8182 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8183   unsigned NElts = SVI->getType()->getNumElements();
8184   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8185     return std::vector<unsigned>(NElts, 0);
8186   if (isa<UndefValue>(SVI->getOperand(2)))
8187     return std::vector<unsigned>(NElts, 2*NElts);
8188
8189   std::vector<unsigned> Result;
8190   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8191   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8192     if (isa<UndefValue>(CP->getOperand(i)))
8193       Result.push_back(NElts*2);  // undef -> 8
8194     else
8195       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8196   return Result;
8197 }
8198
8199 /// FindScalarElement - Given a vector and an element number, see if the scalar
8200 /// value is already around as a register, for example if it were inserted then
8201 /// extracted from the vector.
8202 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8203   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8204   const PackedType *PTy = cast<PackedType>(V->getType());
8205   unsigned Width = PTy->getNumElements();
8206   if (EltNo >= Width)  // Out of range access.
8207     return UndefValue::get(PTy->getElementType());
8208   
8209   if (isa<UndefValue>(V))
8210     return UndefValue::get(PTy->getElementType());
8211   else if (isa<ConstantAggregateZero>(V))
8212     return Constant::getNullValue(PTy->getElementType());
8213   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8214     return CP->getOperand(EltNo);
8215   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8216     // If this is an insert to a variable element, we don't know what it is.
8217     if (!isa<ConstantInt>(III->getOperand(2))) 
8218       return 0;
8219     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8220     
8221     // If this is an insert to the element we are looking for, return the
8222     // inserted value.
8223     if (EltNo == IIElt) 
8224       return III->getOperand(1);
8225     
8226     // Otherwise, the insertelement doesn't modify the value, recurse on its
8227     // vector input.
8228     return FindScalarElement(III->getOperand(0), EltNo);
8229   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8230     unsigned InEl = getShuffleMask(SVI)[EltNo];
8231     if (InEl < Width)
8232       return FindScalarElement(SVI->getOperand(0), InEl);
8233     else if (InEl < Width*2)
8234       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8235     else
8236       return UndefValue::get(PTy->getElementType());
8237   }
8238   
8239   // Otherwise, we don't know.
8240   return 0;
8241 }
8242
8243 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8244
8245   // If packed val is undef, replace extract with scalar undef.
8246   if (isa<UndefValue>(EI.getOperand(0)))
8247     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8248
8249   // If packed val is constant 0, replace extract with scalar 0.
8250   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8251     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8252   
8253   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8254     // If packed val is constant with uniform operands, replace EI
8255     // with that operand
8256     Constant *op0 = C->getOperand(0);
8257     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8258       if (C->getOperand(i) != op0) {
8259         op0 = 0; 
8260         break;
8261       }
8262     if (op0)
8263       return ReplaceInstUsesWith(EI, op0);
8264   }
8265   
8266   // If extracting a specified index from the vector, see if we can recursively
8267   // find a previously computed scalar that was inserted into the vector.
8268   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8269     // This instruction only demands the single element from the input vector.
8270     // If the input vector has a single use, simplify it based on this use
8271     // property.
8272     uint64_t IndexVal = IdxC->getZExtValue();
8273     if (EI.getOperand(0)->hasOneUse()) {
8274       uint64_t UndefElts;
8275       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8276                                                 1 << IndexVal,
8277                                                 UndefElts)) {
8278         EI.setOperand(0, V);
8279         return &EI;
8280       }
8281     }
8282     
8283     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8284       return ReplaceInstUsesWith(EI, Elt);
8285   }
8286   
8287   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8288     if (I->hasOneUse()) {
8289       // Push extractelement into predecessor operation if legal and
8290       // profitable to do so
8291       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8292         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8293         if (CheapToScalarize(BO, isConstantElt)) {
8294           ExtractElementInst *newEI0 = 
8295             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8296                                    EI.getName()+".lhs");
8297           ExtractElementInst *newEI1 =
8298             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8299                                    EI.getName()+".rhs");
8300           InsertNewInstBefore(newEI0, EI);
8301           InsertNewInstBefore(newEI1, EI);
8302           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8303         }
8304       } else if (isa<LoadInst>(I)) {
8305         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8306                                       PointerType::get(EI.getType()), EI);
8307         GetElementPtrInst *GEP = 
8308           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8309         InsertNewInstBefore(GEP, EI);
8310         return new LoadInst(GEP);
8311       }
8312     }
8313     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8314       // Extracting the inserted element?
8315       if (IE->getOperand(2) == EI.getOperand(1))
8316         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8317       // If the inserted and extracted elements are constants, they must not
8318       // be the same value, extract from the pre-inserted value instead.
8319       if (isa<Constant>(IE->getOperand(2)) &&
8320           isa<Constant>(EI.getOperand(1))) {
8321         AddUsesToWorkList(EI);
8322         EI.setOperand(0, IE->getOperand(0));
8323         return &EI;
8324       }
8325     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8326       // If this is extracting an element from a shufflevector, figure out where
8327       // it came from and extract from the appropriate input element instead.
8328       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8329         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8330         Value *Src;
8331         if (SrcIdx < SVI->getType()->getNumElements())
8332           Src = SVI->getOperand(0);
8333         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8334           SrcIdx -= SVI->getType()->getNumElements();
8335           Src = SVI->getOperand(1);
8336         } else {
8337           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8338         }
8339         return new ExtractElementInst(Src, SrcIdx);
8340       }
8341     }
8342   }
8343   return 0;
8344 }
8345
8346 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8347 /// elements from either LHS or RHS, return the shuffle mask and true. 
8348 /// Otherwise, return false.
8349 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8350                                          std::vector<Constant*> &Mask) {
8351   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8352          "Invalid CollectSingleShuffleElements");
8353   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8354
8355   if (isa<UndefValue>(V)) {
8356     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8357     return true;
8358   } else if (V == LHS) {
8359     for (unsigned i = 0; i != NumElts; ++i)
8360       Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8361     return true;
8362   } else if (V == RHS) {
8363     for (unsigned i = 0; i != NumElts; ++i)
8364       Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
8365     return true;
8366   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8367     // If this is an insert of an extract from some other vector, include it.
8368     Value *VecOp    = IEI->getOperand(0);
8369     Value *ScalarOp = IEI->getOperand(1);
8370     Value *IdxOp    = IEI->getOperand(2);
8371     
8372     if (!isa<ConstantInt>(IdxOp))
8373       return false;
8374     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8375     
8376     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8377       // Okay, we can handle this if the vector we are insertinting into is
8378       // transitively ok.
8379       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8380         // If so, update the mask to reflect the inserted undef.
8381         Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8382         return true;
8383       }      
8384     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8385       if (isa<ConstantInt>(EI->getOperand(1)) &&
8386           EI->getOperand(0)->getType() == V->getType()) {
8387         unsigned ExtractedIdx =
8388           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8389         
8390         // This must be extracting from either LHS or RHS.
8391         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8392           // Okay, we can handle this if the vector we are insertinting into is
8393           // transitively ok.
8394           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8395             // If so, update the mask to reflect the inserted value.
8396             if (EI->getOperand(0) == LHS) {
8397               Mask[InsertedIdx & (NumElts-1)] = 
8398                  ConstantInt::get(Type::UIntTy, ExtractedIdx);
8399             } else {
8400               assert(EI->getOperand(0) == RHS);
8401               Mask[InsertedIdx & (NumElts-1)] = 
8402                 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
8403               
8404             }
8405             return true;
8406           }
8407         }
8408       }
8409     }
8410   }
8411   // TODO: Handle shufflevector here!
8412   
8413   return false;
8414 }
8415
8416 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8417 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8418 /// that computes V and the LHS value of the shuffle.
8419 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8420                                      Value *&RHS) {
8421   assert(isa<PackedType>(V->getType()) && 
8422          (RHS == 0 || V->getType() == RHS->getType()) &&
8423          "Invalid shuffle!");
8424   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8425
8426   if (isa<UndefValue>(V)) {
8427     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8428     return V;
8429   } else if (isa<ConstantAggregateZero>(V)) {
8430     Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
8431     return V;
8432   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8433     // If this is an insert of an extract from some other vector, include it.
8434     Value *VecOp    = IEI->getOperand(0);
8435     Value *ScalarOp = IEI->getOperand(1);
8436     Value *IdxOp    = IEI->getOperand(2);
8437     
8438     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8439       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8440           EI->getOperand(0)->getType() == V->getType()) {
8441         unsigned ExtractedIdx =
8442           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8443         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8444         
8445         // Either the extracted from or inserted into vector must be RHSVec,
8446         // otherwise we'd end up with a shuffle of three inputs.
8447         if (EI->getOperand(0) == RHS || RHS == 0) {
8448           RHS = EI->getOperand(0);
8449           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8450           Mask[InsertedIdx & (NumElts-1)] = 
8451             ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
8452           return V;
8453         }
8454         
8455         if (VecOp == RHS) {
8456           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8457           // Everything but the extracted element is replaced with the RHS.
8458           for (unsigned i = 0; i != NumElts; ++i) {
8459             if (i != InsertedIdx)
8460               Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
8461           }
8462           return V;
8463         }
8464         
8465         // If this insertelement is a chain that comes from exactly these two
8466         // vectors, return the vector and the effective shuffle.
8467         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8468           return EI->getOperand(0);
8469         
8470       }
8471     }
8472   }
8473   // TODO: Handle shufflevector here!
8474   
8475   // Otherwise, can't do anything fancy.  Return an identity vector.
8476   for (unsigned i = 0; i != NumElts; ++i)
8477     Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8478   return V;
8479 }
8480
8481 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8482   Value *VecOp    = IE.getOperand(0);
8483   Value *ScalarOp = IE.getOperand(1);
8484   Value *IdxOp    = IE.getOperand(2);
8485   
8486   // If the inserted element was extracted from some other vector, and if the 
8487   // indexes are constant, try to turn this into a shufflevector operation.
8488   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8489     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8490         EI->getOperand(0)->getType() == IE.getType()) {
8491       unsigned NumVectorElts = IE.getType()->getNumElements();
8492       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8493       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8494       
8495       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8496         return ReplaceInstUsesWith(IE, VecOp);
8497       
8498       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8499         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8500       
8501       // If we are extracting a value from a vector, then inserting it right
8502       // back into the same place, just use the input vector.
8503       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8504         return ReplaceInstUsesWith(IE, VecOp);      
8505       
8506       // We could theoretically do this for ANY input.  However, doing so could
8507       // turn chains of insertelement instructions into a chain of shufflevector
8508       // instructions, and right now we do not merge shufflevectors.  As such,
8509       // only do this in a situation where it is clear that there is benefit.
8510       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8511         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8512         // the values of VecOp, except then one read from EIOp0.
8513         // Build a new shuffle mask.
8514         std::vector<Constant*> Mask;
8515         if (isa<UndefValue>(VecOp))
8516           Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8517         else {
8518           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8519           Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8520                                                        NumVectorElts));
8521         } 
8522         Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8523         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8524                                      ConstantPacked::get(Mask));
8525       }
8526       
8527       // If this insertelement isn't used by some other insertelement, turn it
8528       // (and any insertelements it points to), into one big shuffle.
8529       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8530         std::vector<Constant*> Mask;
8531         Value *RHS = 0;
8532         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8533         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8534         // We now have a shuffle of LHS, RHS, Mask.
8535         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8536       }
8537     }
8538   }
8539
8540   return 0;
8541 }
8542
8543
8544 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8545   Value *LHS = SVI.getOperand(0);
8546   Value *RHS = SVI.getOperand(1);
8547   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8548
8549   bool MadeChange = false;
8550   
8551   // Undefined shuffle mask -> undefined value.
8552   if (isa<UndefValue>(SVI.getOperand(2)))
8553     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8554   
8555   // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8556   // the undef, change them to undefs.
8557   
8558   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8559   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8560   if (LHS == RHS || isa<UndefValue>(LHS)) {
8561     if (isa<UndefValue>(LHS) && LHS == RHS) {
8562       // shuffle(undef,undef,mask) -> undef.
8563       return ReplaceInstUsesWith(SVI, LHS);
8564     }
8565     
8566     // Remap any references to RHS to use LHS.
8567     std::vector<Constant*> Elts;
8568     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8569       if (Mask[i] >= 2*e)
8570         Elts.push_back(UndefValue::get(Type::UIntTy));
8571       else {
8572         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8573             (Mask[i] <  e && isa<UndefValue>(LHS)))
8574           Mask[i] = 2*e;     // Turn into undef.
8575         else
8576           Mask[i] &= (e-1);  // Force to LHS.
8577         Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8578       }
8579     }
8580     SVI.setOperand(0, SVI.getOperand(1));
8581     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8582     SVI.setOperand(2, ConstantPacked::get(Elts));
8583     LHS = SVI.getOperand(0);
8584     RHS = SVI.getOperand(1);
8585     MadeChange = true;
8586   }
8587   
8588   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8589   bool isLHSID = true, isRHSID = true;
8590     
8591   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8592     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8593     // Is this an identity shuffle of the LHS value?
8594     isLHSID &= (Mask[i] == i);
8595       
8596     // Is this an identity shuffle of the RHS value?
8597     isRHSID &= (Mask[i]-e == i);
8598   }
8599
8600   // Eliminate identity shuffles.
8601   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8602   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8603   
8604   // If the LHS is a shufflevector itself, see if we can combine it with this
8605   // one without producing an unusual shuffle.  Here we are really conservative:
8606   // we are absolutely afraid of producing a shuffle mask not in the input
8607   // program, because the code gen may not be smart enough to turn a merged
8608   // shuffle into two specific shuffles: it may produce worse code.  As such,
8609   // we only merge two shuffles if the result is one of the two input shuffle
8610   // masks.  In this case, merging the shuffles just removes one instruction,
8611   // which we know is safe.  This is good for things like turning:
8612   // (splat(splat)) -> splat.
8613   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8614     if (isa<UndefValue>(RHS)) {
8615       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8616
8617       std::vector<unsigned> NewMask;
8618       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8619         if (Mask[i] >= 2*e)
8620           NewMask.push_back(2*e);
8621         else
8622           NewMask.push_back(LHSMask[Mask[i]]);
8623       
8624       // If the result mask is equal to the src shuffle or this shuffle mask, do
8625       // the replacement.
8626       if (NewMask == LHSMask || NewMask == Mask) {
8627         std::vector<Constant*> Elts;
8628         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8629           if (NewMask[i] >= e*2) {
8630             Elts.push_back(UndefValue::get(Type::UIntTy));
8631           } else {
8632             Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8633           }
8634         }
8635         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8636                                      LHSSVI->getOperand(1),
8637                                      ConstantPacked::get(Elts));
8638       }
8639     }
8640   }
8641   
8642   return MadeChange ? &SVI : 0;
8643 }
8644
8645
8646
8647 void InstCombiner::removeFromWorkList(Instruction *I) {
8648   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8649                  WorkList.end());
8650 }
8651
8652
8653 /// TryToSinkInstruction - Try to move the specified instruction from its
8654 /// current block into the beginning of DestBlock, which can only happen if it's
8655 /// safe to move the instruction past all of the instructions between it and the
8656 /// end of its block.
8657 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8658   assert(I->hasOneUse() && "Invariants didn't hold!");
8659
8660   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8661   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8662
8663   // Do not sink alloca instructions out of the entry block.
8664   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8665     return false;
8666
8667   // We can only sink load instructions if there is nothing between the load and
8668   // the end of block that could change the value.
8669   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8670     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8671          Scan != E; ++Scan)
8672       if (Scan->mayWriteToMemory())
8673         return false;
8674   }
8675
8676   BasicBlock::iterator InsertPos = DestBlock->begin();
8677   while (isa<PHINode>(InsertPos)) ++InsertPos;
8678
8679   I->moveBefore(InsertPos);
8680   ++NumSunkInst;
8681   return true;
8682 }
8683
8684 /// OptimizeConstantExpr - Given a constant expression and target data layout
8685 /// information, symbolically evaluate the constant expr to something simpler
8686 /// if possible.
8687 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8688   if (!TD) return CE;
8689   
8690   Constant *Ptr = CE->getOperand(0);
8691   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8692       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8693     // If this is a constant expr gep that is effectively computing an
8694     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8695     bool isFoldableGEP = true;
8696     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8697       if (!isa<ConstantInt>(CE->getOperand(i)))
8698         isFoldableGEP = false;
8699     if (isFoldableGEP) {
8700       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8701       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8702       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
8703       return ConstantExpr::getIntToPtr(C, CE->getType());
8704     }
8705   }
8706   
8707   return CE;
8708 }
8709
8710
8711 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8712 /// all reachable code to the worklist.
8713 ///
8714 /// This has a couple of tricks to make the code faster and more powerful.  In
8715 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8716 /// them to the worklist (this significantly speeds up instcombine on code where
8717 /// many instructions are dead or constant).  Additionally, if we find a branch
8718 /// whose condition is a known constant, we only visit the reachable successors.
8719 ///
8720 static void AddReachableCodeToWorklist(BasicBlock *BB, 
8721                                        std::set<BasicBlock*> &Visited,
8722                                        std::vector<Instruction*> &WorkList,
8723                                        const TargetData *TD) {
8724   // We have now visited this block!  If we've already been here, bail out.
8725   if (!Visited.insert(BB).second) return;
8726     
8727   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8728     Instruction *Inst = BBI++;
8729     
8730     // DCE instruction if trivially dead.
8731     if (isInstructionTriviallyDead(Inst)) {
8732       ++NumDeadInst;
8733       DOUT << "IC: DCE: " << *Inst;
8734       Inst->eraseFromParent();
8735       continue;
8736     }
8737     
8738     // ConstantProp instruction if trivially constant.
8739     if (Constant *C = ConstantFoldInstruction(Inst)) {
8740       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8741         C = OptimizeConstantExpr(CE, TD);
8742       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
8743       Inst->replaceAllUsesWith(C);
8744       ++NumConstProp;
8745       Inst->eraseFromParent();
8746       continue;
8747     }
8748     
8749     WorkList.push_back(Inst);
8750   }
8751
8752   // Recursively visit successors.  If this is a branch or switch on a constant,
8753   // only visit the reachable successor.
8754   TerminatorInst *TI = BB->getTerminator();
8755   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8756     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8757       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8758       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8759                                  TD);
8760       return;
8761     }
8762   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8763     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8764       // See if this is an explicit destination.
8765       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8766         if (SI->getCaseValue(i) == Cond) {
8767           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8768           return;
8769         }
8770       
8771       // Otherwise it is the default destination.
8772       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8773       return;
8774     }
8775   }
8776   
8777   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8778     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8779 }
8780
8781 bool InstCombiner::runOnFunction(Function &F) {
8782   bool Changed = false;
8783   TD = &getAnalysis<TargetData>();
8784
8785   {
8786     // Do a depth-first traversal of the function, populate the worklist with
8787     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
8788     // track of which blocks we visit.
8789     std::set<BasicBlock*> Visited;
8790     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8791
8792     // Do a quick scan over the function.  If we find any blocks that are
8793     // unreachable, remove any instructions inside of them.  This prevents
8794     // the instcombine code from having to deal with some bad special cases.
8795     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8796       if (!Visited.count(BB)) {
8797         Instruction *Term = BB->getTerminator();
8798         while (Term != BB->begin()) {   // Remove instrs bottom-up
8799           BasicBlock::iterator I = Term; --I;
8800
8801           DOUT << "IC: DCE: " << *I;
8802           ++NumDeadInst;
8803
8804           if (!I->use_empty())
8805             I->replaceAllUsesWith(UndefValue::get(I->getType()));
8806           I->eraseFromParent();
8807         }
8808       }
8809   }
8810
8811   while (!WorkList.empty()) {
8812     Instruction *I = WorkList.back();  // Get an instruction from the worklist
8813     WorkList.pop_back();
8814
8815     // Check to see if we can DCE the instruction.
8816     if (isInstructionTriviallyDead(I)) {
8817       // Add operands to the worklist.
8818       if (I->getNumOperands() < 4)
8819         AddUsesToWorkList(*I);
8820       ++NumDeadInst;
8821
8822       DOUT << "IC: DCE: " << *I;
8823
8824       I->eraseFromParent();
8825       removeFromWorkList(I);
8826       continue;
8827     }
8828
8829     // Instruction isn't dead, see if we can constant propagate it.
8830     if (Constant *C = ConstantFoldInstruction(I)) {
8831       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8832         C = OptimizeConstantExpr(CE, TD);
8833       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
8834
8835       // Add operands to the worklist.
8836       AddUsesToWorkList(*I);
8837       ReplaceInstUsesWith(*I, C);
8838
8839       ++NumConstProp;
8840       I->eraseFromParent();
8841       removeFromWorkList(I);
8842       continue;
8843     }
8844
8845     // See if we can trivially sink this instruction to a successor basic block.
8846     if (I->hasOneUse()) {
8847       BasicBlock *BB = I->getParent();
8848       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8849       if (UserParent != BB) {
8850         bool UserIsSuccessor = false;
8851         // See if the user is one of our successors.
8852         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8853           if (*SI == UserParent) {
8854             UserIsSuccessor = true;
8855             break;
8856           }
8857
8858         // If the user is one of our immediate successors, and if that successor
8859         // only has us as a predecessors (we'd have to split the critical edge
8860         // otherwise), we can keep going.
8861         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8862             next(pred_begin(UserParent)) == pred_end(UserParent))
8863           // Okay, the CFG is simple enough, try to sink this instruction.
8864           Changed |= TryToSinkInstruction(I, UserParent);
8865       }
8866     }
8867
8868     // Now that we have an instruction, try combining it to simplify it...
8869     if (Instruction *Result = visit(*I)) {
8870       ++NumCombined;
8871       // Should we replace the old instruction with a new one?
8872       if (Result != I) {
8873         DOUT << "IC: Old = " << *I
8874              << "    New = " << *Result;
8875
8876         // Everything uses the new instruction now.
8877         I->replaceAllUsesWith(Result);
8878
8879         // Push the new instruction and any users onto the worklist.
8880         WorkList.push_back(Result);
8881         AddUsersToWorkList(*Result);
8882
8883         // Move the name to the new instruction first...
8884         std::string OldName = I->getName(); I->setName("");
8885         Result->setName(OldName);
8886
8887         // Insert the new instruction into the basic block...
8888         BasicBlock *InstParent = I->getParent();
8889         BasicBlock::iterator InsertPos = I;
8890
8891         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
8892           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8893             ++InsertPos;
8894
8895         InstParent->getInstList().insert(InsertPos, Result);
8896
8897         // Make sure that we reprocess all operands now that we reduced their
8898         // use counts.
8899         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8900           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8901             WorkList.push_back(OpI);
8902
8903         // Instructions can end up on the worklist more than once.  Make sure
8904         // we do not process an instruction that has been deleted.
8905         removeFromWorkList(I);
8906
8907         // Erase the old instruction.
8908         InstParent->getInstList().erase(I);
8909       } else {
8910         DOUT << "IC: MOD = " << *I;
8911
8912         // If the instruction was modified, it's possible that it is now dead.
8913         // if so, remove it.
8914         if (isInstructionTriviallyDead(I)) {
8915           // Make sure we process all operands now that we are reducing their
8916           // use counts.
8917           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8918             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8919               WorkList.push_back(OpI);
8920
8921           // Instructions may end up in the worklist more than once.  Erase all
8922           // occurrences of this instruction.
8923           removeFromWorkList(I);
8924           I->eraseFromParent();
8925         } else {
8926           WorkList.push_back(Result);
8927           AddUsersToWorkList(*Result);
8928         }
8929       }
8930       Changed = true;
8931     }
8932   }
8933
8934   return Changed;
8935 }
8936
8937 FunctionPass *llvm::createInstructionCombiningPass() {
8938   return new InstCombiner();
8939 }
8940