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