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