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