Comparison of primitive type sizes should now be done in bits, not bytes.
[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. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All cmp instructions on boolean values are replaced with logical ops
29 //    5. add X, X is represented as (X*2) => (X << 1)
30 //    6. Multiplies with a power-of-two constant argument are transformed into
31 //       shifts.
32 //   ... etc.
33 //
34 //===----------------------------------------------------------------------===//
35
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
62 STATISTIC(NumSunkInst , "Number of instructions sunk");
63
64 namespace {
65   class VISIBILITY_HIDDEN InstCombiner
66     : public FunctionPass,
67       public InstVisitor<InstCombiner, Instruction*> {
68     // Worklist of all of the instructions that need to be simplified.
69     std::vector<Instruction*> WorkList;
70     TargetData *TD;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(Value &I) {
77       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78            UI != UE; ++UI)
79         WorkList.push_back(cast<Instruction>(*UI));
80     }
81
82     /// AddUsesToWorkList - When an instruction is simplified, add operands to
83     /// the work lists because they might get more simplified now.
84     ///
85     void AddUsesToWorkList(Instruction &I) {
86       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88           WorkList.push_back(Op);
89     }
90     
91     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
92     /// dead.  Add all of its operands to the worklist, turning them into
93     /// undef's to reduce the number of uses of those instructions.
94     ///
95     /// Return the specified operand before it is turned into an undef.
96     ///
97     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
98       Value *R = I.getOperand(op);
99       
100       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
101         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
102           WorkList.push_back(Op);
103           // Set the operand to undef to drop the use.
104           I.setOperand(i, UndefValue::get(Op->getType()));
105         }
106       
107       return R;
108     }
109
110     // removeFromWorkList - remove all instances of I from the worklist.
111     void removeFromWorkList(Instruction *I);
112   public:
113     virtual bool runOnFunction(Function &F);
114
115     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
116       AU.addRequired<TargetData>();
117       AU.addPreservedID(LCSSAID);
118       AU.setPreservesCFG();
119     }
120
121     TargetData &getTargetData() const { return *TD; }
122
123     // Visitation implementation - Implement instruction combining for different
124     // instruction types.  The semantics are as follows:
125     // Return Value:
126     //    null        - No change was made
127     //     I          - Change was made, I is still valid, I may be dead though
128     //   otherwise    - Change was made, replace I with returned instruction
129     //
130     Instruction *visitAdd(BinaryOperator &I);
131     Instruction *visitSub(BinaryOperator &I);
132     Instruction *visitMul(BinaryOperator &I);
133     Instruction *visitURem(BinaryOperator &I);
134     Instruction *visitSRem(BinaryOperator &I);
135     Instruction *visitFRem(BinaryOperator &I);
136     Instruction *commonRemTransforms(BinaryOperator &I);
137     Instruction *commonIRemTransforms(BinaryOperator &I);
138     Instruction *commonDivTransforms(BinaryOperator &I);
139     Instruction *commonIDivTransforms(BinaryOperator &I);
140     Instruction *visitUDiv(BinaryOperator &I);
141     Instruction *visitSDiv(BinaryOperator &I);
142     Instruction *visitFDiv(BinaryOperator &I);
143     Instruction *visitAnd(BinaryOperator &I);
144     Instruction *visitOr (BinaryOperator &I);
145     Instruction *visitXor(BinaryOperator &I);
146     Instruction *visitFCmpInst(FCmpInst &I);
147     Instruction *visitICmpInst(ICmpInst &I);
148     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
149
150     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
151                              ICmpInst::Predicate Cond, Instruction &I);
152     Instruction *visitShiftInst(ShiftInst &I);
153     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154                                      ShiftInst &I);
155     Instruction *commonCastTransforms(CastInst &CI);
156     Instruction *commonIntCastTransforms(CastInst &CI);
157     Instruction *visitTrunc(CastInst &CI);
158     Instruction *visitZExt(CastInst &CI);
159     Instruction *visitSExt(CastInst &CI);
160     Instruction *visitFPTrunc(CastInst &CI);
161     Instruction *visitFPExt(CastInst &CI);
162     Instruction *visitFPToUI(CastInst &CI);
163     Instruction *visitFPToSI(CastInst &CI);
164     Instruction *visitUIToFP(CastInst &CI);
165     Instruction *visitSIToFP(CastInst &CI);
166     Instruction *visitPtrToInt(CastInst &CI);
167     Instruction *visitIntToPtr(CastInst &CI);
168     Instruction *visitBitCast(CastInst &CI);
169     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
170                                 Instruction *FI);
171     Instruction *visitSelectInst(SelectInst &CI);
172     Instruction *visitCallInst(CallInst &CI);
173     Instruction *visitInvokeInst(InvokeInst &II);
174     Instruction *visitPHINode(PHINode &PN);
175     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
176     Instruction *visitAllocationInst(AllocationInst &AI);
177     Instruction *visitFreeInst(FreeInst &FI);
178     Instruction *visitLoadInst(LoadInst &LI);
179     Instruction *visitStoreInst(StoreInst &SI);
180     Instruction *visitBranchInst(BranchInst &BI);
181     Instruction *visitSwitchInst(SwitchInst &SI);
182     Instruction *visitInsertElementInst(InsertElementInst &IE);
183     Instruction *visitExtractElementInst(ExtractElementInst &EI);
184     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
185
186     // visitInstruction - Specify what to return for unhandled instructions...
187     Instruction *visitInstruction(Instruction &I) { return 0; }
188
189   private:
190     Instruction *visitCallSite(CallSite CS);
191     bool transformConstExprCastCall(CallSite CS);
192
193   public:
194     // InsertNewInstBefore - insert an instruction New before instruction Old
195     // in the program.  Add the new instruction to the worklist.
196     //
197     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
198       assert(New && New->getParent() == 0 &&
199              "New instruction already inserted into a basic block!");
200       BasicBlock *BB = Old.getParent();
201       BB->getInstList().insert(&Old, New);  // Insert inst
202       WorkList.push_back(New);              // Add to worklist
203       return New;
204     }
205
206     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
207     /// This also adds the cast to the worklist.  Finally, this returns the
208     /// cast.
209     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
210                             Instruction &Pos) {
211       if (V->getType() == Ty) return V;
212
213       if (Constant *CV = dyn_cast<Constant>(V))
214         return ConstantExpr::getCast(opc, CV, Ty);
215       
216       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
217       WorkList.push_back(C);
218       return C;
219     }
220
221     // ReplaceInstUsesWith - This method is to be used when an instruction is
222     // found to be dead, replacable with another preexisting expression.  Here
223     // we add all uses of I to the worklist, replace all uses of I with the new
224     // value, then return I, so that the inst combiner will know that I was
225     // modified.
226     //
227     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
228       AddUsersToWorkList(I);         // Add all modified instrs to worklist
229       if (&I != V) {
230         I.replaceAllUsesWith(V);
231         return &I;
232       } else {
233         // If we are replacing the instruction with itself, this must be in a
234         // segment of unreachable code, so just clobber the instruction.
235         I.replaceAllUsesWith(UndefValue::get(I.getType()));
236         return &I;
237       }
238     }
239
240     // UpdateValueUsesWith - This method is to be used when an value is
241     // found to be replacable with another preexisting expression or was
242     // updated.  Here we add all uses of I to the worklist, replace all uses of
243     // I with the new value (unless the instruction was just updated), then
244     // return true, so that the inst combiner will know that I was modified.
245     //
246     bool UpdateValueUsesWith(Value *Old, Value *New) {
247       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
248       if (Old != New)
249         Old->replaceAllUsesWith(New);
250       if (Instruction *I = dyn_cast<Instruction>(Old))
251         WorkList.push_back(I);
252       if (Instruction *I = dyn_cast<Instruction>(New))
253         WorkList.push_back(I);
254       return true;
255     }
256     
257     // EraseInstFromFunction - When dealing with an instruction that has side
258     // effects or produces a void value, we can't rely on DCE to delete the
259     // instruction.  Instead, visit methods should return the value returned by
260     // this function.
261     Instruction *EraseInstFromFunction(Instruction &I) {
262       assert(I.use_empty() && "Cannot erase instruction that is used!");
263       AddUsesToWorkList(I);
264       removeFromWorkList(&I);
265       I.eraseFromParent();
266       return 0;  // Don't do anything with FI
267     }
268
269   private:
270     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
271     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
272     /// casts that are known to not do anything...
273     ///
274     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
275                                    Value *V, const Type *DestTy,
276                                    Instruction *InsertBefore);
277
278     /// SimplifyCommutative - This performs a few simplifications for 
279     /// commutative operators.
280     bool SimplifyCommutative(BinaryOperator &I);
281
282     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
283     /// most-complex to least-complex order.
284     bool SimplifyCompare(CmpInst &I);
285
286     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
287                               uint64_t &KnownZero, uint64_t &KnownOne,
288                               unsigned Depth = 0);
289
290     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
291                                       uint64_t &UndefElts, unsigned Depth = 0);
292       
293     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
294     // PHI node as operand #0, see if we can fold the instruction into the PHI
295     // (which is only possible if all operands to the PHI are constants).
296     Instruction *FoldOpIntoPhi(Instruction &I);
297
298     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
299     // operator and they all are only used by the PHI, PHI together their
300     // inputs, and do the operation once, to the result of the PHI.
301     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
302     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
303     
304     
305     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
306                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
307     
308     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
309                               bool isSub, Instruction &I);
310     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
311                                  bool isSigned, bool Inside, Instruction &IB);
312     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
313     Instruction *MatchBSwap(BinaryOperator &I);
314
315     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
316   };
317
318   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
319 }
320
321 // getComplexity:  Assign a complexity or rank value to LLVM Values...
322 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
323 static unsigned getComplexity(Value *V) {
324   if (isa<Instruction>(V)) {
325     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
326       return 3;
327     return 4;
328   }
329   if (isa<Argument>(V)) return 3;
330   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
331 }
332
333 // isOnlyUse - Return true if this instruction will be deleted if we stop using
334 // it.
335 static bool isOnlyUse(Value *V) {
336   return V->hasOneUse() || isa<Constant>(V);
337 }
338
339 // getPromotedType - Return the specified type promoted as it would be to pass
340 // though a va_arg area...
341 static const Type *getPromotedType(const Type *Ty) {
342   switch (Ty->getTypeID()) {
343   case Type::Int8TyID:
344   case Type::Int16TyID:  return Type::Int32Ty;
345   case Type::FloatTyID:  return Type::DoubleTy;
346   default:               return Ty;
347   }
348 }
349
350 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
351 /// expression bitcast,  return the operand value, otherwise return null.
352 static Value *getBitCastOperand(Value *V) {
353   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
354     return I->getOperand(0);
355   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
356     if (CE->getOpcode() == Instruction::BitCast)
357       return CE->getOperand(0);
358   return 0;
359 }
360
361 /// This function is a wrapper around CastInst::isEliminableCastPair. It
362 /// simply extracts arguments and returns what that function returns.
363 /// @Determine if it is valid to eliminate a Convert pair
364 static Instruction::CastOps 
365 isEliminableCastPair(
366   const CastInst *CI, ///< The first cast instruction
367   unsigned opcode,       ///< The opcode of the second cast instruction
368   const Type *DstTy,     ///< The target type for the second cast instruction
369   TargetData *TD         ///< The target data for pointer size
370 ) {
371   
372   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
373   const Type *MidTy = CI->getType();                  // B from above
374
375   // Get the opcodes of the two Cast instructions
376   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
377   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
378
379   return Instruction::CastOps(
380       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
381                                      DstTy, TD->getIntPtrType()));
382 }
383
384 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
385 /// in any code being generated.  It does not require codegen if V is simple
386 /// enough or if the cast can be folded into other casts.
387 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
388                               const Type *Ty, TargetData *TD) {
389   if (V->getType() == Ty || isa<Constant>(V)) return false;
390   
391   // If this is another cast that can be eliminated, it isn't codegen either.
392   if (const CastInst *CI = dyn_cast<CastInst>(V))
393     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
394       return false;
395   return true;
396 }
397
398 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
399 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
400 /// casts that are known to not do anything...
401 ///
402 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
403                                              Value *V, const Type *DestTy,
404                                              Instruction *InsertBefore) {
405   if (V->getType() == DestTy) return V;
406   if (Constant *C = dyn_cast<Constant>(V))
407     return ConstantExpr::getCast(opcode, C, DestTy);
408   
409   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
410 }
411
412 // SimplifyCommutative - This performs a few simplifications for commutative
413 // operators:
414 //
415 //  1. Order operands such that they are listed from right (least complex) to
416 //     left (most complex).  This puts constants before unary operators before
417 //     binary operators.
418 //
419 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
420 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
421 //
422 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
423   bool Changed = false;
424   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
425     Changed = !I.swapOperands();
426
427   if (!I.isAssociative()) return Changed;
428   Instruction::BinaryOps Opcode = I.getOpcode();
429   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
430     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
431       if (isa<Constant>(I.getOperand(1))) {
432         Constant *Folded = ConstantExpr::get(I.getOpcode(),
433                                              cast<Constant>(I.getOperand(1)),
434                                              cast<Constant>(Op->getOperand(1)));
435         I.setOperand(0, Op->getOperand(0));
436         I.setOperand(1, Folded);
437         return true;
438       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
439         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
440             isOnlyUse(Op) && isOnlyUse(Op1)) {
441           Constant *C1 = cast<Constant>(Op->getOperand(1));
442           Constant *C2 = cast<Constant>(Op1->getOperand(1));
443
444           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
445           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
446           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
447                                                     Op1->getOperand(0),
448                                                     Op1->getName(), &I);
449           WorkList.push_back(New);
450           I.setOperand(0, New);
451           I.setOperand(1, Folded);
452           return true;
453         }
454     }
455   return Changed;
456 }
457
458 /// SimplifyCompare - For a CmpInst this function just orders the operands
459 /// so that theyare listed from right (least complex) to left (most complex).
460 /// This puts constants before unary operators before binary operators.
461 bool InstCombiner::SimplifyCompare(CmpInst &I) {
462   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
463     return false;
464   I.swapOperands();
465   // Compare instructions are not associative so there's nothing else we can do.
466   return true;
467 }
468
469 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
470 // if the LHS is a constant zero (which is the 'negate' form).
471 //
472 static inline Value *dyn_castNegVal(Value *V) {
473   if (BinaryOperator::isNeg(V))
474     return BinaryOperator::getNegArgument(V);
475
476   // Constants can be considered to be negated values if they can be folded.
477   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
478     return ConstantExpr::getNeg(C);
479   return 0;
480 }
481
482 static inline Value *dyn_castNotVal(Value *V) {
483   if (BinaryOperator::isNot(V))
484     return BinaryOperator::getNotArgument(V);
485
486   // Constants can be considered to be not'ed values...
487   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
488     return ConstantExpr::getNot(C);
489   return 0;
490 }
491
492 // dyn_castFoldableMul - If this value is a multiply that can be folded into
493 // other computations (because it has a constant operand), return the
494 // non-constant operand of the multiply, and set CST to point to the multiplier.
495 // Otherwise, return null.
496 //
497 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
498   if (V->hasOneUse() && V->getType()->isInteger())
499     if (Instruction *I = dyn_cast<Instruction>(V)) {
500       if (I->getOpcode() == Instruction::Mul)
501         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
502           return I->getOperand(0);
503       if (I->getOpcode() == Instruction::Shl)
504         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
505           // The multiplier is really 1 << CST.
506           Constant *One = ConstantInt::get(V->getType(), 1);
507           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
508           return I->getOperand(0);
509         }
510     }
511   return 0;
512 }
513
514 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
515 /// expression, return it.
516 static User *dyn_castGetElementPtr(Value *V) {
517   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
518   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
519     if (CE->getOpcode() == Instruction::GetElementPtr)
520       return cast<User>(V);
521   return false;
522 }
523
524 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
525 static ConstantInt *AddOne(ConstantInt *C) {
526   return cast<ConstantInt>(ConstantExpr::getAdd(C,
527                                          ConstantInt::get(C->getType(), 1)));
528 }
529 static ConstantInt *SubOne(ConstantInt *C) {
530   return cast<ConstantInt>(ConstantExpr::getSub(C,
531                                          ConstantInt::get(C->getType(), 1)));
532 }
533
534 /// GetConstantInType - Return a ConstantInt with the specified type and value.
535 ///
536 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
537   if (Ty->getTypeID() == Type::BoolTyID)
538     return ConstantBool::get(Val);
539   return ConstantInt::get(Ty, Val);
540 }
541
542
543 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
544 /// known to be either zero or one and return them in the KnownZero/KnownOne
545 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
546 /// processing.
547 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
548                               uint64_t &KnownOne, unsigned Depth = 0) {
549   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
550   // we cannot optimize based on the assumption that it is zero without changing
551   // it to be an explicit zero.  If we don't change it to zero, other code could
552   // optimized based on the contradictory assumption that it is non-zero.
553   // Because instcombine aggressively folds operations with undef args anyway,
554   // this won't lose us code quality.
555   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
556     // We know all of the bits for a constant!
557     KnownOne = CI->getZExtValue() & Mask;
558     KnownZero = ~KnownOne & Mask;
559     return;
560   }
561
562   KnownZero = KnownOne = 0;   // Don't know anything.
563   if (Depth == 6 || Mask == 0)
564     return;  // Limit search depth.
565
566   uint64_t KnownZero2, KnownOne2;
567   Instruction *I = dyn_cast<Instruction>(V);
568   if (!I) return;
569
570   Mask &= V->getType()->getIntegralTypeMask();
571   
572   switch (I->getOpcode()) {
573   case Instruction::And:
574     // If either the LHS or the RHS are Zero, the result is zero.
575     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
576     Mask &= ~KnownZero;
577     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
578     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
579     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
580     
581     // Output known-1 bits are only known if set in both the LHS & RHS.
582     KnownOne &= KnownOne2;
583     // Output known-0 are known to be clear if zero in either the LHS | RHS.
584     KnownZero |= KnownZero2;
585     return;
586   case Instruction::Or:
587     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
588     Mask &= ~KnownOne;
589     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
590     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
591     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
592     
593     // Output known-0 bits are only known if clear in both the LHS & RHS.
594     KnownZero &= KnownZero2;
595     // Output known-1 are known to be set if set in either the LHS | RHS.
596     KnownOne |= KnownOne2;
597     return;
598   case Instruction::Xor: {
599     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
600     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
601     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
602     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
603     
604     // Output known-0 bits are known if clear or set in both the LHS & RHS.
605     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
606     // Output known-1 are known to be set if set in only one of the LHS, RHS.
607     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
608     KnownZero = KnownZeroOut;
609     return;
610   }
611   case Instruction::Select:
612     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
613     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
614     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
615     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
616
617     // Only known if known in both the LHS and RHS.
618     KnownOne &= KnownOne2;
619     KnownZero &= KnownZero2;
620     return;
621   case Instruction::FPTrunc:
622   case Instruction::FPExt:
623   case Instruction::FPToUI:
624   case Instruction::FPToSI:
625   case Instruction::SIToFP:
626   case Instruction::PtrToInt:
627   case Instruction::UIToFP:
628   case Instruction::IntToPtr:
629     return; // Can't work with floating point or pointers
630   case Instruction::Trunc: 
631     // All these have integer operands
632     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
633     return;
634   case Instruction::BitCast: {
635     const Type *SrcTy = I->getOperand(0)->getType();
636     if (SrcTy->isIntegral()) {
637       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
638       return;
639     }
640     break;
641   }
642   case Instruction::ZExt:  {
643     // Compute the bits in the result that are not present in the input.
644     const Type *SrcTy = I->getOperand(0)->getType();
645     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
646     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
647       
648     Mask &= SrcTy->getIntegralTypeMask();
649     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
650     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
651     // The top bits are known to be zero.
652     KnownZero |= NewBits;
653     return;
654   }
655   case Instruction::SExt: {
656     // Compute the bits in the result that are not present in the input.
657     const Type *SrcTy = I->getOperand(0)->getType();
658     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
659     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
660       
661     Mask &= SrcTy->getIntegralTypeMask();
662     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
663     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
664
665     // If the sign bit of the input is known set or clear, then we know the
666     // top bits of the result.
667     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
668     if (KnownZero & InSignBit) {          // Input sign bit known zero
669       KnownZero |= NewBits;
670       KnownOne &= ~NewBits;
671     } else if (KnownOne & InSignBit) {    // Input sign bit known set
672       KnownOne |= NewBits;
673       KnownZero &= ~NewBits;
674     } else {                              // Input sign bit unknown
675       KnownZero &= ~NewBits;
676       KnownOne &= ~NewBits;
677     }
678     return;
679   }
680   case Instruction::Shl:
681     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
682     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
683       uint64_t ShiftAmt = SA->getZExtValue();
684       Mask >>= ShiftAmt;
685       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
686       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
687       KnownZero <<= ShiftAmt;
688       KnownOne  <<= ShiftAmt;
689       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
690       return;
691     }
692     break;
693   case Instruction::LShr:
694     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
695     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
696       // Compute the new bits that are at the top now.
697       uint64_t ShiftAmt = SA->getZExtValue();
698       uint64_t HighBits = (1ULL << ShiftAmt)-1;
699       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
700       
701       // Unsigned shift right.
702       Mask <<= ShiftAmt;
703       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
704       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
705       KnownZero >>= ShiftAmt;
706       KnownOne  >>= ShiftAmt;
707       KnownZero |= HighBits;  // high bits known zero.
708       return;
709     }
710     break;
711   case Instruction::AShr:
712     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
713     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
714       // Compute the new bits that are at the top now.
715       uint64_t ShiftAmt = SA->getZExtValue();
716       uint64_t HighBits = (1ULL << ShiftAmt)-1;
717       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
718       
719       // Signed shift right.
720       Mask <<= ShiftAmt;
721       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
722       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
723       KnownZero >>= ShiftAmt;
724       KnownOne  >>= ShiftAmt;
725         
726       // Handle the sign bits.
727       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
728       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
729         
730       if (KnownZero & SignBit) {       // New bits are known zero.
731         KnownZero |= HighBits;
732       } else if (KnownOne & SignBit) { // New bits are known one.
733         KnownOne |= HighBits;
734       }
735       return;
736     }
737     break;
738   }
739 }
740
741 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
742 /// this predicate to simplify operations downstream.  Mask is known to be zero
743 /// for bits that V cannot have.
744 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
745   uint64_t KnownZero, KnownOne;
746   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
747   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
748   return (KnownZero & Mask) == Mask;
749 }
750
751 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
752 /// specified instruction is a constant integer.  If so, check to see if there
753 /// are any bits set in the constant that are not demanded.  If so, shrink the
754 /// constant and return true.
755 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
756                                    uint64_t Demanded) {
757   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
758   if (!OpC) return false;
759
760   // If there are no bits set that aren't demanded, nothing to do.
761   if ((~Demanded & OpC->getZExtValue()) == 0)
762     return false;
763
764   // This is producing any bits that are not needed, shrink the RHS.
765   uint64_t Val = Demanded & OpC->getZExtValue();
766   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
767   return true;
768 }
769
770 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
771 // set of known zero and one bits, compute the maximum and minimum values that
772 // could have the specified known zero and known one bits, returning them in
773 // min/max.
774 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
775                                                    uint64_t KnownZero,
776                                                    uint64_t KnownOne,
777                                                    int64_t &Min, int64_t &Max) {
778   uint64_t TypeBits = Ty->getIntegralTypeMask();
779   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
780
781   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
782   
783   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
784   // bit if it is unknown.
785   Min = KnownOne;
786   Max = KnownOne|UnknownBits;
787   
788   if (SignBit & UnknownBits) { // Sign bit is unknown
789     Min |= SignBit;
790     Max &= ~SignBit;
791   }
792   
793   // Sign extend the min/max values.
794   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
795   Min = (Min << ShAmt) >> ShAmt;
796   Max = (Max << ShAmt) >> ShAmt;
797 }
798
799 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
800 // a set of known zero and one bits, compute the maximum and minimum values that
801 // could have the specified known zero and known one bits, returning them in
802 // min/max.
803 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
804                                                      uint64_t KnownZero,
805                                                      uint64_t KnownOne,
806                                                      uint64_t &Min,
807                                                      uint64_t &Max) {
808   uint64_t TypeBits = Ty->getIntegralTypeMask();
809   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
810   
811   // The minimum value is when the unknown bits are all zeros.
812   Min = KnownOne;
813   // The maximum value is when the unknown bits are all ones.
814   Max = KnownOne|UnknownBits;
815 }
816
817
818 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
819 /// DemandedMask bits of the result of V are ever used downstream.  If we can
820 /// use this information to simplify V, do so and return true.  Otherwise,
821 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
822 /// the expression (used to simplify the caller).  The KnownZero/One bits may
823 /// only be accurate for those bits in the DemandedMask.
824 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
825                                         uint64_t &KnownZero, uint64_t &KnownOne,
826                                         unsigned Depth) {
827   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
828     // We know all of the bits for a constant!
829     KnownOne = CI->getZExtValue() & DemandedMask;
830     KnownZero = ~KnownOne & DemandedMask;
831     return false;
832   }
833   
834   KnownZero = KnownOne = 0;
835   if (!V->hasOneUse()) {    // Other users may use these bits.
836     if (Depth != 0) {       // Not at the root.
837       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
838       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
839       return false;
840     }
841     // If this is the root being simplified, allow it to have multiple uses,
842     // just set the DemandedMask to all bits.
843     DemandedMask = V->getType()->getIntegralTypeMask();
844   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
845     if (V != UndefValue::get(V->getType()))
846       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
847     return false;
848   } else if (Depth == 6) {        // Limit search depth.
849     return false;
850   }
851   
852   Instruction *I = dyn_cast<Instruction>(V);
853   if (!I) return false;        // Only analyze instructions.
854
855   DemandedMask &= V->getType()->getIntegralTypeMask();
856   
857   uint64_t KnownZero2 = 0, KnownOne2 = 0;
858   switch (I->getOpcode()) {
859   default: break;
860   case Instruction::And:
861     // If either the LHS or the RHS are Zero, the result is zero.
862     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
863                              KnownZero, KnownOne, Depth+1))
864       return true;
865     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
866
867     // If something is known zero on the RHS, the bits aren't demanded on the
868     // LHS.
869     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
870                              KnownZero2, KnownOne2, Depth+1))
871       return true;
872     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
873
874     // If all of the demanded bits are known 1 on one side, return the other.
875     // These bits cannot contribute to the result of the 'and'.
876     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
877       return UpdateValueUsesWith(I, I->getOperand(0));
878     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
879       return UpdateValueUsesWith(I, I->getOperand(1));
880     
881     // If all of the demanded bits in the inputs are known zeros, return zero.
882     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
883       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
884       
885     // If the RHS is a constant, see if we can simplify it.
886     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
887       return UpdateValueUsesWith(I, I);
888       
889     // Output known-1 bits are only known if set in both the LHS & RHS.
890     KnownOne &= KnownOne2;
891     // Output known-0 are known to be clear if zero in either the LHS | RHS.
892     KnownZero |= KnownZero2;
893     break;
894   case Instruction::Or:
895     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
896                              KnownZero, KnownOne, Depth+1))
897       return true;
898     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
899     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
900                              KnownZero2, KnownOne2, Depth+1))
901       return true;
902     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
903     
904     // If all of the demanded bits are known zero on one side, return the other.
905     // These bits cannot contribute to the result of the 'or'.
906     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
907       return UpdateValueUsesWith(I, I->getOperand(0));
908     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
909       return UpdateValueUsesWith(I, I->getOperand(1));
910
911     // If all of the potentially set bits on one side are known to be set on
912     // the other side, just use the 'other' side.
913     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
914         (DemandedMask & (~KnownZero)))
915       return UpdateValueUsesWith(I, I->getOperand(0));
916     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
917         (DemandedMask & (~KnownZero2)))
918       return UpdateValueUsesWith(I, I->getOperand(1));
919         
920     // If the RHS is a constant, see if we can simplify it.
921     if (ShrinkDemandedConstant(I, 1, DemandedMask))
922       return UpdateValueUsesWith(I, I);
923           
924     // Output known-0 bits are only known if clear in both the LHS & RHS.
925     KnownZero &= KnownZero2;
926     // Output known-1 are known to be set if set in either the LHS | RHS.
927     KnownOne |= KnownOne2;
928     break;
929   case Instruction::Xor: {
930     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
931                              KnownZero, KnownOne, Depth+1))
932       return true;
933     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
934     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
935                              KnownZero2, KnownOne2, Depth+1))
936       return true;
937     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
938     
939     // If all of the demanded bits are known zero on one side, return the other.
940     // These bits cannot contribute to the result of the 'xor'.
941     if ((DemandedMask & KnownZero) == DemandedMask)
942       return UpdateValueUsesWith(I, I->getOperand(0));
943     if ((DemandedMask & KnownZero2) == DemandedMask)
944       return UpdateValueUsesWith(I, I->getOperand(1));
945     
946     // Output known-0 bits are known if clear or set in both the LHS & RHS.
947     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
948     // Output known-1 are known to be set if set in only one of the LHS, RHS.
949     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
950     
951     // If all of the demanded bits are known to be zero on one side or the
952     // other, turn this into an *inclusive* or.
953     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
954     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
955       Instruction *Or =
956         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
957                                  I->getName());
958       InsertNewInstBefore(Or, *I);
959       return UpdateValueUsesWith(I, Or);
960     }
961     
962     // If all of the demanded bits on one side are known, and all of the set
963     // bits on that side are also known to be set on the other side, turn this
964     // into an AND, as we know the bits will be cleared.
965     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
966     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
967       if ((KnownOne & KnownOne2) == KnownOne) {
968         Constant *AndC = GetConstantInType(I->getType(), 
969                                            ~KnownOne & DemandedMask);
970         Instruction *And = 
971           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
972         InsertNewInstBefore(And, *I);
973         return UpdateValueUsesWith(I, And);
974       }
975     }
976     
977     // If the RHS is a constant, see if we can simplify it.
978     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
979     if (ShrinkDemandedConstant(I, 1, DemandedMask))
980       return UpdateValueUsesWith(I, I);
981     
982     KnownZero = KnownZeroOut;
983     KnownOne  = KnownOneOut;
984     break;
985   }
986   case Instruction::Select:
987     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
988                              KnownZero, KnownOne, Depth+1))
989       return true;
990     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
991                              KnownZero2, KnownOne2, Depth+1))
992       return true;
993     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
994     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
995     
996     // If the operands are constants, see if we can simplify them.
997     if (ShrinkDemandedConstant(I, 1, DemandedMask))
998       return UpdateValueUsesWith(I, I);
999     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1000       return UpdateValueUsesWith(I, I);
1001     
1002     // Only known if known in both the LHS and RHS.
1003     KnownOne &= KnownOne2;
1004     KnownZero &= KnownZero2;
1005     break;
1006   case Instruction::Trunc:
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::BitCast:
1013     if (!I->getOperand(0)->getType()->isIntegral())
1014       return false;
1015       
1016     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1017                              KnownZero, KnownOne, Depth+1))
1018       return true;
1019     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1020     break;
1021   case Instruction::ZExt: {
1022     // Compute the bits in the result that are not present in the input.
1023     const Type *SrcTy = I->getOperand(0)->getType();
1024     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1025     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1026     
1027     DemandedMask &= SrcTy->getIntegralTypeMask();
1028     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1029                              KnownZero, KnownOne, Depth+1))
1030       return true;
1031     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1032     // The top bits are known to be zero.
1033     KnownZero |= NewBits;
1034     break;
1035   }
1036   case Instruction::SExt: {
1037     // Compute the bits in the result that are not present in the input.
1038     const Type *SrcTy = I->getOperand(0)->getType();
1039     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1040     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1041     
1042     // Get the sign bit for the source type
1043     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1044     int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1045
1046     // If any of the sign extended bits are demanded, we know that the sign
1047     // bit is demanded.
1048     if (NewBits & DemandedMask)
1049       InputDemandedBits |= InSignBit;
1050       
1051     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1052                              KnownZero, KnownOne, Depth+1))
1053       return true;
1054     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1055       
1056     // If the sign bit of the input is known set or clear, then we know the
1057     // top bits of the result.
1058
1059     // If the input sign bit is known zero, or if the NewBits are not demanded
1060     // convert this into a zero extension.
1061     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1062       // Convert to ZExt cast
1063       CastInst *NewCast = CastInst::create(
1064         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1065       return UpdateValueUsesWith(I, NewCast);
1066     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1067       KnownOne |= NewBits;
1068       KnownZero &= ~NewBits;
1069     } else {                              // Input sign bit unknown
1070       KnownZero &= ~NewBits;
1071       KnownOne &= ~NewBits;
1072     }
1073     break;
1074   }
1075   case Instruction::Add:
1076     // If there is a constant on the RHS, there are a variety of xformations
1077     // we can do.
1078     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1079       // If null, this should be simplified elsewhere.  Some of the xforms here
1080       // won't work if the RHS is zero.
1081       if (RHS->isNullValue())
1082         break;
1083       
1084       // Figure out what the input bits are.  If the top bits of the and result
1085       // are not demanded, then the add doesn't demand them from its input
1086       // either.
1087       
1088       // Shift the demanded mask up so that it's at the top of the uint64_t.
1089       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1090       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1091       
1092       // If the top bit of the output is demanded, demand everything from the
1093       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1094       uint64_t InDemandedBits = ~0ULL >> 64-BitWidth+NLZ;
1095
1096       // Find information about known zero/one bits in the input.
1097       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1098                                KnownZero2, KnownOne2, Depth+1))
1099         return true;
1100
1101       // If the RHS of the add has bits set that can't affect the input, reduce
1102       // the constant.
1103       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1104         return UpdateValueUsesWith(I, I);
1105       
1106       // Avoid excess work.
1107       if (KnownZero2 == 0 && KnownOne2 == 0)
1108         break;
1109       
1110       // Turn it into OR if input bits are zero.
1111       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1112         Instruction *Or =
1113           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1114                                    I->getName());
1115         InsertNewInstBefore(Or, *I);
1116         return UpdateValueUsesWith(I, Or);
1117       }
1118       
1119       // We can say something about the output known-zero and known-one bits,
1120       // depending on potential carries from the input constant and the
1121       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1122       // bits set and the RHS constant is 0x01001, then we know we have a known
1123       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1124       
1125       // To compute this, we first compute the potential carry bits.  These are
1126       // the bits which may be modified.  I'm not aware of a better way to do
1127       // this scan.
1128       uint64_t RHSVal = RHS->getZExtValue();
1129       
1130       bool CarryIn = false;
1131       uint64_t CarryBits = 0;
1132       uint64_t CurBit = 1;
1133       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1134         // Record the current carry in.
1135         if (CarryIn) CarryBits |= CurBit;
1136         
1137         bool CarryOut;
1138         
1139         // This bit has a carry out unless it is "zero + zero" or
1140         // "zero + anything" with no carry in.
1141         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1142           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1143         } else if (!CarryIn &&
1144                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1145           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1146         } else {
1147           // Otherwise, we have to assume we have a carry out.
1148           CarryOut = true;
1149         }
1150         
1151         // This stage's carry out becomes the next stage's carry-in.
1152         CarryIn = CarryOut;
1153       }
1154       
1155       // Now that we know which bits have carries, compute the known-1/0 sets.
1156       
1157       // Bits are known one if they are known zero in one operand and one in the
1158       // other, and there is no input carry.
1159       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1160       
1161       // Bits are known zero if they are known zero in both operands and there
1162       // is no input carry.
1163       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1164     }
1165     break;
1166   case Instruction::Shl:
1167     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1168       uint64_t ShiftAmt = SA->getZExtValue();
1169       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1170                                KnownZero, KnownOne, Depth+1))
1171         return true;
1172       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1173       KnownZero <<= ShiftAmt;
1174       KnownOne  <<= ShiftAmt;
1175       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1176     }
1177     break;
1178   case Instruction::LShr:
1179     // For a logical shift right
1180     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1181       unsigned ShiftAmt = SA->getZExtValue();
1182       
1183       // Compute the new bits that are at the top now.
1184       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1185       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1186       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1187       // Unsigned shift right.
1188       if (SimplifyDemandedBits(I->getOperand(0),
1189                               (DemandedMask << ShiftAmt) & TypeMask,
1190                                KnownZero, KnownOne, Depth+1))
1191         return true;
1192       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1193       KnownZero &= TypeMask;
1194       KnownOne  &= TypeMask;
1195       KnownZero >>= ShiftAmt;
1196       KnownOne  >>= ShiftAmt;
1197       KnownZero |= HighBits;  // high bits known zero.
1198     }
1199     break;
1200   case Instruction::AShr:
1201     // If this is an arithmetic shift right and only the low-bit is set, we can
1202     // always convert this into a logical shr, even if the shift amount is
1203     // variable.  The low bit of the shift cannot be an input sign bit unless
1204     // the shift amount is >= the size of the datatype, which is undefined.
1205     if (DemandedMask == 1) {
1206       // Perform the logical shift right.
1207       Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1208                                     I->getOperand(1), I->getName());
1209       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1210       return UpdateValueUsesWith(I, NewVal);
1211     }    
1212     
1213     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1214       unsigned ShiftAmt = SA->getZExtValue();
1215       
1216       // Compute the new bits that are at the top now.
1217       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1218       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1219       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1220       // Signed shift right.
1221       if (SimplifyDemandedBits(I->getOperand(0),
1222                                (DemandedMask << ShiftAmt) & TypeMask,
1223                                KnownZero, KnownOne, Depth+1))
1224         return true;
1225       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1226       KnownZero &= TypeMask;
1227       KnownOne  &= TypeMask;
1228       KnownZero >>= ShiftAmt;
1229       KnownOne  >>= ShiftAmt;
1230         
1231       // Handle the sign bits.
1232       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1233       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1234         
1235       // If the input sign bit is known to be zero, or if none of the top bits
1236       // are demanded, turn this into an unsigned shift right.
1237       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1238         // Perform the logical shift right.
1239         Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0), 
1240                                       SA, I->getName());
1241         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1242         return UpdateValueUsesWith(I, NewVal);
1243       } else if (KnownOne & SignBit) { // New bits are known one.
1244         KnownOne |= HighBits;
1245       }
1246     }
1247     break;
1248   }
1249   
1250   // If the client is only demanding bits that we know, return the known
1251   // constant.
1252   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1253     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1254   return false;
1255 }  
1256
1257
1258 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1259 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1260 /// actually used by the caller.  This method analyzes which elements of the
1261 /// operand are undef and returns that information in UndefElts.
1262 ///
1263 /// If the information about demanded elements can be used to simplify the
1264 /// operation, the operation is simplified, then the resultant value is
1265 /// returned.  This returns null if no change was made.
1266 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1267                                                 uint64_t &UndefElts,
1268                                                 unsigned Depth) {
1269   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1270   assert(VWidth <= 64 && "Vector too wide to analyze!");
1271   uint64_t EltMask = ~0ULL >> (64-VWidth);
1272   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1273          "Invalid DemandedElts!");
1274
1275   if (isa<UndefValue>(V)) {
1276     // If the entire vector is undefined, just return this info.
1277     UndefElts = EltMask;
1278     return 0;
1279   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1280     UndefElts = EltMask;
1281     return UndefValue::get(V->getType());
1282   }
1283   
1284   UndefElts = 0;
1285   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1286     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1287     Constant *Undef = UndefValue::get(EltTy);
1288
1289     std::vector<Constant*> Elts;
1290     for (unsigned i = 0; i != VWidth; ++i)
1291       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1292         Elts.push_back(Undef);
1293         UndefElts |= (1ULL << i);
1294       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1295         Elts.push_back(Undef);
1296         UndefElts |= (1ULL << i);
1297       } else {                               // Otherwise, defined.
1298         Elts.push_back(CP->getOperand(i));
1299       }
1300         
1301     // If we changed the constant, return it.
1302     Constant *NewCP = ConstantPacked::get(Elts);
1303     return NewCP != CP ? NewCP : 0;
1304   } else if (isa<ConstantAggregateZero>(V)) {
1305     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1306     // set to undef.
1307     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1308     Constant *Zero = Constant::getNullValue(EltTy);
1309     Constant *Undef = UndefValue::get(EltTy);
1310     std::vector<Constant*> Elts;
1311     for (unsigned i = 0; i != VWidth; ++i)
1312       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1313     UndefElts = DemandedElts ^ EltMask;
1314     return ConstantPacked::get(Elts);
1315   }
1316   
1317   if (!V->hasOneUse()) {    // Other users may use these bits.
1318     if (Depth != 0) {       // Not at the root.
1319       // TODO: Just compute the UndefElts information recursively.
1320       return false;
1321     }
1322     return false;
1323   } else if (Depth == 10) {        // Limit search depth.
1324     return false;
1325   }
1326   
1327   Instruction *I = dyn_cast<Instruction>(V);
1328   if (!I) return false;        // Only analyze instructions.
1329   
1330   bool MadeChange = false;
1331   uint64_t UndefElts2;
1332   Value *TmpV;
1333   switch (I->getOpcode()) {
1334   default: break;
1335     
1336   case Instruction::InsertElement: {
1337     // If this is a variable index, we don't know which element it overwrites.
1338     // demand exactly the same input as we produce.
1339     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1340     if (Idx == 0) {
1341       // Note that we can't propagate undef elt info, because we don't know
1342       // which elt is getting updated.
1343       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1344                                         UndefElts2, Depth+1);
1345       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1346       break;
1347     }
1348     
1349     // If this is inserting an element that isn't demanded, remove this
1350     // insertelement.
1351     unsigned IdxNo = Idx->getZExtValue();
1352     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1353       return AddSoonDeadInstToWorklist(*I, 0);
1354     
1355     // Otherwise, the element inserted overwrites whatever was there, so the
1356     // input demanded set is simpler than the output set.
1357     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1358                                       DemandedElts & ~(1ULL << IdxNo),
1359                                       UndefElts, Depth+1);
1360     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1361
1362     // The inserted element is defined.
1363     UndefElts |= 1ULL << IdxNo;
1364     break;
1365   }
1366     
1367   case Instruction::And:
1368   case Instruction::Or:
1369   case Instruction::Xor:
1370   case Instruction::Add:
1371   case Instruction::Sub:
1372   case Instruction::Mul:
1373     // div/rem demand all inputs, because they don't want divide by zero.
1374     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1375                                       UndefElts, Depth+1);
1376     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1377     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1378                                       UndefElts2, Depth+1);
1379     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1380       
1381     // Output elements are undefined if both are undefined.  Consider things
1382     // like undef&0.  The result is known zero, not undef.
1383     UndefElts &= UndefElts2;
1384     break;
1385     
1386   case Instruction::Call: {
1387     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1388     if (!II) break;
1389     switch (II->getIntrinsicID()) {
1390     default: break;
1391       
1392     // Binary vector operations that work column-wise.  A dest element is a
1393     // function of the corresponding input elements from the two inputs.
1394     case Intrinsic::x86_sse_sub_ss:
1395     case Intrinsic::x86_sse_mul_ss:
1396     case Intrinsic::x86_sse_min_ss:
1397     case Intrinsic::x86_sse_max_ss:
1398     case Intrinsic::x86_sse2_sub_sd:
1399     case Intrinsic::x86_sse2_mul_sd:
1400     case Intrinsic::x86_sse2_min_sd:
1401     case Intrinsic::x86_sse2_max_sd:
1402       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1403                                         UndefElts, Depth+1);
1404       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1405       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1406                                         UndefElts2, Depth+1);
1407       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1408
1409       // If only the low elt is demanded and this is a scalarizable intrinsic,
1410       // scalarize it now.
1411       if (DemandedElts == 1) {
1412         switch (II->getIntrinsicID()) {
1413         default: break;
1414         case Intrinsic::x86_sse_sub_ss:
1415         case Intrinsic::x86_sse_mul_ss:
1416         case Intrinsic::x86_sse2_sub_sd:
1417         case Intrinsic::x86_sse2_mul_sd:
1418           // TODO: Lower MIN/MAX/ABS/etc
1419           Value *LHS = II->getOperand(1);
1420           Value *RHS = II->getOperand(2);
1421           // Extract the element as scalars.
1422           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1423           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1424           
1425           switch (II->getIntrinsicID()) {
1426           default: assert(0 && "Case stmts out of sync!");
1427           case Intrinsic::x86_sse_sub_ss:
1428           case Intrinsic::x86_sse2_sub_sd:
1429             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1430                                                         II->getName()), *II);
1431             break;
1432           case Intrinsic::x86_sse_mul_ss:
1433           case Intrinsic::x86_sse2_mul_sd:
1434             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1435                                                          II->getName()), *II);
1436             break;
1437           }
1438           
1439           Instruction *New =
1440             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1441                                   II->getName());
1442           InsertNewInstBefore(New, *II);
1443           AddSoonDeadInstToWorklist(*II, 0);
1444           return New;
1445         }            
1446       }
1447         
1448       // Output elements are undefined if both are undefined.  Consider things
1449       // like undef&0.  The result is known zero, not undef.
1450       UndefElts &= UndefElts2;
1451       break;
1452     }
1453     break;
1454   }
1455   }
1456   return MadeChange ? I : 0;
1457 }
1458
1459 /// @returns true if the specified compare instruction is
1460 /// true when both operands are equal...
1461 /// @brief Determine if the ICmpInst returns true if both operands are equal
1462 static bool isTrueWhenEqual(ICmpInst &ICI) {
1463   ICmpInst::Predicate pred = ICI.getPredicate();
1464   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1465          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1466          pred == ICmpInst::ICMP_SLE;
1467 }
1468
1469 /// @returns true if the specified compare instruction is
1470 /// true when both operands are equal...
1471 /// @brief Determine if the FCmpInst returns true if both operands are equal
1472 static bool isTrueWhenEqual(FCmpInst &FCI) {
1473   FCmpInst::Predicate pred = FCI.getPredicate();
1474   return pred == FCmpInst::FCMP_OEQ || pred == FCmpInst::FCMP_UEQ ||
1475          pred == FCmpInst::FCMP_OGE || pred == FCmpInst::FCMP_UGE ||
1476          pred == FCmpInst::FCMP_OLE || pred == FCmpInst::FCMP_ULE;
1477 }
1478
1479 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1480 /// function is designed to check a chain of associative operators for a
1481 /// potential to apply a certain optimization.  Since the optimization may be
1482 /// applicable if the expression was reassociated, this checks the chain, then
1483 /// reassociates the expression as necessary to expose the optimization
1484 /// opportunity.  This makes use of a special Functor, which must define
1485 /// 'shouldApply' and 'apply' methods.
1486 ///
1487 template<typename Functor>
1488 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1489   unsigned Opcode = Root.getOpcode();
1490   Value *LHS = Root.getOperand(0);
1491
1492   // Quick check, see if the immediate LHS matches...
1493   if (F.shouldApply(LHS))
1494     return F.apply(Root);
1495
1496   // Otherwise, if the LHS is not of the same opcode as the root, return.
1497   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1498   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1499     // Should we apply this transform to the RHS?
1500     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1501
1502     // If not to the RHS, check to see if we should apply to the LHS...
1503     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1504       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1505       ShouldApply = true;
1506     }
1507
1508     // If the functor wants to apply the optimization to the RHS of LHSI,
1509     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1510     if (ShouldApply) {
1511       BasicBlock *BB = Root.getParent();
1512
1513       // Now all of the instructions are in the current basic block, go ahead
1514       // and perform the reassociation.
1515       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1516
1517       // First move the selected RHS to the LHS of the root...
1518       Root.setOperand(0, LHSI->getOperand(1));
1519
1520       // Make what used to be the LHS of the root be the user of the root...
1521       Value *ExtraOperand = TmpLHSI->getOperand(1);
1522       if (&Root == TmpLHSI) {
1523         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1524         return 0;
1525       }
1526       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1527       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1528       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1529       BasicBlock::iterator ARI = &Root; ++ARI;
1530       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1531       ARI = Root;
1532
1533       // Now propagate the ExtraOperand down the chain of instructions until we
1534       // get to LHSI.
1535       while (TmpLHSI != LHSI) {
1536         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1537         // Move the instruction to immediately before the chain we are
1538         // constructing to avoid breaking dominance properties.
1539         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1540         BB->getInstList().insert(ARI, NextLHSI);
1541         ARI = NextLHSI;
1542
1543         Value *NextOp = NextLHSI->getOperand(1);
1544         NextLHSI->setOperand(1, ExtraOperand);
1545         TmpLHSI = NextLHSI;
1546         ExtraOperand = NextOp;
1547       }
1548
1549       // Now that the instructions are reassociated, have the functor perform
1550       // the transformation...
1551       return F.apply(Root);
1552     }
1553
1554     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1555   }
1556   return 0;
1557 }
1558
1559
1560 // AddRHS - Implements: X + X --> X << 1
1561 struct AddRHS {
1562   Value *RHS;
1563   AddRHS(Value *rhs) : RHS(rhs) {}
1564   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1565   Instruction *apply(BinaryOperator &Add) const {
1566     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1567                          ConstantInt::get(Type::Int8Ty, 1));
1568   }
1569 };
1570
1571 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1572 //                 iff C1&C2 == 0
1573 struct AddMaskingAnd {
1574   Constant *C2;
1575   AddMaskingAnd(Constant *c) : C2(c) {}
1576   bool shouldApply(Value *LHS) const {
1577     ConstantInt *C1;
1578     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1579            ConstantExpr::getAnd(C1, C2)->isNullValue();
1580   }
1581   Instruction *apply(BinaryOperator &Add) const {
1582     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1583   }
1584 };
1585
1586 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1587                                              InstCombiner *IC) {
1588   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1589     if (Constant *SOC = dyn_cast<Constant>(SO))
1590       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1591
1592     return IC->InsertNewInstBefore(CastInst::create(
1593           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1594   }
1595
1596   // Figure out if the constant is the left or the right argument.
1597   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1598   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1599
1600   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1601     if (ConstIsRHS)
1602       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1603     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1604   }
1605
1606   Value *Op0 = SO, *Op1 = ConstOperand;
1607   if (!ConstIsRHS)
1608     std::swap(Op0, Op1);
1609   Instruction *New;
1610   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1611     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1612   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1613     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1614                           SO->getName()+".cmp");
1615   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1616     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1617   else {
1618     assert(0 && "Unknown binary instruction type!");
1619     abort();
1620   }
1621   return IC->InsertNewInstBefore(New, I);
1622 }
1623
1624 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1625 // constant as the other operand, try to fold the binary operator into the
1626 // select arguments.  This also works for Cast instructions, which obviously do
1627 // not have a second operand.
1628 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1629                                      InstCombiner *IC) {
1630   // Don't modify shared select instructions
1631   if (!SI->hasOneUse()) return 0;
1632   Value *TV = SI->getOperand(1);
1633   Value *FV = SI->getOperand(2);
1634
1635   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1636     // Bool selects with constant operands can be folded to logical ops.
1637     if (SI->getType() == Type::BoolTy) return 0;
1638
1639     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1640     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1641
1642     return new SelectInst(SI->getCondition(), SelectTrueVal,
1643                           SelectFalseVal);
1644   }
1645   return 0;
1646 }
1647
1648
1649 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1650 /// node as operand #0, see if we can fold the instruction into the PHI (which
1651 /// is only possible if all operands to the PHI are constants).
1652 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1653   PHINode *PN = cast<PHINode>(I.getOperand(0));
1654   unsigned NumPHIValues = PN->getNumIncomingValues();
1655   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1656
1657   // Check to see if all of the operands of the PHI are constants.  If there is
1658   // one non-constant value, remember the BB it is.  If there is more than one
1659   // bail out.
1660   BasicBlock *NonConstBB = 0;
1661   for (unsigned i = 0; i != NumPHIValues; ++i)
1662     if (!isa<Constant>(PN->getIncomingValue(i))) {
1663       if (NonConstBB) return 0;  // More than one non-const value.
1664       NonConstBB = PN->getIncomingBlock(i);
1665       
1666       // If the incoming non-constant value is in I's block, we have an infinite
1667       // loop.
1668       if (NonConstBB == I.getParent())
1669         return 0;
1670     }
1671   
1672   // If there is exactly one non-constant value, we can insert a copy of the
1673   // operation in that block.  However, if this is a critical edge, we would be
1674   // inserting the computation one some other paths (e.g. inside a loop).  Only
1675   // do this if the pred block is unconditionally branching into the phi block.
1676   if (NonConstBB) {
1677     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1678     if (!BI || !BI->isUnconditional()) return 0;
1679   }
1680
1681   // Okay, we can do the transformation: create the new PHI node.
1682   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1683   I.setName("");
1684   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1685   InsertNewInstBefore(NewPN, *PN);
1686
1687   // Next, add all of the operands to the PHI.
1688   if (I.getNumOperands() == 2) {
1689     Constant *C = cast<Constant>(I.getOperand(1));
1690     for (unsigned i = 0; i != NumPHIValues; ++i) {
1691       Value *InV;
1692       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1693         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1694           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1695         else
1696           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1697       } else {
1698         assert(PN->getIncomingBlock(i) == NonConstBB);
1699         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1700           InV = BinaryOperator::create(BO->getOpcode(),
1701                                        PN->getIncomingValue(i), C, "phitmp",
1702                                        NonConstBB->getTerminator());
1703         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1704           InV = CmpInst::create(CI->getOpcode(), 
1705                                 CI->getPredicate(),
1706                                 PN->getIncomingValue(i), C, "phitmp",
1707                                 NonConstBB->getTerminator());
1708         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1709           InV = new ShiftInst(SI->getOpcode(),
1710                               PN->getIncomingValue(i), C, "phitmp",
1711                               NonConstBB->getTerminator());
1712         else
1713           assert(0 && "Unknown binop!");
1714         
1715         WorkList.push_back(cast<Instruction>(InV));
1716       }
1717       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1718     }
1719   } else { 
1720     CastInst *CI = cast<CastInst>(&I);
1721     const Type *RetTy = CI->getType();
1722     for (unsigned i = 0; i != NumPHIValues; ++i) {
1723       Value *InV;
1724       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1725         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1726       } else {
1727         assert(PN->getIncomingBlock(i) == NonConstBB);
1728         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1729                                I.getType(), "phitmp", 
1730                                NonConstBB->getTerminator());
1731         WorkList.push_back(cast<Instruction>(InV));
1732       }
1733       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1734     }
1735   }
1736   return ReplaceInstUsesWith(I, NewPN);
1737 }
1738
1739 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1740   bool Changed = SimplifyCommutative(I);
1741   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1742
1743   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1744     // X + undef -> undef
1745     if (isa<UndefValue>(RHS))
1746       return ReplaceInstUsesWith(I, RHS);
1747
1748     // X + 0 --> X
1749     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1750       if (RHSC->isNullValue())
1751         return ReplaceInstUsesWith(I, LHS);
1752     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1753       if (CFP->isExactlyValue(-0.0))
1754         return ReplaceInstUsesWith(I, LHS);
1755     }
1756
1757     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1758       // X + (signbit) --> X ^ signbit
1759       uint64_t Val = CI->getZExtValue();
1760       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1761         return BinaryOperator::createXor(LHS, RHS);
1762       
1763       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1764       // (X & 254)+1 -> (X&254)|1
1765       uint64_t KnownZero, KnownOne;
1766       if (!isa<PackedType>(I.getType()) &&
1767           SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
1768                                KnownZero, KnownOne))
1769         return &I;
1770     }
1771
1772     if (isa<PHINode>(LHS))
1773       if (Instruction *NV = FoldOpIntoPhi(I))
1774         return NV;
1775     
1776     ConstantInt *XorRHS = 0;
1777     Value *XorLHS = 0;
1778     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1779       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1780       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1781       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1782       
1783       uint64_t C0080Val = 1ULL << 31;
1784       int64_t CFF80Val = -C0080Val;
1785       unsigned Size = 32;
1786       do {
1787         if (TySizeBits > Size) {
1788           bool Found = false;
1789           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1790           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1791           if (RHSSExt == CFF80Val) {
1792             if (XorRHS->getZExtValue() == C0080Val)
1793               Found = true;
1794           } else if (RHSZExt == C0080Val) {
1795             if (XorRHS->getSExtValue() == CFF80Val)
1796               Found = true;
1797           }
1798           if (Found) {
1799             // This is a sign extend if the top bits are known zero.
1800             uint64_t Mask = ~0ULL;
1801             Mask <<= 64-(TySizeBits-Size);
1802             Mask &= XorLHS->getType()->getIntegralTypeMask();
1803             if (!MaskedValueIsZero(XorLHS, Mask))
1804               Size = 0;  // Not a sign ext, but can't be any others either.
1805             goto FoundSExt;
1806           }
1807         }
1808         Size >>= 1;
1809         C0080Val >>= Size;
1810         CFF80Val >>= Size;
1811       } while (Size >= 8);
1812       
1813 FoundSExt:
1814       const Type *MiddleType = 0;
1815       switch (Size) {
1816       default: break;
1817       case 32: MiddleType = Type::Int32Ty; break;
1818       case 16: MiddleType = Type::Int16Ty; break;
1819       case 8:  MiddleType = Type::Int8Ty; break;
1820       }
1821       if (MiddleType) {
1822         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1823         InsertNewInstBefore(NewTrunc, I);
1824         return new SExtInst(NewTrunc, I.getType());
1825       }
1826     }
1827   }
1828
1829   // X + X --> X << 1
1830   if (I.getType()->isInteger()) {
1831     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1832
1833     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1834       if (RHSI->getOpcode() == Instruction::Sub)
1835         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1836           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1837     }
1838     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1839       if (LHSI->getOpcode() == Instruction::Sub)
1840         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1841           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1842     }
1843   }
1844
1845   // -A + B  -->  B - A
1846   if (Value *V = dyn_castNegVal(LHS))
1847     return BinaryOperator::createSub(RHS, V);
1848
1849   // A + -B  -->  A - B
1850   if (!isa<Constant>(RHS))
1851     if (Value *V = dyn_castNegVal(RHS))
1852       return BinaryOperator::createSub(LHS, V);
1853
1854
1855   ConstantInt *C2;
1856   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1857     if (X == RHS)   // X*C + X --> X * (C+1)
1858       return BinaryOperator::createMul(RHS, AddOne(C2));
1859
1860     // X*C1 + X*C2 --> X * (C1+C2)
1861     ConstantInt *C1;
1862     if (X == dyn_castFoldableMul(RHS, C1))
1863       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1864   }
1865
1866   // X + X*C --> X * (C+1)
1867   if (dyn_castFoldableMul(RHS, C2) == LHS)
1868     return BinaryOperator::createMul(LHS, AddOne(C2));
1869
1870   // X + ~X --> -1   since   ~X = -X-1
1871   if (dyn_castNotVal(LHS) == RHS ||
1872       dyn_castNotVal(RHS) == LHS)
1873     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1874   
1875
1876   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1877   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1878     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1879       return R;
1880
1881   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1882     Value *X = 0;
1883     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1884       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1885       return BinaryOperator::createSub(C, X);
1886     }
1887
1888     // (X & FF00) + xx00  -> (X+xx00) & FF00
1889     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1890       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1891       if (Anded == CRHS) {
1892         // See if all bits from the first bit set in the Add RHS up are included
1893         // in the mask.  First, get the rightmost bit.
1894         uint64_t AddRHSV = CRHS->getZExtValue();
1895
1896         // Form a mask of all bits from the lowest bit added through the top.
1897         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1898         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1899
1900         // See if the and mask includes all of these bits.
1901         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1902
1903         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1904           // Okay, the xform is safe.  Insert the new add pronto.
1905           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1906                                                             LHS->getName()), I);
1907           return BinaryOperator::createAnd(NewAdd, C2);
1908         }
1909       }
1910     }
1911
1912     // Try to fold constant add into select arguments.
1913     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1914       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1915         return R;
1916   }
1917
1918   // add (cast *A to intptrtype) B -> 
1919   //   cast (GEP (cast *A to sbyte*) B) -> 
1920   //     intptrtype
1921   {
1922     CastInst *CI = dyn_cast<CastInst>(LHS);
1923     Value *Other = RHS;
1924     if (!CI) {
1925       CI = dyn_cast<CastInst>(RHS);
1926       Other = LHS;
1927     }
1928     if (CI && CI->getType()->isSized() && 
1929         (CI->getType()->getPrimitiveSizeInBits() == 
1930          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1931         && isa<PointerType>(CI->getOperand(0)->getType())) {
1932       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1933                                    PointerType::get(Type::Int8Ty), I);
1934       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1935       return new PtrToIntInst(I2, CI->getType());
1936     }
1937   }
1938
1939   return Changed ? &I : 0;
1940 }
1941
1942 // isSignBit - Return true if the value represented by the constant only has the
1943 // highest order bit set.
1944 static bool isSignBit(ConstantInt *CI) {
1945   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1946   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1947 }
1948
1949 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1950 ///
1951 static Value *RemoveNoopCast(Value *V) {
1952   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1953     const Type *CTy = CI->getType();
1954     const Type *OpTy = CI->getOperand(0)->getType();
1955     if (CTy->isInteger() && OpTy->isInteger()) {
1956       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1957         return RemoveNoopCast(CI->getOperand(0));
1958     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1959       return RemoveNoopCast(CI->getOperand(0));
1960   }
1961   return V;
1962 }
1963
1964 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1965   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1966
1967   if (Op0 == Op1)         // sub X, X  -> 0
1968     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1969
1970   // If this is a 'B = x-(-A)', change to B = x+A...
1971   if (Value *V = dyn_castNegVal(Op1))
1972     return BinaryOperator::createAdd(Op0, V);
1973
1974   if (isa<UndefValue>(Op0))
1975     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1976   if (isa<UndefValue>(Op1))
1977     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1978
1979   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1980     // Replace (-1 - A) with (~A)...
1981     if (C->isAllOnesValue())
1982       return BinaryOperator::createNot(Op1);
1983
1984     // C - ~X == X + (1+C)
1985     Value *X = 0;
1986     if (match(Op1, m_Not(m_Value(X))))
1987       return BinaryOperator::createAdd(X,
1988                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1989     // -((uint)X >> 31) -> ((int)X >> 31)
1990     // -((int)X >> 31) -> ((uint)X >> 31)
1991     if (C->isNullValue()) {
1992       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1993       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1994         if (SI->getOpcode() == Instruction::LShr) {
1995           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1996             // Check to see if we are shifting out everything but the sign bit.
1997             if (CU->getZExtValue() == 
1998                 SI->getType()->getPrimitiveSizeInBits()-1) {
1999               // Ok, the transformation is safe.  Insert AShr.
2000               // FIXME: Once integer types are signless, this cast should be 
2001               // removed.  
2002               Value *ShiftOp = SI->getOperand(0); 
2003               return new ShiftInst(Instruction::AShr, ShiftOp, CU,
2004                                    SI->getName());
2005             }
2006           }
2007         }
2008         else if (SI->getOpcode() == Instruction::AShr) {
2009           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2010             // Check to see if we are shifting out everything but the sign bit.
2011             if (CU->getZExtValue() == 
2012                 SI->getType()->getPrimitiveSizeInBits()-1) {
2013               
2014               // Ok, the transformation is safe.  Insert LShr. 
2015               return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU, 
2016                                    SI->getName());
2017             }
2018           }
2019         } 
2020     }
2021
2022     // Try to fold constant sub into select arguments.
2023     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2024       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2025         return R;
2026
2027     if (isa<PHINode>(Op0))
2028       if (Instruction *NV = FoldOpIntoPhi(I))
2029         return NV;
2030   }
2031
2032   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2033     if (Op1I->getOpcode() == Instruction::Add &&
2034         !Op0->getType()->isFPOrFPVector()) {
2035       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2036         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2037       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2038         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2039       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2040         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2041           // C1-(X+C2) --> (C1-C2)-X
2042           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2043                                            Op1I->getOperand(0));
2044       }
2045     }
2046
2047     if (Op1I->hasOneUse()) {
2048       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2049       // is not used by anyone else...
2050       //
2051       if (Op1I->getOpcode() == Instruction::Sub &&
2052           !Op1I->getType()->isFPOrFPVector()) {
2053         // Swap the two operands of the subexpr...
2054         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2055         Op1I->setOperand(0, IIOp1);
2056         Op1I->setOperand(1, IIOp0);
2057
2058         // Create the new top level add instruction...
2059         return BinaryOperator::createAdd(Op0, Op1);
2060       }
2061
2062       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2063       //
2064       if (Op1I->getOpcode() == Instruction::And &&
2065           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2066         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2067
2068         Value *NewNot =
2069           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2070         return BinaryOperator::createAnd(Op0, NewNot);
2071       }
2072
2073       // 0 - (X sdiv C)  -> (X sdiv -C)
2074       if (Op1I->getOpcode() == Instruction::SDiv)
2075         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2076           if (CSI->isNullValue())
2077             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2078               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2079                                                ConstantExpr::getNeg(DivRHS));
2080
2081       // X - X*C --> X * (1-C)
2082       ConstantInt *C2 = 0;
2083       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2084         Constant *CP1 =
2085           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2086         return BinaryOperator::createMul(Op0, CP1);
2087       }
2088     }
2089   }
2090
2091   if (!Op0->getType()->isFPOrFPVector())
2092     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2093       if (Op0I->getOpcode() == Instruction::Add) {
2094         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2095           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2096         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2097           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2098       } else if (Op0I->getOpcode() == Instruction::Sub) {
2099         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2100           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2101       }
2102
2103   ConstantInt *C1;
2104   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2105     if (X == Op1) { // X*C - X --> X * (C-1)
2106       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2107       return BinaryOperator::createMul(Op1, CP1);
2108     }
2109
2110     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2111     if (X == dyn_castFoldableMul(Op1, C2))
2112       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2113   }
2114   return 0;
2115 }
2116
2117 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2118 /// really just returns true if the most significant (sign) bit is set.
2119 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2120   switch (pred) {
2121     case ICmpInst::ICMP_SLT: 
2122       // True if LHS s< RHS and RHS == 0
2123       return RHS->isNullValue();
2124     case ICmpInst::ICMP_SLE: 
2125       // True if LHS s<= RHS and RHS == -1
2126       return RHS->isAllOnesValue();
2127     case ICmpInst::ICMP_UGE: 
2128       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2129       return RHS->getZExtValue() == (1ULL << 
2130         (RHS->getType()->getPrimitiveSizeInBits()-1));
2131     case ICmpInst::ICMP_UGT:
2132       // True if LHS u> RHS and RHS == high-bit-mask - 1
2133       return RHS->getZExtValue() ==
2134         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2135     default:
2136       return false;
2137   }
2138 }
2139
2140 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2141   bool Changed = SimplifyCommutative(I);
2142   Value *Op0 = I.getOperand(0);
2143
2144   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2145     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2146
2147   // Simplify mul instructions with a constant RHS...
2148   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2149     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2150
2151       // ((X << C1)*C2) == (X * (C2 << C1))
2152       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2153         if (SI->getOpcode() == Instruction::Shl)
2154           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2155             return BinaryOperator::createMul(SI->getOperand(0),
2156                                              ConstantExpr::getShl(CI, ShOp));
2157
2158       if (CI->isNullValue())
2159         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2160       if (CI->equalsInt(1))                  // X * 1  == X
2161         return ReplaceInstUsesWith(I, Op0);
2162       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2163         return BinaryOperator::createNeg(Op0, I.getName());
2164
2165       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2166       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2167         uint64_t C = Log2_64(Val);
2168         return new ShiftInst(Instruction::Shl, Op0,
2169                              ConstantInt::get(Type::Int8Ty, C));
2170       }
2171     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2172       if (Op1F->isNullValue())
2173         return ReplaceInstUsesWith(I, Op1);
2174
2175       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2176       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2177       if (Op1F->getValue() == 1.0)
2178         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2179     }
2180     
2181     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2182       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2183           isa<ConstantInt>(Op0I->getOperand(1))) {
2184         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2185         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2186                                                      Op1, "tmp");
2187         InsertNewInstBefore(Add, I);
2188         Value *C1C2 = ConstantExpr::getMul(Op1, 
2189                                            cast<Constant>(Op0I->getOperand(1)));
2190         return BinaryOperator::createAdd(Add, C1C2);
2191         
2192       }
2193
2194     // Try to fold constant mul into select arguments.
2195     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2196       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2197         return R;
2198
2199     if (isa<PHINode>(Op0))
2200       if (Instruction *NV = FoldOpIntoPhi(I))
2201         return NV;
2202   }
2203
2204   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2205     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2206       return BinaryOperator::createMul(Op0v, Op1v);
2207
2208   // If one of the operands of the multiply is a cast from a boolean value, then
2209   // we know the bool is either zero or one, so this is a 'masking' multiply.
2210   // See if we can simplify things based on how the boolean was originally
2211   // formed.
2212   CastInst *BoolCast = 0;
2213   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2214     if (CI->getOperand(0)->getType() == Type::BoolTy)
2215       BoolCast = CI;
2216   if (!BoolCast)
2217     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2218       if (CI->getOperand(0)->getType() == Type::BoolTy)
2219         BoolCast = CI;
2220   if (BoolCast) {
2221     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2222       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2223       const Type *SCOpTy = SCIOp0->getType();
2224
2225       // If the icmp is true iff the sign bit of X is set, then convert this
2226       // multiply into a shift/and combination.
2227       if (isa<ConstantInt>(SCIOp1) &&
2228           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2229         // Shift the X value right to turn it into "all signbits".
2230         Constant *Amt = ConstantInt::get(Type::Int8Ty,
2231                                           SCOpTy->getPrimitiveSizeInBits()-1);
2232         Value *V =
2233           InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2234                                             BoolCast->getOperand(0)->getName()+
2235                                             ".mask"), I);
2236
2237         // If the multiply type is not the same as the source type, sign extend
2238         // or truncate to the multiply type.
2239         if (I.getType() != V->getType()) {
2240           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2241           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2242           Instruction::CastOps opcode = 
2243             (SrcBits == DstBits ? Instruction::BitCast : 
2244              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2245           V = InsertCastBefore(opcode, V, I.getType(), I);
2246         }
2247
2248         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2249         return BinaryOperator::createAnd(V, OtherOp);
2250       }
2251     }
2252   }
2253
2254   return Changed ? &I : 0;
2255 }
2256
2257 /// This function implements the transforms on div instructions that work
2258 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2259 /// used by the visitors to those instructions.
2260 /// @brief Transforms common to all three div instructions
2261 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2262   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2263
2264   // undef / X -> 0
2265   if (isa<UndefValue>(Op0))
2266     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2267
2268   // X / undef -> undef
2269   if (isa<UndefValue>(Op1))
2270     return ReplaceInstUsesWith(I, Op1);
2271
2272   // Handle cases involving: div X, (select Cond, Y, Z)
2273   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2274     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2275     // same basic block, then we replace the select with Y, and the condition 
2276     // of the select with false (if the cond value is in the same BB).  If the
2277     // select has uses other than the div, this allows them to be simplified
2278     // also. Note that div X, Y is just as good as div X, 0 (undef)
2279     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2280       if (ST->isNullValue()) {
2281         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2282         if (CondI && CondI->getParent() == I.getParent())
2283           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2284         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2285           I.setOperand(1, SI->getOperand(2));
2286         else
2287           UpdateValueUsesWith(SI, SI->getOperand(2));
2288         return &I;
2289       }
2290
2291     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2292     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2293       if (ST->isNullValue()) {
2294         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2295         if (CondI && CondI->getParent() == I.getParent())
2296           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2297         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2298           I.setOperand(1, SI->getOperand(1));
2299         else
2300           UpdateValueUsesWith(SI, SI->getOperand(1));
2301         return &I;
2302       }
2303   }
2304
2305   return 0;
2306 }
2307
2308 /// This function implements the transforms common to both integer division
2309 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2310 /// division instructions.
2311 /// @brief Common integer divide transforms
2312 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2313   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2314
2315   if (Instruction *Common = commonDivTransforms(I))
2316     return Common;
2317
2318   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2319     // div X, 1 == X
2320     if (RHS->equalsInt(1))
2321       return ReplaceInstUsesWith(I, Op0);
2322
2323     // (X / C1) / C2  -> X / (C1*C2)
2324     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2325       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2326         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2327           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2328                                         ConstantExpr::getMul(RHS, LHSRHS));
2329         }
2330
2331     if (!RHS->isNullValue()) { // avoid X udiv 0
2332       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2333         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2334           return R;
2335       if (isa<PHINode>(Op0))
2336         if (Instruction *NV = FoldOpIntoPhi(I))
2337           return NV;
2338     }
2339   }
2340
2341   // 0 / X == 0, we don't need to preserve faults!
2342   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2343     if (LHS->equalsInt(0))
2344       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2345
2346   return 0;
2347 }
2348
2349 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2350   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2351
2352   // Handle the integer div common cases
2353   if (Instruction *Common = commonIDivTransforms(I))
2354     return Common;
2355
2356   // X udiv C^2 -> X >> C
2357   // Check to see if this is an unsigned division with an exact power of 2,
2358   // if so, convert to a right shift.
2359   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2360     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2361       if (isPowerOf2_64(Val)) {
2362         uint64_t ShiftAmt = Log2_64(Val);
2363         return new ShiftInst(Instruction::LShr, Op0, 
2364                               ConstantInt::get(Type::Int8Ty, ShiftAmt));
2365       }
2366   }
2367
2368   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2369   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2370     if (RHSI->getOpcode() == Instruction::Shl &&
2371         isa<ConstantInt>(RHSI->getOperand(0))) {
2372       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2373       if (isPowerOf2_64(C1)) {
2374         Value *N = RHSI->getOperand(1);
2375         const Type *NTy = N->getType();
2376         if (uint64_t C2 = Log2_64(C1)) {
2377           Constant *C2V = ConstantInt::get(NTy, C2);
2378           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2379         }
2380         return new ShiftInst(Instruction::LShr, Op0, N);
2381       }
2382     }
2383   }
2384   
2385   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2386   // where C1&C2 are powers of two.
2387   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2388     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2389       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2390         if (!STO->isNullValue() && !STO->isNullValue()) {
2391           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2392           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2393             // Compute the shift amounts
2394             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2395             // Construct the "on true" case of the select
2396             Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2397             Instruction *TSI = 
2398               new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2399             TSI = InsertNewInstBefore(TSI, I);
2400     
2401             // Construct the "on false" case of the select
2402             Constant *FC = ConstantInt::get(Type::Int8Ty, FSA); 
2403             Instruction *FSI = 
2404               new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2405             FSI = InsertNewInstBefore(FSI, I);
2406
2407             // construct the select instruction and return it.
2408             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2409           }
2410         }
2411   }
2412   return 0;
2413 }
2414
2415 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2416   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2417
2418   // Handle the integer div common cases
2419   if (Instruction *Common = commonIDivTransforms(I))
2420     return Common;
2421
2422   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2423     // sdiv X, -1 == -X
2424     if (RHS->isAllOnesValue())
2425       return BinaryOperator::createNeg(Op0);
2426
2427     // -X/C -> X/-C
2428     if (Value *LHSNeg = dyn_castNegVal(Op0))
2429       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2430   }
2431
2432   // If the sign bits of both operands are zero (i.e. we can prove they are
2433   // unsigned inputs), turn this into a udiv.
2434   if (I.getType()->isInteger()) {
2435     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2436     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2437       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2438     }
2439   }      
2440   
2441   return 0;
2442 }
2443
2444 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2445   return commonDivTransforms(I);
2446 }
2447
2448 /// GetFactor - If we can prove that the specified value is at least a multiple
2449 /// of some factor, return that factor.
2450 static Constant *GetFactor(Value *V) {
2451   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2452     return CI;
2453   
2454   // Unless we can be tricky, we know this is a multiple of 1.
2455   Constant *Result = ConstantInt::get(V->getType(), 1);
2456   
2457   Instruction *I = dyn_cast<Instruction>(V);
2458   if (!I) return Result;
2459   
2460   if (I->getOpcode() == Instruction::Mul) {
2461     // Handle multiplies by a constant, etc.
2462     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2463                                 GetFactor(I->getOperand(1)));
2464   } else if (I->getOpcode() == Instruction::Shl) {
2465     // (X<<C) -> X * (1 << C)
2466     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2467       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2468       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2469     }
2470   } else if (I->getOpcode() == Instruction::And) {
2471     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2472       // X & 0xFFF0 is known to be a multiple of 16.
2473       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2474       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2475         return ConstantExpr::getShl(Result, 
2476                                     ConstantInt::get(Type::Int8Ty, Zeros));
2477     }
2478   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2479     // Only handle int->int casts.
2480     if (!CI->isIntegerCast())
2481       return Result;
2482     Value *Op = CI->getOperand(0);
2483     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2484   }    
2485   return Result;
2486 }
2487
2488 /// This function implements the transforms on rem instructions that work
2489 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2490 /// is used by the visitors to those instructions.
2491 /// @brief Transforms common to all three rem instructions
2492 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2493   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2494
2495   // 0 % X == 0, we don't need to preserve faults!
2496   if (Constant *LHS = dyn_cast<Constant>(Op0))
2497     if (LHS->isNullValue())
2498       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2499
2500   if (isa<UndefValue>(Op0))              // undef % X -> 0
2501     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2502   if (isa<UndefValue>(Op1))
2503     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2504
2505   // Handle cases involving: rem X, (select Cond, Y, Z)
2506   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2507     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2508     // the same basic block, then we replace the select with Y, and the
2509     // condition of the select with false (if the cond value is in the same
2510     // BB).  If the select has uses other than the div, this allows them to be
2511     // simplified also.
2512     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2513       if (ST->isNullValue()) {
2514         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2515         if (CondI && CondI->getParent() == I.getParent())
2516           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2517         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2518           I.setOperand(1, SI->getOperand(2));
2519         else
2520           UpdateValueUsesWith(SI, SI->getOperand(2));
2521         return &I;
2522       }
2523     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2524     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2525       if (ST->isNullValue()) {
2526         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2527         if (CondI && CondI->getParent() == I.getParent())
2528           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2529         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2530           I.setOperand(1, SI->getOperand(1));
2531         else
2532           UpdateValueUsesWith(SI, SI->getOperand(1));
2533         return &I;
2534       }
2535   }
2536
2537   return 0;
2538 }
2539
2540 /// This function implements the transforms common to both integer remainder
2541 /// instructions (urem and srem). It is called by the visitors to those integer
2542 /// remainder instructions.
2543 /// @brief Common integer remainder transforms
2544 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2545   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2546
2547   if (Instruction *common = commonRemTransforms(I))
2548     return common;
2549
2550   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2551     // X % 0 == undef, we don't need to preserve faults!
2552     if (RHS->equalsInt(0))
2553       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2554     
2555     if (RHS->equalsInt(1))  // X % 1 == 0
2556       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2557
2558     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2559       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2560         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2561           return R;
2562       } else if (isa<PHINode>(Op0I)) {
2563         if (Instruction *NV = FoldOpIntoPhi(I))
2564           return NV;
2565       }
2566       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2567       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2568         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2569     }
2570   }
2571
2572   return 0;
2573 }
2574
2575 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2576   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2577
2578   if (Instruction *common = commonIRemTransforms(I))
2579     return common;
2580   
2581   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2582     // X urem C^2 -> X and C
2583     // Check to see if this is an unsigned remainder with an exact power of 2,
2584     // if so, convert to a bitwise and.
2585     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2586       if (isPowerOf2_64(C->getZExtValue()))
2587         return BinaryOperator::createAnd(Op0, SubOne(C));
2588   }
2589
2590   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2591     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2592     if (RHSI->getOpcode() == Instruction::Shl &&
2593         isa<ConstantInt>(RHSI->getOperand(0))) {
2594       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2595       if (isPowerOf2_64(C1)) {
2596         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2597         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2598                                                                    "tmp"), I);
2599         return BinaryOperator::createAnd(Op0, Add);
2600       }
2601     }
2602   }
2603
2604   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2605   // where C1&C2 are powers of two.
2606   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2607     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2608       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2609         // STO == 0 and SFO == 0 handled above.
2610         if (isPowerOf2_64(STO->getZExtValue()) && 
2611             isPowerOf2_64(SFO->getZExtValue())) {
2612           Value *TrueAnd = InsertNewInstBefore(
2613             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2614           Value *FalseAnd = InsertNewInstBefore(
2615             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2616           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2617         }
2618       }
2619   }
2620   
2621   return 0;
2622 }
2623
2624 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2625   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2626
2627   if (Instruction *common = commonIRemTransforms(I))
2628     return common;
2629   
2630   if (Value *RHSNeg = dyn_castNegVal(Op1))
2631     if (!isa<ConstantInt>(RHSNeg) || 
2632         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2633       // X % -Y -> X % Y
2634       AddUsesToWorkList(I);
2635       I.setOperand(1, RHSNeg);
2636       return &I;
2637     }
2638  
2639   // If the top bits of both operands are zero (i.e. we can prove they are
2640   // unsigned inputs), turn this into a urem.
2641   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2642   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2643     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2644     return BinaryOperator::createURem(Op0, Op1, I.getName());
2645   }
2646
2647   return 0;
2648 }
2649
2650 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2651   return commonRemTransforms(I);
2652 }
2653
2654 // isMaxValueMinusOne - return true if this is Max-1
2655 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2656   if (isSigned) {
2657     // Calculate 0111111111..11111
2658     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2659     int64_t Val = INT64_MAX;             // All ones
2660     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2661     return C->getSExtValue() == Val-1;
2662   }
2663   return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2664 }
2665
2666 // isMinValuePlusOne - return true if this is Min+1
2667 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2668   if (isSigned) {
2669     // Calculate 1111111111000000000000
2670     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2671     int64_t Val = -1;                    // All ones
2672     Val <<= TypeBits-1;                  // Shift over to the right spot
2673     return C->getSExtValue() == Val+1;
2674   }
2675   return C->getZExtValue() == 1; // unsigned
2676 }
2677
2678 // isOneBitSet - Return true if there is exactly one bit set in the specified
2679 // constant.
2680 static bool isOneBitSet(const ConstantInt *CI) {
2681   uint64_t V = CI->getZExtValue();
2682   return V && (V & (V-1)) == 0;
2683 }
2684
2685 #if 0   // Currently unused
2686 // isLowOnes - Return true if the constant is of the form 0+1+.
2687 static bool isLowOnes(const ConstantInt *CI) {
2688   uint64_t V = CI->getZExtValue();
2689
2690   // There won't be bits set in parts that the type doesn't contain.
2691   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2692
2693   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2694   return U && V && (U & V) == 0;
2695 }
2696 #endif
2697
2698 // isHighOnes - Return true if the constant is of the form 1+0+.
2699 // This is the same as lowones(~X).
2700 static bool isHighOnes(const ConstantInt *CI) {
2701   uint64_t V = ~CI->getZExtValue();
2702   if (~V == 0) return false;  // 0's does not match "1+"
2703
2704   // There won't be bits set in parts that the type doesn't contain.
2705   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2706
2707   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2708   return U && V && (U & V) == 0;
2709 }
2710
2711 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2712 /// are carefully arranged to allow folding of expressions such as:
2713 ///
2714 ///      (A < B) | (A > B) --> (A != B)
2715 ///
2716 /// Note that this is only valid if the first and second predicates have the
2717 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2718 ///
2719 /// Three bits are used to represent the condition, as follows:
2720 ///   0  A > B
2721 ///   1  A == B
2722 ///   2  A < B
2723 ///
2724 /// <=>  Value  Definition
2725 /// 000     0   Always false
2726 /// 001     1   A >  B
2727 /// 010     2   A == B
2728 /// 011     3   A >= B
2729 /// 100     4   A <  B
2730 /// 101     5   A != B
2731 /// 110     6   A <= B
2732 /// 111     7   Always true
2733 ///  
2734 static unsigned getICmpCode(const ICmpInst *ICI) {
2735   switch (ICI->getPredicate()) {
2736     // False -> 0
2737   case ICmpInst::ICMP_UGT: return 1;  // 001
2738   case ICmpInst::ICMP_SGT: return 1;  // 001
2739   case ICmpInst::ICMP_EQ:  return 2;  // 010
2740   case ICmpInst::ICMP_UGE: return 3;  // 011
2741   case ICmpInst::ICMP_SGE: return 3;  // 011
2742   case ICmpInst::ICMP_ULT: return 4;  // 100
2743   case ICmpInst::ICMP_SLT: return 4;  // 100
2744   case ICmpInst::ICMP_NE:  return 5;  // 101
2745   case ICmpInst::ICMP_ULE: return 6;  // 110
2746   case ICmpInst::ICMP_SLE: return 6;  // 110
2747     // True -> 7
2748   default:
2749     assert(0 && "Invalid ICmp predicate!");
2750     return 0;
2751   }
2752 }
2753
2754 /// getICmpValue - This is the complement of getICmpCode, which turns an
2755 /// opcode and two operands into either a constant true or false, or a brand 
2756 /// new /// ICmp instruction. The sign is passed in to determine which kind
2757 /// of predicate to use in new icmp instructions.
2758 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2759   switch (code) {
2760   default: assert(0 && "Illegal ICmp code!");
2761   case  0: return ConstantBool::getFalse();
2762   case  1: 
2763     if (sign)
2764       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2765     else
2766       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2767   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2768   case  3: 
2769     if (sign)
2770       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2771     else
2772       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2773   case  4: 
2774     if (sign)
2775       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2776     else
2777       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2778   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2779   case  6: 
2780     if (sign)
2781       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2782     else
2783       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2784   case  7: return ConstantBool::getTrue();
2785   }
2786 }
2787
2788 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2789   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2790     (ICmpInst::isSignedPredicate(p1) && 
2791      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2792     (ICmpInst::isSignedPredicate(p2) && 
2793      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2794 }
2795
2796 namespace { 
2797 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2798 struct FoldICmpLogical {
2799   InstCombiner &IC;
2800   Value *LHS, *RHS;
2801   ICmpInst::Predicate pred;
2802   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2803     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2804       pred(ICI->getPredicate()) {}
2805   bool shouldApply(Value *V) const {
2806     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2807       if (PredicatesFoldable(pred, ICI->getPredicate()))
2808         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2809                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2810     return false;
2811   }
2812   Instruction *apply(Instruction &Log) const {
2813     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2814     if (ICI->getOperand(0) != LHS) {
2815       assert(ICI->getOperand(1) == LHS);
2816       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2817     }
2818
2819     unsigned LHSCode = getICmpCode(ICI);
2820     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2821     unsigned Code;
2822     switch (Log.getOpcode()) {
2823     case Instruction::And: Code = LHSCode & RHSCode; break;
2824     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2825     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2826     default: assert(0 && "Illegal logical opcode!"); return 0;
2827     }
2828
2829     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2830     if (Instruction *I = dyn_cast<Instruction>(RV))
2831       return I;
2832     // Otherwise, it's a constant boolean value...
2833     return IC.ReplaceInstUsesWith(Log, RV);
2834   }
2835 };
2836 } // end anonymous namespace
2837
2838 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2839 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2840 // guaranteed to be either a shift instruction or a binary operator.
2841 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2842                                     ConstantIntegral *OpRHS,
2843                                     ConstantIntegral *AndRHS,
2844                                     BinaryOperator &TheAnd) {
2845   Value *X = Op->getOperand(0);
2846   Constant *Together = 0;
2847   if (!isa<ShiftInst>(Op))
2848     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2849
2850   switch (Op->getOpcode()) {
2851   case Instruction::Xor:
2852     if (Op->hasOneUse()) {
2853       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2854       std::string OpName = Op->getName(); Op->setName("");
2855       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2856       InsertNewInstBefore(And, TheAnd);
2857       return BinaryOperator::createXor(And, Together);
2858     }
2859     break;
2860   case Instruction::Or:
2861     if (Together == AndRHS) // (X | C) & C --> C
2862       return ReplaceInstUsesWith(TheAnd, AndRHS);
2863
2864     if (Op->hasOneUse() && Together != OpRHS) {
2865       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2866       std::string Op0Name = Op->getName(); Op->setName("");
2867       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2868       InsertNewInstBefore(Or, TheAnd);
2869       return BinaryOperator::createAnd(Or, AndRHS);
2870     }
2871     break;
2872   case Instruction::Add:
2873     if (Op->hasOneUse()) {
2874       // Adding a one to a single bit bit-field should be turned into an XOR
2875       // of the bit.  First thing to check is to see if this AND is with a
2876       // single bit constant.
2877       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2878
2879       // Clear bits that are not part of the constant.
2880       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2881
2882       // If there is only one bit set...
2883       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2884         // Ok, at this point, we know that we are masking the result of the
2885         // ADD down to exactly one bit.  If the constant we are adding has
2886         // no bits set below this bit, then we can eliminate the ADD.
2887         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2888
2889         // Check to see if any bits below the one bit set in AndRHSV are set.
2890         if ((AddRHS & (AndRHSV-1)) == 0) {
2891           // If not, the only thing that can effect the output of the AND is
2892           // the bit specified by AndRHSV.  If that bit is set, the effect of
2893           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2894           // no effect.
2895           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2896             TheAnd.setOperand(0, X);
2897             return &TheAnd;
2898           } else {
2899             std::string Name = Op->getName(); Op->setName("");
2900             // Pull the XOR out of the AND.
2901             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2902             InsertNewInstBefore(NewAnd, TheAnd);
2903             return BinaryOperator::createXor(NewAnd, AndRHS);
2904           }
2905         }
2906       }
2907     }
2908     break;
2909
2910   case Instruction::Shl: {
2911     // We know that the AND will not produce any of the bits shifted in, so if
2912     // the anded constant includes them, clear them now!
2913     //
2914     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2915     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2916     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2917
2918     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2919       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2920     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2921       TheAnd.setOperand(1, CI);
2922       return &TheAnd;
2923     }
2924     break;
2925   }
2926   case Instruction::LShr:
2927   {
2928     // We know that the AND will not produce any of the bits shifted in, so if
2929     // the anded constant includes them, clear them now!  This only applies to
2930     // unsigned shifts, because a signed shr may bring in set bits!
2931     //
2932     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2933     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2934     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2935
2936     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2937       return ReplaceInstUsesWith(TheAnd, Op);
2938     } else if (CI != AndRHS) {
2939       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2940       return &TheAnd;
2941     }
2942     break;
2943   }
2944   case Instruction::AShr:
2945     // Signed shr.
2946     // See if this is shifting in some sign extension, then masking it out
2947     // with an and.
2948     if (Op->hasOneUse()) {
2949       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2950       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2951       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2952       if (C == AndRHS) {          // Masking out bits shifted in.
2953         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2954         // Make the argument unsigned.
2955         Value *ShVal = Op->getOperand(0);
2956         ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal, 
2957                                     OpRHS, Op->getName()), TheAnd);
2958         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2959       }
2960     }
2961     break;
2962   }
2963   return 0;
2964 }
2965
2966
2967 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2968 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2969 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2970 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2971 /// insert new instructions.
2972 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2973                                            bool isSigned, bool Inside, 
2974                                            Instruction &IB) {
2975   assert(cast<ConstantBool>(ConstantExpr::getICmp((isSigned ? 
2976             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getValue() &&
2977          "Lo is not <= Hi in range emission code!");
2978     
2979   if (Inside) {
2980     if (Lo == Hi)  // Trivially false.
2981       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2982
2983     // V >= Min && V < Hi --> V < Hi
2984     if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
2985     ICmpInst::Predicate pred = (isSigned ? 
2986         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2987       return new ICmpInst(pred, V, Hi);
2988     }
2989
2990     // Emit V-Lo <u Hi-Lo
2991     Constant *NegLo = ConstantExpr::getNeg(Lo);
2992     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2993     InsertNewInstBefore(Add, IB);
2994     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2995     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2996   }
2997
2998   if (Lo == Hi)  // Trivially true.
2999     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3000
3001   // V < Min || V >= Hi ->'V > Hi-1'
3002   Hi = SubOne(cast<ConstantInt>(Hi));
3003   if (cast<ConstantIntegral>(Lo)->isMinValue(isSigned)) {
3004     ICmpInst::Predicate pred = (isSigned ? 
3005         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3006     return new ICmpInst(pred, V, Hi);
3007   }
3008
3009   // Emit V-Lo > Hi-1-Lo
3010   Constant *NegLo = ConstantExpr::getNeg(Lo);
3011   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3012   InsertNewInstBefore(Add, IB);
3013   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3014   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3015 }
3016
3017 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3018 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3019 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3020 // not, since all 1s are not contiguous.
3021 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
3022   uint64_t V = Val->getZExtValue();
3023   if (!isShiftedMask_64(V)) return false;
3024
3025   // look for the first zero bit after the run of ones
3026   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3027   // look for the first non-zero bit
3028   ME = 64-CountLeadingZeros_64(V);
3029   return true;
3030 }
3031
3032
3033
3034 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3035 /// where isSub determines whether the operator is a sub.  If we can fold one of
3036 /// the following xforms:
3037 /// 
3038 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3039 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3040 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3041 ///
3042 /// return (A +/- B).
3043 ///
3044 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3045                                         ConstantIntegral *Mask, bool isSub,
3046                                         Instruction &I) {
3047   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3048   if (!LHSI || LHSI->getNumOperands() != 2 ||
3049       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3050
3051   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3052
3053   switch (LHSI->getOpcode()) {
3054   default: return 0;
3055   case Instruction::And:
3056     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3057       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3058       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3059         break;
3060
3061       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3062       // part, we don't need any explicit masks to take them out of A.  If that
3063       // is all N is, ignore it.
3064       unsigned MB, ME;
3065       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3066         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
3067         Mask >>= 64-MB+1;
3068         if (MaskedValueIsZero(RHS, Mask))
3069           break;
3070       }
3071     }
3072     return 0;
3073   case Instruction::Or:
3074   case Instruction::Xor:
3075     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3076     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3077         ConstantExpr::getAnd(N, Mask)->isNullValue())
3078       break;
3079     return 0;
3080   }
3081   
3082   Instruction *New;
3083   if (isSub)
3084     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3085   else
3086     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3087   return InsertNewInstBefore(New, I);
3088 }
3089
3090 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3091   bool Changed = SimplifyCommutative(I);
3092   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3093
3094   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3095     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3096
3097   // and X, X = X
3098   if (Op0 == Op1)
3099     return ReplaceInstUsesWith(I, Op1);
3100
3101   // See if we can simplify any instructions used by the instruction whose sole 
3102   // purpose is to compute bits we don't care about.
3103   uint64_t KnownZero, KnownOne;
3104   if (!isa<PackedType>(I.getType()) &&
3105       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3106                            KnownZero, KnownOne))
3107     return &I;
3108   
3109   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
3110     uint64_t AndRHSMask = AndRHS->getZExtValue();
3111     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
3112     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3113
3114     // Optimize a variety of ((val OP C1) & C2) combinations...
3115     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3116       Instruction *Op0I = cast<Instruction>(Op0);
3117       Value *Op0LHS = Op0I->getOperand(0);
3118       Value *Op0RHS = Op0I->getOperand(1);
3119       switch (Op0I->getOpcode()) {
3120       case Instruction::Xor:
3121       case Instruction::Or:
3122         // If the mask is only needed on one incoming arm, push it up.
3123         if (Op0I->hasOneUse()) {
3124           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3125             // Not masking anything out for the LHS, move to RHS.
3126             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3127                                                    Op0RHS->getName()+".masked");
3128             InsertNewInstBefore(NewRHS, I);
3129             return BinaryOperator::create(
3130                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3131           }
3132           if (!isa<Constant>(Op0RHS) &&
3133               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3134             // Not masking anything out for the RHS, move to LHS.
3135             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3136                                                    Op0LHS->getName()+".masked");
3137             InsertNewInstBefore(NewLHS, I);
3138             return BinaryOperator::create(
3139                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3140           }
3141         }
3142
3143         break;
3144       case Instruction::Add:
3145         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3146         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3147         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3148         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3149           return BinaryOperator::createAnd(V, AndRHS);
3150         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3151           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3152         break;
3153
3154       case Instruction::Sub:
3155         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3156         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3157         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3158         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3159           return BinaryOperator::createAnd(V, AndRHS);
3160         break;
3161       }
3162
3163       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3164         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3165           return Res;
3166     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3167       // If this is an integer truncation or change from signed-to-unsigned, and
3168       // if the source is an and/or with immediate, transform it.  This
3169       // frequently occurs for bitfield accesses.
3170       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3171         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3172             CastOp->getNumOperands() == 2)
3173           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3174             if (CastOp->getOpcode() == Instruction::And) {
3175               // Change: and (cast (and X, C1) to T), C2
3176               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3177               // This will fold the two constants together, which may allow 
3178               // other simplifications.
3179               Instruction *NewCast = CastInst::createTruncOrBitCast(
3180                 CastOp->getOperand(0), I.getType(), 
3181                 CastOp->getName()+".shrunk");
3182               NewCast = InsertNewInstBefore(NewCast, I);
3183               // trunc_or_bitcast(C1)&C2
3184               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3185               C3 = ConstantExpr::getAnd(C3, AndRHS);
3186               return BinaryOperator::createAnd(NewCast, C3);
3187             } else if (CastOp->getOpcode() == Instruction::Or) {
3188               // Change: and (cast (or X, C1) to T), C2
3189               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3190               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3191               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3192                 return ReplaceInstUsesWith(I, AndRHS);
3193             }
3194       }
3195     }
3196
3197     // Try to fold constant and into select arguments.
3198     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3199       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3200         return R;
3201     if (isa<PHINode>(Op0))
3202       if (Instruction *NV = FoldOpIntoPhi(I))
3203         return NV;
3204   }
3205
3206   Value *Op0NotVal = dyn_castNotVal(Op0);
3207   Value *Op1NotVal = dyn_castNotVal(Op1);
3208
3209   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3210     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3211
3212   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3213   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3214     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3215                                                I.getName()+".demorgan");
3216     InsertNewInstBefore(Or, I);
3217     return BinaryOperator::createNot(Or);
3218   }
3219   
3220   {
3221     Value *A = 0, *B = 0;
3222     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3223       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3224         return ReplaceInstUsesWith(I, Op1);
3225     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3226       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3227         return ReplaceInstUsesWith(I, Op0);
3228     
3229     if (Op0->hasOneUse() &&
3230         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3231       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3232         I.swapOperands();     // Simplify below
3233         std::swap(Op0, Op1);
3234       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3235         cast<BinaryOperator>(Op0)->swapOperands();
3236         I.swapOperands();     // Simplify below
3237         std::swap(Op0, Op1);
3238       }
3239     }
3240     if (Op1->hasOneUse() &&
3241         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3242       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3243         cast<BinaryOperator>(Op1)->swapOperands();
3244         std::swap(A, B);
3245       }
3246       if (A == Op0) {                                // A&(A^B) -> A & ~B
3247         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3248         InsertNewInstBefore(NotB, I);
3249         return BinaryOperator::createAnd(A, NotB);
3250       }
3251     }
3252   }
3253   
3254   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3255     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3256     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3257       return R;
3258
3259     Value *LHSVal, *RHSVal;
3260     ConstantInt *LHSCst, *RHSCst;
3261     ICmpInst::Predicate LHSCC, RHSCC;
3262     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3263       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3264         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3265             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3266             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3267             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3268             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3269             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3270           // Ensure that the larger constant is on the RHS.
3271           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3272             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3273           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3274           ICmpInst *LHS = cast<ICmpInst>(Op0);
3275           if (cast<ConstantBool>(Cmp)->getValue()) {
3276             std::swap(LHS, RHS);
3277             std::swap(LHSCst, RHSCst);
3278             std::swap(LHSCC, RHSCC);
3279           }
3280
3281           // At this point, we know we have have two icmp instructions
3282           // comparing a value against two constants and and'ing the result
3283           // together.  Because of the above check, we know that we only have
3284           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3285           // (from the FoldICmpLogical check above), that the two constants 
3286           // are not equal and that the larger constant is on the RHS
3287           assert(LHSCst != RHSCst && "Compares not folded above?");
3288
3289           switch (LHSCC) {
3290           default: assert(0 && "Unknown integer condition code!");
3291           case ICmpInst::ICMP_EQ:
3292             switch (RHSCC) {
3293             default: assert(0 && "Unknown integer condition code!");
3294             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3295             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3296             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3297               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3298             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3299             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3300             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3301               return ReplaceInstUsesWith(I, LHS);
3302             }
3303           case ICmpInst::ICMP_NE:
3304             switch (RHSCC) {
3305             default: assert(0 && "Unknown integer condition code!");
3306             case ICmpInst::ICMP_ULT:
3307               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3308                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3309               break;                        // (X != 13 & X u< 15) -> no change
3310             case ICmpInst::ICMP_SLT:
3311               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3312                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3313               break;                        // (X != 13 & X s< 15) -> no change
3314             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3315             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3316             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3317               return ReplaceInstUsesWith(I, RHS);
3318             case ICmpInst::ICMP_NE:
3319               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3320                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3321                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3322                                                       LHSVal->getName()+".off");
3323                 InsertNewInstBefore(Add, I);
3324                 return new ICmpInst(ICmpInst::ICMP_UGT, Add, AddCST);
3325               }
3326               break;                        // (X != 13 & X != 15) -> no change
3327             }
3328             break;
3329           case ICmpInst::ICMP_ULT:
3330             switch (RHSCC) {
3331             default: assert(0 && "Unknown integer condition code!");
3332             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3333             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3334               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3335             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3336               break;
3337             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3338             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3339               return ReplaceInstUsesWith(I, LHS);
3340             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3341               break;
3342             }
3343             break;
3344           case ICmpInst::ICMP_SLT:
3345             switch (RHSCC) {
3346             default: assert(0 && "Unknown integer condition code!");
3347             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3348             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3349               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3350             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3351               break;
3352             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3353             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3354               return ReplaceInstUsesWith(I, LHS);
3355             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3356               break;
3357             }
3358             break;
3359           case ICmpInst::ICMP_UGT:
3360             switch (RHSCC) {
3361             default: assert(0 && "Unknown integer condition code!");
3362             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3363               return ReplaceInstUsesWith(I, LHS);
3364             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3365               return ReplaceInstUsesWith(I, RHS);
3366             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3367               break;
3368             case ICmpInst::ICMP_NE:
3369               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3370                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3371               break;                        // (X u> 13 & X != 15) -> no change
3372             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3373               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3374                                      true, I);
3375             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3376               break;
3377             }
3378             break;
3379           case ICmpInst::ICMP_SGT:
3380             switch (RHSCC) {
3381             default: assert(0 && "Unknown integer condition code!");
3382             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3383               return ReplaceInstUsesWith(I, LHS);
3384             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3385               return ReplaceInstUsesWith(I, RHS);
3386             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3387               break;
3388             case ICmpInst::ICMP_NE:
3389               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3390                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3391               break;                        // (X s> 13 & X != 15) -> no change
3392             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3393               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3394                                      true, I);
3395             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3396               break;
3397             }
3398             break;
3399           }
3400         }
3401   }
3402
3403   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3404   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3405     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3406       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3407         const Type *SrcTy = Op0C->getOperand(0)->getType();
3408         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3409             // Only do this if the casts both really cause code to be generated.
3410             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3411                               I.getType(), TD) &&
3412             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3413                               I.getType(), TD)) {
3414           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3415                                                          Op1C->getOperand(0),
3416                                                          I.getName());
3417           InsertNewInstBefore(NewOp, I);
3418           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3419         }
3420       }
3421     
3422   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3423   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3424     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3425       if (SI0->getOpcode() == SI1->getOpcode() && 
3426           SI0->getOperand(1) == SI1->getOperand(1) &&
3427           (SI0->hasOneUse() || SI1->hasOneUse())) {
3428         Instruction *NewOp =
3429           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3430                                                         SI1->getOperand(0),
3431                                                         SI0->getName()), I);
3432         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3433       }
3434   }
3435
3436   return Changed ? &I : 0;
3437 }
3438
3439 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3440 /// in the result.  If it does, and if the specified byte hasn't been filled in
3441 /// yet, fill it in and return false.
3442 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3443   Instruction *I = dyn_cast<Instruction>(V);
3444   if (I == 0) return true;
3445
3446   // If this is an or instruction, it is an inner node of the bswap.
3447   if (I->getOpcode() == Instruction::Or)
3448     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3449            CollectBSwapParts(I->getOperand(1), ByteValues);
3450   
3451   // If this is a shift by a constant int, and it is "24", then its operand
3452   // defines a byte.  We only handle unsigned types here.
3453   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3454     // Not shifting the entire input by N-1 bytes?
3455     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3456         8*(ByteValues.size()-1))
3457       return true;
3458     
3459     unsigned DestNo;
3460     if (I->getOpcode() == Instruction::Shl) {
3461       // X << 24 defines the top byte with the lowest of the input bytes.
3462       DestNo = ByteValues.size()-1;
3463     } else {
3464       // X >>u 24 defines the low byte with the highest of the input bytes.
3465       DestNo = 0;
3466     }
3467     
3468     // If the destination byte value is already defined, the values are or'd
3469     // together, which isn't a bswap (unless it's an or of the same bits).
3470     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3471       return true;
3472     ByteValues[DestNo] = I->getOperand(0);
3473     return false;
3474   }
3475   
3476   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3477   // don't have this.
3478   Value *Shift = 0, *ShiftLHS = 0;
3479   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3480   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3481       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3482     return true;
3483   Instruction *SI = cast<Instruction>(Shift);
3484
3485   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3486   if (ShiftAmt->getZExtValue() & 7 ||
3487       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3488     return true;
3489   
3490   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3491   unsigned DestByte;
3492   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3493     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3494       break;
3495   // Unknown mask for bswap.
3496   if (DestByte == ByteValues.size()) return true;
3497   
3498   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3499   unsigned SrcByte;
3500   if (SI->getOpcode() == Instruction::Shl)
3501     SrcByte = DestByte - ShiftBytes;
3502   else
3503     SrcByte = DestByte + ShiftBytes;
3504   
3505   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3506   if (SrcByte != ByteValues.size()-DestByte-1)
3507     return true;
3508   
3509   // If the destination byte value is already defined, the values are or'd
3510   // together, which isn't a bswap (unless it's an or of the same bits).
3511   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3512     return true;
3513   ByteValues[DestByte] = SI->getOperand(0);
3514   return false;
3515 }
3516
3517 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3518 /// If so, insert the new bswap intrinsic and return it.
3519 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3520   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3521   if (I.getType() == Type::Int8Ty)
3522     return 0;
3523   
3524   /// ByteValues - For each byte of the result, we keep track of which value
3525   /// defines each byte.
3526   std::vector<Value*> ByteValues;
3527   ByteValues.resize(I.getType()->getPrimitiveSize());
3528     
3529   // Try to find all the pieces corresponding to the bswap.
3530   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3531       CollectBSwapParts(I.getOperand(1), ByteValues))
3532     return 0;
3533   
3534   // Check to see if all of the bytes come from the same value.
3535   Value *V = ByteValues[0];
3536   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3537   
3538   // Check to make sure that all of the bytes come from the same value.
3539   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3540     if (ByteValues[i] != V)
3541       return 0;
3542     
3543   // If they do then *success* we can turn this into a bswap.  Figure out what
3544   // bswap to make it into.
3545   Module *M = I.getParent()->getParent()->getParent();
3546   const char *FnName = 0;
3547   if (I.getType() == Type::Int16Ty)
3548     FnName = "llvm.bswap.i16";
3549   else if (I.getType() == Type::Int32Ty)
3550     FnName = "llvm.bswap.i32";
3551   else if (I.getType() == Type::Int64Ty)
3552     FnName = "llvm.bswap.i64";
3553   else
3554     assert(0 && "Unknown integer type!");
3555   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3556   return new CallInst(F, V);
3557 }
3558
3559
3560 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3561   bool Changed = SimplifyCommutative(I);
3562   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3563
3564   if (isa<UndefValue>(Op1))
3565     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3566                                ConstantIntegral::getAllOnesValue(I.getType()));
3567
3568   // or X, X = X
3569   if (Op0 == Op1)
3570     return ReplaceInstUsesWith(I, Op0);
3571
3572   // See if we can simplify any instructions used by the instruction whose sole 
3573   // purpose is to compute bits we don't care about.
3574   uint64_t KnownZero, KnownOne;
3575   if (!isa<PackedType>(I.getType()) &&
3576       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3577                            KnownZero, KnownOne))
3578     return &I;
3579   
3580   // or X, -1 == -1
3581   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3582     ConstantInt *C1 = 0; Value *X = 0;
3583     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3584     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3585       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3586       Op0->setName("");
3587       InsertNewInstBefore(Or, I);
3588       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3589     }
3590
3591     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3592     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3593       std::string Op0Name = Op0->getName(); Op0->setName("");
3594       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3595       InsertNewInstBefore(Or, I);
3596       return BinaryOperator::createXor(Or,
3597                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3598     }
3599
3600     // Try to fold constant and into select arguments.
3601     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3602       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3603         return R;
3604     if (isa<PHINode>(Op0))
3605       if (Instruction *NV = FoldOpIntoPhi(I))
3606         return NV;
3607   }
3608
3609   Value *A = 0, *B = 0;
3610   ConstantInt *C1 = 0, *C2 = 0;
3611
3612   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3613     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3614       return ReplaceInstUsesWith(I, Op1);
3615   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3616     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3617       return ReplaceInstUsesWith(I, Op0);
3618
3619   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3620   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3621   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3622       match(Op1, m_Or(m_Value(), m_Value())) ||
3623       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3624        match(Op1, m_Shift(m_Value(), m_Value())))) {
3625     if (Instruction *BSwap = MatchBSwap(I))
3626       return BSwap;
3627   }
3628   
3629   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3630   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3631       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3632     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3633     Op0->setName("");
3634     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3635   }
3636
3637   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3638   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3639       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3640     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3641     Op0->setName("");
3642     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3643   }
3644
3645   // (A & C1)|(B & C2)
3646   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3647       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3648
3649     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3650       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3651
3652
3653     // If we have: ((V + N) & C1) | (V & C2)
3654     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3655     // replace with V+N.
3656     if (C1 == ConstantExpr::getNot(C2)) {
3657       Value *V1 = 0, *V2 = 0;
3658       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3659           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3660         // Add commutes, try both ways.
3661         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3662           return ReplaceInstUsesWith(I, A);
3663         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3664           return ReplaceInstUsesWith(I, A);
3665       }
3666       // Or commutes, try both ways.
3667       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3668           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3669         // Add commutes, try both ways.
3670         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3671           return ReplaceInstUsesWith(I, B);
3672         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3673           return ReplaceInstUsesWith(I, B);
3674       }
3675     }
3676   }
3677   
3678   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3679   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3680     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3681       if (SI0->getOpcode() == SI1->getOpcode() && 
3682           SI0->getOperand(1) == SI1->getOperand(1) &&
3683           (SI0->hasOneUse() || SI1->hasOneUse())) {
3684         Instruction *NewOp =
3685         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3686                                                      SI1->getOperand(0),
3687                                                      SI0->getName()), I);
3688         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3689       }
3690   }
3691
3692   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3693     if (A == Op1)   // ~A | A == -1
3694       return ReplaceInstUsesWith(I,
3695                                 ConstantIntegral::getAllOnesValue(I.getType()));
3696   } else {
3697     A = 0;
3698   }
3699   // Note, A is still live here!
3700   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3701     if (Op0 == B)
3702       return ReplaceInstUsesWith(I,
3703                                 ConstantIntegral::getAllOnesValue(I.getType()));
3704
3705     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3706     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3707       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3708                                               I.getName()+".demorgan"), I);
3709       return BinaryOperator::createNot(And);
3710     }
3711   }
3712
3713   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3714   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3715     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3716       return R;
3717
3718     Value *LHSVal, *RHSVal;
3719     ConstantInt *LHSCst, *RHSCst;
3720     ICmpInst::Predicate LHSCC, RHSCC;
3721     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3722       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3723         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3724             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3725             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3726             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3727             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3728             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3729           // Ensure that the larger constant is on the RHS.
3730           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3731             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3732           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3733           ICmpInst *LHS = cast<ICmpInst>(Op0);
3734           if (cast<ConstantBool>(Cmp)->getValue()) {
3735             std::swap(LHS, RHS);
3736             std::swap(LHSCst, RHSCst);
3737             std::swap(LHSCC, RHSCC);
3738           }
3739
3740           // At this point, we know we have have two icmp instructions
3741           // comparing a value against two constants and or'ing the result
3742           // together.  Because of the above check, we know that we only have
3743           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3744           // FoldICmpLogical check above), that the two constants are not
3745           // equal.
3746           assert(LHSCst != RHSCst && "Compares not folded above?");
3747
3748           switch (LHSCC) {
3749           default: assert(0 && "Unknown integer condition code!");
3750           case ICmpInst::ICMP_EQ:
3751             switch (RHSCC) {
3752             default: assert(0 && "Unknown integer condition code!");
3753             case ICmpInst::ICMP_EQ:
3754               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3755                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3756                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3757                                                       LHSVal->getName()+".off");
3758                 InsertNewInstBefore(Add, I);
3759                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3760                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3761               }
3762               break;                         // (X == 13 | X == 15) -> no change
3763             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3764             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3765               break;
3766             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3767             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3768             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3769               return ReplaceInstUsesWith(I, RHS);
3770             }
3771             break;
3772           case ICmpInst::ICMP_NE:
3773             switch (RHSCC) {
3774             default: assert(0 && "Unknown integer condition code!");
3775             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3776             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3777             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3778               return ReplaceInstUsesWith(I, LHS);
3779             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3780             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3781             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3782               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3783             }
3784             break;
3785           case ICmpInst::ICMP_ULT:
3786             switch (RHSCC) {
3787             default: assert(0 && "Unknown integer condition code!");
3788             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3789               break;
3790             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3791               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3792                                      false, I);
3793             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3794               break;
3795             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3796             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3797               return ReplaceInstUsesWith(I, RHS);
3798             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3799               break;
3800             }
3801             break;
3802           case ICmpInst::ICMP_SLT:
3803             switch (RHSCC) {
3804             default: assert(0 && "Unknown integer condition code!");
3805             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3806               break;
3807             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3808               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3809                                      false, I);
3810             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3811               break;
3812             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3813             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3814               return ReplaceInstUsesWith(I, RHS);
3815             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3816               break;
3817             }
3818             break;
3819           case ICmpInst::ICMP_UGT:
3820             switch (RHSCC) {
3821             default: assert(0 && "Unknown integer condition code!");
3822             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3823             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3824               return ReplaceInstUsesWith(I, LHS);
3825             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3826               break;
3827             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3828             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3829               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3830             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3831               break;
3832             }
3833             break;
3834           case ICmpInst::ICMP_SGT:
3835             switch (RHSCC) {
3836             default: assert(0 && "Unknown integer condition code!");
3837             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3838             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3839               return ReplaceInstUsesWith(I, LHS);
3840             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3841               break;
3842             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3843             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3844               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3845             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3846               break;
3847             }
3848             break;
3849           }
3850         }
3851   }
3852     
3853   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3854   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3855     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3856       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3857         const Type *SrcTy = Op0C->getOperand(0)->getType();
3858         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3859             // Only do this if the casts both really cause code to be generated.
3860             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3861                               I.getType(), TD) &&
3862             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3863                               I.getType(), TD)) {
3864           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3865                                                         Op1C->getOperand(0),
3866                                                         I.getName());
3867           InsertNewInstBefore(NewOp, I);
3868           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3869         }
3870       }
3871       
3872
3873   return Changed ? &I : 0;
3874 }
3875
3876 // XorSelf - Implements: X ^ X --> 0
3877 struct XorSelf {
3878   Value *RHS;
3879   XorSelf(Value *rhs) : RHS(rhs) {}
3880   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3881   Instruction *apply(BinaryOperator &Xor) const {
3882     return &Xor;
3883   }
3884 };
3885
3886
3887 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3888   bool Changed = SimplifyCommutative(I);
3889   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3890
3891   if (isa<UndefValue>(Op1))
3892     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3893
3894   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3895   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3896     assert(Result == &I && "AssociativeOpt didn't work?");
3897     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3898   }
3899   
3900   // See if we can simplify any instructions used by the instruction whose sole 
3901   // purpose is to compute bits we don't care about.
3902   uint64_t KnownZero, KnownOne;
3903   if (!isa<PackedType>(I.getType()) &&
3904       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3905                            KnownZero, KnownOne))
3906     return &I;
3907
3908   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3909     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3910     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3911       if (RHS == ConstantBool::getTrue() && ICI->hasOneUse())
3912         return new ICmpInst(ICI->getInversePredicate(),
3913                             ICI->getOperand(0), ICI->getOperand(1));
3914
3915     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3916       // ~(c-X) == X-c-1 == X+(-c-1)
3917       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3918         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3919           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3920           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3921                                               ConstantInt::get(I.getType(), 1));
3922           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3923         }
3924
3925       // ~(~X & Y) --> (X | ~Y)
3926       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3927         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3928         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3929           Instruction *NotY =
3930             BinaryOperator::createNot(Op0I->getOperand(1),
3931                                       Op0I->getOperand(1)->getName()+".not");
3932           InsertNewInstBefore(NotY, I);
3933           return BinaryOperator::createOr(Op0NotVal, NotY);
3934         }
3935       }
3936
3937       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3938         if (Op0I->getOpcode() == Instruction::Add) {
3939           // ~(X-c) --> (-c-1)-X
3940           if (RHS->isAllOnesValue()) {
3941             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3942             return BinaryOperator::createSub(
3943                            ConstantExpr::getSub(NegOp0CI,
3944                                              ConstantInt::get(I.getType(), 1)),
3945                                           Op0I->getOperand(0));
3946           }
3947         } else if (Op0I->getOpcode() == Instruction::Or) {
3948           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3949           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3950             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3951             // Anything in both C1 and C2 is known to be zero, remove it from
3952             // NewRHS.
3953             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3954             NewRHS = ConstantExpr::getAnd(NewRHS, 
3955                                           ConstantExpr::getNot(CommonBits));
3956             WorkList.push_back(Op0I);
3957             I.setOperand(0, Op0I->getOperand(0));
3958             I.setOperand(1, NewRHS);
3959             return &I;
3960           }
3961         }
3962     }
3963
3964     // Try to fold constant and into select arguments.
3965     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3966       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3967         return R;
3968     if (isa<PHINode>(Op0))
3969       if (Instruction *NV = FoldOpIntoPhi(I))
3970         return NV;
3971   }
3972
3973   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3974     if (X == Op1)
3975       return ReplaceInstUsesWith(I,
3976                                 ConstantIntegral::getAllOnesValue(I.getType()));
3977
3978   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3979     if (X == Op0)
3980       return ReplaceInstUsesWith(I,
3981                                 ConstantIntegral::getAllOnesValue(I.getType()));
3982
3983   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3984     if (Op1I->getOpcode() == Instruction::Or) {
3985       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3986         Op1I->swapOperands();
3987         I.swapOperands();
3988         std::swap(Op0, Op1);
3989       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3990         I.swapOperands();     // Simplified below.
3991         std::swap(Op0, Op1);
3992       }
3993     } else if (Op1I->getOpcode() == Instruction::Xor) {
3994       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3995         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3996       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3997         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3998     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3999       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
4000         Op1I->swapOperands();
4001       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
4002         I.swapOperands();     // Simplified below.
4003         std::swap(Op0, Op1);
4004       }
4005     }
4006
4007   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4008     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4009       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4010         Op0I->swapOperands();
4011       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4012         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4013         InsertNewInstBefore(NotB, I);
4014         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4015       }
4016     } else if (Op0I->getOpcode() == Instruction::Xor) {
4017       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4018         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4019       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4020         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4021     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4022       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4023         Op0I->swapOperands();
4024       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4025           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4026         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4027         InsertNewInstBefore(N, I);
4028         return BinaryOperator::createAnd(N, Op1);
4029       }
4030     }
4031
4032   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4033   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4034     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4035       return R;
4036
4037   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4038   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4039     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4040       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4041         const Type *SrcTy = Op0C->getOperand(0)->getType();
4042         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
4043             // Only do this if the casts both really cause code to be generated.
4044             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4045                               I.getType(), TD) &&
4046             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4047                               I.getType(), TD)) {
4048           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4049                                                          Op1C->getOperand(0),
4050                                                          I.getName());
4051           InsertNewInstBefore(NewOp, I);
4052           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4053         }
4054       }
4055
4056   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4057   if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4058     if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4059       if (SI0->getOpcode() == SI1->getOpcode() && 
4060           SI0->getOperand(1) == SI1->getOperand(1) &&
4061           (SI0->hasOneUse() || SI1->hasOneUse())) {
4062         Instruction *NewOp =
4063         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4064                                                       SI1->getOperand(0),
4065                                                       SI0->getName()), I);
4066         return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4067       }
4068   }
4069     
4070   return Changed ? &I : 0;
4071 }
4072
4073 static bool isPositive(ConstantInt *C) {
4074   return C->getSExtValue() >= 0;
4075 }
4076
4077 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4078 /// overflowed for this type.
4079 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4080                             ConstantInt *In2) {
4081   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4082
4083   return cast<ConstantInt>(Result)->getZExtValue() <
4084          cast<ConstantInt>(In1)->getZExtValue();
4085 }
4086
4087 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4088 /// code necessary to compute the offset from the base pointer (without adding
4089 /// in the base pointer).  Return the result as a signed integer of intptr size.
4090 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4091   TargetData &TD = IC.getTargetData();
4092   gep_type_iterator GTI = gep_type_begin(GEP);
4093   const Type *IntPtrTy = TD.getIntPtrType();
4094   Value *Result = Constant::getNullValue(IntPtrTy);
4095
4096   // Build a mask for high order bits.
4097   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4098
4099   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4100     Value *Op = GEP->getOperand(i);
4101     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4102     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4103     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4104       if (!OpC->isNullValue()) {
4105         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4106         Scale = ConstantExpr::getMul(OpC, Scale);
4107         if (Constant *RC = dyn_cast<Constant>(Result))
4108           Result = ConstantExpr::getAdd(RC, Scale);
4109         else {
4110           // Emit an add instruction.
4111           Result = IC.InsertNewInstBefore(
4112              BinaryOperator::createAdd(Result, Scale,
4113                                        GEP->getName()+".offs"), I);
4114         }
4115       }
4116     } else {
4117       // Convert to correct type.
4118       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4119                                                Op->getName()+".c"), I);
4120       if (Size != 1)
4121         // We'll let instcombine(mul) convert this to a shl if possible.
4122         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4123                                                     GEP->getName()+".idx"), I);
4124
4125       // Emit an add instruction.
4126       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4127                                                     GEP->getName()+".offs"), I);
4128     }
4129   }
4130   return Result;
4131 }
4132
4133 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4134 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4135 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4136                                        ICmpInst::Predicate Cond,
4137                                        Instruction &I) {
4138   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4139
4140   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4141     if (isa<PointerType>(CI->getOperand(0)->getType()))
4142       RHS = CI->getOperand(0);
4143
4144   Value *PtrBase = GEPLHS->getOperand(0);
4145   if (PtrBase == RHS) {
4146     // As an optimization, we don't actually have to compute the actual value of
4147     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4148     // each index is zero or not.
4149     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4150       Instruction *InVal = 0;
4151       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4152       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4153         bool EmitIt = true;
4154         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4155           if (isa<UndefValue>(C))  // undef index -> undef.
4156             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4157           if (C->isNullValue())
4158             EmitIt = false;
4159           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4160             EmitIt = false;  // This is indexing into a zero sized array?
4161           } else if (isa<ConstantInt>(C))
4162             return ReplaceInstUsesWith(I, // No comparison is needed here.
4163                                  ConstantBool::get(Cond == ICmpInst::ICMP_NE));
4164         }
4165
4166         if (EmitIt) {
4167           Instruction *Comp =
4168             new ICmpInst(Cond, GEPLHS->getOperand(i),
4169                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4170           if (InVal == 0)
4171             InVal = Comp;
4172           else {
4173             InVal = InsertNewInstBefore(InVal, I);
4174             InsertNewInstBefore(Comp, I);
4175             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4176               InVal = BinaryOperator::createOr(InVal, Comp);
4177             else                              // True if all are equal
4178               InVal = BinaryOperator::createAnd(InVal, Comp);
4179           }
4180         }
4181       }
4182
4183       if (InVal)
4184         return InVal;
4185       else
4186         // No comparison is needed here, all indexes = 0
4187         ReplaceInstUsesWith(I, ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4188     }
4189
4190     // Only lower this if the icmp is the only user of the GEP or if we expect
4191     // the result to fold to a constant!
4192     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4193       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4194       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4195       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4196                           Constant::getNullValue(Offset->getType()));
4197     }
4198   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4199     // If the base pointers are different, but the indices are the same, just
4200     // compare the base pointer.
4201     if (PtrBase != GEPRHS->getOperand(0)) {
4202       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4203       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4204                         GEPRHS->getOperand(0)->getType();
4205       if (IndicesTheSame)
4206         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4207           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4208             IndicesTheSame = false;
4209             break;
4210           }
4211
4212       // If all indices are the same, just compare the base pointers.
4213       if (IndicesTheSame)
4214         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4215                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4216
4217       // Otherwise, the base pointers are different and the indices are
4218       // different, bail out.
4219       return 0;
4220     }
4221
4222     // If one of the GEPs has all zero indices, recurse.
4223     bool AllZeros = true;
4224     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4225       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4226           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4227         AllZeros = false;
4228         break;
4229       }
4230     if (AllZeros)
4231       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4232                           ICmpInst::getSwappedPredicate(Cond), I);
4233
4234     // If the other GEP has all zero indices, recurse.
4235     AllZeros = true;
4236     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4237       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4238           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4239         AllZeros = false;
4240         break;
4241       }
4242     if (AllZeros)
4243       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4244
4245     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4246       // If the GEPs only differ by one index, compare it.
4247       unsigned NumDifferences = 0;  // Keep track of # differences.
4248       unsigned DiffOperand = 0;     // The operand that differs.
4249       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4250         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4251           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4252                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4253             // Irreconcilable differences.
4254             NumDifferences = 2;
4255             break;
4256           } else {
4257             if (NumDifferences++) break;
4258             DiffOperand = i;
4259           }
4260         }
4261
4262       if (NumDifferences == 0)   // SAME GEP?
4263         return ReplaceInstUsesWith(I, // No comparison is needed here.
4264                                  ConstantBool::get(Cond == ICmpInst::ICMP_EQ));
4265       else if (NumDifferences == 1) {
4266         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4267         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4268         // Make sure we do a signed comparison here.
4269         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4270       }
4271     }
4272
4273     // Only lower this if the icmp is the only user of the GEP or if we expect
4274     // the result to fold to a constant!
4275     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4276         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4277       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4278       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4279       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4280       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4281     }
4282   }
4283   return 0;
4284 }
4285
4286 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4287   bool Changed = SimplifyCompare(I);
4288   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4289
4290   // fcmp pred X, X
4291   if (Op0 == Op1)
4292     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4293
4294   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4295     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4296
4297   // Handle fcmp with constant RHS
4298   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4299     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4300       switch (LHSI->getOpcode()) {
4301       case Instruction::PHI:
4302         if (Instruction *NV = FoldOpIntoPhi(I))
4303           return NV;
4304         break;
4305       case Instruction::Select:
4306         // If either operand of the select is a constant, we can fold the
4307         // comparison into the select arms, which will cause one to be
4308         // constant folded and the select turned into a bitwise or.
4309         Value *Op1 = 0, *Op2 = 0;
4310         if (LHSI->hasOneUse()) {
4311           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4312             // Fold the known value into the constant operand.
4313             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4314             // Insert a new FCmp of the other select operand.
4315             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4316                                                       LHSI->getOperand(2), RHSC,
4317                                                       I.getName()), I);
4318           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4319             // Fold the known value into the constant operand.
4320             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4321             // Insert a new FCmp of the other select operand.
4322             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4323                                                       LHSI->getOperand(1), RHSC,
4324                                                       I.getName()), I);
4325           }
4326         }
4327
4328         if (Op1)
4329           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4330         break;
4331       }
4332   }
4333
4334   return Changed ? &I : 0;
4335 }
4336
4337 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4338   bool Changed = SimplifyCompare(I);
4339   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4340   const Type *Ty = Op0->getType();
4341
4342   // icmp X, X
4343   if (Op0 == Op1)
4344     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4345
4346   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4347     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4348
4349   // icmp of GlobalValues can never equal each other as long as they aren't
4350   // external weak linkage type.
4351   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4352     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4353       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4354         return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4355
4356   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4357   // addresses never equal each other!  We already know that Op0 != Op1.
4358   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4359        isa<ConstantPointerNull>(Op0)) &&
4360       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4361        isa<ConstantPointerNull>(Op1)))
4362     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4363
4364   // icmp's with boolean values can always be turned into bitwise operations
4365   if (Ty == Type::BoolTy) {
4366     switch (I.getPredicate()) {
4367     default: assert(0 && "Invalid icmp instruction!");
4368     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4369       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4370       InsertNewInstBefore(Xor, I);
4371       return BinaryOperator::createNot(Xor);
4372     }
4373     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4374       return BinaryOperator::createXor(Op0, Op1);
4375
4376     case ICmpInst::ICMP_UGT:
4377     case ICmpInst::ICMP_SGT:
4378       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4379       // FALL THROUGH
4380     case ICmpInst::ICMP_ULT:
4381     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4382       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4383       InsertNewInstBefore(Not, I);
4384       return BinaryOperator::createAnd(Not, Op1);
4385     }
4386     case ICmpInst::ICMP_UGE:
4387     case ICmpInst::ICMP_SGE:
4388       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4389       // FALL THROUGH
4390     case ICmpInst::ICMP_ULE:
4391     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4392       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4393       InsertNewInstBefore(Not, I);
4394       return BinaryOperator::createOr(Not, Op1);
4395     }
4396     }
4397   }
4398
4399   // See if we are doing a comparison between a constant and an instruction that
4400   // can be folded into the comparison.
4401   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4402     switch (I.getPredicate()) {
4403     default: break;
4404     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4405       if (CI->isMinValue(false))
4406         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4407       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4408         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4409       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4410         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4411       break;
4412
4413     case ICmpInst::ICMP_SLT:
4414       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4415         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4416       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4417         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4418       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4419         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4420       break;
4421
4422     case ICmpInst::ICMP_UGT:
4423       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4424         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4425       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4426         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4427       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4428         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4429       break;
4430
4431     case ICmpInst::ICMP_SGT:
4432       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4433         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4434       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4435         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4436       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4437         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4438       break;
4439
4440     case ICmpInst::ICMP_ULE:
4441       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4442         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4443       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4444         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4445       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4446         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4447       break;
4448
4449     case ICmpInst::ICMP_SLE:
4450       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4451         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4452       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4453         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4454       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4455         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4456       break;
4457
4458     case ICmpInst::ICMP_UGE:
4459       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4460         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4461       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4462         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4463       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4464         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4465       break;
4466
4467     case ICmpInst::ICMP_SGE:
4468       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4469         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4470       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4471         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4472       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4473         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4474       break;
4475     }
4476
4477     // If we still have a icmp le or icmp ge instruction, turn it into the
4478     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4479     // already been handled above, this requires little checking.
4480     //
4481     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4482       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4483     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4484       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4485     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4486       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4487     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4488       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4489     
4490     // See if we can fold the comparison based on bits known to be zero or one
4491     // in the input.
4492     uint64_t KnownZero, KnownOne;
4493     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4494                              KnownZero, KnownOne, 0))
4495       return &I;
4496         
4497     // Given the known and unknown bits, compute a range that the LHS could be
4498     // in.
4499     if (KnownOne | KnownZero) {
4500       // Compute the Min, Max and RHS values based on the known bits. For the
4501       // EQ and NE we use unsigned values.
4502       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4503       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4504       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4505         SRHSVal = CI->getSExtValue();
4506         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4507                                                SMax);
4508       } else {
4509         URHSVal = CI->getZExtValue();
4510         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4511                                                  UMax);
4512       }
4513       switch (I.getPredicate()) {  // LE/GE have been folded already.
4514       default: assert(0 && "Unknown icmp opcode!");
4515       case ICmpInst::ICMP_EQ:
4516         if (UMax < URHSVal || UMin > URHSVal)
4517           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4518         break;
4519       case ICmpInst::ICMP_NE:
4520         if (UMax < URHSVal || UMin > URHSVal)
4521           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4522         break;
4523       case ICmpInst::ICMP_ULT:
4524         if (UMax < URHSVal)
4525           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4526         if (UMin > URHSVal)
4527           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4528         break;
4529       case ICmpInst::ICMP_UGT:
4530         if (UMin > URHSVal)
4531           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4532         if (UMax < URHSVal)
4533           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4534         break;
4535       case ICmpInst::ICMP_SLT:
4536         if (SMax < SRHSVal)
4537           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4538         if (SMin > SRHSVal)
4539           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4540         break;
4541       case ICmpInst::ICMP_SGT: 
4542         if (SMin > SRHSVal)
4543           return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4544         if (SMax < SRHSVal)
4545           return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4546         break;
4547       }
4548     }
4549           
4550     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4551     // instruction, see if that instruction also has constants so that the 
4552     // instruction can be folded into the icmp 
4553     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4554       switch (LHSI->getOpcode()) {
4555       case Instruction::And:
4556         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4557             LHSI->getOperand(0)->hasOneUse()) {
4558           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4559
4560           // If the LHS is an AND of a truncating cast, we can widen the
4561           // and/compare to be the input width without changing the value
4562           // produced, eliminating a cast.
4563           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4564             // We can do this transformation if either the AND constant does not
4565             // have its sign bit set or if it is an equality comparison. 
4566             // Extending a relational comparison when we're checking the sign
4567             // bit would not work.
4568             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4569                 (I.isEquality() ||
4570                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4571                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4572               ConstantInt *NewCST;
4573               ConstantInt *NewCI;
4574               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4575                                          AndCST->getZExtValue());
4576               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4577                                         CI->getZExtValue());
4578               Instruction *NewAnd = 
4579                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4580                                           LHSI->getName());
4581               InsertNewInstBefore(NewAnd, I);
4582               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4583             }
4584           }
4585           
4586           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4587           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4588           // happens a LOT in code produced by the C front-end, for bitfield
4589           // access.
4590           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4591
4592           // Check to see if there is a noop-cast between the shift and the and.
4593           if (!Shift) {
4594             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4595               if (CI->getOpcode() == Instruction::BitCast)
4596                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4597           }
4598
4599           ConstantInt *ShAmt;
4600           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4601           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4602           const Type *AndTy = AndCST->getType();          // Type of the and.
4603
4604           // We can fold this as long as we can't shift unknown bits
4605           // into the mask.  This can only happen with signed shift
4606           // rights, as they sign-extend.
4607           if (ShAmt) {
4608             bool CanFold = Shift->isLogicalShift();
4609             if (!CanFold) {
4610               // To test for the bad case of the signed shr, see if any
4611               // of the bits shifted in could be tested after the mask.
4612               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4613               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4614
4615               Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4616               Constant *ShVal =
4617                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4618                                      OShAmt);
4619               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4620                 CanFold = true;
4621             }
4622
4623             if (CanFold) {
4624               Constant *NewCst;
4625               if (Shift->getOpcode() == Instruction::Shl)
4626                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4627               else
4628                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4629
4630               // Check to see if we are shifting out any of the bits being
4631               // compared.
4632               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4633                 // If we shifted bits out, the fold is not going to work out.
4634                 // As a special case, check to see if this means that the
4635                 // result is always true or false now.
4636                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4637                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4638                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4639                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4640               } else {
4641                 I.setOperand(1, NewCst);
4642                 Constant *NewAndCST;
4643                 if (Shift->getOpcode() == Instruction::Shl)
4644                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4645                 else
4646                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4647                 LHSI->setOperand(1, NewAndCST);
4648                 LHSI->setOperand(0, Shift->getOperand(0));
4649                 WorkList.push_back(Shift); // Shift is dead.
4650                 AddUsesToWorkList(I);
4651                 return &I;
4652               }
4653             }
4654           }
4655           
4656           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4657           // preferable because it allows the C<<Y expression to be hoisted out
4658           // of a loop if Y is invariant and X is not.
4659           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4660               I.isEquality() && !Shift->isArithmeticShift() &&
4661               isa<Instruction>(Shift->getOperand(0))) {
4662             // Compute C << Y.
4663             Value *NS;
4664             if (Shift->getOpcode() == Instruction::LShr) {
4665               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4666                                  "tmp");
4667             } else {
4668               // Insert a logical shift.
4669               NS = new ShiftInst(Instruction::LShr, AndCST,
4670                                  Shift->getOperand(1), "tmp");
4671             }
4672             InsertNewInstBefore(cast<Instruction>(NS), I);
4673
4674             // Compute X & (C << Y).
4675             Instruction *NewAnd = BinaryOperator::createAnd(
4676                 Shift->getOperand(0), NS, LHSI->getName());
4677             InsertNewInstBefore(NewAnd, I);
4678             
4679             I.setOperand(0, NewAnd);
4680             return &I;
4681           }
4682         }
4683         break;
4684
4685       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4686         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4687           if (I.isEquality()) {
4688             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4689
4690             // Check that the shift amount is in range.  If not, don't perform
4691             // undefined shifts.  When the shift is visited it will be
4692             // simplified.
4693             if (ShAmt->getZExtValue() >= TypeBits)
4694               break;
4695
4696             // If we are comparing against bits always shifted out, the
4697             // comparison cannot succeed.
4698             Constant *Comp =
4699               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4700             if (Comp != CI) {// Comparing against a bit that we know is zero.
4701               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4702               Constant *Cst = ConstantBool::get(IsICMP_NE);
4703               return ReplaceInstUsesWith(I, Cst);
4704             }
4705
4706             if (LHSI->hasOneUse()) {
4707               // Otherwise strength reduce the shift into an and.
4708               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4709               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4710               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4711
4712               Instruction *AndI =
4713                 BinaryOperator::createAnd(LHSI->getOperand(0),
4714                                           Mask, LHSI->getName()+".mask");
4715               Value *And = InsertNewInstBefore(AndI, I);
4716               return new ICmpInst(I.getPredicate(), And,
4717                                      ConstantExpr::getLShr(CI, ShAmt));
4718             }
4719           }
4720         }
4721         break;
4722
4723       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4724       case Instruction::AShr:
4725         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4726           if (I.isEquality()) {
4727             // Check that the shift amount is in range.  If not, don't perform
4728             // undefined shifts.  When the shift is visited it will be
4729             // simplified.
4730             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4731             if (ShAmt->getZExtValue() >= TypeBits)
4732               break;
4733
4734             // If we are comparing against bits always shifted out, the
4735             // comparison cannot succeed.
4736             Constant *Comp;
4737             if (LHSI->getOpcode() == Instruction::LShr) 
4738               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4739                                            ShAmt);
4740             else
4741               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4742                                            ShAmt);
4743
4744             if (Comp != CI) {// Comparing against a bit that we know is zero.
4745               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4746               Constant *Cst = ConstantBool::get(IsICMP_NE);
4747               return ReplaceInstUsesWith(I, Cst);
4748             }
4749
4750             if (LHSI->hasOneUse() || CI->isNullValue()) {
4751               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4752
4753               // Otherwise strength reduce the shift into an and.
4754               uint64_t Val = ~0ULL;          // All ones.
4755               Val <<= ShAmtVal;              // Shift over to the right spot.
4756               Val &= ~0ULL >> (64-TypeBits);
4757               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4758
4759               Instruction *AndI =
4760                 BinaryOperator::createAnd(LHSI->getOperand(0),
4761                                           Mask, LHSI->getName()+".mask");
4762               Value *And = InsertNewInstBefore(AndI, I);
4763               return new ICmpInst(I.getPredicate(), And,
4764                                      ConstantExpr::getShl(CI, ShAmt));
4765             }
4766           }
4767         }
4768         break;
4769
4770       case Instruction::SDiv:
4771       case Instruction::UDiv:
4772         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4773         // Fold this div into the comparison, producing a range check. 
4774         // Determine, based on the divide type, what the range is being 
4775         // checked.  If there is an overflow on the low or high side, remember 
4776         // it, otherwise compute the range [low, hi) bounding the new value.
4777         // See: InsertRangeTest above for the kinds of replacements possible.
4778         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4779           // FIXME: If the operand types don't match the type of the divide 
4780           // then don't attempt this transform. The code below doesn't have the
4781           // logic to deal with a signed divide and an unsigned compare (and
4782           // vice versa). This is because (x /s C1) <s C2  produces different 
4783           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4784           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4785           // work. :(  The if statement below tests that condition and bails 
4786           // if it finds it. 
4787           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4788           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4789             break;
4790
4791           // Initialize the variables that will indicate the nature of the
4792           // range check.
4793           bool LoOverflow = false, HiOverflow = false;
4794           ConstantInt *LoBound = 0, *HiBound = 0;
4795
4796           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4797           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4798           // C2 (CI). By solving for X we can turn this into a range check 
4799           // instead of computing a divide. 
4800           ConstantInt *Prod = 
4801             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4802
4803           // Determine if the product overflows by seeing if the product is
4804           // not equal to the divide. Make sure we do the same kind of divide
4805           // as in the LHS instruction that we're folding. 
4806           bool ProdOV = !DivRHS->isNullValue() && 
4807             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4808               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4809
4810           // Get the ICmp opcode
4811           ICmpInst::Predicate predicate = I.getPredicate();
4812
4813           if (DivRHS->isNullValue()) {  
4814             // Don't hack on divide by zeros!
4815           } else if (!DivIsSigned) {  // udiv
4816             LoBound = Prod;
4817             LoOverflow = ProdOV;
4818             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4819           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4820             if (CI->isNullValue()) {       // (X / pos) op 0
4821               // Can't overflow.
4822               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4823               HiBound = DivRHS;
4824             } else if (isPositive(CI)) {   // (X / pos) op pos
4825               LoBound = Prod;
4826               LoOverflow = ProdOV;
4827               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4828             } else {                       // (X / pos) op neg
4829               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4830               LoOverflow = AddWithOverflow(LoBound, Prod,
4831                                            cast<ConstantInt>(DivRHSH));
4832               HiBound = Prod;
4833               HiOverflow = ProdOV;
4834             }
4835           } else {                         // Divisor is < 0.
4836             if (CI->isNullValue()) {       // (X / neg) op 0
4837               LoBound = AddOne(DivRHS);
4838               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4839               if (HiBound == DivRHS)
4840                 LoBound = 0;               // - INTMIN = INTMIN
4841             } else if (isPositive(CI)) {   // (X / neg) op pos
4842               HiOverflow = LoOverflow = ProdOV;
4843               if (!LoOverflow)
4844                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4845               HiBound = AddOne(Prod);
4846             } else {                       // (X / neg) op neg
4847               LoBound = Prod;
4848               LoOverflow = HiOverflow = ProdOV;
4849               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4850             }
4851
4852             // Dividing by a negate swaps the condition.
4853             predicate = ICmpInst::getSwappedPredicate(predicate);
4854           }
4855
4856           if (LoBound) {
4857             Value *X = LHSI->getOperand(0);
4858             switch (predicate) {
4859             default: assert(0 && "Unhandled icmp opcode!");
4860             case ICmpInst::ICMP_EQ:
4861               if (LoOverflow && HiOverflow)
4862                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4863               else if (HiOverflow)
4864                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4865                                     ICmpInst::ICMP_UGE, X, LoBound);
4866               else if (LoOverflow)
4867                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4868                                     ICmpInst::ICMP_ULT, X, HiBound);
4869               else
4870                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4871                                        true, I);
4872             case ICmpInst::ICMP_NE:
4873               if (LoOverflow && HiOverflow)
4874                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4875               else if (HiOverflow)
4876                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4877                                     ICmpInst::ICMP_ULT, X, LoBound);
4878               else if (LoOverflow)
4879                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4880                                     ICmpInst::ICMP_UGE, X, HiBound);
4881               else
4882                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4883                                        false, I);
4884             case ICmpInst::ICMP_ULT:
4885             case ICmpInst::ICMP_SLT:
4886               if (LoOverflow)
4887                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4888               return new ICmpInst(predicate, X, LoBound);
4889             case ICmpInst::ICMP_UGT:
4890             case ICmpInst::ICMP_SGT:
4891               if (HiOverflow)
4892                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4893               if (predicate == ICmpInst::ICMP_UGT)
4894                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4895               else
4896                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4897             }
4898           }
4899         }
4900         break;
4901       }
4902
4903     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4904     if (I.isEquality()) {
4905       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4906
4907       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4908       // the second operand is a constant, simplify a bit.
4909       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4910         switch (BO->getOpcode()) {
4911         case Instruction::SRem:
4912           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4913           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4914               BO->hasOneUse()) {
4915             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4916             if (V > 1 && isPowerOf2_64(V)) {
4917               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4918                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4919               return new ICmpInst(I.getPredicate(), NewRem, 
4920                                   Constant::getNullValue(BO->getType()));
4921             }
4922           }
4923           break;
4924         case Instruction::Add:
4925           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4926           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4927             if (BO->hasOneUse())
4928               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4929                                   ConstantExpr::getSub(CI, BOp1C));
4930           } else if (CI->isNullValue()) {
4931             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4932             // efficiently invertible, or if the add has just this one use.
4933             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4934
4935             if (Value *NegVal = dyn_castNegVal(BOp1))
4936               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4937             else if (Value *NegVal = dyn_castNegVal(BOp0))
4938               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4939             else if (BO->hasOneUse()) {
4940               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4941               BO->setName("");
4942               InsertNewInstBefore(Neg, I);
4943               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4944             }
4945           }
4946           break;
4947         case Instruction::Xor:
4948           // For the xor case, we can xor two constants together, eliminating
4949           // the explicit xor.
4950           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4951             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4952                                 ConstantExpr::getXor(CI, BOC));
4953
4954           // FALLTHROUGH
4955         case Instruction::Sub:
4956           // Replace (([sub|xor] A, B) != 0) with (A != B)
4957           if (CI->isNullValue())
4958             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4959                                 BO->getOperand(1));
4960           break;
4961
4962         case Instruction::Or:
4963           // If bits are being or'd in that are not present in the constant we
4964           // are comparing against, then the comparison could never succeed!
4965           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4966             Constant *NotCI = ConstantExpr::getNot(CI);
4967             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4968               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
4969           }
4970           break;
4971
4972         case Instruction::And:
4973           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4974             // If bits are being compared against that are and'd out, then the
4975             // comparison can never succeed!
4976             if (!ConstantExpr::getAnd(CI,
4977                                       ConstantExpr::getNot(BOC))->isNullValue())
4978               return ReplaceInstUsesWith(I, ConstantBool::get(isICMP_NE));
4979
4980             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4981             if (CI == BOC && isOneBitSet(CI))
4982               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4983                                   ICmpInst::ICMP_NE, Op0,
4984                                   Constant::getNullValue(CI->getType()));
4985
4986             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
4987             if (isSignBit(BOC)) {
4988               Value *X = BO->getOperand(0);
4989               Constant *Zero = Constant::getNullValue(X->getType());
4990               ICmpInst::Predicate pred = isICMP_NE ? 
4991                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
4992               return new ICmpInst(pred, X, Zero);
4993             }
4994
4995             // ((X & ~7) == 0) --> X < 8
4996             if (CI->isNullValue() && isHighOnes(BOC)) {
4997               Value *X = BO->getOperand(0);
4998               Constant *NegX = ConstantExpr::getNeg(BOC);
4999               ICmpInst::Predicate pred = isICMP_NE ? 
5000                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5001               return new ICmpInst(pred, X, NegX);
5002             }
5003
5004           }
5005         default: break;
5006         }
5007       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5008         // Handle set{eq|ne} <intrinsic>, intcst.
5009         switch (II->getIntrinsicID()) {
5010         default: break;
5011         case Intrinsic::bswap_i16: 
5012           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5013           WorkList.push_back(II);  // Dead?
5014           I.setOperand(0, II->getOperand(1));
5015           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5016                                            ByteSwap_16(CI->getZExtValue())));
5017           return &I;
5018         case Intrinsic::bswap_i32:   
5019           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5020           WorkList.push_back(II);  // Dead?
5021           I.setOperand(0, II->getOperand(1));
5022           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5023                                            ByteSwap_32(CI->getZExtValue())));
5024           return &I;
5025         case Intrinsic::bswap_i64:   
5026           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5027           WorkList.push_back(II);  // Dead?
5028           I.setOperand(0, II->getOperand(1));
5029           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5030                                            ByteSwap_64(CI->getZExtValue())));
5031           return &I;
5032         }
5033       }
5034     } else {  // Not a ICMP_EQ/ICMP_NE
5035       // If the LHS is a cast from an integral value of the same size, then 
5036       // since we know the RHS is a constant, try to simlify.
5037       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5038         Value *CastOp = Cast->getOperand(0);
5039         const Type *SrcTy = CastOp->getType();
5040         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5041         if (SrcTy->isInteger() && 
5042             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5043           // If this is an unsigned comparison, try to make the comparison use
5044           // smaller constant values.
5045           switch (I.getPredicate()) {
5046             default: break;
5047             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5048               ConstantInt *CUI = cast<ConstantInt>(CI);
5049               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5050                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5051                                     ConstantInt::get(SrcTy, -1));
5052               break;
5053             }
5054             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5055               ConstantInt *CUI = cast<ConstantInt>(CI);
5056               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5057                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5058                                     Constant::getNullValue(SrcTy));
5059               break;
5060             }
5061           }
5062
5063         }
5064       }
5065     }
5066   }
5067
5068   // Handle icmp with constant RHS
5069   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5070     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5071       switch (LHSI->getOpcode()) {
5072       case Instruction::GetElementPtr:
5073         if (RHSC->isNullValue()) {
5074           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5075           bool isAllZeros = true;
5076           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5077             if (!isa<Constant>(LHSI->getOperand(i)) ||
5078                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5079               isAllZeros = false;
5080               break;
5081             }
5082           if (isAllZeros)
5083             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5084                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5085         }
5086         break;
5087
5088       case Instruction::PHI:
5089         if (Instruction *NV = FoldOpIntoPhi(I))
5090           return NV;
5091         break;
5092       case Instruction::Select:
5093         // If either operand of the select is a constant, we can fold the
5094         // comparison into the select arms, which will cause one to be
5095         // constant folded and the select turned into a bitwise or.
5096         Value *Op1 = 0, *Op2 = 0;
5097         if (LHSI->hasOneUse()) {
5098           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5099             // Fold the known value into the constant operand.
5100             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5101             // Insert a new ICmp of the other select operand.
5102             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5103                                                    LHSI->getOperand(2), RHSC,
5104                                                    I.getName()), I);
5105           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5106             // Fold the known value into the constant operand.
5107             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5108             // Insert a new ICmp of the other select operand.
5109             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5110                                                    LHSI->getOperand(1), RHSC,
5111                                                    I.getName()), I);
5112           }
5113         }
5114
5115         if (Op1)
5116           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5117         break;
5118       }
5119   }
5120
5121   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5122   if (User *GEP = dyn_castGetElementPtr(Op0))
5123     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5124       return NI;
5125   if (User *GEP = dyn_castGetElementPtr(Op1))
5126     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5127                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5128       return NI;
5129
5130   // Test to see if the operands of the icmp are casted versions of other
5131   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5132   // now.
5133   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5134     if (isa<PointerType>(Op0->getType()) && 
5135         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5136       // We keep moving the cast from the left operand over to the right
5137       // operand, where it can often be eliminated completely.
5138       Op0 = CI->getOperand(0);
5139
5140       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5141       // so eliminate it as well.
5142       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5143         Op1 = CI2->getOperand(0);
5144
5145       // If Op1 is a constant, we can fold the cast into the constant.
5146       if (Op0->getType() != Op1->getType())
5147         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5148           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5149         } else {
5150           // Otherwise, cast the RHS right before the icmp
5151           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5152         }
5153       return new ICmpInst(I.getPredicate(), Op0, Op1);
5154     }
5155   }
5156   
5157   if (isa<CastInst>(Op0)) {
5158     // Handle the special case of: icmp (cast bool to X), <cst>
5159     // This comes up when you have code like
5160     //   int X = A < B;
5161     //   if (X) ...
5162     // For generality, we handle any zero-extension of any operand comparison
5163     // with a constant or another cast from the same type.
5164     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5165       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5166         return R;
5167   }
5168   
5169   if (I.isEquality()) {
5170     Value *A, *B, *C, *D;
5171     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5172       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5173         Value *OtherVal = A == Op1 ? B : A;
5174         return new ICmpInst(I.getPredicate(), OtherVal,
5175                             Constant::getNullValue(A->getType()));
5176       }
5177
5178       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5179         // A^c1 == C^c2 --> A == C^(c1^c2)
5180         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5181           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5182             if (Op1->hasOneUse()) {
5183               Constant *NC = ConstantExpr::getXor(C1, C2);
5184               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5185               return new ICmpInst(I.getPredicate(), A,
5186                                   InsertNewInstBefore(Xor, I));
5187             }
5188         
5189         // A^B == A^D -> B == D
5190         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5191         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5192         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5193         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5194       }
5195     }
5196     
5197     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5198         (A == Op0 || B == Op0)) {
5199       // A == (A^B)  ->  B == 0
5200       Value *OtherVal = A == Op0 ? B : A;
5201       return new ICmpInst(I.getPredicate(), OtherVal,
5202                           Constant::getNullValue(A->getType()));
5203     }
5204     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5205       // (A-B) == A  ->  B == 0
5206       return new ICmpInst(I.getPredicate(), B,
5207                           Constant::getNullValue(B->getType()));
5208     }
5209     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5210       // A == (A-B)  ->  B == 0
5211       return new ICmpInst(I.getPredicate(), B,
5212                           Constant::getNullValue(B->getType()));
5213     }
5214     
5215     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5216     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5217         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5218         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5219       Value *X = 0, *Y = 0, *Z = 0;
5220       
5221       if (A == C) {
5222         X = B; Y = D; Z = A;
5223       } else if (A == D) {
5224         X = B; Y = C; Z = A;
5225       } else if (B == C) {
5226         X = A; Y = D; Z = B;
5227       } else if (B == D) {
5228         X = A; Y = C; Z = B;
5229       }
5230       
5231       if (X) {   // Build (X^Y) & Z
5232         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5233         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5234         I.setOperand(0, Op1);
5235         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5236         return &I;
5237       }
5238     }
5239   }
5240   return Changed ? &I : 0;
5241 }
5242
5243 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5244 // We only handle extending casts so far.
5245 //
5246 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5247   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5248   Value *LHSCIOp        = LHSCI->getOperand(0);
5249   const Type *SrcTy     = LHSCIOp->getType();
5250   const Type *DestTy    = LHSCI->getType();
5251   Value *RHSCIOp;
5252
5253   // We only handle extension cast instructions, so far. Enforce this.
5254   if (LHSCI->getOpcode() != Instruction::ZExt &&
5255       LHSCI->getOpcode() != Instruction::SExt)
5256     return 0;
5257
5258   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5259   bool isSignedCmp = ICI.isSignedPredicate();
5260
5261   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5262     // Not an extension from the same type?
5263     RHSCIOp = CI->getOperand(0);
5264     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5265       return 0;
5266     else
5267       // Okay, just insert a compare of the reduced operands now!
5268       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5269   }
5270
5271   // If we aren't dealing with a constant on the RHS, exit early
5272   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5273   if (!CI)
5274     return 0;
5275
5276   // Compute the constant that would happen if we truncated to SrcTy then
5277   // reextended to DestTy.
5278   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5279   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5280
5281   // If the re-extended constant didn't change...
5282   if (Res2 == CI) {
5283     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5284     // For example, we might have:
5285     //    %A = sext short %X to uint
5286     //    %B = icmp ugt uint %A, 1330
5287     // It is incorrect to transform this into 
5288     //    %B = icmp ugt short %X, 1330 
5289     // because %A may have negative value. 
5290     //
5291     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5292     // OR operation is EQ/NE.
5293     if (isSignedExt == isSignedCmp || SrcTy == Type::BoolTy || ICI.isEquality())
5294       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5295     else
5296       return 0;
5297   }
5298
5299   // The re-extended constant changed so the constant cannot be represented 
5300   // in the shorter type. Consequently, we cannot emit a simple comparison.
5301
5302   // First, handle some easy cases. We know the result cannot be equal at this
5303   // point so handle the ICI.isEquality() cases
5304   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5305     return ReplaceInstUsesWith(ICI, ConstantBool::getFalse());
5306   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5307     return ReplaceInstUsesWith(ICI, ConstantBool::getTrue());
5308
5309   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5310   // should have been folded away previously and not enter in here.
5311   Value *Result;
5312   if (isSignedCmp) {
5313     // We're performing a signed comparison.
5314     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5315       Result = ConstantBool::getFalse();          // X < (small) --> false
5316     else
5317       Result = ConstantBool::getTrue();           // X < (large) --> true
5318   } else {
5319     // We're performing an unsigned comparison.
5320     if (isSignedExt) {
5321       // We're performing an unsigned comp with a sign extended value.
5322       // This is true if the input is >= 0. [aka >s -1]
5323       Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
5324       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5325                                    NegOne, ICI.getName()), ICI);
5326     } else {
5327       // Unsigned extend & unsigned compare -> always true.
5328       Result = ConstantBool::getTrue();
5329     }
5330   }
5331
5332   // Finally, return the value computed.
5333   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5334       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5335     return ReplaceInstUsesWith(ICI, Result);
5336   } else {
5337     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5338             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5339            "ICmp should be folded!");
5340     if (Constant *CI = dyn_cast<Constant>(Result))
5341       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5342     else
5343       return BinaryOperator::createNot(Result);
5344   }
5345 }
5346
5347 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5348   assert(I.getOperand(1)->getType() == Type::Int8Ty);
5349   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5350
5351   // shl X, 0 == X and shr X, 0 == X
5352   // shl 0, X == 0 and shr 0, X == 0
5353   if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5354       Op0 == Constant::getNullValue(Op0->getType()))
5355     return ReplaceInstUsesWith(I, Op0);
5356   
5357   if (isa<UndefValue>(Op0)) {            
5358     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5359       return ReplaceInstUsesWith(I, Op0);
5360     else                                    // undef << X -> 0, undef >>u X -> 0
5361       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5362   }
5363   if (isa<UndefValue>(Op1)) {
5364     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5365       return ReplaceInstUsesWith(I, Op0);          
5366     else                                     // X << undef, X >>u undef -> 0
5367       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5368   }
5369
5370   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5371   if (I.getOpcode() == Instruction::AShr)
5372     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5373       if (CSI->isAllOnesValue())
5374         return ReplaceInstUsesWith(I, CSI);
5375
5376   // Try to fold constant and into select arguments.
5377   if (isa<Constant>(Op0))
5378     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5379       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5380         return R;
5381
5382   // See if we can turn a signed shr into an unsigned shr.
5383   if (I.isArithmeticShift()) {
5384     if (MaskedValueIsZero(Op0,
5385                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5386       return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5387     }
5388   }
5389
5390   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5391     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5392       return Res;
5393   return 0;
5394 }
5395
5396 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5397                                                ShiftInst &I) {
5398   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5399   bool isSignedShift  = I.getOpcode() == Instruction::AShr;
5400   bool isUnsignedShift = !isSignedShift;
5401
5402   // See if we can simplify any instructions used by the instruction whose sole 
5403   // purpose is to compute bits we don't care about.
5404   uint64_t KnownZero, KnownOne;
5405   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5406                            KnownZero, KnownOne))
5407     return &I;
5408   
5409   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5410   // of a signed value.
5411   //
5412   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5413   if (Op1->getZExtValue() >= TypeBits) {
5414     if (isUnsignedShift || isLeftShift)
5415       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5416     else {
5417       I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5418       return &I;
5419     }
5420   }
5421   
5422   // ((X*C1) << C2) == (X * (C1 << C2))
5423   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5424     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5425       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5426         return BinaryOperator::createMul(BO->getOperand(0),
5427                                          ConstantExpr::getShl(BOOp, Op1));
5428   
5429   // Try to fold constant and into select arguments.
5430   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5431     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5432       return R;
5433   if (isa<PHINode>(Op0))
5434     if (Instruction *NV = FoldOpIntoPhi(I))
5435       return NV;
5436   
5437   if (Op0->hasOneUse()) {
5438     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5439       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5440       Value *V1, *V2;
5441       ConstantInt *CC;
5442       switch (Op0BO->getOpcode()) {
5443         default: break;
5444         case Instruction::Add:
5445         case Instruction::And:
5446         case Instruction::Or:
5447         case Instruction::Xor:
5448           // These operators commute.
5449           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5450           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5451               match(Op0BO->getOperand(1),
5452                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5453             Instruction *YS = new ShiftInst(Instruction::Shl, 
5454                                             Op0BO->getOperand(0), Op1,
5455                                             Op0BO->getName());
5456             InsertNewInstBefore(YS, I); // (Y << C)
5457             Instruction *X = 
5458               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5459                                      Op0BO->getOperand(1)->getName());
5460             InsertNewInstBefore(X, I);  // (X + (Y << C))
5461             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5462             C2 = ConstantExpr::getShl(C2, Op1);
5463             return BinaryOperator::createAnd(X, C2);
5464           }
5465           
5466           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5467           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5468               match(Op0BO->getOperand(1),
5469                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5470                           m_ConstantInt(CC))) && V2 == Op1 &&
5471       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5472             Instruction *YS = new ShiftInst(Instruction::Shl, 
5473                                             Op0BO->getOperand(0), Op1,
5474                                             Op0BO->getName());
5475             InsertNewInstBefore(YS, I); // (Y << C)
5476             Instruction *XM =
5477               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5478                                         V1->getName()+".mask");
5479             InsertNewInstBefore(XM, I); // X & (CC << C)
5480             
5481             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5482           }
5483           
5484           // FALL THROUGH.
5485         case Instruction::Sub:
5486           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5487           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5488               match(Op0BO->getOperand(0),
5489                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5490             Instruction *YS = new ShiftInst(Instruction::Shl, 
5491                                             Op0BO->getOperand(1), Op1,
5492                                             Op0BO->getName());
5493             InsertNewInstBefore(YS, I); // (Y << C)
5494             Instruction *X =
5495               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5496                                      Op0BO->getOperand(0)->getName());
5497             InsertNewInstBefore(X, I);  // (X + (Y << C))
5498             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5499             C2 = ConstantExpr::getShl(C2, Op1);
5500             return BinaryOperator::createAnd(X, C2);
5501           }
5502           
5503           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5504           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5505               match(Op0BO->getOperand(0),
5506                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5507                           m_ConstantInt(CC))) && V2 == Op1 &&
5508               cast<BinaryOperator>(Op0BO->getOperand(0))
5509                   ->getOperand(0)->hasOneUse()) {
5510             Instruction *YS = new ShiftInst(Instruction::Shl, 
5511                                             Op0BO->getOperand(1), Op1,
5512                                             Op0BO->getName());
5513             InsertNewInstBefore(YS, I); // (Y << C)
5514             Instruction *XM =
5515               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5516                                         V1->getName()+".mask");
5517             InsertNewInstBefore(XM, I); // X & (CC << C)
5518             
5519             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5520           }
5521           
5522           break;
5523       }
5524       
5525       
5526       // If the operand is an bitwise operator with a constant RHS, and the
5527       // shift is the only use, we can pull it out of the shift.
5528       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5529         bool isValid = true;     // Valid only for And, Or, Xor
5530         bool highBitSet = false; // Transform if high bit of constant set?
5531         
5532         switch (Op0BO->getOpcode()) {
5533           default: isValid = false; break;   // Do not perform transform!
5534           case Instruction::Add:
5535             isValid = isLeftShift;
5536             break;
5537           case Instruction::Or:
5538           case Instruction::Xor:
5539             highBitSet = false;
5540             break;
5541           case Instruction::And:
5542             highBitSet = true;
5543             break;
5544         }
5545         
5546         // If this is a signed shift right, and the high bit is modified
5547         // by the logical operation, do not perform the transformation.
5548         // The highBitSet boolean indicates the value of the high bit of
5549         // the constant which would cause it to be modified for this
5550         // operation.
5551         //
5552         if (isValid && !isLeftShift && isSignedShift) {
5553           uint64_t Val = Op0C->getZExtValue();
5554           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5555         }
5556         
5557         if (isValid) {
5558           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5559           
5560           Instruction *NewShift =
5561             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5562                           Op0BO->getName());
5563           Op0BO->setName("");
5564           InsertNewInstBefore(NewShift, I);
5565           
5566           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5567                                         NewRHS);
5568         }
5569       }
5570     }
5571   }
5572   
5573   // Find out if this is a shift of a shift by a constant.
5574   ShiftInst *ShiftOp = 0;
5575   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5576     ShiftOp = Op0SI;
5577   else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5578     // If this is a noop-integer cast of a shift instruction, use the shift.
5579     if (isa<ShiftInst>(CI->getOperand(0))) {
5580       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5581     }
5582   }
5583   
5584   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5585     // Find the operands and properties of the input shift.  Note that the
5586     // signedness of the input shift may differ from the current shift if there
5587     // is a noop cast between the two.
5588     bool isShiftOfLeftShift   = ShiftOp->getOpcode() == Instruction::Shl;
5589     bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5590     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5591     
5592     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5593
5594     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5595     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5596     
5597     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5598     if (isLeftShift == isShiftOfLeftShift) {
5599       // Do not fold these shifts if the first one is signed and the second one
5600       // is unsigned and this is a right shift.  Further, don't do any folding
5601       // on them.
5602       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5603         return 0;
5604       
5605       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5606       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5607         Amt = Op0->getType()->getPrimitiveSizeInBits();
5608       
5609       Value *Op = ShiftOp->getOperand(0);
5610       ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5611                                           ConstantInt::get(Type::Int8Ty, Amt));
5612       if (I.getType() == ShiftResult->getType())
5613         return ShiftResult;
5614       InsertNewInstBefore(ShiftResult, I);
5615       return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5616     }
5617     
5618     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5619     // signed types, we can only support the (A >> c1) << c2 configuration,
5620     // because it can not turn an arbitrary bit of A into a sign bit.
5621     if (isUnsignedShift || isLeftShift) {
5622       // Calculate bitmask for what gets shifted off the edge.
5623       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5624       if (isLeftShift)
5625         C = ConstantExpr::getShl(C, ShiftAmt1C);
5626       else
5627         C = ConstantExpr::getLShr(C, ShiftAmt1C);
5628       
5629       Value *Op = ShiftOp->getOperand(0);
5630       
5631       Instruction *Mask =
5632         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5633       InsertNewInstBefore(Mask, I);
5634       
5635       // Figure out what flavor of shift we should use...
5636       if (ShiftAmt1 == ShiftAmt2) {
5637         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5638       } else if (ShiftAmt1 < ShiftAmt2) {
5639         return new ShiftInst(I.getOpcode(), Mask,
5640                          ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5641       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5642         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5643           return new ShiftInst(Instruction::LShr, Mask, 
5644             ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5645         } else {
5646           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5647                     ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5648         }
5649       } else {
5650         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5651         Instruction *Shift =
5652           new ShiftInst(ShiftOp->getOpcode(), Mask,
5653                         ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5654         InsertNewInstBefore(Shift, I);
5655         
5656         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5657         C = ConstantExpr::getShl(C, Op1);
5658         return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5659       }
5660     } else {
5661       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5662       // this case, C1 == C2 and C1 is 8, 16, or 32.
5663       if (ShiftAmt1 == ShiftAmt2) {
5664         const Type *SExtType = 0;
5665         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5666         case 8 : SExtType = Type::Int8Ty; break;
5667         case 16: SExtType = Type::Int16Ty; break;
5668         case 32: SExtType = Type::Int32Ty; break;
5669         }
5670         
5671         if (SExtType) {
5672           Instruction *NewTrunc = 
5673             new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5674           InsertNewInstBefore(NewTrunc, I);
5675           return new SExtInst(NewTrunc, I.getType());
5676         }
5677       }
5678     }
5679   }
5680   return 0;
5681 }
5682
5683
5684 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5685 /// expression.  If so, decompose it, returning some value X, such that Val is
5686 /// X*Scale+Offset.
5687 ///
5688 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5689                                         unsigned &Offset) {
5690   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5691   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5692     Offset = CI->getZExtValue();
5693     Scale  = 1;
5694     return ConstantInt::get(Type::Int32Ty, 0);
5695   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5696     if (I->getNumOperands() == 2) {
5697       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5698         if (I->getOpcode() == Instruction::Shl) {
5699           // This is a value scaled by '1 << the shift amt'.
5700           Scale = 1U << CUI->getZExtValue();
5701           Offset = 0;
5702           return I->getOperand(0);
5703         } else if (I->getOpcode() == Instruction::Mul) {
5704           // This value is scaled by 'CUI'.
5705           Scale = CUI->getZExtValue();
5706           Offset = 0;
5707           return I->getOperand(0);
5708         } else if (I->getOpcode() == Instruction::Add) {
5709           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5710           // where C1 is divisible by C2.
5711           unsigned SubScale;
5712           Value *SubVal = 
5713             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5714           Offset += CUI->getZExtValue();
5715           if (SubScale > 1 && (Offset % SubScale == 0)) {
5716             Scale = SubScale;
5717             return SubVal;
5718           }
5719         }
5720       }
5721     }
5722   }
5723
5724   // Otherwise, we can't look past this.
5725   Scale = 1;
5726   Offset = 0;
5727   return Val;
5728 }
5729
5730
5731 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5732 /// try to eliminate the cast by moving the type information into the alloc.
5733 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5734                                                    AllocationInst &AI) {
5735   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5736   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5737   
5738   // Remove any uses of AI that are dead.
5739   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5740   std::vector<Instruction*> DeadUsers;
5741   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5742     Instruction *User = cast<Instruction>(*UI++);
5743     if (isInstructionTriviallyDead(User)) {
5744       while (UI != E && *UI == User)
5745         ++UI; // If this instruction uses AI more than once, don't break UI.
5746       
5747       // Add operands to the worklist.
5748       AddUsesToWorkList(*User);
5749       ++NumDeadInst;
5750       DOUT << "IC: DCE: " << *User;
5751       
5752       User->eraseFromParent();
5753       removeFromWorkList(User);
5754     }
5755   }
5756   
5757   // Get the type really allocated and the type casted to.
5758   const Type *AllocElTy = AI.getAllocatedType();
5759   const Type *CastElTy = PTy->getElementType();
5760   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5761
5762   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5763   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5764   if (CastElTyAlign < AllocElTyAlign) return 0;
5765
5766   // If the allocation has multiple uses, only promote it if we are strictly
5767   // increasing the alignment of the resultant allocation.  If we keep it the
5768   // same, we open the door to infinite loops of various kinds.
5769   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5770
5771   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5772   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5773   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5774
5775   // See if we can satisfy the modulus by pulling a scale out of the array
5776   // size argument.
5777   unsigned ArraySizeScale, ArrayOffset;
5778   Value *NumElements = // See if the array size is a decomposable linear expr.
5779     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5780  
5781   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5782   // do the xform.
5783   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5784       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5785
5786   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5787   Value *Amt = 0;
5788   if (Scale == 1) {
5789     Amt = NumElements;
5790   } else {
5791     // If the allocation size is constant, form a constant mul expression
5792     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5793     if (isa<ConstantInt>(NumElements))
5794       Amt = ConstantExpr::getMul(
5795               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5796     // otherwise multiply the amount and the number of elements
5797     else if (Scale != 1) {
5798       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5799       Amt = InsertNewInstBefore(Tmp, AI);
5800     }
5801   }
5802   
5803   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5804     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5805     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5806     Amt = InsertNewInstBefore(Tmp, AI);
5807   }
5808   
5809   std::string Name = AI.getName(); AI.setName("");
5810   AllocationInst *New;
5811   if (isa<MallocInst>(AI))
5812     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5813   else
5814     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5815   InsertNewInstBefore(New, AI);
5816   
5817   // If the allocation has multiple uses, insert a cast and change all things
5818   // that used it to use the new cast.  This will also hack on CI, but it will
5819   // die soon.
5820   if (!AI.hasOneUse()) {
5821     AddUsesToWorkList(AI);
5822     // New is the allocation instruction, pointer typed. AI is the original
5823     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5824     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5825     InsertNewInstBefore(NewCast, AI);
5826     AI.replaceAllUsesWith(NewCast);
5827   }
5828   return ReplaceInstUsesWith(CI, New);
5829 }
5830
5831 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5832 /// and return it without inserting any new casts.  This is used by code that
5833 /// tries to decide whether promoting or shrinking integer operations to wider
5834 /// or smaller types will allow us to eliminate a truncate or extend.
5835 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5836                                        int &NumCastsRemoved) {
5837   if (isa<Constant>(V)) return true;
5838   
5839   Instruction *I = dyn_cast<Instruction>(V);
5840   if (!I || !I->hasOneUse()) return false;
5841   
5842   switch (I->getOpcode()) {
5843   case Instruction::And:
5844   case Instruction::Or:
5845   case Instruction::Xor:
5846     // These operators can all arbitrarily be extended or truncated.
5847     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5848            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5849   case Instruction::AShr:
5850   case Instruction::LShr:
5851   case Instruction::Shl:
5852     // If this is just a bitcast changing the sign of the operation, we can
5853     // convert if the operand can be converted.
5854     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5855       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5856     break;
5857   case Instruction::Trunc:
5858   case Instruction::ZExt:
5859   case Instruction::SExt:
5860   case Instruction::BitCast:
5861     // If this is a cast from the destination type, we can trivially eliminate
5862     // it, and this will remove a cast overall.
5863     if (I->getOperand(0)->getType() == Ty) {
5864       // If the first operand is itself a cast, and is eliminable, do not count
5865       // this as an eliminable cast.  We would prefer to eliminate those two
5866       // casts first.
5867       if (isa<CastInst>(I->getOperand(0)))
5868         return true;
5869       
5870       ++NumCastsRemoved;
5871       return true;
5872     }
5873     break;
5874   default:
5875     // TODO: Can handle more cases here.
5876     break;
5877   }
5878   
5879   return false;
5880 }
5881
5882 /// EvaluateInDifferentType - Given an expression that 
5883 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5884 /// evaluate the expression.
5885 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5886                                              bool isSigned ) {
5887   if (Constant *C = dyn_cast<Constant>(V))
5888     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5889
5890   // Otherwise, it must be an instruction.
5891   Instruction *I = cast<Instruction>(V);
5892   Instruction *Res = 0;
5893   switch (I->getOpcode()) {
5894   case Instruction::And:
5895   case Instruction::Or:
5896   case Instruction::Xor: {
5897     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5898     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5899     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5900                                  LHS, RHS, I->getName());
5901     break;
5902   }
5903   case Instruction::AShr:
5904   case Instruction::LShr:
5905   case Instruction::Shl: {
5906     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5907     Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5908                         I->getOperand(1), I->getName());
5909     break;
5910   }    
5911   case Instruction::Trunc:
5912   case Instruction::ZExt:
5913   case Instruction::SExt:
5914   case Instruction::BitCast:
5915     // If the source type of the cast is the type we're trying for then we can
5916     // just return the source. There's no need to insert it because its not new.
5917     if (I->getOperand(0)->getType() == Ty)
5918       return I->getOperand(0);
5919     
5920     // Some other kind of cast, which shouldn't happen, so just ..
5921     // FALL THROUGH
5922   default: 
5923     // TODO: Can handle more cases here.
5924     assert(0 && "Unreachable!");
5925     break;
5926   }
5927   
5928   return InsertNewInstBefore(Res, *I);
5929 }
5930
5931 /// @brief Implement the transforms common to all CastInst visitors.
5932 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5933   Value *Src = CI.getOperand(0);
5934
5935   // Casting undef to anything results in undef so might as just replace it and
5936   // get rid of the cast.
5937   if (isa<UndefValue>(Src))   // cast undef -> undef
5938     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5939
5940   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5941   // eliminate it now.
5942   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5943     if (Instruction::CastOps opc = 
5944         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5945       // The first cast (CSrc) is eliminable so we need to fix up or replace
5946       // the second cast (CI). CSrc will then have a good chance of being dead.
5947       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5948     }
5949   }
5950
5951   // If casting the result of a getelementptr instruction with no offset, turn
5952   // this into a cast of the original pointer!
5953   //
5954   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5955     bool AllZeroOperands = true;
5956     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5957       if (!isa<Constant>(GEP->getOperand(i)) ||
5958           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5959         AllZeroOperands = false;
5960         break;
5961       }
5962     if (AllZeroOperands) {
5963       // Changing the cast operand is usually not a good idea but it is safe
5964       // here because the pointer operand is being replaced with another 
5965       // pointer operand so the opcode doesn't need to change.
5966       CI.setOperand(0, GEP->getOperand(0));
5967       return &CI;
5968     }
5969   }
5970     
5971   // If we are casting a malloc or alloca to a pointer to a type of the same
5972   // size, rewrite the allocation instruction to allocate the "right" type.
5973   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5974     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5975       return V;
5976
5977   // If we are casting a select then fold the cast into the select
5978   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5979     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5980       return NV;
5981
5982   // If we are casting a PHI then fold the cast into the PHI
5983   if (isa<PHINode>(Src))
5984     if (Instruction *NV = FoldOpIntoPhi(CI))
5985       return NV;
5986   
5987   return 0;
5988 }
5989
5990 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
5991 /// integers. This function implements the common transforms for all those
5992 /// cases.
5993 /// @brief Implement the transforms common to CastInst with integer operands
5994 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
5995   if (Instruction *Result = commonCastTransforms(CI))
5996     return Result;
5997
5998   Value *Src = CI.getOperand(0);
5999   const Type *SrcTy = Src->getType();
6000   const Type *DestTy = CI.getType();
6001   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6002   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6003
6004   // See if we can simplify any instructions used by the LHS whose sole 
6005   // purpose is to compute bits we don't care about.
6006   uint64_t KnownZero = 0, KnownOne = 0;
6007   if (SimplifyDemandedBits(&CI, DestTy->getIntegralTypeMask(),
6008                            KnownZero, KnownOne))
6009     return &CI;
6010
6011   // If the source isn't an instruction or has more than one use then we
6012   // can't do anything more. 
6013   Instruction *SrcI = dyn_cast<Instruction>(Src);
6014   if (!SrcI || !Src->hasOneUse())
6015     return 0;
6016
6017   // Attempt to propagate the cast into the instruction.
6018   int NumCastsRemoved = 0;
6019   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6020     // If this cast is a truncate, evaluting in a different type always
6021     // eliminates the cast, so it is always a win.  If this is a noop-cast
6022     // this just removes a noop cast which isn't pointful, but simplifies
6023     // the code.  If this is a zero-extension, we need to do an AND to
6024     // maintain the clear top-part of the computation, so we require that
6025     // the input have eliminated at least one cast.  If this is a sign
6026     // extension, we insert two new casts (to do the extension) so we
6027     // require that two casts have been eliminated.
6028     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6029     if (!DoXForm) {
6030       switch (CI.getOpcode()) {
6031         case Instruction::Trunc:
6032           DoXForm = true;
6033           break;
6034         case Instruction::ZExt:
6035           DoXForm = NumCastsRemoved >= 1;
6036           break;
6037         case Instruction::SExt:
6038           DoXForm = NumCastsRemoved >= 2;
6039           break;
6040         case Instruction::BitCast:
6041           DoXForm = false;
6042           break;
6043         default:
6044           // All the others use floating point so we shouldn't actually 
6045           // get here because of the check above.
6046           assert(!"Unknown cast type .. unreachable");
6047           break;
6048       }
6049     }
6050     
6051     if (DoXForm) {
6052       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6053                                            CI.getOpcode() == Instruction::SExt);
6054       assert(Res->getType() == DestTy);
6055       switch (CI.getOpcode()) {
6056       default: assert(0 && "Unknown cast type!");
6057       case Instruction::Trunc:
6058       case Instruction::BitCast:
6059         // Just replace this cast with the result.
6060         return ReplaceInstUsesWith(CI, Res);
6061       case Instruction::ZExt: {
6062         // We need to emit an AND to clear the high bits.
6063         assert(SrcBitSize < DestBitSize && "Not a zext?");
6064         Constant *C = 
6065           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6066         if (DestBitSize < 64)
6067           C = ConstantExpr::getTrunc(C, DestTy);
6068         return BinaryOperator::createAnd(Res, C);
6069       }
6070       case Instruction::SExt:
6071         // We need to emit a cast to truncate, then a cast to sext.
6072         return CastInst::create(Instruction::SExt,
6073             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6074                              CI), DestTy);
6075       }
6076     }
6077   }
6078   
6079   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6080   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6081
6082   switch (SrcI->getOpcode()) {
6083   case Instruction::Add:
6084   case Instruction::Mul:
6085   case Instruction::And:
6086   case Instruction::Or:
6087   case Instruction::Xor:
6088     // If we are discarding information, or just changing the sign, 
6089     // rewrite.
6090     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6091       // Don't insert two casts if they cannot be eliminated.  We allow 
6092       // two casts to be inserted if the sizes are the same.  This could 
6093       // only be converting signedness, which is a noop.
6094       if (DestBitSize == SrcBitSize || 
6095           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6096           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6097         Instruction::CastOps opcode = CI.getOpcode();
6098         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6099         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6100         return BinaryOperator::create(
6101             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6102       }
6103     }
6104
6105     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6106     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6107         SrcI->getOpcode() == Instruction::Xor &&
6108         Op1 == ConstantBool::getTrue() &&
6109         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6110       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6111       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6112     }
6113     break;
6114   case Instruction::SDiv:
6115   case Instruction::UDiv:
6116   case Instruction::SRem:
6117   case Instruction::URem:
6118     // If we are just changing the sign, rewrite.
6119     if (DestBitSize == SrcBitSize) {
6120       // Don't insert two casts if they cannot be eliminated.  We allow 
6121       // two casts to be inserted if the sizes are the same.  This could 
6122       // only be converting signedness, which is a noop.
6123       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6124           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6125         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6126                                               Op0, DestTy, SrcI);
6127         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6128                                               Op1, DestTy, SrcI);
6129         return BinaryOperator::create(
6130           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6131       }
6132     }
6133     break;
6134
6135   case Instruction::Shl:
6136     // Allow changing the sign of the source operand.  Do not allow 
6137     // changing the size of the shift, UNLESS the shift amount is a 
6138     // constant.  We must not change variable sized shifts to a smaller 
6139     // size, because it is undefined to shift more bits out than exist 
6140     // in the value.
6141     if (DestBitSize == SrcBitSize ||
6142         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6143       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6144           Instruction::BitCast : Instruction::Trunc);
6145       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6146       return new ShiftInst(Instruction::Shl, Op0c, Op1);
6147     }
6148     break;
6149   case Instruction::AShr:
6150     // If this is a signed shr, and if all bits shifted in are about to be
6151     // truncated off, turn it into an unsigned shr to allow greater
6152     // simplifications.
6153     if (DestBitSize < SrcBitSize &&
6154         isa<ConstantInt>(Op1)) {
6155       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6156       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6157         // Insert the new logical shift right.
6158         return new ShiftInst(Instruction::LShr, Op0, Op1);
6159       }
6160     }
6161     break;
6162
6163   case Instruction::ICmp:
6164     // If we are just checking for a icmp eq of a single bit and casting it
6165     // to an integer, then shift the bit to the appropriate place and then
6166     // cast to integer to avoid the comparison.
6167     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6168       uint64_t Op1CV = Op1C->getZExtValue();
6169       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6170       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6171       // cast (X == 1) to int --> X        iff X has only the low bit set.
6172       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6173       // cast (X != 0) to int --> X        iff X has only the low bit set.
6174       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6175       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6176       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6177       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6178         // If Op1C some other power of two, convert:
6179         uint64_t KnownZero, KnownOne;
6180         uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
6181         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6182
6183         // This only works for EQ and NE
6184         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6185         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6186           break;
6187         
6188         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6189           bool isNE = pred == ICmpInst::ICMP_NE;
6190           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6191             // (X&4) == 2 --> false
6192             // (X&4) != 2 --> true
6193             Constant *Res = ConstantBool::get(isNE);
6194             Res = ConstantExpr::getZExt(Res, CI.getType());
6195             return ReplaceInstUsesWith(CI, Res);
6196           }
6197           
6198           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6199           Value *In = Op0;
6200           if (ShiftAmt) {
6201             // Perform a logical shr by shiftamt.
6202             // Insert the shift to put the result in the low bit.
6203             In = InsertNewInstBefore(
6204               new ShiftInst(Instruction::LShr, In,
6205                             ConstantInt::get(Type::Int8Ty, ShiftAmt),
6206                             In->getName()+".lobit"), CI);
6207           }
6208           
6209           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6210             Constant *One = ConstantInt::get(In->getType(), 1);
6211             In = BinaryOperator::createXor(In, One, "tmp");
6212             InsertNewInstBefore(cast<Instruction>(In), CI);
6213           }
6214           
6215           if (CI.getType() == In->getType())
6216             return ReplaceInstUsesWith(CI, In);
6217           else
6218             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6219         }
6220       }
6221     }
6222     break;
6223   }
6224   return 0;
6225 }
6226
6227 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6228   if (Instruction *Result = commonIntCastTransforms(CI))
6229     return Result;
6230   
6231   Value *Src = CI.getOperand(0);
6232   const Type *Ty = CI.getType();
6233   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6234   
6235   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6236     switch (SrcI->getOpcode()) {
6237     default: break;
6238     case Instruction::LShr:
6239       // We can shrink lshr to something smaller if we know the bits shifted in
6240       // are already zeros.
6241       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6242         unsigned ShAmt = ShAmtV->getZExtValue();
6243         
6244         // Get a mask for the bits shifting in.
6245         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6246         Value* SrcIOp0 = SrcI->getOperand(0);
6247         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6248           if (ShAmt >= DestBitWidth)        // All zeros.
6249             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6250
6251           // Okay, we can shrink this.  Truncate the input, then return a new
6252           // shift.
6253           Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6254           return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6255         }
6256       } else {     // This is a variable shr.
6257         
6258         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6259         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6260         // loop-invariant and CSE'd.
6261         if (CI.getType() == Type::BoolTy && SrcI->hasOneUse()) {
6262           Value *One = ConstantInt::get(SrcI->getType(), 1);
6263
6264           Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6265                                                        SrcI->getOperand(1),
6266                                                        "tmp"), CI);
6267           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6268                                                             SrcI->getOperand(0),
6269                                                             "tmp"), CI);
6270           Value *Zero = Constant::getNullValue(V->getType());
6271           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6272         }
6273       }
6274       break;
6275     }
6276   }
6277   
6278   return 0;
6279 }
6280
6281 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6282   // If one of the common conversion will work ..
6283   if (Instruction *Result = commonIntCastTransforms(CI))
6284     return Result;
6285
6286   Value *Src = CI.getOperand(0);
6287
6288   // If this is a cast of a cast
6289   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6290     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6291     // types and if the sizes are just right we can convert this into a logical
6292     // 'and' which will be much cheaper than the pair of casts.
6293     if (isa<TruncInst>(CSrc)) {
6294       // Get the sizes of the types involved
6295       Value *A = CSrc->getOperand(0);
6296       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6297       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6298       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6299       // If we're actually extending zero bits and the trunc is a no-op
6300       if (MidSize < DstSize && SrcSize == DstSize) {
6301         // Replace both of the casts with an And of the type mask.
6302         uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
6303         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6304         Instruction *And = 
6305           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6306         // Unfortunately, if the type changed, we need to cast it back.
6307         if (And->getType() != CI.getType()) {
6308           And->setName(CSrc->getName()+".mask");
6309           InsertNewInstBefore(And, CI);
6310           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6311         }
6312         return And;
6313       }
6314     }
6315   }
6316
6317   return 0;
6318 }
6319
6320 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6321   return commonIntCastTransforms(CI);
6322 }
6323
6324 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6325   return commonCastTransforms(CI);
6326 }
6327
6328 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6329   return commonCastTransforms(CI);
6330 }
6331
6332 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6333   return commonCastTransforms(CI);
6334 }
6335
6336 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6337   return commonCastTransforms(CI);
6338 }
6339
6340 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6341   return commonCastTransforms(CI);
6342 }
6343
6344 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6345   return commonCastTransforms(CI);
6346 }
6347
6348 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6349   return commonCastTransforms(CI);
6350 }
6351
6352 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6353   return commonCastTransforms(CI);
6354 }
6355
6356 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6357
6358   // If the operands are integer typed then apply the integer transforms,
6359   // otherwise just apply the common ones.
6360   Value *Src = CI.getOperand(0);
6361   const Type *SrcTy = Src->getType();
6362   const Type *DestTy = CI.getType();
6363
6364   if (SrcTy->isInteger() && DestTy->isInteger()) {
6365     if (Instruction *Result = commonIntCastTransforms(CI))
6366       return Result;
6367   } else {
6368     if (Instruction *Result = commonCastTransforms(CI))
6369       return Result;
6370   }
6371
6372
6373   // Get rid of casts from one type to the same type. These are useless and can
6374   // be replaced by the operand.
6375   if (DestTy == Src->getType())
6376     return ReplaceInstUsesWith(CI, Src);
6377
6378   // If the source and destination are pointers, and this cast is equivalent to
6379   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6380   // This can enhance SROA and other transforms that want type-safe pointers.
6381   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6382     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6383       const Type *DstElTy = DstPTy->getElementType();
6384       const Type *SrcElTy = SrcPTy->getElementType();
6385       
6386       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6387       unsigned NumZeros = 0;
6388       while (SrcElTy != DstElTy && 
6389              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6390              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6391         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6392         ++NumZeros;
6393       }
6394
6395       // If we found a path from the src to dest, create the getelementptr now.
6396       if (SrcElTy == DstElTy) {
6397         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
6398         return new GetElementPtrInst(Src, Idxs);
6399       }
6400     }
6401   }
6402
6403   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6404     if (SVI->hasOneUse()) {
6405       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6406       // a bitconvert to a vector with the same # elts.
6407       if (isa<PackedType>(DestTy) && 
6408           cast<PackedType>(DestTy)->getNumElements() == 
6409                 SVI->getType()->getNumElements()) {
6410         CastInst *Tmp;
6411         // If either of the operands is a cast from CI.getType(), then
6412         // evaluating the shuffle in the casted destination's type will allow
6413         // us to eliminate at least one cast.
6414         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6415              Tmp->getOperand(0)->getType() == DestTy) ||
6416             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6417              Tmp->getOperand(0)->getType() == DestTy)) {
6418           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6419                                                SVI->getOperand(0), DestTy, &CI);
6420           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6421                                                SVI->getOperand(1), DestTy, &CI);
6422           // Return a new shuffle vector.  Use the same element ID's, as we
6423           // know the vector types match #elts.
6424           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6425         }
6426       }
6427     }
6428   }
6429   return 0;
6430 }
6431
6432 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6433 ///   %C = or %A, %B
6434 ///   %D = select %cond, %C, %A
6435 /// into:
6436 ///   %C = select %cond, %B, 0
6437 ///   %D = or %A, %C
6438 ///
6439 /// Assuming that the specified instruction is an operand to the select, return
6440 /// a bitmask indicating which operands of this instruction are foldable if they
6441 /// equal the other incoming value of the select.
6442 ///
6443 static unsigned GetSelectFoldableOperands(Instruction *I) {
6444   switch (I->getOpcode()) {
6445   case Instruction::Add:
6446   case Instruction::Mul:
6447   case Instruction::And:
6448   case Instruction::Or:
6449   case Instruction::Xor:
6450     return 3;              // Can fold through either operand.
6451   case Instruction::Sub:   // Can only fold on the amount subtracted.
6452   case Instruction::Shl:   // Can only fold on the shift amount.
6453   case Instruction::LShr:
6454   case Instruction::AShr:
6455     return 1;
6456   default:
6457     return 0;              // Cannot fold
6458   }
6459 }
6460
6461 /// GetSelectFoldableConstant - For the same transformation as the previous
6462 /// function, return the identity constant that goes into the select.
6463 static Constant *GetSelectFoldableConstant(Instruction *I) {
6464   switch (I->getOpcode()) {
6465   default: assert(0 && "This cannot happen!"); abort();
6466   case Instruction::Add:
6467   case Instruction::Sub:
6468   case Instruction::Or:
6469   case Instruction::Xor:
6470     return Constant::getNullValue(I->getType());
6471   case Instruction::Shl:
6472   case Instruction::LShr:
6473   case Instruction::AShr:
6474     return Constant::getNullValue(Type::Int8Ty);
6475   case Instruction::And:
6476     return ConstantInt::getAllOnesValue(I->getType());
6477   case Instruction::Mul:
6478     return ConstantInt::get(I->getType(), 1);
6479   }
6480 }
6481
6482 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6483 /// have the same opcode and only one use each.  Try to simplify this.
6484 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6485                                           Instruction *FI) {
6486   if (TI->getNumOperands() == 1) {
6487     // If this is a non-volatile load or a cast from the same type,
6488     // merge.
6489     if (TI->isCast()) {
6490       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6491         return 0;
6492     } else {
6493       return 0;  // unknown unary op.
6494     }
6495
6496     // Fold this by inserting a select from the input values.
6497     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6498                                        FI->getOperand(0), SI.getName()+".v");
6499     InsertNewInstBefore(NewSI, SI);
6500     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6501                             TI->getType());
6502   }
6503
6504   // Only handle binary, compare and shift operators here.
6505   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6506     return 0;
6507
6508   // Figure out if the operations have any operands in common.
6509   Value *MatchOp, *OtherOpT, *OtherOpF;
6510   bool MatchIsOpZero;
6511   if (TI->getOperand(0) == FI->getOperand(0)) {
6512     MatchOp  = TI->getOperand(0);
6513     OtherOpT = TI->getOperand(1);
6514     OtherOpF = FI->getOperand(1);
6515     MatchIsOpZero = true;
6516   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6517     MatchOp  = TI->getOperand(1);
6518     OtherOpT = TI->getOperand(0);
6519     OtherOpF = FI->getOperand(0);
6520     MatchIsOpZero = false;
6521   } else if (!TI->isCommutative()) {
6522     return 0;
6523   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6524     MatchOp  = TI->getOperand(0);
6525     OtherOpT = TI->getOperand(1);
6526     OtherOpF = FI->getOperand(0);
6527     MatchIsOpZero = true;
6528   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6529     MatchOp  = TI->getOperand(1);
6530     OtherOpT = TI->getOperand(0);
6531     OtherOpF = FI->getOperand(1);
6532     MatchIsOpZero = true;
6533   } else {
6534     return 0;
6535   }
6536
6537   // If we reach here, they do have operations in common.
6538   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6539                                      OtherOpF, SI.getName()+".v");
6540   InsertNewInstBefore(NewSI, SI);
6541
6542   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6543     if (MatchIsOpZero)
6544       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6545     else
6546       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6547   }
6548
6549   assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6550   if (MatchIsOpZero)
6551     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6552   else
6553     return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6554 }
6555
6556 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6557   Value *CondVal = SI.getCondition();
6558   Value *TrueVal = SI.getTrueValue();
6559   Value *FalseVal = SI.getFalseValue();
6560
6561   // select true, X, Y  -> X
6562   // select false, X, Y -> Y
6563   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6564     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6565
6566   // select C, X, X -> X
6567   if (TrueVal == FalseVal)
6568     return ReplaceInstUsesWith(SI, TrueVal);
6569
6570   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6571     return ReplaceInstUsesWith(SI, FalseVal);
6572   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6573     return ReplaceInstUsesWith(SI, TrueVal);
6574   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6575     if (isa<Constant>(TrueVal))
6576       return ReplaceInstUsesWith(SI, TrueVal);
6577     else
6578       return ReplaceInstUsesWith(SI, FalseVal);
6579   }
6580
6581   if (SI.getType() == Type::BoolTy)
6582     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6583       if (C->getValue()) {
6584         // Change: A = select B, true, C --> A = or B, C
6585         return BinaryOperator::createOr(CondVal, FalseVal);
6586       } else {
6587         // Change: A = select B, false, C --> A = and !B, C
6588         Value *NotCond =
6589           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6590                                              "not."+CondVal->getName()), SI);
6591         return BinaryOperator::createAnd(NotCond, FalseVal);
6592       }
6593     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6594       if (C->getValue() == false) {
6595         // Change: A = select B, C, false --> A = and B, C
6596         return BinaryOperator::createAnd(CondVal, TrueVal);
6597       } else {
6598         // Change: A = select B, C, true --> A = or !B, C
6599         Value *NotCond =
6600           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6601                                              "not."+CondVal->getName()), SI);
6602         return BinaryOperator::createOr(NotCond, TrueVal);
6603       }
6604     }
6605
6606   // Selecting between two integer constants?
6607   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6608     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6609       // select C, 1, 0 -> cast C to int
6610       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6611         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6612       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6613         // select C, 0, 1 -> cast !C to int
6614         Value *NotCond =
6615           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6616                                                "not."+CondVal->getName()), SI);
6617         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6618       }
6619
6620       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6621
6622         // (x <s 0) ? -1 : 0 -> ashr x, 31
6623         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6624         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6625           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6626             bool CanXForm = false;
6627             if (IC->isSignedPredicate())
6628               CanXForm = CmpCst->isNullValue() && 
6629                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6630             else {
6631               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6632               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6633                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6634             }
6635             
6636             if (CanXForm) {
6637               // The comparison constant and the result are not neccessarily the
6638               // same width. Make an all-ones value by inserting a AShr.
6639               Value *X = IC->getOperand(0);
6640               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6641               Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6642               Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6643                                                ShAmt, "ones");
6644               InsertNewInstBefore(SRA, SI);
6645               
6646               // Finally, convert to the type of the select RHS.  We figure out
6647               // if this requires a SExt, Trunc or BitCast based on the sizes.
6648               Instruction::CastOps opc = Instruction::BitCast;
6649               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6650               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6651               if (SRASize < SISize)
6652                 opc = Instruction::SExt;
6653               else if (SRASize > SISize)
6654                 opc = Instruction::Trunc;
6655               return CastInst::create(opc, SRA, SI.getType());
6656             }
6657           }
6658
6659
6660         // If one of the constants is zero (we know they can't both be) and we
6661         // have a fcmp instruction with zero, and we have an 'and' with the
6662         // non-constant value, eliminate this whole mess.  This corresponds to
6663         // cases like this: ((X & 27) ? 27 : 0)
6664         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6665           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6666               cast<Constant>(IC->getOperand(1))->isNullValue())
6667             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6668               if (ICA->getOpcode() == Instruction::And &&
6669                   isa<ConstantInt>(ICA->getOperand(1)) &&
6670                   (ICA->getOperand(1) == TrueValC ||
6671                    ICA->getOperand(1) == FalseValC) &&
6672                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6673                 // Okay, now we know that everything is set up, we just don't
6674                 // know whether we have a icmp_ne or icmp_eq and whether the 
6675                 // true or false val is the zero.
6676                 bool ShouldNotVal = !TrueValC->isNullValue();
6677                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6678                 Value *V = ICA;
6679                 if (ShouldNotVal)
6680                   V = InsertNewInstBefore(BinaryOperator::create(
6681                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6682                 return ReplaceInstUsesWith(SI, V);
6683               }
6684       }
6685     }
6686
6687   // See if we are selecting two values based on a comparison of the two values.
6688   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6689     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6690       // Transform (X == Y) ? X : Y  -> Y
6691       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6692         return ReplaceInstUsesWith(SI, FalseVal);
6693       // Transform (X != Y) ? X : Y  -> X
6694       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6695         return ReplaceInstUsesWith(SI, TrueVal);
6696       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6697
6698     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6699       // Transform (X == Y) ? Y : X  -> X
6700       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6701         return ReplaceInstUsesWith(SI, FalseVal);
6702       // Transform (X != Y) ? Y : X  -> Y
6703       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6704         return ReplaceInstUsesWith(SI, TrueVal);
6705       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6706     }
6707   }
6708
6709   // See if we are selecting two values based on a comparison of the two values.
6710   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6711     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6712       // Transform (X == Y) ? X : Y  -> Y
6713       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6714         return ReplaceInstUsesWith(SI, FalseVal);
6715       // Transform (X != Y) ? X : Y  -> X
6716       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6717         return ReplaceInstUsesWith(SI, TrueVal);
6718       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6719
6720     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6721       // Transform (X == Y) ? Y : X  -> X
6722       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6723         return ReplaceInstUsesWith(SI, FalseVal);
6724       // Transform (X != Y) ? Y : X  -> Y
6725       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6726         return ReplaceInstUsesWith(SI, TrueVal);
6727       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6728     }
6729   }
6730
6731   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6732     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6733       if (TI->hasOneUse() && FI->hasOneUse()) {
6734         Instruction *AddOp = 0, *SubOp = 0;
6735
6736         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6737         if (TI->getOpcode() == FI->getOpcode())
6738           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6739             return IV;
6740
6741         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6742         // even legal for FP.
6743         if (TI->getOpcode() == Instruction::Sub &&
6744             FI->getOpcode() == Instruction::Add) {
6745           AddOp = FI; SubOp = TI;
6746         } else if (FI->getOpcode() == Instruction::Sub &&
6747                    TI->getOpcode() == Instruction::Add) {
6748           AddOp = TI; SubOp = FI;
6749         }
6750
6751         if (AddOp) {
6752           Value *OtherAddOp = 0;
6753           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6754             OtherAddOp = AddOp->getOperand(1);
6755           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6756             OtherAddOp = AddOp->getOperand(0);
6757           }
6758
6759           if (OtherAddOp) {
6760             // So at this point we know we have (Y -> OtherAddOp):
6761             //        select C, (add X, Y), (sub X, Z)
6762             Value *NegVal;  // Compute -Z
6763             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6764               NegVal = ConstantExpr::getNeg(C);
6765             } else {
6766               NegVal = InsertNewInstBefore(
6767                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6768             }
6769
6770             Value *NewTrueOp = OtherAddOp;
6771             Value *NewFalseOp = NegVal;
6772             if (AddOp != TI)
6773               std::swap(NewTrueOp, NewFalseOp);
6774             Instruction *NewSel =
6775               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6776
6777             NewSel = InsertNewInstBefore(NewSel, SI);
6778             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6779           }
6780         }
6781       }
6782
6783   // See if we can fold the select into one of our operands.
6784   if (SI.getType()->isInteger()) {
6785     // See the comment above GetSelectFoldableOperands for a description of the
6786     // transformation we are doing here.
6787     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6788       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6789           !isa<Constant>(FalseVal))
6790         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6791           unsigned OpToFold = 0;
6792           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6793             OpToFold = 1;
6794           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6795             OpToFold = 2;
6796           }
6797
6798           if (OpToFold) {
6799             Constant *C = GetSelectFoldableConstant(TVI);
6800             std::string Name = TVI->getName(); TVI->setName("");
6801             Instruction *NewSel =
6802               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6803                              Name);
6804             InsertNewInstBefore(NewSel, SI);
6805             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6806               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6807             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6808               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6809             else {
6810               assert(0 && "Unknown instruction!!");
6811             }
6812           }
6813         }
6814
6815     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6816       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6817           !isa<Constant>(TrueVal))
6818         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6819           unsigned OpToFold = 0;
6820           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6821             OpToFold = 1;
6822           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6823             OpToFold = 2;
6824           }
6825
6826           if (OpToFold) {
6827             Constant *C = GetSelectFoldableConstant(FVI);
6828             std::string Name = FVI->getName(); FVI->setName("");
6829             Instruction *NewSel =
6830               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6831                              Name);
6832             InsertNewInstBefore(NewSel, SI);
6833             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6834               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6835             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6836               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6837             else {
6838               assert(0 && "Unknown instruction!!");
6839             }
6840           }
6841         }
6842   }
6843
6844   if (BinaryOperator::isNot(CondVal)) {
6845     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6846     SI.setOperand(1, FalseVal);
6847     SI.setOperand(2, TrueVal);
6848     return &SI;
6849   }
6850
6851   return 0;
6852 }
6853
6854 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6855 /// determine, return it, otherwise return 0.
6856 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6857   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6858     unsigned Align = GV->getAlignment();
6859     if (Align == 0 && TD) 
6860       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6861     return Align;
6862   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6863     unsigned Align = AI->getAlignment();
6864     if (Align == 0 && TD) {
6865       if (isa<AllocaInst>(AI))
6866         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6867       else if (isa<MallocInst>(AI)) {
6868         // Malloc returns maximally aligned memory.
6869         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6870         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6871         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::Int64Ty));
6872       }
6873     }
6874     return Align;
6875   } else if (isa<BitCastInst>(V) ||
6876              (isa<ConstantExpr>(V) && 
6877               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6878     User *CI = cast<User>(V);
6879     if (isa<PointerType>(CI->getOperand(0)->getType()))
6880       return GetKnownAlignment(CI->getOperand(0), TD);
6881     return 0;
6882   } else if (isa<GetElementPtrInst>(V) ||
6883              (isa<ConstantExpr>(V) && 
6884               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6885     User *GEPI = cast<User>(V);
6886     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6887     if (BaseAlignment == 0) return 0;
6888     
6889     // If all indexes are zero, it is just the alignment of the base pointer.
6890     bool AllZeroOperands = true;
6891     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6892       if (!isa<Constant>(GEPI->getOperand(i)) ||
6893           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6894         AllZeroOperands = false;
6895         break;
6896       }
6897     if (AllZeroOperands)
6898       return BaseAlignment;
6899     
6900     // Otherwise, if the base alignment is >= the alignment we expect for the
6901     // base pointer type, then we know that the resultant pointer is aligned at
6902     // least as much as its type requires.
6903     if (!TD) return 0;
6904
6905     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6906     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6907         <= BaseAlignment) {
6908       const Type *GEPTy = GEPI->getType();
6909       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6910     }
6911     return 0;
6912   }
6913   return 0;
6914 }
6915
6916
6917 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6918 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6919 /// the heavy lifting.
6920 ///
6921 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6922   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6923   if (!II) return visitCallSite(&CI);
6924   
6925   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6926   // visitCallSite.
6927   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6928     bool Changed = false;
6929
6930     // memmove/cpy/set of zero bytes is a noop.
6931     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6932       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6933
6934       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6935         if (CI->getZExtValue() == 1) {
6936           // Replace the instruction with just byte operations.  We would
6937           // transform other cases to loads/stores, but we don't know if
6938           // alignment is sufficient.
6939         }
6940     }
6941
6942     // If we have a memmove and the source operation is a constant global,
6943     // then the source and dest pointers can't alias, so we can change this
6944     // into a call to memcpy.
6945     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6946       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6947         if (GVSrc->isConstant()) {
6948           Module *M = CI.getParent()->getParent()->getParent();
6949           const char *Name;
6950           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
6951               Type::Int32Ty)
6952             Name = "llvm.memcpy.i32";
6953           else
6954             Name = "llvm.memcpy.i64";
6955           Constant *MemCpy = M->getOrInsertFunction(Name,
6956                                      CI.getCalledFunction()->getFunctionType());
6957           CI.setOperand(0, MemCpy);
6958           Changed = true;
6959         }
6960     }
6961
6962     // If we can determine a pointer alignment that is bigger than currently
6963     // set, update the alignment.
6964     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6965       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6966       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6967       unsigned Align = std::min(Alignment1, Alignment2);
6968       if (MI->getAlignment()->getZExtValue() < Align) {
6969         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
6970         Changed = true;
6971       }
6972     } else if (isa<MemSetInst>(MI)) {
6973       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6974       if (MI->getAlignment()->getZExtValue() < Alignment) {
6975         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
6976         Changed = true;
6977       }
6978     }
6979           
6980     if (Changed) return II;
6981   } else {
6982     switch (II->getIntrinsicID()) {
6983     default: break;
6984     case Intrinsic::ppc_altivec_lvx:
6985     case Intrinsic::ppc_altivec_lvxl:
6986     case Intrinsic::x86_sse_loadu_ps:
6987     case Intrinsic::x86_sse2_loadu_pd:
6988     case Intrinsic::x86_sse2_loadu_dq:
6989       // Turn PPC lvx     -> load if the pointer is known aligned.
6990       // Turn X86 loadups -> load if the pointer is known aligned.
6991       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6992         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
6993                                       PointerType::get(II->getType()), CI);
6994         return new LoadInst(Ptr);
6995       }
6996       break;
6997     case Intrinsic::ppc_altivec_stvx:
6998     case Intrinsic::ppc_altivec_stvxl:
6999       // Turn stvx -> store if the pointer is known aligned.
7000       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7001         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7002         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7003                                       OpPtrTy, CI);
7004         return new StoreInst(II->getOperand(1), Ptr);
7005       }
7006       break;
7007     case Intrinsic::x86_sse_storeu_ps:
7008     case Intrinsic::x86_sse2_storeu_pd:
7009     case Intrinsic::x86_sse2_storeu_dq:
7010     case Intrinsic::x86_sse2_storel_dq:
7011       // Turn X86 storeu -> store if the pointer is known aligned.
7012       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7013         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7014         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7015                                       OpPtrTy, CI);
7016         return new StoreInst(II->getOperand(2), Ptr);
7017       }
7018       break;
7019       
7020     case Intrinsic::x86_sse_cvttss2si: {
7021       // These intrinsics only demands the 0th element of its input vector.  If
7022       // we can simplify the input based on that, do so now.
7023       uint64_t UndefElts;
7024       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7025                                                 UndefElts)) {
7026         II->setOperand(1, V);
7027         return II;
7028       }
7029       break;
7030     }
7031       
7032     case Intrinsic::ppc_altivec_vperm:
7033       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7034       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7035         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7036         
7037         // Check that all of the elements are integer constants or undefs.
7038         bool AllEltsOk = true;
7039         for (unsigned i = 0; i != 16; ++i) {
7040           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7041               !isa<UndefValue>(Mask->getOperand(i))) {
7042             AllEltsOk = false;
7043             break;
7044           }
7045         }
7046         
7047         if (AllEltsOk) {
7048           // Cast the input vectors to byte vectors.
7049           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7050                                         II->getOperand(1), Mask->getType(), CI);
7051           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7052                                         II->getOperand(2), Mask->getType(), CI);
7053           Value *Result = UndefValue::get(Op0->getType());
7054           
7055           // Only extract each element once.
7056           Value *ExtractedElts[32];
7057           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7058           
7059           for (unsigned i = 0; i != 16; ++i) {
7060             if (isa<UndefValue>(Mask->getOperand(i)))
7061               continue;
7062             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7063             Idx &= 31;  // Match the hardware behavior.
7064             
7065             if (ExtractedElts[Idx] == 0) {
7066               Instruction *Elt = 
7067                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7068               InsertNewInstBefore(Elt, CI);
7069               ExtractedElts[Idx] = Elt;
7070             }
7071           
7072             // Insert this value into the result vector.
7073             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7074             InsertNewInstBefore(cast<Instruction>(Result), CI);
7075           }
7076           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7077         }
7078       }
7079       break;
7080
7081     case Intrinsic::stackrestore: {
7082       // If the save is right next to the restore, remove the restore.  This can
7083       // happen when variable allocas are DCE'd.
7084       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7085         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7086           BasicBlock::iterator BI = SS;
7087           if (&*++BI == II)
7088             return EraseInstFromFunction(CI);
7089         }
7090       }
7091       
7092       // If the stack restore is in a return/unwind block and if there are no
7093       // allocas or calls between the restore and the return, nuke the restore.
7094       TerminatorInst *TI = II->getParent()->getTerminator();
7095       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7096         BasicBlock::iterator BI = II;
7097         bool CannotRemove = false;
7098         for (++BI; &*BI != TI; ++BI) {
7099           if (isa<AllocaInst>(BI) ||
7100               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7101             CannotRemove = true;
7102             break;
7103           }
7104         }
7105         if (!CannotRemove)
7106           return EraseInstFromFunction(CI);
7107       }
7108       break;
7109     }
7110     }
7111   }
7112
7113   return visitCallSite(II);
7114 }
7115
7116 // InvokeInst simplification
7117 //
7118 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7119   return visitCallSite(&II);
7120 }
7121
7122 // visitCallSite - Improvements for call and invoke instructions.
7123 //
7124 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7125   bool Changed = false;
7126
7127   // If the callee is a constexpr cast of a function, attempt to move the cast
7128   // to the arguments of the call/invoke.
7129   if (transformConstExprCastCall(CS)) return 0;
7130
7131   Value *Callee = CS.getCalledValue();
7132
7133   if (Function *CalleeF = dyn_cast<Function>(Callee))
7134     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7135       Instruction *OldCall = CS.getInstruction();
7136       // If the call and callee calling conventions don't match, this call must
7137       // be unreachable, as the call is undefined.
7138       new StoreInst(ConstantBool::getTrue(),
7139                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
7140       if (!OldCall->use_empty())
7141         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7142       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7143         return EraseInstFromFunction(*OldCall);
7144       return 0;
7145     }
7146
7147   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7148     // This instruction is not reachable, just remove it.  We insert a store to
7149     // undef so that we know that this code is not reachable, despite the fact
7150     // that we can't modify the CFG here.
7151     new StoreInst(ConstantBool::getTrue(),
7152                   UndefValue::get(PointerType::get(Type::BoolTy)),
7153                   CS.getInstruction());
7154
7155     if (!CS.getInstruction()->use_empty())
7156       CS.getInstruction()->
7157         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7158
7159     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7160       // Don't break the CFG, insert a dummy cond branch.
7161       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7162                      ConstantBool::getTrue(), II);
7163     }
7164     return EraseInstFromFunction(*CS.getInstruction());
7165   }
7166
7167   const PointerType *PTy = cast<PointerType>(Callee->getType());
7168   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7169   if (FTy->isVarArg()) {
7170     // See if we can optimize any arguments passed through the varargs area of
7171     // the call.
7172     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7173            E = CS.arg_end(); I != E; ++I)
7174       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7175         // If this cast does not effect the value passed through the varargs
7176         // area, we can eliminate the use of the cast.
7177         Value *Op = CI->getOperand(0);
7178         if (CI->isLosslessCast()) {
7179           *I = Op;
7180           Changed = true;
7181         }
7182       }
7183   }
7184
7185   return Changed ? CS.getInstruction() : 0;
7186 }
7187
7188 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7189 // attempt to move the cast to the arguments of the call/invoke.
7190 //
7191 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7192   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7193   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7194   if (CE->getOpcode() != Instruction::BitCast || 
7195       !isa<Function>(CE->getOperand(0)))
7196     return false;
7197   Function *Callee = cast<Function>(CE->getOperand(0));
7198   Instruction *Caller = CS.getInstruction();
7199
7200   // Okay, this is a cast from a function to a different type.  Unless doing so
7201   // would cause a type conversion of one of our arguments, change this call to
7202   // be a direct call with arguments casted to the appropriate types.
7203   //
7204   const FunctionType *FT = Callee->getFunctionType();
7205   const Type *OldRetTy = Caller->getType();
7206
7207   // Check to see if we are changing the return type...
7208   if (OldRetTy != FT->getReturnType()) {
7209     if (Callee->isExternal() && !Caller->use_empty() && 
7210         OldRetTy != FT->getReturnType() &&
7211         // Conversion is ok if changing from pointer to int of same size.
7212         !(isa<PointerType>(FT->getReturnType()) &&
7213           TD->getIntPtrType() == OldRetTy))
7214       return false;   // Cannot transform this return value.
7215
7216     // If the callsite is an invoke instruction, and the return value is used by
7217     // a PHI node in a successor, we cannot change the return type of the call
7218     // because there is no place to put the cast instruction (without breaking
7219     // the critical edge).  Bail out in this case.
7220     if (!Caller->use_empty())
7221       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7222         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7223              UI != E; ++UI)
7224           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7225             if (PN->getParent() == II->getNormalDest() ||
7226                 PN->getParent() == II->getUnwindDest())
7227               return false;
7228   }
7229
7230   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7231   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7232
7233   CallSite::arg_iterator AI = CS.arg_begin();
7234   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7235     const Type *ParamTy = FT->getParamType(i);
7236     const Type *ActTy = (*AI)->getType();
7237     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7238     //Either we can cast directly, or we can upconvert the argument
7239     bool isConvertible = ActTy == ParamTy ||
7240       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7241       (ParamTy->isIntegral() && ActTy->isIntegral() &&
7242        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7243       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7244        && c->getSExtValue() > 0);
7245     if (Callee->isExternal() && !isConvertible) return false;
7246   }
7247
7248   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7249       Callee->isExternal())
7250     return false;   // Do not delete arguments unless we have a function body...
7251
7252   // Okay, we decided that this is a safe thing to do: go ahead and start
7253   // inserting cast instructions as necessary...
7254   std::vector<Value*> Args;
7255   Args.reserve(NumActualArgs);
7256
7257   AI = CS.arg_begin();
7258   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7259     const Type *ParamTy = FT->getParamType(i);
7260     if ((*AI)->getType() == ParamTy) {
7261       Args.push_back(*AI);
7262     } else {
7263       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7264           false, ParamTy, false);
7265       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7266       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7267     }
7268   }
7269
7270   // If the function takes more arguments than the call was taking, add them
7271   // now...
7272   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7273     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7274
7275   // If we are removing arguments to the function, emit an obnoxious warning...
7276   if (FT->getNumParams() < NumActualArgs)
7277     if (!FT->isVarArg()) {
7278       cerr << "WARNING: While resolving call to function '"
7279            << Callee->getName() << "' arguments were dropped!\n";
7280     } else {
7281       // Add all of the arguments in their promoted form to the arg list...
7282       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7283         const Type *PTy = getPromotedType((*AI)->getType());
7284         if (PTy != (*AI)->getType()) {
7285           // Must promote to pass through va_arg area!
7286           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7287                                                                 PTy, false);
7288           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7289           InsertNewInstBefore(Cast, *Caller);
7290           Args.push_back(Cast);
7291         } else {
7292           Args.push_back(*AI);
7293         }
7294       }
7295     }
7296
7297   if (FT->getReturnType() == Type::VoidTy)
7298     Caller->setName("");   // Void type should not have a name...
7299
7300   Instruction *NC;
7301   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7302     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7303                         Args, Caller->getName(), Caller);
7304     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7305   } else {
7306     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7307     if (cast<CallInst>(Caller)->isTailCall())
7308       cast<CallInst>(NC)->setTailCall();
7309    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7310   }
7311
7312   // Insert a cast of the return type as necessary...
7313   Value *NV = NC;
7314   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7315     if (NV->getType() != Type::VoidTy) {
7316       const Type *CallerTy = Caller->getType();
7317       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7318                                                             CallerTy, false);
7319       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7320
7321       // If this is an invoke instruction, we should insert it after the first
7322       // non-phi, instruction in the normal successor block.
7323       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7324         BasicBlock::iterator I = II->getNormalDest()->begin();
7325         while (isa<PHINode>(I)) ++I;
7326         InsertNewInstBefore(NC, *I);
7327       } else {
7328         // Otherwise, it's a call, just insert cast right after the call instr
7329         InsertNewInstBefore(NC, *Caller);
7330       }
7331       AddUsersToWorkList(*Caller);
7332     } else {
7333       NV = UndefValue::get(Caller->getType());
7334     }
7335   }
7336
7337   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7338     Caller->replaceAllUsesWith(NV);
7339   Caller->getParent()->getInstList().erase(Caller);
7340   removeFromWorkList(Caller);
7341   return true;
7342 }
7343
7344 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7345 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7346 /// and a single binop.
7347 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7348   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7349   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7350          isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7351   unsigned Opc = FirstInst->getOpcode();
7352   Value *LHSVal = FirstInst->getOperand(0);
7353   Value *RHSVal = FirstInst->getOperand(1);
7354     
7355   const Type *LHSType = LHSVal->getType();
7356   const Type *RHSType = RHSVal->getType();
7357   
7358   // Scan to see if all operands are the same opcode, all have one use, and all
7359   // kill their operands (i.e. the operands have one use).
7360   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7361     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7362     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7363         // Verify type of the LHS matches so we don't fold cmp's of different
7364         // types or GEP's with different index types.
7365         I->getOperand(0)->getType() != LHSType ||
7366         I->getOperand(1)->getType() != RHSType)
7367       return 0;
7368
7369     // If they are CmpInst instructions, check their predicates
7370     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7371       if (cast<CmpInst>(I)->getPredicate() !=
7372           cast<CmpInst>(FirstInst)->getPredicate())
7373         return 0;
7374     
7375     // Keep track of which operand needs a phi node.
7376     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7377     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7378   }
7379   
7380   // Otherwise, this is safe to transform, determine if it is profitable.
7381
7382   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7383   // Indexes are often folded into load/store instructions, so we don't want to
7384   // hide them behind a phi.
7385   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7386     return 0;
7387   
7388   Value *InLHS = FirstInst->getOperand(0);
7389   Value *InRHS = FirstInst->getOperand(1);
7390   PHINode *NewLHS = 0, *NewRHS = 0;
7391   if (LHSVal == 0) {
7392     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7393     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7394     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7395     InsertNewInstBefore(NewLHS, PN);
7396     LHSVal = NewLHS;
7397   }
7398   
7399   if (RHSVal == 0) {
7400     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7401     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7402     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7403     InsertNewInstBefore(NewRHS, PN);
7404     RHSVal = NewRHS;
7405   }
7406   
7407   // Add all operands to the new PHIs.
7408   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7409     if (NewLHS) {
7410       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7411       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7412     }
7413     if (NewRHS) {
7414       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7415       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7416     }
7417   }
7418     
7419   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7420     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7421   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7422     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7423                            RHSVal);
7424   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7425     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7426   else {
7427     assert(isa<GetElementPtrInst>(FirstInst));
7428     return new GetElementPtrInst(LHSVal, RHSVal);
7429   }
7430 }
7431
7432 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7433 /// of the block that defines it.  This means that it must be obvious the value
7434 /// of the load is not changed from the point of the load to the end of the
7435 /// block it is in.
7436 static bool isSafeToSinkLoad(LoadInst *L) {
7437   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7438   
7439   for (++BBI; BBI != E; ++BBI)
7440     if (BBI->mayWriteToMemory())
7441       return false;
7442   return true;
7443 }
7444
7445
7446 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7447 // operator and they all are only used by the PHI, PHI together their
7448 // inputs, and do the operation once, to the result of the PHI.
7449 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7450   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7451
7452   // Scan the instruction, looking for input operations that can be folded away.
7453   // If all input operands to the phi are the same instruction (e.g. a cast from
7454   // the same type or "+42") we can pull the operation through the PHI, reducing
7455   // code size and simplifying code.
7456   Constant *ConstantOp = 0;
7457   const Type *CastSrcTy = 0;
7458   bool isVolatile = false;
7459   if (isa<CastInst>(FirstInst)) {
7460     CastSrcTy = FirstInst->getOperand(0)->getType();
7461   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7462              isa<CmpInst>(FirstInst)) {
7463     // Can fold binop, compare or shift here if the RHS is a constant, 
7464     // otherwise call FoldPHIArgBinOpIntoPHI.
7465     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7466     if (ConstantOp == 0)
7467       return FoldPHIArgBinOpIntoPHI(PN);
7468   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7469     isVolatile = LI->isVolatile();
7470     // We can't sink the load if the loaded value could be modified between the
7471     // load and the PHI.
7472     if (LI->getParent() != PN.getIncomingBlock(0) ||
7473         !isSafeToSinkLoad(LI))
7474       return 0;
7475   } else if (isa<GetElementPtrInst>(FirstInst)) {
7476     if (FirstInst->getNumOperands() == 2)
7477       return FoldPHIArgBinOpIntoPHI(PN);
7478     // Can't handle general GEPs yet.
7479     return 0;
7480   } else {
7481     return 0;  // Cannot fold this operation.
7482   }
7483
7484   // Check to see if all arguments are the same operation.
7485   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7486     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7487     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7488     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7489       return 0;
7490     if (CastSrcTy) {
7491       if (I->getOperand(0)->getType() != CastSrcTy)
7492         return 0;  // Cast operation must match.
7493     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7494       // We can't sink the load if the loaded value could be modified between 
7495       // the load and the PHI.
7496       if (LI->isVolatile() != isVolatile ||
7497           LI->getParent() != PN.getIncomingBlock(i) ||
7498           !isSafeToSinkLoad(LI))
7499         return 0;
7500     } else if (I->getOperand(1) != ConstantOp) {
7501       return 0;
7502     }
7503   }
7504
7505   // Okay, they are all the same operation.  Create a new PHI node of the
7506   // correct type, and PHI together all of the LHS's of the instructions.
7507   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7508                                PN.getName()+".in");
7509   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7510
7511   Value *InVal = FirstInst->getOperand(0);
7512   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7513
7514   // Add all operands to the new PHI.
7515   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7516     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7517     if (NewInVal != InVal)
7518       InVal = 0;
7519     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7520   }
7521
7522   Value *PhiVal;
7523   if (InVal) {
7524     // The new PHI unions all of the same values together.  This is really
7525     // common, so we handle it intelligently here for compile-time speed.
7526     PhiVal = InVal;
7527     delete NewPN;
7528   } else {
7529     InsertNewInstBefore(NewPN, PN);
7530     PhiVal = NewPN;
7531   }
7532
7533   // Insert and return the new operation.
7534   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7535     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7536   else if (isa<LoadInst>(FirstInst))
7537     return new LoadInst(PhiVal, "", isVolatile);
7538   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7539     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7540   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7541     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7542                            PhiVal, ConstantOp);
7543   else
7544     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7545                          PhiVal, ConstantOp);
7546 }
7547
7548 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7549 /// that is dead.
7550 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7551   if (PN->use_empty()) return true;
7552   if (!PN->hasOneUse()) return false;
7553
7554   // Remember this node, and if we find the cycle, return.
7555   if (!PotentiallyDeadPHIs.insert(PN).second)
7556     return true;
7557
7558   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7559     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7560
7561   return false;
7562 }
7563
7564 // PHINode simplification
7565 //
7566 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7567   // If LCSSA is around, don't mess with Phi nodes
7568   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7569   
7570   if (Value *V = PN.hasConstantValue())
7571     return ReplaceInstUsesWith(PN, V);
7572
7573   // If all PHI operands are the same operation, pull them through the PHI,
7574   // reducing code size.
7575   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7576       PN.getIncomingValue(0)->hasOneUse())
7577     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7578       return Result;
7579
7580   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7581   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7582   // PHI)... break the cycle.
7583   if (PN.hasOneUse())
7584     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7585       std::set<PHINode*> PotentiallyDeadPHIs;
7586       PotentiallyDeadPHIs.insert(&PN);
7587       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7588         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7589     }
7590
7591   return 0;
7592 }
7593
7594 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7595                                    Instruction *InsertPoint,
7596                                    InstCombiner *IC) {
7597   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7598   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7599   // We must cast correctly to the pointer type. Ensure that we
7600   // sign extend the integer value if it is smaller as this is
7601   // used for address computation.
7602   Instruction::CastOps opcode = 
7603      (VTySize < PtrSize ? Instruction::SExt :
7604       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7605   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7606 }
7607
7608
7609 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7610   Value *PtrOp = GEP.getOperand(0);
7611   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7612   // If so, eliminate the noop.
7613   if (GEP.getNumOperands() == 1)
7614     return ReplaceInstUsesWith(GEP, PtrOp);
7615
7616   if (isa<UndefValue>(GEP.getOperand(0)))
7617     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7618
7619   bool HasZeroPointerIndex = false;
7620   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7621     HasZeroPointerIndex = C->isNullValue();
7622
7623   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7624     return ReplaceInstUsesWith(GEP, PtrOp);
7625
7626   // Eliminate unneeded casts for indices.
7627   bool MadeChange = false;
7628   gep_type_iterator GTI = gep_type_begin(GEP);
7629   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7630     if (isa<SequentialType>(*GTI)) {
7631       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7632         Value *Src = CI->getOperand(0);
7633         const Type *SrcTy = Src->getType();
7634         const Type *DestTy = CI->getType();
7635         if (Src->getType()->isInteger()) {
7636           if (SrcTy->getPrimitiveSizeInBits() ==
7637                        DestTy->getPrimitiveSizeInBits()) {
7638             // We can always eliminate a cast from ulong or long to the other.
7639             // We can always eliminate a cast from uint to int or the other on
7640             // 32-bit pointer platforms.
7641             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7642               MadeChange = true;
7643               GEP.setOperand(i, Src);
7644             }
7645           } else if (SrcTy->getPrimitiveSizeInBits() < 
7646                      DestTy->getPrimitiveSizeInBits() &&
7647                      SrcTy->getPrimitiveSize() == 4) {
7648             // We can eliminate a cast from [u]int to [u]long iff the target 
7649             // is a 32-bit pointer target.
7650             if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7651               MadeChange = true;
7652               GEP.setOperand(i, Src);
7653             }
7654           }
7655         }
7656       }
7657       // If we are using a wider index than needed for this platform, shrink it
7658       // to what we need.  If the incoming value needs a cast instruction,
7659       // insert it.  This explicit cast can make subsequent optimizations more
7660       // obvious.
7661       Value *Op = GEP.getOperand(i);
7662       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7663         if (Constant *C = dyn_cast<Constant>(Op)) {
7664           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7665           MadeChange = true;
7666         } else {
7667           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7668                                 GEP);
7669           GEP.setOperand(i, Op);
7670           MadeChange = true;
7671         }
7672     }
7673   if (MadeChange) return &GEP;
7674
7675   // Combine Indices - If the source pointer to this getelementptr instruction
7676   // is a getelementptr instruction, combine the indices of the two
7677   // getelementptr instructions into a single instruction.
7678   //
7679   std::vector<Value*> SrcGEPOperands;
7680   if (User *Src = dyn_castGetElementPtr(PtrOp))
7681     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7682
7683   if (!SrcGEPOperands.empty()) {
7684     // Note that if our source is a gep chain itself that we wait for that
7685     // chain to be resolved before we perform this transformation.  This
7686     // avoids us creating a TON of code in some cases.
7687     //
7688     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7689         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7690       return 0;   // Wait until our source is folded to completion.
7691
7692     std::vector<Value *> Indices;
7693
7694     // Find out whether the last index in the source GEP is a sequential idx.
7695     bool EndsWithSequential = false;
7696     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7697            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7698       EndsWithSequential = !isa<StructType>(*I);
7699
7700     // Can we combine the two pointer arithmetics offsets?
7701     if (EndsWithSequential) {
7702       // Replace: gep (gep %P, long B), long A, ...
7703       // With:    T = long A+B; gep %P, T, ...
7704       //
7705       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7706       if (SO1 == Constant::getNullValue(SO1->getType())) {
7707         Sum = GO1;
7708       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7709         Sum = SO1;
7710       } else {
7711         // If they aren't the same type, convert both to an integer of the
7712         // target's pointer size.
7713         if (SO1->getType() != GO1->getType()) {
7714           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7715             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7716           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7717             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7718           } else {
7719             unsigned PS = TD->getPointerSize();
7720             if (SO1->getType()->getPrimitiveSize() == PS) {
7721               // Convert GO1 to SO1's type.
7722               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7723
7724             } else if (GO1->getType()->getPrimitiveSize() == PS) {
7725               // Convert SO1 to GO1's type.
7726               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7727             } else {
7728               const Type *PT = TD->getIntPtrType();
7729               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7730               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7731             }
7732           }
7733         }
7734         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7735           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7736         else {
7737           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7738           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7739         }
7740       }
7741
7742       // Recycle the GEP we already have if possible.
7743       if (SrcGEPOperands.size() == 2) {
7744         GEP.setOperand(0, SrcGEPOperands[0]);
7745         GEP.setOperand(1, Sum);
7746         return &GEP;
7747       } else {
7748         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7749                        SrcGEPOperands.end()-1);
7750         Indices.push_back(Sum);
7751         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7752       }
7753     } else if (isa<Constant>(*GEP.idx_begin()) &&
7754                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7755                SrcGEPOperands.size() != 1) {
7756       // Otherwise we can do the fold if the first index of the GEP is a zero
7757       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7758                      SrcGEPOperands.end());
7759       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7760     }
7761
7762     if (!Indices.empty())
7763       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7764
7765   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7766     // GEP of global variable.  If all of the indices for this GEP are
7767     // constants, we can promote this to a constexpr instead of an instruction.
7768
7769     // Scan for nonconstants...
7770     std::vector<Constant*> Indices;
7771     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7772     for (; I != E && isa<Constant>(*I); ++I)
7773       Indices.push_back(cast<Constant>(*I));
7774
7775     if (I == E) {  // If they are all constants...
7776       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7777
7778       // Replace all uses of the GEP with the new constexpr...
7779       return ReplaceInstUsesWith(GEP, CE);
7780     }
7781   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7782     if (!isa<PointerType>(X->getType())) {
7783       // Not interesting.  Source pointer must be a cast from pointer.
7784     } else if (HasZeroPointerIndex) {
7785       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7786       // into     : GEP [10 x ubyte]* X, long 0, ...
7787       //
7788       // This occurs when the program declares an array extern like "int X[];"
7789       //
7790       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7791       const PointerType *XTy = cast<PointerType>(X->getType());
7792       if (const ArrayType *XATy =
7793           dyn_cast<ArrayType>(XTy->getElementType()))
7794         if (const ArrayType *CATy =
7795             dyn_cast<ArrayType>(CPTy->getElementType()))
7796           if (CATy->getElementType() == XATy->getElementType()) {
7797             // At this point, we know that the cast source type is a pointer
7798             // to an array of the same type as the destination pointer
7799             // array.  Because the array type is never stepped over (there
7800             // is a leading zero) we can fold the cast into this GEP.
7801             GEP.setOperand(0, X);
7802             return &GEP;
7803           }
7804     } else if (GEP.getNumOperands() == 2) {
7805       // Transform things like:
7806       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7807       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7808       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7809       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7810       if (isa<ArrayType>(SrcElTy) &&
7811           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7812           TD->getTypeSize(ResElTy)) {
7813         Value *V = InsertNewInstBefore(
7814                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7815                                      GEP.getOperand(1), GEP.getName()), GEP);
7816         // V and GEP are both pointer types --> BitCast
7817         return new BitCastInst(V, GEP.getType());
7818       }
7819       
7820       // Transform things like:
7821       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7822       //   (where tmp = 8*tmp2) into:
7823       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7824       
7825       if (isa<ArrayType>(SrcElTy) &&
7826           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7827         uint64_t ArrayEltSize =
7828             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7829         
7830         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7831         // allow either a mul, shift, or constant here.
7832         Value *NewIdx = 0;
7833         ConstantInt *Scale = 0;
7834         if (ArrayEltSize == 1) {
7835           NewIdx = GEP.getOperand(1);
7836           Scale = ConstantInt::get(NewIdx->getType(), 1);
7837         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7838           NewIdx = ConstantInt::get(CI->getType(), 1);
7839           Scale = CI;
7840         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7841           if (Inst->getOpcode() == Instruction::Shl &&
7842               isa<ConstantInt>(Inst->getOperand(1))) {
7843             unsigned ShAmt =
7844               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7845             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7846             NewIdx = Inst->getOperand(0);
7847           } else if (Inst->getOpcode() == Instruction::Mul &&
7848                      isa<ConstantInt>(Inst->getOperand(1))) {
7849             Scale = cast<ConstantInt>(Inst->getOperand(1));
7850             NewIdx = Inst->getOperand(0);
7851           }
7852         }
7853
7854         // If the index will be to exactly the right offset with the scale taken
7855         // out, perform the transformation.
7856         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7857           if (isa<ConstantInt>(Scale))
7858             Scale = ConstantInt::get(Scale->getType(),
7859                                       Scale->getZExtValue() / ArrayEltSize);
7860           if (Scale->getZExtValue() != 1) {
7861             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7862                                                        true /*SExt*/);
7863             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7864             NewIdx = InsertNewInstBefore(Sc, GEP);
7865           }
7866
7867           // Insert the new GEP instruction.
7868           Instruction *NewGEP =
7869             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7870                                   NewIdx, GEP.getName());
7871           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7872           // The NewGEP must be pointer typed, so must the old one -> BitCast
7873           return new BitCastInst(NewGEP, GEP.getType());
7874         }
7875       }
7876     }
7877   }
7878
7879   return 0;
7880 }
7881
7882 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7883   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7884   if (AI.isArrayAllocation())    // Check C != 1
7885     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7886       const Type *NewTy = 
7887         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7888       AllocationInst *New = 0;
7889
7890       // Create and insert the replacement instruction...
7891       if (isa<MallocInst>(AI))
7892         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7893       else {
7894         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7895         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7896       }
7897
7898       InsertNewInstBefore(New, AI);
7899
7900       // Scan to the end of the allocation instructions, to skip over a block of
7901       // allocas if possible...
7902       //
7903       BasicBlock::iterator It = New;
7904       while (isa<AllocationInst>(*It)) ++It;
7905
7906       // Now that I is pointing to the first non-allocation-inst in the block,
7907       // insert our getelementptr instruction...
7908       //
7909       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7910       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7911                                        New->getName()+".sub", It);
7912
7913       // Now make everything use the getelementptr instead of the original
7914       // allocation.
7915       return ReplaceInstUsesWith(AI, V);
7916     } else if (isa<UndefValue>(AI.getArraySize())) {
7917       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7918     }
7919
7920   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7921   // Note that we only do this for alloca's, because malloc should allocate and
7922   // return a unique pointer, even for a zero byte allocation.
7923   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7924       TD->getTypeSize(AI.getAllocatedType()) == 0)
7925     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7926
7927   return 0;
7928 }
7929
7930 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7931   Value *Op = FI.getOperand(0);
7932
7933   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7934   if (CastInst *CI = dyn_cast<CastInst>(Op))
7935     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7936       FI.setOperand(0, CI->getOperand(0));
7937       return &FI;
7938     }
7939
7940   // free undef -> unreachable.
7941   if (isa<UndefValue>(Op)) {
7942     // Insert a new store to null because we cannot modify the CFG here.
7943     new StoreInst(ConstantBool::getTrue(),
7944                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7945     return EraseInstFromFunction(FI);
7946   }
7947
7948   // If we have 'free null' delete the instruction.  This can happen in stl code
7949   // when lots of inlining happens.
7950   if (isa<ConstantPointerNull>(Op))
7951     return EraseInstFromFunction(FI);
7952
7953   return 0;
7954 }
7955
7956
7957 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7958 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7959   User *CI = cast<User>(LI.getOperand(0));
7960   Value *CastOp = CI->getOperand(0);
7961
7962   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7963   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7964     const Type *SrcPTy = SrcTy->getElementType();
7965
7966     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7967         isa<PackedType>(DestPTy)) {
7968       // If the source is an array, the code below will not succeed.  Check to
7969       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7970       // constants.
7971       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7972         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7973           if (ASrcTy->getNumElements() != 0) {
7974             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
7975             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7976             SrcTy = cast<PointerType>(CastOp->getType());
7977             SrcPTy = SrcTy->getElementType();
7978           }
7979
7980       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7981            isa<PackedType>(SrcPTy)) &&
7982           // Do not allow turning this into a load of an integer, which is then
7983           // casted to a pointer, this pessimizes pointer analysis a lot.
7984           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7985           IC.getTargetData().getTypeSize(SrcPTy) ==
7986                IC.getTargetData().getTypeSize(DestPTy)) {
7987
7988         // Okay, we are casting from one integer or pointer type to another of
7989         // the same size.  Instead of casting the pointer before the load, cast
7990         // the result of the loaded value.
7991         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7992                                                              CI->getName(),
7993                                                          LI.isVolatile()),LI);
7994         // Now cast the result of the load.
7995         return new BitCastInst(NewLoad, LI.getType());
7996       }
7997     }
7998   }
7999   return 0;
8000 }
8001
8002 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8003 /// from this value cannot trap.  If it is not obviously safe to load from the
8004 /// specified pointer, we do a quick local scan of the basic block containing
8005 /// ScanFrom, to determine if the address is already accessed.
8006 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8007   // If it is an alloca or global variable, it is always safe to load from.
8008   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8009
8010   // Otherwise, be a little bit agressive by scanning the local block where we
8011   // want to check to see if the pointer is already being loaded or stored
8012   // from/to.  If so, the previous load or store would have already trapped,
8013   // so there is no harm doing an extra load (also, CSE will later eliminate
8014   // the load entirely).
8015   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8016
8017   while (BBI != E) {
8018     --BBI;
8019
8020     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8021       if (LI->getOperand(0) == V) return true;
8022     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8023       if (SI->getOperand(1) == V) return true;
8024
8025   }
8026   return false;
8027 }
8028
8029 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8030   Value *Op = LI.getOperand(0);
8031
8032   // load (cast X) --> cast (load X) iff safe
8033   if (isa<CastInst>(Op))
8034     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8035       return Res;
8036
8037   // None of the following transforms are legal for volatile loads.
8038   if (LI.isVolatile()) return 0;
8039   
8040   if (&LI.getParent()->front() != &LI) {
8041     BasicBlock::iterator BBI = &LI; --BBI;
8042     // If the instruction immediately before this is a store to the same
8043     // address, do a simple form of store->load forwarding.
8044     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8045       if (SI->getOperand(1) == LI.getOperand(0))
8046         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8047     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8048       if (LIB->getOperand(0) == LI.getOperand(0))
8049         return ReplaceInstUsesWith(LI, LIB);
8050   }
8051
8052   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8053     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8054         isa<UndefValue>(GEPI->getOperand(0))) {
8055       // Insert a new store to null instruction before the load to indicate
8056       // that this code is not reachable.  We do this instead of inserting
8057       // an unreachable instruction directly because we cannot modify the
8058       // CFG.
8059       new StoreInst(UndefValue::get(LI.getType()),
8060                     Constant::getNullValue(Op->getType()), &LI);
8061       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8062     }
8063
8064   if (Constant *C = dyn_cast<Constant>(Op)) {
8065     // load null/undef -> undef
8066     if ((C->isNullValue() || isa<UndefValue>(C))) {
8067       // Insert a new store to null instruction before the load to indicate that
8068       // this code is not reachable.  We do this instead of inserting an
8069       // unreachable instruction directly because we cannot modify the CFG.
8070       new StoreInst(UndefValue::get(LI.getType()),
8071                     Constant::getNullValue(Op->getType()), &LI);
8072       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8073     }
8074
8075     // Instcombine load (constant global) into the value loaded.
8076     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8077       if (GV->isConstant() && !GV->isExternal())
8078         return ReplaceInstUsesWith(LI, GV->getInitializer());
8079
8080     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8081     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8082       if (CE->getOpcode() == Instruction::GetElementPtr) {
8083         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8084           if (GV->isConstant() && !GV->isExternal())
8085             if (Constant *V = 
8086                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8087               return ReplaceInstUsesWith(LI, V);
8088         if (CE->getOperand(0)->isNullValue()) {
8089           // Insert a new store to null instruction before the load to indicate
8090           // that this code is not reachable.  We do this instead of inserting
8091           // an unreachable instruction directly because we cannot modify the
8092           // CFG.
8093           new StoreInst(UndefValue::get(LI.getType()),
8094                         Constant::getNullValue(Op->getType()), &LI);
8095           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8096         }
8097
8098       } else if (CE->isCast()) {
8099         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8100           return Res;
8101       }
8102   }
8103
8104   if (Op->hasOneUse()) {
8105     // Change select and PHI nodes to select values instead of addresses: this
8106     // helps alias analysis out a lot, allows many others simplifications, and
8107     // exposes redundancy in the code.
8108     //
8109     // Note that we cannot do the transformation unless we know that the
8110     // introduced loads cannot trap!  Something like this is valid as long as
8111     // the condition is always false: load (select bool %C, int* null, int* %G),
8112     // but it would not be valid if we transformed it to load from null
8113     // unconditionally.
8114     //
8115     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8116       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8117       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8118           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8119         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8120                                      SI->getOperand(1)->getName()+".val"), LI);
8121         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8122                                      SI->getOperand(2)->getName()+".val"), LI);
8123         return new SelectInst(SI->getCondition(), V1, V2);
8124       }
8125
8126       // load (select (cond, null, P)) -> load P
8127       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8128         if (C->isNullValue()) {
8129           LI.setOperand(0, SI->getOperand(2));
8130           return &LI;
8131         }
8132
8133       // load (select (cond, P, null)) -> load P
8134       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8135         if (C->isNullValue()) {
8136           LI.setOperand(0, SI->getOperand(1));
8137           return &LI;
8138         }
8139     }
8140   }
8141   return 0;
8142 }
8143
8144 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
8145 /// when possible.
8146 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8147   User *CI = cast<User>(SI.getOperand(1));
8148   Value *CastOp = CI->getOperand(0);
8149
8150   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8151   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8152     const Type *SrcPTy = SrcTy->getElementType();
8153
8154     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8155       // If the source is an array, the code below will not succeed.  Check to
8156       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8157       // constants.
8158       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8159         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8160           if (ASrcTy->getNumElements() != 0) {
8161             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::Int32Ty));
8162             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
8163             SrcTy = cast<PointerType>(CastOp->getType());
8164             SrcPTy = SrcTy->getElementType();
8165           }
8166
8167       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8168           IC.getTargetData().getTypeSize(SrcPTy) ==
8169                IC.getTargetData().getTypeSize(DestPTy)) {
8170
8171         // Okay, we are casting from one integer or pointer type to another of
8172         // the same size.  Instead of casting the pointer before the store, cast
8173         // the value to be stored.
8174         Value *NewCast;
8175         Instruction::CastOps opcode = Instruction::BitCast;
8176         Value *SIOp0 = SI.getOperand(0);
8177         if (isa<PointerType>(SrcPTy)) {
8178           if (SIOp0->getType()->isIntegral())
8179             opcode = Instruction::IntToPtr;
8180         } else if (SrcPTy->isIntegral()) {
8181           if (isa<PointerType>(SIOp0->getType()))
8182             opcode = Instruction::PtrToInt;
8183         }
8184         if (Constant *C = dyn_cast<Constant>(SIOp0))
8185           NewCast = ConstantExpr::getCast(opcode, C, SrcPTy);
8186         else
8187           NewCast = IC.InsertNewInstBefore(
8188             CastInst::create(opcode, SIOp0, SrcPTy, SIOp0->getName()+".c"), SI);
8189         return new StoreInst(NewCast, CastOp);
8190       }
8191     }
8192   }
8193   return 0;
8194 }
8195
8196 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8197   Value *Val = SI.getOperand(0);
8198   Value *Ptr = SI.getOperand(1);
8199
8200   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8201     EraseInstFromFunction(SI);
8202     ++NumCombined;
8203     return 0;
8204   }
8205
8206   // Do really simple DSE, to catch cases where there are several consequtive
8207   // stores to the same location, separated by a few arithmetic operations. This
8208   // situation often occurs with bitfield accesses.
8209   BasicBlock::iterator BBI = &SI;
8210   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8211        --ScanInsts) {
8212     --BBI;
8213     
8214     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8215       // Prev store isn't volatile, and stores to the same location?
8216       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8217         ++NumDeadStore;
8218         ++BBI;
8219         EraseInstFromFunction(*PrevSI);
8220         continue;
8221       }
8222       break;
8223     }
8224     
8225     // If this is a load, we have to stop.  However, if the loaded value is from
8226     // the pointer we're loading and is producing the pointer we're storing,
8227     // then *this* store is dead (X = load P; store X -> P).
8228     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8229       if (LI == Val && LI->getOperand(0) == Ptr) {
8230         EraseInstFromFunction(SI);
8231         ++NumCombined;
8232         return 0;
8233       }
8234       // Otherwise, this is a load from some other location.  Stores before it
8235       // may not be dead.
8236       break;
8237     }
8238     
8239     // Don't skip over loads or things that can modify memory.
8240     if (BBI->mayWriteToMemory())
8241       break;
8242   }
8243   
8244   
8245   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8246
8247   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8248   if (isa<ConstantPointerNull>(Ptr)) {
8249     if (!isa<UndefValue>(Val)) {
8250       SI.setOperand(0, UndefValue::get(Val->getType()));
8251       if (Instruction *U = dyn_cast<Instruction>(Val))
8252         WorkList.push_back(U);  // Dropped a use.
8253       ++NumCombined;
8254     }
8255     return 0;  // Do not modify these!
8256   }
8257
8258   // store undef, Ptr -> noop
8259   if (isa<UndefValue>(Val)) {
8260     EraseInstFromFunction(SI);
8261     ++NumCombined;
8262     return 0;
8263   }
8264
8265   // If the pointer destination is a cast, see if we can fold the cast into the
8266   // source instead.
8267   if (isa<CastInst>(Ptr))
8268     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8269       return Res;
8270   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8271     if (CE->isCast())
8272       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8273         return Res;
8274
8275   
8276   // If this store is the last instruction in the basic block, and if the block
8277   // ends with an unconditional branch, try to move it to the successor block.
8278   BBI = &SI; ++BBI;
8279   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8280     if (BI->isUnconditional()) {
8281       // Check to see if the successor block has exactly two incoming edges.  If
8282       // so, see if the other predecessor contains a store to the same location.
8283       // if so, insert a PHI node (if needed) and move the stores down.
8284       BasicBlock *Dest = BI->getSuccessor(0);
8285
8286       pred_iterator PI = pred_begin(Dest);
8287       BasicBlock *Other = 0;
8288       if (*PI != BI->getParent())
8289         Other = *PI;
8290       ++PI;
8291       if (PI != pred_end(Dest)) {
8292         if (*PI != BI->getParent())
8293           if (Other)
8294             Other = 0;
8295           else
8296             Other = *PI;
8297         if (++PI != pred_end(Dest))
8298           Other = 0;
8299       }
8300       if (Other) {  // If only one other pred...
8301         BBI = Other->getTerminator();
8302         // Make sure this other block ends in an unconditional branch and that
8303         // there is an instruction before the branch.
8304         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8305             BBI != Other->begin()) {
8306           --BBI;
8307           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8308           
8309           // If this instruction is a store to the same location.
8310           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8311             // Okay, we know we can perform this transformation.  Insert a PHI
8312             // node now if we need it.
8313             Value *MergedVal = OtherStore->getOperand(0);
8314             if (MergedVal != SI.getOperand(0)) {
8315               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8316               PN->reserveOperandSpace(2);
8317               PN->addIncoming(SI.getOperand(0), SI.getParent());
8318               PN->addIncoming(OtherStore->getOperand(0), Other);
8319               MergedVal = InsertNewInstBefore(PN, Dest->front());
8320             }
8321             
8322             // Advance to a place where it is safe to insert the new store and
8323             // insert it.
8324             BBI = Dest->begin();
8325             while (isa<PHINode>(BBI)) ++BBI;
8326             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8327                                               OtherStore->isVolatile()), *BBI);
8328
8329             // Nuke the old stores.
8330             EraseInstFromFunction(SI);
8331             EraseInstFromFunction(*OtherStore);
8332             ++NumCombined;
8333             return 0;
8334           }
8335         }
8336       }
8337     }
8338   
8339   return 0;
8340 }
8341
8342
8343 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8344   // Change br (not X), label True, label False to: br X, label False, True
8345   Value *X = 0;
8346   BasicBlock *TrueDest;
8347   BasicBlock *FalseDest;
8348   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8349       !isa<Constant>(X)) {
8350     // Swap Destinations and condition...
8351     BI.setCondition(X);
8352     BI.setSuccessor(0, FalseDest);
8353     BI.setSuccessor(1, TrueDest);
8354     return &BI;
8355   }
8356
8357   // Cannonicalize fcmp_one -> fcmp_oeq
8358   FCmpInst::Predicate FPred; Value *Y;
8359   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8360                              TrueDest, FalseDest)))
8361     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8362          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8363       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8364       std::string Name = I->getName(); I->setName("");
8365       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8366       Value *NewSCC =  new FCmpInst(NewPred, X, Y, Name, I);
8367       // Swap Destinations and condition...
8368       BI.setCondition(NewSCC);
8369       BI.setSuccessor(0, FalseDest);
8370       BI.setSuccessor(1, TrueDest);
8371       removeFromWorkList(I);
8372       I->getParent()->getInstList().erase(I);
8373       WorkList.push_back(cast<Instruction>(NewSCC));
8374       return &BI;
8375     }
8376
8377   // Cannonicalize icmp_ne -> icmp_eq
8378   ICmpInst::Predicate IPred;
8379   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8380                       TrueDest, FalseDest)))
8381     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8382          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8383          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8384       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8385       std::string Name = I->getName(); I->setName("");
8386       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8387       Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8388       // Swap Destinations and condition...
8389       BI.setCondition(NewSCC);
8390       BI.setSuccessor(0, FalseDest);
8391       BI.setSuccessor(1, TrueDest);
8392       removeFromWorkList(I);
8393       I->getParent()->getInstList().erase(I);
8394       WorkList.push_back(cast<Instruction>(NewSCC));
8395       return &BI;
8396     }
8397
8398   return 0;
8399 }
8400
8401 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8402   Value *Cond = SI.getCondition();
8403   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8404     if (I->getOpcode() == Instruction::Add)
8405       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8406         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8407         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8408           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8409                                                 AddRHS));
8410         SI.setOperand(0, I->getOperand(0));
8411         WorkList.push_back(I);
8412         return &SI;
8413       }
8414   }
8415   return 0;
8416 }
8417
8418 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8419 /// is to leave as a vector operation.
8420 static bool CheapToScalarize(Value *V, bool isConstant) {
8421   if (isa<ConstantAggregateZero>(V)) 
8422     return true;
8423   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8424     if (isConstant) return true;
8425     // If all elts are the same, we can extract.
8426     Constant *Op0 = C->getOperand(0);
8427     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8428       if (C->getOperand(i) != Op0)
8429         return false;
8430     return true;
8431   }
8432   Instruction *I = dyn_cast<Instruction>(V);
8433   if (!I) return false;
8434   
8435   // Insert element gets simplified to the inserted element or is deleted if
8436   // this is constant idx extract element and its a constant idx insertelt.
8437   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8438       isa<ConstantInt>(I->getOperand(2)))
8439     return true;
8440   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8441     return true;
8442   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8443     if (BO->hasOneUse() &&
8444         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8445          CheapToScalarize(BO->getOperand(1), isConstant)))
8446       return true;
8447   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8448     if (CI->hasOneUse() &&
8449         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8450          CheapToScalarize(CI->getOperand(1), isConstant)))
8451       return true;
8452   
8453   return false;
8454 }
8455
8456 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
8457 /// elements into values that are larger than the #elts in the input.
8458 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8459   unsigned NElts = SVI->getType()->getNumElements();
8460   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8461     return std::vector<unsigned>(NElts, 0);
8462   if (isa<UndefValue>(SVI->getOperand(2)))
8463     return std::vector<unsigned>(NElts, 2*NElts);
8464
8465   std::vector<unsigned> Result;
8466   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8467   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8468     if (isa<UndefValue>(CP->getOperand(i)))
8469       Result.push_back(NElts*2);  // undef -> 8
8470     else
8471       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8472   return Result;
8473 }
8474
8475 /// FindScalarElement - Given a vector and an element number, see if the scalar
8476 /// value is already around as a register, for example if it were inserted then
8477 /// extracted from the vector.
8478 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8479   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8480   const PackedType *PTy = cast<PackedType>(V->getType());
8481   unsigned Width = PTy->getNumElements();
8482   if (EltNo >= Width)  // Out of range access.
8483     return UndefValue::get(PTy->getElementType());
8484   
8485   if (isa<UndefValue>(V))
8486     return UndefValue::get(PTy->getElementType());
8487   else if (isa<ConstantAggregateZero>(V))
8488     return Constant::getNullValue(PTy->getElementType());
8489   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8490     return CP->getOperand(EltNo);
8491   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8492     // If this is an insert to a variable element, we don't know what it is.
8493     if (!isa<ConstantInt>(III->getOperand(2))) 
8494       return 0;
8495     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8496     
8497     // If this is an insert to the element we are looking for, return the
8498     // inserted value.
8499     if (EltNo == IIElt) 
8500       return III->getOperand(1);
8501     
8502     // Otherwise, the insertelement doesn't modify the value, recurse on its
8503     // vector input.
8504     return FindScalarElement(III->getOperand(0), EltNo);
8505   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8506     unsigned InEl = getShuffleMask(SVI)[EltNo];
8507     if (InEl < Width)
8508       return FindScalarElement(SVI->getOperand(0), InEl);
8509     else if (InEl < Width*2)
8510       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8511     else
8512       return UndefValue::get(PTy->getElementType());
8513   }
8514   
8515   // Otherwise, we don't know.
8516   return 0;
8517 }
8518
8519 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8520
8521   // If packed val is undef, replace extract with scalar undef.
8522   if (isa<UndefValue>(EI.getOperand(0)))
8523     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8524
8525   // If packed val is constant 0, replace extract with scalar 0.
8526   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8527     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8528   
8529   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8530     // If packed val is constant with uniform operands, replace EI
8531     // with that operand
8532     Constant *op0 = C->getOperand(0);
8533     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8534       if (C->getOperand(i) != op0) {
8535         op0 = 0; 
8536         break;
8537       }
8538     if (op0)
8539       return ReplaceInstUsesWith(EI, op0);
8540   }
8541   
8542   // If extracting a specified index from the vector, see if we can recursively
8543   // find a previously computed scalar that was inserted into the vector.
8544   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8545     // This instruction only demands the single element from the input vector.
8546     // If the input vector has a single use, simplify it based on this use
8547     // property.
8548     uint64_t IndexVal = IdxC->getZExtValue();
8549     if (EI.getOperand(0)->hasOneUse()) {
8550       uint64_t UndefElts;
8551       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8552                                                 1 << IndexVal,
8553                                                 UndefElts)) {
8554         EI.setOperand(0, V);
8555         return &EI;
8556       }
8557     }
8558     
8559     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8560       return ReplaceInstUsesWith(EI, Elt);
8561   }
8562   
8563   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8564     if (I->hasOneUse()) {
8565       // Push extractelement into predecessor operation if legal and
8566       // profitable to do so
8567       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8568         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8569         if (CheapToScalarize(BO, isConstantElt)) {
8570           ExtractElementInst *newEI0 = 
8571             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8572                                    EI.getName()+".lhs");
8573           ExtractElementInst *newEI1 =
8574             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8575                                    EI.getName()+".rhs");
8576           InsertNewInstBefore(newEI0, EI);
8577           InsertNewInstBefore(newEI1, EI);
8578           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8579         }
8580       } else if (isa<LoadInst>(I)) {
8581         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8582                                       PointerType::get(EI.getType()), EI);
8583         GetElementPtrInst *GEP = 
8584           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8585         InsertNewInstBefore(GEP, EI);
8586         return new LoadInst(GEP);
8587       }
8588     }
8589     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8590       // Extracting the inserted element?
8591       if (IE->getOperand(2) == EI.getOperand(1))
8592         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8593       // If the inserted and extracted elements are constants, they must not
8594       // be the same value, extract from the pre-inserted value instead.
8595       if (isa<Constant>(IE->getOperand(2)) &&
8596           isa<Constant>(EI.getOperand(1))) {
8597         AddUsesToWorkList(EI);
8598         EI.setOperand(0, IE->getOperand(0));
8599         return &EI;
8600       }
8601     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8602       // If this is extracting an element from a shufflevector, figure out where
8603       // it came from and extract from the appropriate input element instead.
8604       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8605         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8606         Value *Src;
8607         if (SrcIdx < SVI->getType()->getNumElements())
8608           Src = SVI->getOperand(0);
8609         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8610           SrcIdx -= SVI->getType()->getNumElements();
8611           Src = SVI->getOperand(1);
8612         } else {
8613           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8614         }
8615         return new ExtractElementInst(Src, SrcIdx);
8616       }
8617     }
8618   }
8619   return 0;
8620 }
8621
8622 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8623 /// elements from either LHS or RHS, return the shuffle mask and true. 
8624 /// Otherwise, return false.
8625 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8626                                          std::vector<Constant*> &Mask) {
8627   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8628          "Invalid CollectSingleShuffleElements");
8629   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8630
8631   if (isa<UndefValue>(V)) {
8632     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8633     return true;
8634   } else if (V == LHS) {
8635     for (unsigned i = 0; i != NumElts; ++i)
8636       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8637     return true;
8638   } else if (V == RHS) {
8639     for (unsigned i = 0; i != NumElts; ++i)
8640       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8641     return true;
8642   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8643     // If this is an insert of an extract from some other vector, include it.
8644     Value *VecOp    = IEI->getOperand(0);
8645     Value *ScalarOp = IEI->getOperand(1);
8646     Value *IdxOp    = IEI->getOperand(2);
8647     
8648     if (!isa<ConstantInt>(IdxOp))
8649       return false;
8650     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8651     
8652     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8653       // Okay, we can handle this if the vector we are insertinting into is
8654       // transitively ok.
8655       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8656         // If so, update the mask to reflect the inserted undef.
8657         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8658         return true;
8659       }      
8660     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8661       if (isa<ConstantInt>(EI->getOperand(1)) &&
8662           EI->getOperand(0)->getType() == V->getType()) {
8663         unsigned ExtractedIdx =
8664           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8665         
8666         // This must be extracting from either LHS or RHS.
8667         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8668           // Okay, we can handle this if the vector we are insertinting into is
8669           // transitively ok.
8670           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8671             // If so, update the mask to reflect the inserted value.
8672             if (EI->getOperand(0) == LHS) {
8673               Mask[InsertedIdx & (NumElts-1)] = 
8674                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8675             } else {
8676               assert(EI->getOperand(0) == RHS);
8677               Mask[InsertedIdx & (NumElts-1)] = 
8678                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8679               
8680             }
8681             return true;
8682           }
8683         }
8684       }
8685     }
8686   }
8687   // TODO: Handle shufflevector here!
8688   
8689   return false;
8690 }
8691
8692 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8693 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8694 /// that computes V and the LHS value of the shuffle.
8695 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8696                                      Value *&RHS) {
8697   assert(isa<PackedType>(V->getType()) && 
8698          (RHS == 0 || V->getType() == RHS->getType()) &&
8699          "Invalid shuffle!");
8700   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8701
8702   if (isa<UndefValue>(V)) {
8703     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8704     return V;
8705   } else if (isa<ConstantAggregateZero>(V)) {
8706     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8707     return V;
8708   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8709     // If this is an insert of an extract from some other vector, include it.
8710     Value *VecOp    = IEI->getOperand(0);
8711     Value *ScalarOp = IEI->getOperand(1);
8712     Value *IdxOp    = IEI->getOperand(2);
8713     
8714     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8715       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8716           EI->getOperand(0)->getType() == V->getType()) {
8717         unsigned ExtractedIdx =
8718           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8719         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8720         
8721         // Either the extracted from or inserted into vector must be RHSVec,
8722         // otherwise we'd end up with a shuffle of three inputs.
8723         if (EI->getOperand(0) == RHS || RHS == 0) {
8724           RHS = EI->getOperand(0);
8725           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8726           Mask[InsertedIdx & (NumElts-1)] = 
8727             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8728           return V;
8729         }
8730         
8731         if (VecOp == RHS) {
8732           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8733           // Everything but the extracted element is replaced with the RHS.
8734           for (unsigned i = 0; i != NumElts; ++i) {
8735             if (i != InsertedIdx)
8736               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8737           }
8738           return V;
8739         }
8740         
8741         // If this insertelement is a chain that comes from exactly these two
8742         // vectors, return the vector and the effective shuffle.
8743         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8744           return EI->getOperand(0);
8745         
8746       }
8747     }
8748   }
8749   // TODO: Handle shufflevector here!
8750   
8751   // Otherwise, can't do anything fancy.  Return an identity vector.
8752   for (unsigned i = 0; i != NumElts; ++i)
8753     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8754   return V;
8755 }
8756
8757 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8758   Value *VecOp    = IE.getOperand(0);
8759   Value *ScalarOp = IE.getOperand(1);
8760   Value *IdxOp    = IE.getOperand(2);
8761   
8762   // If the inserted element was extracted from some other vector, and if the 
8763   // indexes are constant, try to turn this into a shufflevector operation.
8764   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8765     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8766         EI->getOperand(0)->getType() == IE.getType()) {
8767       unsigned NumVectorElts = IE.getType()->getNumElements();
8768       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8769       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8770       
8771       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8772         return ReplaceInstUsesWith(IE, VecOp);
8773       
8774       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8775         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8776       
8777       // If we are extracting a value from a vector, then inserting it right
8778       // back into the same place, just use the input vector.
8779       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8780         return ReplaceInstUsesWith(IE, VecOp);      
8781       
8782       // We could theoretically do this for ANY input.  However, doing so could
8783       // turn chains of insertelement instructions into a chain of shufflevector
8784       // instructions, and right now we do not merge shufflevectors.  As such,
8785       // only do this in a situation where it is clear that there is benefit.
8786       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8787         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8788         // the values of VecOp, except then one read from EIOp0.
8789         // Build a new shuffle mask.
8790         std::vector<Constant*> Mask;
8791         if (isa<UndefValue>(VecOp))
8792           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8793         else {
8794           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8795           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8796                                                        NumVectorElts));
8797         } 
8798         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8799         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8800                                      ConstantPacked::get(Mask));
8801       }
8802       
8803       // If this insertelement isn't used by some other insertelement, turn it
8804       // (and any insertelements it points to), into one big shuffle.
8805       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8806         std::vector<Constant*> Mask;
8807         Value *RHS = 0;
8808         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8809         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8810         // We now have a shuffle of LHS, RHS, Mask.
8811         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8812       }
8813     }
8814   }
8815
8816   return 0;
8817 }
8818
8819
8820 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8821   Value *LHS = SVI.getOperand(0);
8822   Value *RHS = SVI.getOperand(1);
8823   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8824
8825   bool MadeChange = false;
8826   
8827   // Undefined shuffle mask -> undefined value.
8828   if (isa<UndefValue>(SVI.getOperand(2)))
8829     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8830   
8831   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8832   // the undef, change them to undefs.
8833   if (isa<UndefValue>(SVI.getOperand(1))) {
8834     // Scan to see if there are any references to the RHS.  If so, replace them
8835     // with undef element refs and set MadeChange to true.
8836     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8837       if (Mask[i] >= e && Mask[i] != 2*e) {
8838         Mask[i] = 2*e;
8839         MadeChange = true;
8840       }
8841     }
8842     
8843     if (MadeChange) {
8844       // Remap any references to RHS to use LHS.
8845       std::vector<Constant*> Elts;
8846       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8847         if (Mask[i] == 2*e)
8848           Elts.push_back(UndefValue::get(Type::Int32Ty));
8849         else
8850           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8851       }
8852       SVI.setOperand(2, ConstantPacked::get(Elts));
8853     }
8854   }
8855   
8856   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8857   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8858   if (LHS == RHS || isa<UndefValue>(LHS)) {
8859     if (isa<UndefValue>(LHS) && LHS == RHS) {
8860       // shuffle(undef,undef,mask) -> undef.
8861       return ReplaceInstUsesWith(SVI, LHS);
8862     }
8863     
8864     // Remap any references to RHS to use LHS.
8865     std::vector<Constant*> Elts;
8866     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8867       if (Mask[i] >= 2*e)
8868         Elts.push_back(UndefValue::get(Type::Int32Ty));
8869       else {
8870         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8871             (Mask[i] <  e && isa<UndefValue>(LHS)))
8872           Mask[i] = 2*e;     // Turn into undef.
8873         else
8874           Mask[i] &= (e-1);  // Force to LHS.
8875         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8876       }
8877     }
8878     SVI.setOperand(0, SVI.getOperand(1));
8879     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8880     SVI.setOperand(2, ConstantPacked::get(Elts));
8881     LHS = SVI.getOperand(0);
8882     RHS = SVI.getOperand(1);
8883     MadeChange = true;
8884   }
8885   
8886   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8887   bool isLHSID = true, isRHSID = true;
8888     
8889   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8890     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8891     // Is this an identity shuffle of the LHS value?
8892     isLHSID &= (Mask[i] == i);
8893       
8894     // Is this an identity shuffle of the RHS value?
8895     isRHSID &= (Mask[i]-e == i);
8896   }
8897
8898   // Eliminate identity shuffles.
8899   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8900   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8901   
8902   // If the LHS is a shufflevector itself, see if we can combine it with this
8903   // one without producing an unusual shuffle.  Here we are really conservative:
8904   // we are absolutely afraid of producing a shuffle mask not in the input
8905   // program, because the code gen may not be smart enough to turn a merged
8906   // shuffle into two specific shuffles: it may produce worse code.  As such,
8907   // we only merge two shuffles if the result is one of the two input shuffle
8908   // masks.  In this case, merging the shuffles just removes one instruction,
8909   // which we know is safe.  This is good for things like turning:
8910   // (splat(splat)) -> splat.
8911   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8912     if (isa<UndefValue>(RHS)) {
8913       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8914
8915       std::vector<unsigned> NewMask;
8916       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8917         if (Mask[i] >= 2*e)
8918           NewMask.push_back(2*e);
8919         else
8920           NewMask.push_back(LHSMask[Mask[i]]);
8921       
8922       // If the result mask is equal to the src shuffle or this shuffle mask, do
8923       // the replacement.
8924       if (NewMask == LHSMask || NewMask == Mask) {
8925         std::vector<Constant*> Elts;
8926         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8927           if (NewMask[i] >= e*2) {
8928             Elts.push_back(UndefValue::get(Type::Int32Ty));
8929           } else {
8930             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8931           }
8932         }
8933         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8934                                      LHSSVI->getOperand(1),
8935                                      ConstantPacked::get(Elts));
8936       }
8937     }
8938   }
8939   
8940   return MadeChange ? &SVI : 0;
8941 }
8942
8943
8944
8945 void InstCombiner::removeFromWorkList(Instruction *I) {
8946   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8947                  WorkList.end());
8948 }
8949
8950
8951 /// TryToSinkInstruction - Try to move the specified instruction from its
8952 /// current block into the beginning of DestBlock, which can only happen if it's
8953 /// safe to move the instruction past all of the instructions between it and the
8954 /// end of its block.
8955 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8956   assert(I->hasOneUse() && "Invariants didn't hold!");
8957
8958   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8959   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8960
8961   // Do not sink alloca instructions out of the entry block.
8962   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8963     return false;
8964
8965   // We can only sink load instructions if there is nothing between the load and
8966   // the end of block that could change the value.
8967   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8968     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8969          Scan != E; ++Scan)
8970       if (Scan->mayWriteToMemory())
8971         return false;
8972   }
8973
8974   BasicBlock::iterator InsertPos = DestBlock->begin();
8975   while (isa<PHINode>(InsertPos)) ++InsertPos;
8976
8977   I->moveBefore(InsertPos);
8978   ++NumSunkInst;
8979   return true;
8980 }
8981
8982 /// OptimizeConstantExpr - Given a constant expression and target data layout
8983 /// information, symbolically evaluate the constant expr to something simpler
8984 /// if possible.
8985 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8986   if (!TD) return CE;
8987   
8988   Constant *Ptr = CE->getOperand(0);
8989   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8990       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8991     // If this is a constant expr gep that is effectively computing an
8992     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8993     bool isFoldableGEP = true;
8994     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8995       if (!isa<ConstantInt>(CE->getOperand(i)))
8996         isFoldableGEP = false;
8997     if (isFoldableGEP) {
8998       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8999       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
9000       Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
9001       return ConstantExpr::getIntToPtr(C, CE->getType());
9002     }
9003   }
9004   
9005   return CE;
9006 }
9007
9008
9009 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9010 /// all reachable code to the worklist.
9011 ///
9012 /// This has a couple of tricks to make the code faster and more powerful.  In
9013 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9014 /// them to the worklist (this significantly speeds up instcombine on code where
9015 /// many instructions are dead or constant).  Additionally, if we find a branch
9016 /// whose condition is a known constant, we only visit the reachable successors.
9017 ///
9018 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9019                                        std::set<BasicBlock*> &Visited,
9020                                        std::vector<Instruction*> &WorkList,
9021                                        const TargetData *TD) {
9022   // We have now visited this block!  If we've already been here, bail out.
9023   if (!Visited.insert(BB).second) return;
9024     
9025   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9026     Instruction *Inst = BBI++;
9027     
9028     // DCE instruction if trivially dead.
9029     if (isInstructionTriviallyDead(Inst)) {
9030       ++NumDeadInst;
9031       DOUT << "IC: DCE: " << *Inst;
9032       Inst->eraseFromParent();
9033       continue;
9034     }
9035     
9036     // ConstantProp instruction if trivially constant.
9037     if (Constant *C = ConstantFoldInstruction(Inst)) {
9038       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9039         C = OptimizeConstantExpr(CE, TD);
9040       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9041       Inst->replaceAllUsesWith(C);
9042       ++NumConstProp;
9043       Inst->eraseFromParent();
9044       continue;
9045     }
9046     
9047     WorkList.push_back(Inst);
9048   }
9049
9050   // Recursively visit successors.  If this is a branch or switch on a constant,
9051   // only visit the reachable successor.
9052   TerminatorInst *TI = BB->getTerminator();
9053   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9054     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
9055       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
9056       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9057                                  TD);
9058       return;
9059     }
9060   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9061     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9062       // See if this is an explicit destination.
9063       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9064         if (SI->getCaseValue(i) == Cond) {
9065           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9066           return;
9067         }
9068       
9069       // Otherwise it is the default destination.
9070       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9071       return;
9072     }
9073   }
9074   
9075   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9076     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9077 }
9078
9079 bool InstCombiner::runOnFunction(Function &F) {
9080   bool Changed = false;
9081   TD = &getAnalysis<TargetData>();
9082
9083   {
9084     // Do a depth-first traversal of the function, populate the worklist with
9085     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9086     // track of which blocks we visit.
9087     std::set<BasicBlock*> Visited;
9088     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9089
9090     // Do a quick scan over the function.  If we find any blocks that are
9091     // unreachable, remove any instructions inside of them.  This prevents
9092     // the instcombine code from having to deal with some bad special cases.
9093     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9094       if (!Visited.count(BB)) {
9095         Instruction *Term = BB->getTerminator();
9096         while (Term != BB->begin()) {   // Remove instrs bottom-up
9097           BasicBlock::iterator I = Term; --I;
9098
9099           DOUT << "IC: DCE: " << *I;
9100           ++NumDeadInst;
9101
9102           if (!I->use_empty())
9103             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9104           I->eraseFromParent();
9105         }
9106       }
9107   }
9108
9109   while (!WorkList.empty()) {
9110     Instruction *I = WorkList.back();  // Get an instruction from the worklist
9111     WorkList.pop_back();
9112
9113     // Check to see if we can DCE the instruction.
9114     if (isInstructionTriviallyDead(I)) {
9115       // Add operands to the worklist.
9116       if (I->getNumOperands() < 4)
9117         AddUsesToWorkList(*I);
9118       ++NumDeadInst;
9119
9120       DOUT << "IC: DCE: " << *I;
9121
9122       I->eraseFromParent();
9123       removeFromWorkList(I);
9124       continue;
9125     }
9126
9127     // Instruction isn't dead, see if we can constant propagate it.
9128     if (Constant *C = ConstantFoldInstruction(I)) {
9129       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
9130         C = OptimizeConstantExpr(CE, TD);
9131       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9132
9133       // Add operands to the worklist.
9134       AddUsesToWorkList(*I);
9135       ReplaceInstUsesWith(*I, C);
9136
9137       ++NumConstProp;
9138       I->eraseFromParent();
9139       removeFromWorkList(I);
9140       continue;
9141     }
9142
9143     // See if we can trivially sink this instruction to a successor basic block.
9144     if (I->hasOneUse()) {
9145       BasicBlock *BB = I->getParent();
9146       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9147       if (UserParent != BB) {
9148         bool UserIsSuccessor = false;
9149         // See if the user is one of our successors.
9150         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9151           if (*SI == UserParent) {
9152             UserIsSuccessor = true;
9153             break;
9154           }
9155
9156         // If the user is one of our immediate successors, and if that successor
9157         // only has us as a predecessors (we'd have to split the critical edge
9158         // otherwise), we can keep going.
9159         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9160             next(pred_begin(UserParent)) == pred_end(UserParent))
9161           // Okay, the CFG is simple enough, try to sink this instruction.
9162           Changed |= TryToSinkInstruction(I, UserParent);
9163       }
9164     }
9165
9166     // Now that we have an instruction, try combining it to simplify it...
9167     if (Instruction *Result = visit(*I)) {
9168       ++NumCombined;
9169       // Should we replace the old instruction with a new one?
9170       if (Result != I) {
9171         DOUT << "IC: Old = " << *I
9172              << "    New = " << *Result;
9173
9174         // Everything uses the new instruction now.
9175         I->replaceAllUsesWith(Result);
9176
9177         // Push the new instruction and any users onto the worklist.
9178         WorkList.push_back(Result);
9179         AddUsersToWorkList(*Result);
9180
9181         // Move the name to the new instruction first...
9182         std::string OldName = I->getName(); I->setName("");
9183         Result->setName(OldName);
9184
9185         // Insert the new instruction into the basic block...
9186         BasicBlock *InstParent = I->getParent();
9187         BasicBlock::iterator InsertPos = I;
9188
9189         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9190           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9191             ++InsertPos;
9192
9193         InstParent->getInstList().insert(InsertPos, Result);
9194
9195         // Make sure that we reprocess all operands now that we reduced their
9196         // use counts.
9197         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9198           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9199             WorkList.push_back(OpI);
9200
9201         // Instructions can end up on the worklist more than once.  Make sure
9202         // we do not process an instruction that has been deleted.
9203         removeFromWorkList(I);
9204
9205         // Erase the old instruction.
9206         InstParent->getInstList().erase(I);
9207       } else {
9208         DOUT << "IC: MOD = " << *I;
9209
9210         // If the instruction was modified, it's possible that it is now dead.
9211         // if so, remove it.
9212         if (isInstructionTriviallyDead(I)) {
9213           // Make sure we process all operands now that we are reducing their
9214           // use counts.
9215           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9216             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9217               WorkList.push_back(OpI);
9218
9219           // Instructions may end up in the worklist more than once.  Erase all
9220           // occurrences of this instruction.
9221           removeFromWorkList(I);
9222           I->eraseFromParent();
9223         } else {
9224           WorkList.push_back(Result);
9225           AddUsersToWorkList(*Result);
9226         }
9227       }
9228       Changed = true;
9229     }
9230   }
9231
9232   return Changed;
9233 }
9234
9235 FunctionPass *llvm::createInstructionCombiningPass() {
9236   return new InstCombiner();
9237 }
9238