b20ff9711d78f8f6157fe6f5c7af0184c5d3f8df
[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/DenseMap.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include <algorithm>
59 #include <set>
60 using namespace llvm;
61 using namespace llvm::PatternMatch;
62
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
68
69 namespace {
70   class VISIBILITY_HIDDEN InstCombiner
71     : public FunctionPass,
72       public InstVisitor<InstCombiner, Instruction*> {
73     // Worklist of all of the instructions that need to be simplified.
74     std::vector<Instruction*> Worklist;
75     DenseMap<Instruction*, unsigned> WorklistMap;
76     TargetData *TD;
77   public:
78     /// AddToWorkList - Add the specified instruction to the worklist if it
79     /// isn't already in it.
80     void AddToWorkList(Instruction *I) {
81       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
82         Worklist.push_back(I);
83     }
84     
85     // RemoveFromWorkList - remove I from the worklist if it exists.
86     void RemoveFromWorkList(Instruction *I) {
87       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
88       if (It == WorklistMap.end()) return; // Not in worklist.
89       
90       // Don't bother moving everything down, just null out the slot.
91       Worklist[It->second] = 0;
92       
93       WorklistMap.erase(It);
94     }
95     
96     Instruction *RemoveOneFromWorkList() {
97       Instruction *I = Worklist.back();
98       Worklist.pop_back();
99       WorklistMap.erase(I);
100       return I;
101     }
102
103     
104     /// AddUsersToWorkList - When an instruction is simplified, add all users of
105     /// the instruction to the work lists because they might get more simplified
106     /// now.
107     ///
108     void AddUsersToWorkList(Value &I) {
109       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
110            UI != UE; ++UI)
111         AddToWorkList(cast<Instruction>(*UI));
112     }
113
114     /// AddUsesToWorkList - When an instruction is simplified, add operands to
115     /// the work lists because they might get more simplified now.
116     ///
117     void AddUsesToWorkList(Instruction &I) {
118       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
119         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
120           AddToWorkList(Op);
121     }
122     
123     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
124     /// dead.  Add all of its operands to the worklist, turning them into
125     /// undef's to reduce the number of uses of those instructions.
126     ///
127     /// Return the specified operand before it is turned into an undef.
128     ///
129     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
130       Value *R = I.getOperand(op);
131       
132       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
133         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
134           AddToWorkList(Op);
135           // Set the operand to undef to drop the use.
136           I.setOperand(i, UndefValue::get(Op->getType()));
137         }
138       
139       return R;
140     }
141
142   public:
143     virtual bool runOnFunction(Function &F);
144     
145     bool DoOneIteration(Function &F, unsigned ItNum);
146
147     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
148       AU.addRequired<TargetData>();
149       AU.addPreservedID(LCSSAID);
150       AU.setPreservesCFG();
151     }
152
153     TargetData &getTargetData() const { return *TD; }
154
155     // Visitation implementation - Implement instruction combining for different
156     // instruction types.  The semantics are as follows:
157     // Return Value:
158     //    null        - No change was made
159     //     I          - Change was made, I is still valid, I may be dead though
160     //   otherwise    - Change was made, replace I with returned instruction
161     //
162     Instruction *visitAdd(BinaryOperator &I);
163     Instruction *visitSub(BinaryOperator &I);
164     Instruction *visitMul(BinaryOperator &I);
165     Instruction *visitURem(BinaryOperator &I);
166     Instruction *visitSRem(BinaryOperator &I);
167     Instruction *visitFRem(BinaryOperator &I);
168     Instruction *commonRemTransforms(BinaryOperator &I);
169     Instruction *commonIRemTransforms(BinaryOperator &I);
170     Instruction *commonDivTransforms(BinaryOperator &I);
171     Instruction *commonIDivTransforms(BinaryOperator &I);
172     Instruction *visitUDiv(BinaryOperator &I);
173     Instruction *visitSDiv(BinaryOperator &I);
174     Instruction *visitFDiv(BinaryOperator &I);
175     Instruction *visitAnd(BinaryOperator &I);
176     Instruction *visitOr (BinaryOperator &I);
177     Instruction *visitXor(BinaryOperator &I);
178     Instruction *visitShl(BinaryOperator &I);
179     Instruction *visitAShr(BinaryOperator &I);
180     Instruction *visitLShr(BinaryOperator &I);
181     Instruction *commonShiftTransforms(BinaryOperator &I);
182     Instruction *visitFCmpInst(FCmpInst &I);
183     Instruction *visitICmpInst(ICmpInst &I);
184     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
185
186     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
187                              ICmpInst::Predicate Cond, Instruction &I);
188     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
189                                      BinaryOperator &I);
190     Instruction *commonCastTransforms(CastInst &CI);
191     Instruction *commonIntCastTransforms(CastInst &CI);
192     Instruction *visitTrunc(CastInst &CI);
193     Instruction *visitZExt(CastInst &CI);
194     Instruction *visitSExt(CastInst &CI);
195     Instruction *visitFPTrunc(CastInst &CI);
196     Instruction *visitFPExt(CastInst &CI);
197     Instruction *visitFPToUI(CastInst &CI);
198     Instruction *visitFPToSI(CastInst &CI);
199     Instruction *visitUIToFP(CastInst &CI);
200     Instruction *visitSIToFP(CastInst &CI);
201     Instruction *visitPtrToInt(CastInst &CI);
202     Instruction *visitIntToPtr(CastInst &CI);
203     Instruction *visitBitCast(CastInst &CI);
204     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
205                                 Instruction *FI);
206     Instruction *visitSelectInst(SelectInst &CI);
207     Instruction *visitCallInst(CallInst &CI);
208     Instruction *visitInvokeInst(InvokeInst &II);
209     Instruction *visitPHINode(PHINode &PN);
210     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
211     Instruction *visitAllocationInst(AllocationInst &AI);
212     Instruction *visitFreeInst(FreeInst &FI);
213     Instruction *visitLoadInst(LoadInst &LI);
214     Instruction *visitStoreInst(StoreInst &SI);
215     Instruction *visitBranchInst(BranchInst &BI);
216     Instruction *visitSwitchInst(SwitchInst &SI);
217     Instruction *visitInsertElementInst(InsertElementInst &IE);
218     Instruction *visitExtractElementInst(ExtractElementInst &EI);
219     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
220
221     // visitInstruction - Specify what to return for unhandled instructions...
222     Instruction *visitInstruction(Instruction &I) { return 0; }
223
224   private:
225     Instruction *visitCallSite(CallSite CS);
226     bool transformConstExprCastCall(CallSite CS);
227
228   public:
229     // InsertNewInstBefore - insert an instruction New before instruction Old
230     // in the program.  Add the new instruction to the worklist.
231     //
232     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
233       assert(New && New->getParent() == 0 &&
234              "New instruction already inserted into a basic block!");
235       BasicBlock *BB = Old.getParent();
236       BB->getInstList().insert(&Old, New);  // Insert inst
237       AddToWorkList(New);
238       return New;
239     }
240
241     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
242     /// This also adds the cast to the worklist.  Finally, this returns the
243     /// cast.
244     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
245                             Instruction &Pos) {
246       if (V->getType() == Ty) return V;
247
248       if (Constant *CV = dyn_cast<Constant>(V))
249         return ConstantExpr::getCast(opc, CV, Ty);
250       
251       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
252       AddToWorkList(C);
253       return C;
254     }
255
256     // ReplaceInstUsesWith - This method is to be used when an instruction is
257     // found to be dead, replacable with another preexisting expression.  Here
258     // we add all uses of I to the worklist, replace all uses of I with the new
259     // value, then return I, so that the inst combiner will know that I was
260     // modified.
261     //
262     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
263       AddUsersToWorkList(I);         // Add all modified instrs to worklist
264       if (&I != V) {
265         I.replaceAllUsesWith(V);
266         return &I;
267       } else {
268         // If we are replacing the instruction with itself, this must be in a
269         // segment of unreachable code, so just clobber the instruction.
270         I.replaceAllUsesWith(UndefValue::get(I.getType()));
271         return &I;
272       }
273     }
274
275     // UpdateValueUsesWith - This method is to be used when an value is
276     // found to be replacable with another preexisting expression or was
277     // updated.  Here we add all uses of I to the worklist, replace all uses of
278     // I with the new value (unless the instruction was just updated), then
279     // return true, so that the inst combiner will know that I was modified.
280     //
281     bool UpdateValueUsesWith(Value *Old, Value *New) {
282       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
283       if (Old != New)
284         Old->replaceAllUsesWith(New);
285       if (Instruction *I = dyn_cast<Instruction>(Old))
286         AddToWorkList(I);
287       if (Instruction *I = dyn_cast<Instruction>(New))
288         AddToWorkList(I);
289       return true;
290     }
291     
292     // EraseInstFromFunction - When dealing with an instruction that has side
293     // effects or produces a void value, we can't rely on DCE to delete the
294     // instruction.  Instead, visit methods should return the value returned by
295     // this function.
296     Instruction *EraseInstFromFunction(Instruction &I) {
297       assert(I.use_empty() && "Cannot erase instruction that is used!");
298       AddUsesToWorkList(I);
299       RemoveFromWorkList(&I);
300       I.eraseFromParent();
301       return 0;  // Don't do anything with FI
302     }
303
304   private:
305     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
306     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
307     /// casts that are known to not do anything...
308     ///
309     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
310                                    Value *V, const Type *DestTy,
311                                    Instruction *InsertBefore);
312
313     /// SimplifyCommutative - This performs a few simplifications for 
314     /// commutative operators.
315     bool SimplifyCommutative(BinaryOperator &I);
316
317     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
318     /// most-complex to least-complex order.
319     bool SimplifyCompare(CmpInst &I);
320
321     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
322                               uint64_t &KnownZero, uint64_t &KnownOne,
323                               unsigned Depth = 0);
324
325     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
326                                       uint64_t &UndefElts, unsigned Depth = 0);
327       
328     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
329     // PHI node as operand #0, see if we can fold the instruction into the PHI
330     // (which is only possible if all operands to the PHI are constants).
331     Instruction *FoldOpIntoPhi(Instruction &I);
332
333     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
334     // operator and they all are only used by the PHI, PHI together their
335     // inputs, and do the operation once, to the result of the PHI.
336     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
337     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
338     
339     
340     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
341                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
342     
343     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
344                               bool isSub, Instruction &I);
345     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
346                                  bool isSigned, bool Inside, Instruction &IB);
347     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
348     Instruction *MatchBSwap(BinaryOperator &I);
349
350     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
351   };
352
353   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
354 }
355
356 // getComplexity:  Assign a complexity or rank value to LLVM Values...
357 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
358 static unsigned getComplexity(Value *V) {
359   if (isa<Instruction>(V)) {
360     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
361       return 3;
362     return 4;
363   }
364   if (isa<Argument>(V)) return 3;
365   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
366 }
367
368 // isOnlyUse - Return true if this instruction will be deleted if we stop using
369 // it.
370 static bool isOnlyUse(Value *V) {
371   return V->hasOneUse() || isa<Constant>(V);
372 }
373
374 // getPromotedType - Return the specified type promoted as it would be to pass
375 // though a va_arg area...
376 static const Type *getPromotedType(const Type *Ty) {
377   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
378     if (ITy->getBitWidth() < 32)
379       return Type::Int32Ty;
380   } else if (Ty == Type::FloatTy)
381     return Type::DoubleTy;
382   return Ty;
383 }
384
385 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
386 /// expression bitcast,  return the operand value, otherwise return null.
387 static Value *getBitCastOperand(Value *V) {
388   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
389     return I->getOperand(0);
390   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
391     if (CE->getOpcode() == Instruction::BitCast)
392       return CE->getOperand(0);
393   return 0;
394 }
395
396 /// This function is a wrapper around CastInst::isEliminableCastPair. It
397 /// simply extracts arguments and returns what that function returns.
398 static Instruction::CastOps 
399 isEliminableCastPair(
400   const CastInst *CI, ///< The first cast instruction
401   unsigned opcode,       ///< The opcode of the second cast instruction
402   const Type *DstTy,     ///< The target type for the second cast instruction
403   TargetData *TD         ///< The target data for pointer size
404 ) {
405   
406   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
407   const Type *MidTy = CI->getType();                  // B from above
408
409   // Get the opcodes of the two Cast instructions
410   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
411   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
412
413   return Instruction::CastOps(
414       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
415                                      DstTy, TD->getIntPtrType()));
416 }
417
418 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
419 /// in any code being generated.  It does not require codegen if V is simple
420 /// enough or if the cast can be folded into other casts.
421 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
422                               const Type *Ty, TargetData *TD) {
423   if (V->getType() == Ty || isa<Constant>(V)) return false;
424   
425   // If this is another cast that can be eliminated, it isn't codegen either.
426   if (const CastInst *CI = dyn_cast<CastInst>(V))
427     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
428       return false;
429   return true;
430 }
431
432 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
433 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
434 /// casts that are known to not do anything...
435 ///
436 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
437                                              Value *V, const Type *DestTy,
438                                              Instruction *InsertBefore) {
439   if (V->getType() == DestTy) return V;
440   if (Constant *C = dyn_cast<Constant>(V))
441     return ConstantExpr::getCast(opcode, C, DestTy);
442   
443   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
444 }
445
446 // SimplifyCommutative - This performs a few simplifications for commutative
447 // operators:
448 //
449 //  1. Order operands such that they are listed from right (least complex) to
450 //     left (most complex).  This puts constants before unary operators before
451 //     binary operators.
452 //
453 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
454 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
455 //
456 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
457   bool Changed = false;
458   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
459     Changed = !I.swapOperands();
460
461   if (!I.isAssociative()) return Changed;
462   Instruction::BinaryOps Opcode = I.getOpcode();
463   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
464     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
465       if (isa<Constant>(I.getOperand(1))) {
466         Constant *Folded = ConstantExpr::get(I.getOpcode(),
467                                              cast<Constant>(I.getOperand(1)),
468                                              cast<Constant>(Op->getOperand(1)));
469         I.setOperand(0, Op->getOperand(0));
470         I.setOperand(1, Folded);
471         return true;
472       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
473         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
474             isOnlyUse(Op) && isOnlyUse(Op1)) {
475           Constant *C1 = cast<Constant>(Op->getOperand(1));
476           Constant *C2 = cast<Constant>(Op1->getOperand(1));
477
478           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
479           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
480           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
481                                                     Op1->getOperand(0),
482                                                     Op1->getName(), &I);
483           AddToWorkList(New);
484           I.setOperand(0, New);
485           I.setOperand(1, Folded);
486           return true;
487         }
488     }
489   return Changed;
490 }
491
492 /// SimplifyCompare - For a CmpInst this function just orders the operands
493 /// so that theyare listed from right (least complex) to left (most complex).
494 /// This puts constants before unary operators before binary operators.
495 bool InstCombiner::SimplifyCompare(CmpInst &I) {
496   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
497     return false;
498   I.swapOperands();
499   // Compare instructions are not associative so there's nothing else we can do.
500   return true;
501 }
502
503 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
504 // if the LHS is a constant zero (which is the 'negate' form).
505 //
506 static inline Value *dyn_castNegVal(Value *V) {
507   if (BinaryOperator::isNeg(V))
508     return BinaryOperator::getNegArgument(V);
509
510   // Constants can be considered to be negated values if they can be folded.
511   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
512     return ConstantExpr::getNeg(C);
513   return 0;
514 }
515
516 static inline Value *dyn_castNotVal(Value *V) {
517   if (BinaryOperator::isNot(V))
518     return BinaryOperator::getNotArgument(V);
519
520   // Constants can be considered to be not'ed values...
521   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
522     return ConstantExpr::getNot(C);
523   return 0;
524 }
525
526 // dyn_castFoldableMul - If this value is a multiply that can be folded into
527 // other computations (because it has a constant operand), return the
528 // non-constant operand of the multiply, and set CST to point to the multiplier.
529 // Otherwise, return null.
530 //
531 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
532   if (V->hasOneUse() && V->getType()->isInteger())
533     if (Instruction *I = dyn_cast<Instruction>(V)) {
534       if (I->getOpcode() == Instruction::Mul)
535         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
536           return I->getOperand(0);
537       if (I->getOpcode() == Instruction::Shl)
538         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
539           // The multiplier is really 1 << CST.
540           Constant *One = ConstantInt::get(V->getType(), 1);
541           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
542           return I->getOperand(0);
543         }
544     }
545   return 0;
546 }
547
548 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
549 /// expression, return it.
550 static User *dyn_castGetElementPtr(Value *V) {
551   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
552   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
553     if (CE->getOpcode() == Instruction::GetElementPtr)
554       return cast<User>(V);
555   return false;
556 }
557
558 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
559 static ConstantInt *AddOne(ConstantInt *C) {
560   return cast<ConstantInt>(ConstantExpr::getAdd(C,
561                                          ConstantInt::get(C->getType(), 1)));
562 }
563 static ConstantInt *SubOne(ConstantInt *C) {
564   return cast<ConstantInt>(ConstantExpr::getSub(C,
565                                          ConstantInt::get(C->getType(), 1)));
566 }
567
568 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
569 /// known to be either zero or one and return them in the KnownZero/KnownOne
570 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
571 /// processing.
572 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
573                               uint64_t &KnownOne, unsigned Depth = 0) {
574   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
575   // we cannot optimize based on the assumption that it is zero without changing
576   // it to be an explicit zero.  If we don't change it to zero, other code could
577   // optimized based on the contradictory assumption that it is non-zero.
578   // Because instcombine aggressively folds operations with undef args anyway,
579   // this won't lose us code quality.
580   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
581     // We know all of the bits for a constant!
582     KnownOne = CI->getZExtValue() & Mask;
583     KnownZero = ~KnownOne & Mask;
584     return;
585   }
586
587   KnownZero = KnownOne = 0;   // Don't know anything.
588   if (Depth == 6 || Mask == 0)
589     return;  // Limit search depth.
590
591   uint64_t KnownZero2, KnownOne2;
592   Instruction *I = dyn_cast<Instruction>(V);
593   if (!I) return;
594
595   Mask &= cast<IntegerType>(V->getType())->getBitMask();
596   
597   switch (I->getOpcode()) {
598   case Instruction::And:
599     // If either the LHS or the RHS are Zero, the result is zero.
600     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
601     Mask &= ~KnownZero;
602     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
603     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
604     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
605     
606     // Output known-1 bits are only known if set in both the LHS & RHS.
607     KnownOne &= KnownOne2;
608     // Output known-0 are known to be clear if zero in either the LHS | RHS.
609     KnownZero |= KnownZero2;
610     return;
611   case Instruction::Or:
612     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
613     Mask &= ~KnownOne;
614     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
615     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
616     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
617     
618     // Output known-0 bits are only known if clear in both the LHS & RHS.
619     KnownZero &= KnownZero2;
620     // Output known-1 are known to be set if set in either the LHS | RHS.
621     KnownOne |= KnownOne2;
622     return;
623   case Instruction::Xor: {
624     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
625     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
626     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
627     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
628     
629     // Output known-0 bits are known if clear or set in both the LHS & RHS.
630     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
631     // Output known-1 are known to be set if set in only one of the LHS, RHS.
632     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
633     KnownZero = KnownZeroOut;
634     return;
635   }
636   case Instruction::Select:
637     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
638     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
639     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
640     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
641
642     // Only known if known in both the LHS and RHS.
643     KnownOne &= KnownOne2;
644     KnownZero &= KnownZero2;
645     return;
646   case Instruction::FPTrunc:
647   case Instruction::FPExt:
648   case Instruction::FPToUI:
649   case Instruction::FPToSI:
650   case Instruction::SIToFP:
651   case Instruction::PtrToInt:
652   case Instruction::UIToFP:
653   case Instruction::IntToPtr:
654     return; // Can't work with floating point or pointers
655   case Instruction::Trunc: 
656     // All these have integer operands
657     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
658     return;
659   case Instruction::BitCast: {
660     const Type *SrcTy = I->getOperand(0)->getType();
661     if (SrcTy->isInteger()) {
662       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
663       return;
664     }
665     break;
666   }
667   case Instruction::ZExt:  {
668     // Compute the bits in the result that are not present in the input.
669     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
670     uint64_t NotIn = ~SrcTy->getBitMask();
671     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
672       
673     Mask &= SrcTy->getBitMask();
674     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
675     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
676     // The top bits are known to be zero.
677     KnownZero |= NewBits;
678     return;
679   }
680   case Instruction::SExt: {
681     // Compute the bits in the result that are not present in the input.
682     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
683     uint64_t NotIn = ~SrcTy->getBitMask();
684     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
685       
686     Mask &= SrcTy->getBitMask();
687     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
688     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
689
690     // If the sign bit of the input is known set or clear, then we know the
691     // top bits of the result.
692     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
693     if (KnownZero & InSignBit) {          // Input sign bit known zero
694       KnownZero |= NewBits;
695       KnownOne &= ~NewBits;
696     } else if (KnownOne & InSignBit) {    // Input sign bit known set
697       KnownOne |= NewBits;
698       KnownZero &= ~NewBits;
699     } else {                              // Input sign bit unknown
700       KnownZero &= ~NewBits;
701       KnownOne &= ~NewBits;
702     }
703     return;
704   }
705   case Instruction::Shl:
706     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
707     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
708       uint64_t ShiftAmt = SA->getZExtValue();
709       Mask >>= ShiftAmt;
710       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
711       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
712       KnownZero <<= ShiftAmt;
713       KnownOne  <<= ShiftAmt;
714       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
715       return;
716     }
717     break;
718   case Instruction::LShr:
719     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
720     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
721       // Compute the new bits that are at the top now.
722       uint64_t ShiftAmt = SA->getZExtValue();
723       uint64_t HighBits = (1ULL << ShiftAmt)-1;
724       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
725       
726       // Unsigned shift right.
727       Mask <<= ShiftAmt;
728       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
729       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
730       KnownZero >>= ShiftAmt;
731       KnownOne  >>= ShiftAmt;
732       KnownZero |= HighBits;  // high bits known zero.
733       return;
734     }
735     break;
736   case Instruction::AShr:
737     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
738     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
739       // Compute the new bits that are at the top now.
740       uint64_t ShiftAmt = SA->getZExtValue();
741       uint64_t HighBits = (1ULL << ShiftAmt)-1;
742       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
743       
744       // Signed shift right.
745       Mask <<= ShiftAmt;
746       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
747       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
748       KnownZero >>= ShiftAmt;
749       KnownOne  >>= ShiftAmt;
750         
751       // Handle the sign bits.
752       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
753       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
754         
755       if (KnownZero & SignBit) {       // New bits are known zero.
756         KnownZero |= HighBits;
757       } else if (KnownOne & SignBit) { // New bits are known one.
758         KnownOne |= HighBits;
759       }
760       return;
761     }
762     break;
763   }
764 }
765
766 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
767 /// this predicate to simplify operations downstream.  Mask is known to be zero
768 /// for bits that V cannot have.
769 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
770   uint64_t KnownZero, KnownOne;
771   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
772   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
773   return (KnownZero & Mask) == Mask;
774 }
775
776 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
777 /// specified instruction is a constant integer.  If so, check to see if there
778 /// are any bits set in the constant that are not demanded.  If so, shrink the
779 /// constant and return true.
780 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
781                                    uint64_t Demanded) {
782   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
783   if (!OpC) return false;
784
785   // If there are no bits set that aren't demanded, nothing to do.
786   if ((~Demanded & OpC->getZExtValue()) == 0)
787     return false;
788
789   // This is producing any bits that are not needed, shrink the RHS.
790   uint64_t Val = Demanded & OpC->getZExtValue();
791   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
792   return true;
793 }
794
795 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
796 // set of known zero and one bits, compute the maximum and minimum values that
797 // could have the specified known zero and known one bits, returning them in
798 // min/max.
799 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
800                                                    uint64_t KnownZero,
801                                                    uint64_t KnownOne,
802                                                    int64_t &Min, int64_t &Max) {
803   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
804   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
805
806   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
807   
808   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
809   // bit if it is unknown.
810   Min = KnownOne;
811   Max = KnownOne|UnknownBits;
812   
813   if (SignBit & UnknownBits) { // Sign bit is unknown
814     Min |= SignBit;
815     Max &= ~SignBit;
816   }
817   
818   // Sign extend the min/max values.
819   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
820   Min = (Min << ShAmt) >> ShAmt;
821   Max = (Max << ShAmt) >> ShAmt;
822 }
823
824 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
825 // a set of known zero and one bits, compute the maximum and minimum values that
826 // could have the specified known zero and known one bits, returning them in
827 // min/max.
828 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
829                                                      uint64_t KnownZero,
830                                                      uint64_t KnownOne,
831                                                      uint64_t &Min,
832                                                      uint64_t &Max) {
833   uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
834   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
835   
836   // The minimum value is when the unknown bits are all zeros.
837   Min = KnownOne;
838   // The maximum value is when the unknown bits are all ones.
839   Max = KnownOne|UnknownBits;
840 }
841
842
843 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
844 /// DemandedMask bits of the result of V are ever used downstream.  If we can
845 /// use this information to simplify V, do so and return true.  Otherwise,
846 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
847 /// the expression (used to simplify the caller).  The KnownZero/One bits may
848 /// only be accurate for those bits in the DemandedMask.
849 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
850                                         uint64_t &KnownZero, uint64_t &KnownOne,
851                                         unsigned Depth) {
852   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
853     // We know all of the bits for a constant!
854     KnownOne = CI->getZExtValue() & DemandedMask;
855     KnownZero = ~KnownOne & DemandedMask;
856     return false;
857   }
858   
859   KnownZero = KnownOne = 0;
860   if (!V->hasOneUse()) {    // Other users may use these bits.
861     if (Depth != 0) {       // Not at the root.
862       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
863       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
864       return false;
865     }
866     // If this is the root being simplified, allow it to have multiple uses,
867     // just set the DemandedMask to all bits.
868     DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
869   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
870     if (V != UndefValue::get(V->getType()))
871       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
872     return false;
873   } else if (Depth == 6) {        // Limit search depth.
874     return false;
875   }
876   
877   Instruction *I = dyn_cast<Instruction>(V);
878   if (!I) return false;        // Only analyze instructions.
879
880   DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
881   
882   uint64_t KnownZero2 = 0, KnownOne2 = 0;
883   switch (I->getOpcode()) {
884   default: break;
885   case Instruction::And:
886     // If either the LHS or the RHS are Zero, the result is zero.
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
892     // If something is known zero on the RHS, the bits aren't demanded on the
893     // LHS.
894     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
895                              KnownZero2, KnownOne2, Depth+1))
896       return true;
897     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
898
899     // If all of the demanded bits are known 1 on one side, return the other.
900     // These bits cannot contribute to the result of the 'and'.
901     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
902       return UpdateValueUsesWith(I, I->getOperand(0));
903     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
904       return UpdateValueUsesWith(I, I->getOperand(1));
905     
906     // If all of the demanded bits in the inputs are known zeros, return zero.
907     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
908       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
909       
910     // If the RHS is a constant, see if we can simplify it.
911     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
912       return UpdateValueUsesWith(I, I);
913       
914     // Output known-1 bits are only known if set in both the LHS & RHS.
915     KnownOne &= KnownOne2;
916     // Output known-0 are known to be clear if zero in either the LHS | RHS.
917     KnownZero |= KnownZero2;
918     break;
919   case Instruction::Or:
920     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
921                              KnownZero, KnownOne, Depth+1))
922       return true;
923     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
924     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
925                              KnownZero2, KnownOne2, Depth+1))
926       return true;
927     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
928     
929     // If all of the demanded bits are known zero on one side, return the other.
930     // These bits cannot contribute to the result of the 'or'.
931     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
932       return UpdateValueUsesWith(I, I->getOperand(0));
933     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
934       return UpdateValueUsesWith(I, I->getOperand(1));
935
936     // If all of the potentially set bits on one side are known to be set on
937     // the other side, just use the 'other' side.
938     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
939         (DemandedMask & (~KnownZero)))
940       return UpdateValueUsesWith(I, I->getOperand(0));
941     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
942         (DemandedMask & (~KnownZero2)))
943       return UpdateValueUsesWith(I, I->getOperand(1));
944         
945     // If the RHS is a constant, see if we can simplify it.
946     if (ShrinkDemandedConstant(I, 1, DemandedMask))
947       return UpdateValueUsesWith(I, I);
948           
949     // Output known-0 bits are only known if clear in both the LHS & RHS.
950     KnownZero &= KnownZero2;
951     // Output known-1 are known to be set if set in either the LHS | RHS.
952     KnownOne |= KnownOne2;
953     break;
954   case Instruction::Xor: {
955     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
956                              KnownZero, KnownOne, Depth+1))
957       return true;
958     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
959     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
960                              KnownZero2, KnownOne2, Depth+1))
961       return true;
962     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
963     
964     // If all of the demanded bits are known zero on one side, return the other.
965     // These bits cannot contribute to the result of the 'xor'.
966     if ((DemandedMask & KnownZero) == DemandedMask)
967       return UpdateValueUsesWith(I, I->getOperand(0));
968     if ((DemandedMask & KnownZero2) == DemandedMask)
969       return UpdateValueUsesWith(I, I->getOperand(1));
970     
971     // Output known-0 bits are known if clear or set in both the LHS & RHS.
972     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
973     // Output known-1 are known to be set if set in only one of the LHS, RHS.
974     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
975     
976     // If all of the demanded bits are known to be zero on one side or the
977     // other, turn this into an *inclusive* or.
978     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
979     if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
980       Instruction *Or =
981         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
982                                  I->getName());
983       InsertNewInstBefore(Or, *I);
984       return UpdateValueUsesWith(I, Or);
985     }
986     
987     // If all of the demanded bits on one side are known, and all of the set
988     // bits on that side are also known to be set on the other side, turn this
989     // into an AND, as we know the bits will be cleared.
990     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
991     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
992       if ((KnownOne & KnownOne2) == KnownOne) {
993         Constant *AndC = ConstantInt::get(I->getType(), 
994                                           ~KnownOne & DemandedMask);
995         Instruction *And = 
996           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
997         InsertNewInstBefore(And, *I);
998         return UpdateValueUsesWith(I, And);
999       }
1000     }
1001     
1002     // If the RHS is a constant, see if we can simplify it.
1003     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1004     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1005       return UpdateValueUsesWith(I, I);
1006     
1007     KnownZero = KnownZeroOut;
1008     KnownOne  = KnownOneOut;
1009     break;
1010   }
1011   case Instruction::Select:
1012     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1013                              KnownZero, KnownOne, Depth+1))
1014       return true;
1015     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1016                              KnownZero2, KnownOne2, Depth+1))
1017       return true;
1018     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1019     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1020     
1021     // If the operands are constants, see if we can simplify them.
1022     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023       return UpdateValueUsesWith(I, I);
1024     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1025       return UpdateValueUsesWith(I, I);
1026     
1027     // Only known if known in both the LHS and RHS.
1028     KnownOne &= KnownOne2;
1029     KnownZero &= KnownZero2;
1030     break;
1031   case Instruction::Trunc:
1032     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1033                              KnownZero, KnownOne, Depth+1))
1034       return true;
1035     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1036     break;
1037   case Instruction::BitCast:
1038     if (!I->getOperand(0)->getType()->isInteger())
1039       return false;
1040       
1041     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1042                              KnownZero, KnownOne, Depth+1))
1043       return true;
1044     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1045     break;
1046   case Instruction::ZExt: {
1047     // Compute the bits in the result that are not present in the input.
1048     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1049     uint64_t NotIn = ~SrcTy->getBitMask();
1050     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1051     
1052     DemandedMask &= SrcTy->getBitMask();
1053     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1054                              KnownZero, KnownOne, Depth+1))
1055       return true;
1056     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1057     // The top bits are known to be zero.
1058     KnownZero |= NewBits;
1059     break;
1060   }
1061   case Instruction::SExt: {
1062     // Compute the bits in the result that are not present in the input.
1063     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1064     uint64_t NotIn = ~SrcTy->getBitMask();
1065     uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1066     
1067     // Get the sign bit for the source type
1068     uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1069     int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1070
1071     // If any of the sign extended bits are demanded, we know that the sign
1072     // bit is demanded.
1073     if (NewBits & DemandedMask)
1074       InputDemandedBits |= InSignBit;
1075       
1076     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1077                              KnownZero, KnownOne, Depth+1))
1078       return true;
1079     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1080       
1081     // If the sign bit of the input is known set or clear, then we know the
1082     // top bits of the result.
1083
1084     // If the input sign bit is known zero, or if the NewBits are not demanded
1085     // convert this into a zero extension.
1086     if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1087       // Convert to ZExt cast
1088       CastInst *NewCast = CastInst::create(
1089         Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1090       return UpdateValueUsesWith(I, NewCast);
1091     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1092       KnownOne |= NewBits;
1093       KnownZero &= ~NewBits;
1094     } else {                              // Input sign bit unknown
1095       KnownZero &= ~NewBits;
1096       KnownOne &= ~NewBits;
1097     }
1098     break;
1099   }
1100   case Instruction::Add:
1101     // If there is a constant on the RHS, there are a variety of xformations
1102     // we can do.
1103     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1104       // If null, this should be simplified elsewhere.  Some of the xforms here
1105       // won't work if the RHS is zero.
1106       if (RHS->isNullValue())
1107         break;
1108       
1109       // Figure out what the input bits are.  If the top bits of the and result
1110       // are not demanded, then the add doesn't demand them from its input
1111       // either.
1112       
1113       // Shift the demanded mask up so that it's at the top of the uint64_t.
1114       unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1115       unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1116       
1117       // If the top bit of the output is demanded, demand everything from the
1118       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1119       uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1120
1121       // Find information about known zero/one bits in the input.
1122       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1123                                KnownZero2, KnownOne2, Depth+1))
1124         return true;
1125
1126       // If the RHS of the add has bits set that can't affect the input, reduce
1127       // the constant.
1128       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1129         return UpdateValueUsesWith(I, I);
1130       
1131       // Avoid excess work.
1132       if (KnownZero2 == 0 && KnownOne2 == 0)
1133         break;
1134       
1135       // Turn it into OR if input bits are zero.
1136       if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1137         Instruction *Or =
1138           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1139                                    I->getName());
1140         InsertNewInstBefore(Or, *I);
1141         return UpdateValueUsesWith(I, Or);
1142       }
1143       
1144       // We can say something about the output known-zero and known-one bits,
1145       // depending on potential carries from the input constant and the
1146       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1147       // bits set and the RHS constant is 0x01001, then we know we have a known
1148       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1149       
1150       // To compute this, we first compute the potential carry bits.  These are
1151       // the bits which may be modified.  I'm not aware of a better way to do
1152       // this scan.
1153       uint64_t RHSVal = RHS->getZExtValue();
1154       
1155       bool CarryIn = false;
1156       uint64_t CarryBits = 0;
1157       uint64_t CurBit = 1;
1158       for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1159         // Record the current carry in.
1160         if (CarryIn) CarryBits |= CurBit;
1161         
1162         bool CarryOut;
1163         
1164         // This bit has a carry out unless it is "zero + zero" or
1165         // "zero + anything" with no carry in.
1166         if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1167           CarryOut = false;  // 0 + 0 has no carry out, even with carry in.
1168         } else if (!CarryIn &&
1169                    ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1170           CarryOut = false;  // 0 + anything has no carry out if no carry in.
1171         } else {
1172           // Otherwise, we have to assume we have a carry out.
1173           CarryOut = true;
1174         }
1175         
1176         // This stage's carry out becomes the next stage's carry-in.
1177         CarryIn = CarryOut;
1178       }
1179       
1180       // Now that we know which bits have carries, compute the known-1/0 sets.
1181       
1182       // Bits are known one if they are known zero in one operand and one in the
1183       // other, and there is no input carry.
1184       KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1185       
1186       // Bits are known zero if they are known zero in both operands and there
1187       // is no input carry.
1188       KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1189     }
1190     break;
1191   case Instruction::Shl:
1192     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1193       uint64_t ShiftAmt = SA->getZExtValue();
1194       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1195                                KnownZero, KnownOne, Depth+1))
1196         return true;
1197       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1198       KnownZero <<= ShiftAmt;
1199       KnownOne  <<= ShiftAmt;
1200       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1201     }
1202     break;
1203   case Instruction::LShr:
1204     // For a logical shift right
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       // Unsigned 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       KnownZero |= HighBits;  // high bits known zero.
1223     }
1224     break;
1225   case Instruction::AShr:
1226     // If this is an arithmetic shift right and only the low-bit is set, we can
1227     // always convert this into a logical shr, even if the shift amount is
1228     // variable.  The low bit of the shift cannot be an input sign bit unless
1229     // the shift amount is >= the size of the datatype, which is undefined.
1230     if (DemandedMask == 1) {
1231       // Perform the logical shift right.
1232       Value *NewVal = BinaryOperator::createLShr(
1233                         I->getOperand(0), I->getOperand(1), I->getName());
1234       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1235       return UpdateValueUsesWith(I, NewVal);
1236     }    
1237     
1238     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1239       unsigned ShiftAmt = SA->getZExtValue();
1240       
1241       // Compute the new bits that are at the top now.
1242       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1243       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1244       uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
1245       // Signed shift right.
1246       if (SimplifyDemandedBits(I->getOperand(0),
1247                                (DemandedMask << ShiftAmt) & TypeMask,
1248                                KnownZero, KnownOne, Depth+1))
1249         return true;
1250       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1251       KnownZero &= TypeMask;
1252       KnownOne  &= TypeMask;
1253       KnownZero >>= ShiftAmt;
1254       KnownOne  >>= ShiftAmt;
1255         
1256       // Handle the sign bits.
1257       uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1258       SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1259         
1260       // If the input sign bit is known to be zero, or if none of the top bits
1261       // are demanded, turn this into an unsigned shift right.
1262       if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1263         // Perform the logical shift right.
1264         Value *NewVal = BinaryOperator::createLShr(
1265                           I->getOperand(0), SA, I->getName());
1266         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1267         return UpdateValueUsesWith(I, NewVal);
1268       } else if (KnownOne & SignBit) { // New bits are known one.
1269         KnownOne |= HighBits;
1270       }
1271     }
1272     break;
1273   }
1274   
1275   // If the client is only demanding bits that we know, return the known
1276   // constant.
1277   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1278     return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
1279   return false;
1280 }  
1281
1282
1283 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1284 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1285 /// actually used by the caller.  This method analyzes which elements of the
1286 /// operand are undef and returns that information in UndefElts.
1287 ///
1288 /// If the information about demanded elements can be used to simplify the
1289 /// operation, the operation is simplified, then the resultant value is
1290 /// returned.  This returns null if no change was made.
1291 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1292                                                 uint64_t &UndefElts,
1293                                                 unsigned Depth) {
1294   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1295   assert(VWidth <= 64 && "Vector too wide to analyze!");
1296   uint64_t EltMask = ~0ULL >> (64-VWidth);
1297   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1298          "Invalid DemandedElts!");
1299
1300   if (isa<UndefValue>(V)) {
1301     // If the entire vector is undefined, just return this info.
1302     UndefElts = EltMask;
1303     return 0;
1304   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1305     UndefElts = EltMask;
1306     return UndefValue::get(V->getType());
1307   }
1308   
1309   UndefElts = 0;
1310   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1311     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1312     Constant *Undef = UndefValue::get(EltTy);
1313
1314     std::vector<Constant*> Elts;
1315     for (unsigned i = 0; i != VWidth; ++i)
1316       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1317         Elts.push_back(Undef);
1318         UndefElts |= (1ULL << i);
1319       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1320         Elts.push_back(Undef);
1321         UndefElts |= (1ULL << i);
1322       } else {                               // Otherwise, defined.
1323         Elts.push_back(CP->getOperand(i));
1324       }
1325         
1326     // If we changed the constant, return it.
1327     Constant *NewCP = ConstantVector::get(Elts);
1328     return NewCP != CP ? NewCP : 0;
1329   } else if (isa<ConstantAggregateZero>(V)) {
1330     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1331     // set to undef.
1332     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1333     Constant *Zero = Constant::getNullValue(EltTy);
1334     Constant *Undef = UndefValue::get(EltTy);
1335     std::vector<Constant*> Elts;
1336     for (unsigned i = 0; i != VWidth; ++i)
1337       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1338     UndefElts = DemandedElts ^ EltMask;
1339     return ConstantVector::get(Elts);
1340   }
1341   
1342   if (!V->hasOneUse()) {    // Other users may use these bits.
1343     if (Depth != 0) {       // Not at the root.
1344       // TODO: Just compute the UndefElts information recursively.
1345       return false;
1346     }
1347     return false;
1348   } else if (Depth == 10) {        // Limit search depth.
1349     return false;
1350   }
1351   
1352   Instruction *I = dyn_cast<Instruction>(V);
1353   if (!I) return false;        // Only analyze instructions.
1354   
1355   bool MadeChange = false;
1356   uint64_t UndefElts2;
1357   Value *TmpV;
1358   switch (I->getOpcode()) {
1359   default: break;
1360     
1361   case Instruction::InsertElement: {
1362     // If this is a variable index, we don't know which element it overwrites.
1363     // demand exactly the same input as we produce.
1364     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1365     if (Idx == 0) {
1366       // Note that we can't propagate undef elt info, because we don't know
1367       // which elt is getting updated.
1368       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1369                                         UndefElts2, Depth+1);
1370       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1371       break;
1372     }
1373     
1374     // If this is inserting an element that isn't demanded, remove this
1375     // insertelement.
1376     unsigned IdxNo = Idx->getZExtValue();
1377     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1378       return AddSoonDeadInstToWorklist(*I, 0);
1379     
1380     // Otherwise, the element inserted overwrites whatever was there, so the
1381     // input demanded set is simpler than the output set.
1382     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1383                                       DemandedElts & ~(1ULL << IdxNo),
1384                                       UndefElts, Depth+1);
1385     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1386
1387     // The inserted element is defined.
1388     UndefElts |= 1ULL << IdxNo;
1389     break;
1390   }
1391     
1392   case Instruction::And:
1393   case Instruction::Or:
1394   case Instruction::Xor:
1395   case Instruction::Add:
1396   case Instruction::Sub:
1397   case Instruction::Mul:
1398     // div/rem demand all inputs, because they don't want divide by zero.
1399     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1400                                       UndefElts, Depth+1);
1401     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1402     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1403                                       UndefElts2, Depth+1);
1404     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1405       
1406     // Output elements are undefined if both are undefined.  Consider things
1407     // like undef&0.  The result is known zero, not undef.
1408     UndefElts &= UndefElts2;
1409     break;
1410     
1411   case Instruction::Call: {
1412     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1413     if (!II) break;
1414     switch (II->getIntrinsicID()) {
1415     default: break;
1416       
1417     // Binary vector operations that work column-wise.  A dest element is a
1418     // function of the corresponding input elements from the two inputs.
1419     case Intrinsic::x86_sse_sub_ss:
1420     case Intrinsic::x86_sse_mul_ss:
1421     case Intrinsic::x86_sse_min_ss:
1422     case Intrinsic::x86_sse_max_ss:
1423     case Intrinsic::x86_sse2_sub_sd:
1424     case Intrinsic::x86_sse2_mul_sd:
1425     case Intrinsic::x86_sse2_min_sd:
1426     case Intrinsic::x86_sse2_max_sd:
1427       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1428                                         UndefElts, Depth+1);
1429       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1430       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1431                                         UndefElts2, Depth+1);
1432       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1433
1434       // If only the low elt is demanded and this is a scalarizable intrinsic,
1435       // scalarize it now.
1436       if (DemandedElts == 1) {
1437         switch (II->getIntrinsicID()) {
1438         default: break;
1439         case Intrinsic::x86_sse_sub_ss:
1440         case Intrinsic::x86_sse_mul_ss:
1441         case Intrinsic::x86_sse2_sub_sd:
1442         case Intrinsic::x86_sse2_mul_sd:
1443           // TODO: Lower MIN/MAX/ABS/etc
1444           Value *LHS = II->getOperand(1);
1445           Value *RHS = II->getOperand(2);
1446           // Extract the element as scalars.
1447           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1448           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1449           
1450           switch (II->getIntrinsicID()) {
1451           default: assert(0 && "Case stmts out of sync!");
1452           case Intrinsic::x86_sse_sub_ss:
1453           case Intrinsic::x86_sse2_sub_sd:
1454             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1455                                                         II->getName()), *II);
1456             break;
1457           case Intrinsic::x86_sse_mul_ss:
1458           case Intrinsic::x86_sse2_mul_sd:
1459             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1460                                                          II->getName()), *II);
1461             break;
1462           }
1463           
1464           Instruction *New =
1465             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1466                                   II->getName());
1467           InsertNewInstBefore(New, *II);
1468           AddSoonDeadInstToWorklist(*II, 0);
1469           return New;
1470         }            
1471       }
1472         
1473       // Output elements are undefined if both are undefined.  Consider things
1474       // like undef&0.  The result is known zero, not undef.
1475       UndefElts &= UndefElts2;
1476       break;
1477     }
1478     break;
1479   }
1480   }
1481   return MadeChange ? I : 0;
1482 }
1483
1484 /// @returns true if the specified compare instruction is
1485 /// true when both operands are equal...
1486 /// @brief Determine if the ICmpInst returns true if both operands are equal
1487 static bool isTrueWhenEqual(ICmpInst &ICI) {
1488   ICmpInst::Predicate pred = ICI.getPredicate();
1489   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1490          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1491          pred == ICmpInst::ICMP_SLE;
1492 }
1493
1494 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1495 /// function is designed to check a chain of associative operators for a
1496 /// potential to apply a certain optimization.  Since the optimization may be
1497 /// applicable if the expression was reassociated, this checks the chain, then
1498 /// reassociates the expression as necessary to expose the optimization
1499 /// opportunity.  This makes use of a special Functor, which must define
1500 /// 'shouldApply' and 'apply' methods.
1501 ///
1502 template<typename Functor>
1503 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1504   unsigned Opcode = Root.getOpcode();
1505   Value *LHS = Root.getOperand(0);
1506
1507   // Quick check, see if the immediate LHS matches...
1508   if (F.shouldApply(LHS))
1509     return F.apply(Root);
1510
1511   // Otherwise, if the LHS is not of the same opcode as the root, return.
1512   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1513   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1514     // Should we apply this transform to the RHS?
1515     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1516
1517     // If not to the RHS, check to see if we should apply to the LHS...
1518     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1519       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1520       ShouldApply = true;
1521     }
1522
1523     // If the functor wants to apply the optimization to the RHS of LHSI,
1524     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1525     if (ShouldApply) {
1526       BasicBlock *BB = Root.getParent();
1527
1528       // Now all of the instructions are in the current basic block, go ahead
1529       // and perform the reassociation.
1530       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1531
1532       // First move the selected RHS to the LHS of the root...
1533       Root.setOperand(0, LHSI->getOperand(1));
1534
1535       // Make what used to be the LHS of the root be the user of the root...
1536       Value *ExtraOperand = TmpLHSI->getOperand(1);
1537       if (&Root == TmpLHSI) {
1538         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1539         return 0;
1540       }
1541       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1542       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1543       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1544       BasicBlock::iterator ARI = &Root; ++ARI;
1545       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1546       ARI = Root;
1547
1548       // Now propagate the ExtraOperand down the chain of instructions until we
1549       // get to LHSI.
1550       while (TmpLHSI != LHSI) {
1551         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1552         // Move the instruction to immediately before the chain we are
1553         // constructing to avoid breaking dominance properties.
1554         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1555         BB->getInstList().insert(ARI, NextLHSI);
1556         ARI = NextLHSI;
1557
1558         Value *NextOp = NextLHSI->getOperand(1);
1559         NextLHSI->setOperand(1, ExtraOperand);
1560         TmpLHSI = NextLHSI;
1561         ExtraOperand = NextOp;
1562       }
1563
1564       // Now that the instructions are reassociated, have the functor perform
1565       // the transformation...
1566       return F.apply(Root);
1567     }
1568
1569     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1570   }
1571   return 0;
1572 }
1573
1574
1575 // AddRHS - Implements: X + X --> X << 1
1576 struct AddRHS {
1577   Value *RHS;
1578   AddRHS(Value *rhs) : RHS(rhs) {}
1579   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1580   Instruction *apply(BinaryOperator &Add) const {
1581     return BinaryOperator::createShl(Add.getOperand(0),
1582                                   ConstantInt::get(Add.getType(), 1));
1583   }
1584 };
1585
1586 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1587 //                 iff C1&C2 == 0
1588 struct AddMaskingAnd {
1589   Constant *C2;
1590   AddMaskingAnd(Constant *c) : C2(c) {}
1591   bool shouldApply(Value *LHS) const {
1592     ConstantInt *C1;
1593     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1594            ConstantExpr::getAnd(C1, C2)->isNullValue();
1595   }
1596   Instruction *apply(BinaryOperator &Add) const {
1597     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1598   }
1599 };
1600
1601 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1602                                              InstCombiner *IC) {
1603   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1604     if (Constant *SOC = dyn_cast<Constant>(SO))
1605       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1606
1607     return IC->InsertNewInstBefore(CastInst::create(
1608           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1609   }
1610
1611   // Figure out if the constant is the left or the right argument.
1612   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1613   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1614
1615   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1616     if (ConstIsRHS)
1617       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1618     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1619   }
1620
1621   Value *Op0 = SO, *Op1 = ConstOperand;
1622   if (!ConstIsRHS)
1623     std::swap(Op0, Op1);
1624   Instruction *New;
1625   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1626     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1627   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1628     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1629                           SO->getName()+".cmp");
1630   else {
1631     assert(0 && "Unknown binary instruction type!");
1632     abort();
1633   }
1634   return IC->InsertNewInstBefore(New, I);
1635 }
1636
1637 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1638 // constant as the other operand, try to fold the binary operator into the
1639 // select arguments.  This also works for Cast instructions, which obviously do
1640 // not have a second operand.
1641 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1642                                      InstCombiner *IC) {
1643   // Don't modify shared select instructions
1644   if (!SI->hasOneUse()) return 0;
1645   Value *TV = SI->getOperand(1);
1646   Value *FV = SI->getOperand(2);
1647
1648   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1649     // Bool selects with constant operands can be folded to logical ops.
1650     if (SI->getType() == Type::Int1Ty) return 0;
1651
1652     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1653     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1654
1655     return new SelectInst(SI->getCondition(), SelectTrueVal,
1656                           SelectFalseVal);
1657   }
1658   return 0;
1659 }
1660
1661
1662 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1663 /// node as operand #0, see if we can fold the instruction into the PHI (which
1664 /// is only possible if all operands to the PHI are constants).
1665 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1666   PHINode *PN = cast<PHINode>(I.getOperand(0));
1667   unsigned NumPHIValues = PN->getNumIncomingValues();
1668   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1669
1670   // Check to see if all of the operands of the PHI are constants.  If there is
1671   // one non-constant value, remember the BB it is.  If there is more than one
1672   // or if *it* is a PHI, bail out.
1673   BasicBlock *NonConstBB = 0;
1674   for (unsigned i = 0; i != NumPHIValues; ++i)
1675     if (!isa<Constant>(PN->getIncomingValue(i))) {
1676       if (NonConstBB) return 0;  // More than one non-const value.
1677       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1678       NonConstBB = PN->getIncomingBlock(i);
1679       
1680       // If the incoming non-constant value is in I's block, we have an infinite
1681       // loop.
1682       if (NonConstBB == I.getParent())
1683         return 0;
1684     }
1685   
1686   // If there is exactly one non-constant value, we can insert a copy of the
1687   // operation in that block.  However, if this is a critical edge, we would be
1688   // inserting the computation one some other paths (e.g. inside a loop).  Only
1689   // do this if the pred block is unconditionally branching into the phi block.
1690   if (NonConstBB) {
1691     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1692     if (!BI || !BI->isUnconditional()) return 0;
1693   }
1694
1695   // Okay, we can do the transformation: create the new PHI node.
1696   PHINode *NewPN = new PHINode(I.getType(), "");
1697   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1698   InsertNewInstBefore(NewPN, *PN);
1699   NewPN->takeName(PN);
1700
1701   // Next, add all of the operands to the PHI.
1702   if (I.getNumOperands() == 2) {
1703     Constant *C = cast<Constant>(I.getOperand(1));
1704     for (unsigned i = 0; i != NumPHIValues; ++i) {
1705       Value *InV;
1706       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1707         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1708           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1709         else
1710           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1711       } else {
1712         assert(PN->getIncomingBlock(i) == NonConstBB);
1713         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1714           InV = BinaryOperator::create(BO->getOpcode(),
1715                                        PN->getIncomingValue(i), C, "phitmp",
1716                                        NonConstBB->getTerminator());
1717         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1718           InV = CmpInst::create(CI->getOpcode(), 
1719                                 CI->getPredicate(),
1720                                 PN->getIncomingValue(i), C, "phitmp",
1721                                 NonConstBB->getTerminator());
1722         else
1723           assert(0 && "Unknown binop!");
1724         
1725         AddToWorkList(cast<Instruction>(InV));
1726       }
1727       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1728     }
1729   } else { 
1730     CastInst *CI = cast<CastInst>(&I);
1731     const Type *RetTy = CI->getType();
1732     for (unsigned i = 0; i != NumPHIValues; ++i) {
1733       Value *InV;
1734       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1735         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1736       } else {
1737         assert(PN->getIncomingBlock(i) == NonConstBB);
1738         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1739                                I.getType(), "phitmp", 
1740                                NonConstBB->getTerminator());
1741         AddToWorkList(cast<Instruction>(InV));
1742       }
1743       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1744     }
1745   }
1746   return ReplaceInstUsesWith(I, NewPN);
1747 }
1748
1749 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1750   bool Changed = SimplifyCommutative(I);
1751   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1752
1753   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1754     // X + undef -> undef
1755     if (isa<UndefValue>(RHS))
1756       return ReplaceInstUsesWith(I, RHS);
1757
1758     // X + 0 --> X
1759     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1760       if (RHSC->isNullValue())
1761         return ReplaceInstUsesWith(I, LHS);
1762     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1763       if (CFP->isExactlyValue(-0.0))
1764         return ReplaceInstUsesWith(I, LHS);
1765     }
1766
1767     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1768       // X + (signbit) --> X ^ signbit
1769       uint64_t Val = CI->getZExtValue();
1770       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1771         return BinaryOperator::createXor(LHS, RHS);
1772       
1773       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1774       // (X & 254)+1 -> (X&254)|1
1775       uint64_t KnownZero, KnownOne;
1776       if (!isa<VectorType>(I.getType()) &&
1777           SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
1778                                KnownZero, KnownOne))
1779         return &I;
1780     }
1781
1782     if (isa<PHINode>(LHS))
1783       if (Instruction *NV = FoldOpIntoPhi(I))
1784         return NV;
1785     
1786     ConstantInt *XorRHS = 0;
1787     Value *XorLHS = 0;
1788     if (isa<ConstantInt>(RHSC) &&
1789         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1790       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1791       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1792       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1793       
1794       uint64_t C0080Val = 1ULL << 31;
1795       int64_t CFF80Val = -C0080Val;
1796       unsigned Size = 32;
1797       do {
1798         if (TySizeBits > Size) {
1799           bool Found = false;
1800           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1801           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1802           if (RHSSExt == CFF80Val) {
1803             if (XorRHS->getZExtValue() == C0080Val)
1804               Found = true;
1805           } else if (RHSZExt == C0080Val) {
1806             if (XorRHS->getSExtValue() == CFF80Val)
1807               Found = true;
1808           }
1809           if (Found) {
1810             // This is a sign extend if the top bits are known zero.
1811             uint64_t Mask = ~0ULL;
1812             Mask <<= 64-(TySizeBits-Size);
1813             Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
1814             if (!MaskedValueIsZero(XorLHS, Mask))
1815               Size = 0;  // Not a sign ext, but can't be any others either.
1816             goto FoundSExt;
1817           }
1818         }
1819         Size >>= 1;
1820         C0080Val >>= Size;
1821         CFF80Val >>= Size;
1822       } while (Size >= 8);
1823       
1824 FoundSExt:
1825       const Type *MiddleType = 0;
1826       switch (Size) {
1827       default: break;
1828       case 32: MiddleType = Type::Int32Ty; break;
1829       case 16: MiddleType = Type::Int16Ty; break;
1830       case 8:  MiddleType = Type::Int8Ty; break;
1831       }
1832       if (MiddleType) {
1833         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1834         InsertNewInstBefore(NewTrunc, I);
1835         return new SExtInst(NewTrunc, I.getType());
1836       }
1837     }
1838   }
1839
1840   // X + X --> X << 1
1841   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1842     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1843
1844     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1845       if (RHSI->getOpcode() == Instruction::Sub)
1846         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1847           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1848     }
1849     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1850       if (LHSI->getOpcode() == Instruction::Sub)
1851         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1852           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1853     }
1854   }
1855
1856   // -A + B  -->  B - A
1857   if (Value *V = dyn_castNegVal(LHS))
1858     return BinaryOperator::createSub(RHS, V);
1859
1860   // A + -B  -->  A - B
1861   if (!isa<Constant>(RHS))
1862     if (Value *V = dyn_castNegVal(RHS))
1863       return BinaryOperator::createSub(LHS, V);
1864
1865
1866   ConstantInt *C2;
1867   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1868     if (X == RHS)   // X*C + X --> X * (C+1)
1869       return BinaryOperator::createMul(RHS, AddOne(C2));
1870
1871     // X*C1 + X*C2 --> X * (C1+C2)
1872     ConstantInt *C1;
1873     if (X == dyn_castFoldableMul(RHS, C1))
1874       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1875   }
1876
1877   // X + X*C --> X * (C+1)
1878   if (dyn_castFoldableMul(RHS, C2) == LHS)
1879     return BinaryOperator::createMul(LHS, AddOne(C2));
1880
1881   // X + ~X --> -1   since   ~X = -X-1
1882   if (dyn_castNotVal(LHS) == RHS ||
1883       dyn_castNotVal(RHS) == LHS)
1884     return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1885   
1886
1887   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1888   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1889     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1890       return R;
1891
1892   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1893     Value *X = 0;
1894     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1895       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1896       return BinaryOperator::createSub(C, X);
1897     }
1898
1899     // (X & FF00) + xx00  -> (X+xx00) & FF00
1900     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1901       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1902       if (Anded == CRHS) {
1903         // See if all bits from the first bit set in the Add RHS up are included
1904         // in the mask.  First, get the rightmost bit.
1905         uint64_t AddRHSV = CRHS->getZExtValue();
1906
1907         // Form a mask of all bits from the lowest bit added through the top.
1908         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1909         AddRHSHighBits &= C2->getType()->getBitMask();
1910
1911         // See if the and mask includes all of these bits.
1912         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1913
1914         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1915           // Okay, the xform is safe.  Insert the new add pronto.
1916           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1917                                                             LHS->getName()), I);
1918           return BinaryOperator::createAnd(NewAdd, C2);
1919         }
1920       }
1921     }
1922
1923     // Try to fold constant add into select arguments.
1924     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1925       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1926         return R;
1927   }
1928
1929   // add (cast *A to intptrtype) B -> 
1930   //   cast (GEP (cast *A to sbyte*) B) -> 
1931   //     intptrtype
1932   {
1933     CastInst *CI = dyn_cast<CastInst>(LHS);
1934     Value *Other = RHS;
1935     if (!CI) {
1936       CI = dyn_cast<CastInst>(RHS);
1937       Other = LHS;
1938     }
1939     if (CI && CI->getType()->isSized() && 
1940         (CI->getType()->getPrimitiveSizeInBits() == 
1941          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
1942         && isa<PointerType>(CI->getOperand(0)->getType())) {
1943       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1944                                    PointerType::get(Type::Int8Ty), I);
1945       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1946       return new PtrToIntInst(I2, CI->getType());
1947     }
1948   }
1949
1950   return Changed ? &I : 0;
1951 }
1952
1953 // isSignBit - Return true if the value represented by the constant only has the
1954 // highest order bit set.
1955 static bool isSignBit(ConstantInt *CI) {
1956   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1957   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1958 }
1959
1960 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1961   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1962
1963   if (Op0 == Op1)         // sub X, X  -> 0
1964     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1965
1966   // If this is a 'B = x-(-A)', change to B = x+A...
1967   if (Value *V = dyn_castNegVal(Op1))
1968     return BinaryOperator::createAdd(Op0, V);
1969
1970   if (isa<UndefValue>(Op0))
1971     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1972   if (isa<UndefValue>(Op1))
1973     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1974
1975   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1976     // Replace (-1 - A) with (~A)...
1977     if (C->isAllOnesValue())
1978       return BinaryOperator::createNot(Op1);
1979
1980     // C - ~X == X + (1+C)
1981     Value *X = 0;
1982     if (match(Op1, m_Not(m_Value(X))))
1983       return BinaryOperator::createAdd(X,
1984                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1985     // -(X >>u 31) -> (X >>s 31)
1986     // -(X >>s 31) -> (X >>u 31)
1987     if (C->isNullValue()) {
1988       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
1989         if (SI->getOpcode() == Instruction::LShr) {
1990           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1991             // Check to see if we are shifting out everything but the sign bit.
1992             if (CU->getZExtValue() == 
1993                 SI->getType()->getPrimitiveSizeInBits()-1) {
1994               // Ok, the transformation is safe.  Insert AShr.
1995               return BinaryOperator::create(Instruction::AShr, 
1996                                           SI->getOperand(0), CU, SI->getName());
1997             }
1998           }
1999         }
2000         else if (SI->getOpcode() == Instruction::AShr) {
2001           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2002             // Check to see if we are shifting out everything but the sign bit.
2003             if (CU->getZExtValue() == 
2004                 SI->getType()->getPrimitiveSizeInBits()-1) {
2005               // Ok, the transformation is safe.  Insert LShr. 
2006               return BinaryOperator::createLShr(
2007                                           SI->getOperand(0), CU, SI->getName());
2008             }
2009           }
2010         } 
2011     }
2012
2013     // Try to fold constant sub into select arguments.
2014     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2015       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2016         return R;
2017
2018     if (isa<PHINode>(Op0))
2019       if (Instruction *NV = FoldOpIntoPhi(I))
2020         return NV;
2021   }
2022
2023   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2024     if (Op1I->getOpcode() == Instruction::Add &&
2025         !Op0->getType()->isFPOrFPVector()) {
2026       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2027         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2028       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2029         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2030       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2031         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2032           // C1-(X+C2) --> (C1-C2)-X
2033           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2034                                            Op1I->getOperand(0));
2035       }
2036     }
2037
2038     if (Op1I->hasOneUse()) {
2039       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2040       // is not used by anyone else...
2041       //
2042       if (Op1I->getOpcode() == Instruction::Sub &&
2043           !Op1I->getType()->isFPOrFPVector()) {
2044         // Swap the two operands of the subexpr...
2045         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2046         Op1I->setOperand(0, IIOp1);
2047         Op1I->setOperand(1, IIOp0);
2048
2049         // Create the new top level add instruction...
2050         return BinaryOperator::createAdd(Op0, Op1);
2051       }
2052
2053       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2054       //
2055       if (Op1I->getOpcode() == Instruction::And &&
2056           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2057         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2058
2059         Value *NewNot =
2060           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2061         return BinaryOperator::createAnd(Op0, NewNot);
2062       }
2063
2064       // 0 - (X sdiv C)  -> (X sdiv -C)
2065       if (Op1I->getOpcode() == Instruction::SDiv)
2066         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2067           if (CSI->isNullValue())
2068             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2069               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2070                                                ConstantExpr::getNeg(DivRHS));
2071
2072       // X - X*C --> X * (1-C)
2073       ConstantInt *C2 = 0;
2074       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2075         Constant *CP1 =
2076           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2077         return BinaryOperator::createMul(Op0, CP1);
2078       }
2079     }
2080   }
2081
2082   if (!Op0->getType()->isFPOrFPVector())
2083     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2084       if (Op0I->getOpcode() == Instruction::Add) {
2085         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2086           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2087         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2088           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2089       } else if (Op0I->getOpcode() == Instruction::Sub) {
2090         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2091           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2092       }
2093
2094   ConstantInt *C1;
2095   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2096     if (X == Op1) { // X*C - X --> X * (C-1)
2097       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2098       return BinaryOperator::createMul(Op1, CP1);
2099     }
2100
2101     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2102     if (X == dyn_castFoldableMul(Op1, C2))
2103       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2104   }
2105   return 0;
2106 }
2107
2108 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2109 /// really just returns true if the most significant (sign) bit is set.
2110 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2111   switch (pred) {
2112     case ICmpInst::ICMP_SLT: 
2113       // True if LHS s< RHS and RHS == 0
2114       return RHS->isNullValue();
2115     case ICmpInst::ICMP_SLE: 
2116       // True if LHS s<= RHS and RHS == -1
2117       return RHS->isAllOnesValue();
2118     case ICmpInst::ICMP_UGE: 
2119       // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2120       return RHS->getZExtValue() == (1ULL << 
2121         (RHS->getType()->getPrimitiveSizeInBits()-1));
2122     case ICmpInst::ICMP_UGT:
2123       // True if LHS u> RHS and RHS == high-bit-mask - 1
2124       return RHS->getZExtValue() ==
2125         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2126     default:
2127       return false;
2128   }
2129 }
2130
2131 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2132   bool Changed = SimplifyCommutative(I);
2133   Value *Op0 = I.getOperand(0);
2134
2135   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2136     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2137
2138   // Simplify mul instructions with a constant RHS...
2139   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2140     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2141
2142       // ((X << C1)*C2) == (X * (C2 << C1))
2143       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2144         if (SI->getOpcode() == Instruction::Shl)
2145           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2146             return BinaryOperator::createMul(SI->getOperand(0),
2147                                              ConstantExpr::getShl(CI, ShOp));
2148
2149       if (CI->isNullValue())
2150         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2151       if (CI->equalsInt(1))                  // X * 1  == X
2152         return ReplaceInstUsesWith(I, Op0);
2153       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2154         return BinaryOperator::createNeg(Op0, I.getName());
2155
2156       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2157       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2158         uint64_t C = Log2_64(Val);
2159         return BinaryOperator::createShl(Op0,
2160                                       ConstantInt::get(Op0->getType(), C));
2161       }
2162     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2163       if (Op1F->isNullValue())
2164         return ReplaceInstUsesWith(I, Op1);
2165
2166       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2167       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2168       if (Op1F->getValue() == 1.0)
2169         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2170     }
2171     
2172     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2173       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2174           isa<ConstantInt>(Op0I->getOperand(1))) {
2175         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2176         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2177                                                      Op1, "tmp");
2178         InsertNewInstBefore(Add, I);
2179         Value *C1C2 = ConstantExpr::getMul(Op1, 
2180                                            cast<Constant>(Op0I->getOperand(1)));
2181         return BinaryOperator::createAdd(Add, C1C2);
2182         
2183       }
2184
2185     // Try to fold constant mul into select arguments.
2186     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2187       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2188         return R;
2189
2190     if (isa<PHINode>(Op0))
2191       if (Instruction *NV = FoldOpIntoPhi(I))
2192         return NV;
2193   }
2194
2195   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2196     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2197       return BinaryOperator::createMul(Op0v, Op1v);
2198
2199   // If one of the operands of the multiply is a cast from a boolean value, then
2200   // we know the bool is either zero or one, so this is a 'masking' multiply.
2201   // See if we can simplify things based on how the boolean was originally
2202   // formed.
2203   CastInst *BoolCast = 0;
2204   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2205     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2206       BoolCast = CI;
2207   if (!BoolCast)
2208     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2209       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2210         BoolCast = CI;
2211   if (BoolCast) {
2212     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2213       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2214       const Type *SCOpTy = SCIOp0->getType();
2215
2216       // If the icmp is true iff the sign bit of X is set, then convert this
2217       // multiply into a shift/and combination.
2218       if (isa<ConstantInt>(SCIOp1) &&
2219           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2220         // Shift the X value right to turn it into "all signbits".
2221         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2222                                           SCOpTy->getPrimitiveSizeInBits()-1);
2223         Value *V =
2224           InsertNewInstBefore(
2225             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2226                                             BoolCast->getOperand(0)->getName()+
2227                                             ".mask"), I);
2228
2229         // If the multiply type is not the same as the source type, sign extend
2230         // or truncate to the multiply type.
2231         if (I.getType() != V->getType()) {
2232           unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2233           unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2234           Instruction::CastOps opcode = 
2235             (SrcBits == DstBits ? Instruction::BitCast : 
2236              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2237           V = InsertCastBefore(opcode, V, I.getType(), I);
2238         }
2239
2240         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2241         return BinaryOperator::createAnd(V, OtherOp);
2242       }
2243     }
2244   }
2245
2246   return Changed ? &I : 0;
2247 }
2248
2249 /// This function implements the transforms on div instructions that work
2250 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2251 /// used by the visitors to those instructions.
2252 /// @brief Transforms common to all three div instructions
2253 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2254   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2255
2256   // undef / X -> 0
2257   if (isa<UndefValue>(Op0))
2258     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2259
2260   // X / undef -> undef
2261   if (isa<UndefValue>(Op1))
2262     return ReplaceInstUsesWith(I, Op1);
2263
2264   // Handle cases involving: div X, (select Cond, Y, Z)
2265   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2266     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2267     // same basic block, then we replace the select with Y, and the condition 
2268     // of the select with false (if the cond value is in the same BB).  If the
2269     // select has uses other than the div, this allows them to be simplified
2270     // also. Note that div X, Y is just as good as div X, 0 (undef)
2271     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2272       if (ST->isNullValue()) {
2273         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2274         if (CondI && CondI->getParent() == I.getParent())
2275           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2276         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2277           I.setOperand(1, SI->getOperand(2));
2278         else
2279           UpdateValueUsesWith(SI, SI->getOperand(2));
2280         return &I;
2281       }
2282
2283     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2284     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2285       if (ST->isNullValue()) {
2286         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2287         if (CondI && CondI->getParent() == I.getParent())
2288           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2289         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2290           I.setOperand(1, SI->getOperand(1));
2291         else
2292           UpdateValueUsesWith(SI, SI->getOperand(1));
2293         return &I;
2294       }
2295   }
2296
2297   return 0;
2298 }
2299
2300 /// This function implements the transforms common to both integer division
2301 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2302 /// division instructions.
2303 /// @brief Common integer divide transforms
2304 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2305   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2306
2307   if (Instruction *Common = commonDivTransforms(I))
2308     return Common;
2309
2310   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2311     // div X, 1 == X
2312     if (RHS->equalsInt(1))
2313       return ReplaceInstUsesWith(I, Op0);
2314
2315     // (X / C1) / C2  -> X / (C1*C2)
2316     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2317       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2318         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2319           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2320                                         ConstantExpr::getMul(RHS, LHSRHS));
2321         }
2322
2323     if (!RHS->isNullValue()) { // avoid X udiv 0
2324       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2325         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2326           return R;
2327       if (isa<PHINode>(Op0))
2328         if (Instruction *NV = FoldOpIntoPhi(I))
2329           return NV;
2330     }
2331   }
2332
2333   // 0 / X == 0, we don't need to preserve faults!
2334   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2335     if (LHS->equalsInt(0))
2336       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2337
2338   return 0;
2339 }
2340
2341 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2342   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2343
2344   // Handle the integer div common cases
2345   if (Instruction *Common = commonIDivTransforms(I))
2346     return Common;
2347
2348   // X udiv C^2 -> X >> C
2349   // Check to see if this is an unsigned division with an exact power of 2,
2350   // if so, convert to a right shift.
2351   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2352     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2353       if (isPowerOf2_64(Val)) {
2354         uint64_t ShiftAmt = Log2_64(Val);
2355         return BinaryOperator::createLShr(Op0, 
2356                                     ConstantInt::get(Op0->getType(), ShiftAmt));
2357       }
2358   }
2359
2360   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2361   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2362     if (RHSI->getOpcode() == Instruction::Shl &&
2363         isa<ConstantInt>(RHSI->getOperand(0))) {
2364       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2365       if (isPowerOf2_64(C1)) {
2366         Value *N = RHSI->getOperand(1);
2367         const Type *NTy = N->getType();
2368         if (uint64_t C2 = Log2_64(C1)) {
2369           Constant *C2V = ConstantInt::get(NTy, C2);
2370           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2371         }
2372         return BinaryOperator::createLShr(Op0, N);
2373       }
2374     }
2375   }
2376   
2377   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2378   // where C1&C2 are powers of two.
2379   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2380     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2381       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2382         if (!STO->isNullValue() && !STO->isNullValue()) {
2383           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2384           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2385             // Compute the shift amounts
2386             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2387             // Construct the "on true" case of the select
2388             Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2389             Instruction *TSI = BinaryOperator::createLShr(
2390                                                    Op0, TC, SI->getName()+".t");
2391             TSI = InsertNewInstBefore(TSI, I);
2392     
2393             // Construct the "on false" case of the select
2394             Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2395             Instruction *FSI = BinaryOperator::createLShr(
2396                                                    Op0, FC, SI->getName()+".f");
2397             FSI = InsertNewInstBefore(FSI, I);
2398
2399             // construct the select instruction and return it.
2400             return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2401           }
2402         }
2403   }
2404   return 0;
2405 }
2406
2407 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2408   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2409
2410   // Handle the integer div common cases
2411   if (Instruction *Common = commonIDivTransforms(I))
2412     return Common;
2413
2414   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2415     // sdiv X, -1 == -X
2416     if (RHS->isAllOnesValue())
2417       return BinaryOperator::createNeg(Op0);
2418
2419     // -X/C -> X/-C
2420     if (Value *LHSNeg = dyn_castNegVal(Op0))
2421       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2422   }
2423
2424   // If the sign bits of both operands are zero (i.e. we can prove they are
2425   // unsigned inputs), turn this into a udiv.
2426   if (I.getType()->isInteger()) {
2427     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2428     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2429       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2430     }
2431   }      
2432   
2433   return 0;
2434 }
2435
2436 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2437   return commonDivTransforms(I);
2438 }
2439
2440 /// GetFactor - If we can prove that the specified value is at least a multiple
2441 /// of some factor, return that factor.
2442 static Constant *GetFactor(Value *V) {
2443   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2444     return CI;
2445   
2446   // Unless we can be tricky, we know this is a multiple of 1.
2447   Constant *Result = ConstantInt::get(V->getType(), 1);
2448   
2449   Instruction *I = dyn_cast<Instruction>(V);
2450   if (!I) return Result;
2451   
2452   if (I->getOpcode() == Instruction::Mul) {
2453     // Handle multiplies by a constant, etc.
2454     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2455                                 GetFactor(I->getOperand(1)));
2456   } else if (I->getOpcode() == Instruction::Shl) {
2457     // (X<<C) -> X * (1 << C)
2458     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2459       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2460       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2461     }
2462   } else if (I->getOpcode() == Instruction::And) {
2463     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2464       // X & 0xFFF0 is known to be a multiple of 16.
2465       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2466       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2467         return ConstantExpr::getShl(Result, 
2468                                     ConstantInt::get(Result->getType(), Zeros));
2469     }
2470   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2471     // Only handle int->int casts.
2472     if (!CI->isIntegerCast())
2473       return Result;
2474     Value *Op = CI->getOperand(0);
2475     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2476   }    
2477   return Result;
2478 }
2479
2480 /// This function implements the transforms on rem instructions that work
2481 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2482 /// is used by the visitors to those instructions.
2483 /// @brief Transforms common to all three rem instructions
2484 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2485   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2486
2487   // 0 % X == 0, we don't need to preserve faults!
2488   if (Constant *LHS = dyn_cast<Constant>(Op0))
2489     if (LHS->isNullValue())
2490       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2491
2492   if (isa<UndefValue>(Op0))              // undef % X -> 0
2493     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2494   if (isa<UndefValue>(Op1))
2495     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2496
2497   // Handle cases involving: rem X, (select Cond, Y, Z)
2498   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2499     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2500     // the same basic block, then we replace the select with Y, and the
2501     // condition of the select with false (if the cond value is in the same
2502     // BB).  If the select has uses other than the div, this allows them to be
2503     // simplified also.
2504     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2505       if (ST->isNullValue()) {
2506         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2507         if (CondI && CondI->getParent() == I.getParent())
2508           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2509         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2510           I.setOperand(1, SI->getOperand(2));
2511         else
2512           UpdateValueUsesWith(SI, SI->getOperand(2));
2513         return &I;
2514       }
2515     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2516     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2517       if (ST->isNullValue()) {
2518         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2519         if (CondI && CondI->getParent() == I.getParent())
2520           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2521         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2522           I.setOperand(1, SI->getOperand(1));
2523         else
2524           UpdateValueUsesWith(SI, SI->getOperand(1));
2525         return &I;
2526       }
2527   }
2528
2529   return 0;
2530 }
2531
2532 /// This function implements the transforms common to both integer remainder
2533 /// instructions (urem and srem). It is called by the visitors to those integer
2534 /// remainder instructions.
2535 /// @brief Common integer remainder transforms
2536 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2537   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538
2539   if (Instruction *common = commonRemTransforms(I))
2540     return common;
2541
2542   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2543     // X % 0 == undef, we don't need to preserve faults!
2544     if (RHS->equalsInt(0))
2545       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2546     
2547     if (RHS->equalsInt(1))  // X % 1 == 0
2548       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2549
2550     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2551       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2552         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2553           return R;
2554       } else if (isa<PHINode>(Op0I)) {
2555         if (Instruction *NV = FoldOpIntoPhi(I))
2556           return NV;
2557       }
2558       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2559       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2560         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2561     }
2562   }
2563
2564   return 0;
2565 }
2566
2567 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2568   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2569
2570   if (Instruction *common = commonIRemTransforms(I))
2571     return common;
2572   
2573   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2574     // X urem C^2 -> X and C
2575     // Check to see if this is an unsigned remainder with an exact power of 2,
2576     // if so, convert to a bitwise and.
2577     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2578       if (isPowerOf2_64(C->getZExtValue()))
2579         return BinaryOperator::createAnd(Op0, SubOne(C));
2580   }
2581
2582   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2583     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2584     if (RHSI->getOpcode() == Instruction::Shl &&
2585         isa<ConstantInt>(RHSI->getOperand(0))) {
2586       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2587       if (isPowerOf2_64(C1)) {
2588         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2589         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2590                                                                    "tmp"), I);
2591         return BinaryOperator::createAnd(Op0, Add);
2592       }
2593     }
2594   }
2595
2596   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2597   // where C1&C2 are powers of two.
2598   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2599     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2600       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2601         // STO == 0 and SFO == 0 handled above.
2602         if (isPowerOf2_64(STO->getZExtValue()) && 
2603             isPowerOf2_64(SFO->getZExtValue())) {
2604           Value *TrueAnd = InsertNewInstBefore(
2605             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2606           Value *FalseAnd = InsertNewInstBefore(
2607             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2608           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2609         }
2610       }
2611   }
2612   
2613   return 0;
2614 }
2615
2616 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2617   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2618
2619   if (Instruction *common = commonIRemTransforms(I))
2620     return common;
2621   
2622   if (Value *RHSNeg = dyn_castNegVal(Op1))
2623     if (!isa<ConstantInt>(RHSNeg) || 
2624         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2625       // X % -Y -> X % Y
2626       AddUsesToWorkList(I);
2627       I.setOperand(1, RHSNeg);
2628       return &I;
2629     }
2630  
2631   // If the top bits of both operands are zero (i.e. we can prove they are
2632   // unsigned inputs), turn this into a urem.
2633   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2634   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2635     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2636     return BinaryOperator::createURem(Op0, Op1, I.getName());
2637   }
2638
2639   return 0;
2640 }
2641
2642 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2643   return commonRemTransforms(I);
2644 }
2645
2646 // isMaxValueMinusOne - return true if this is Max-1
2647 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2648   if (isSigned) {
2649     // Calculate 0111111111..11111
2650     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2651     int64_t Val = INT64_MAX;             // All ones
2652     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2653     return C->getSExtValue() == Val-1;
2654   }
2655   return C->getZExtValue() == C->getType()->getBitMask()-1;
2656 }
2657
2658 // isMinValuePlusOne - return true if this is Min+1
2659 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2660   if (isSigned) {
2661     // Calculate 1111111111000000000000
2662     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2663     int64_t Val = -1;                    // All ones
2664     Val <<= TypeBits-1;                  // Shift over to the right spot
2665     return C->getSExtValue() == Val+1;
2666   }
2667   return C->getZExtValue() == 1; // unsigned
2668 }
2669
2670 // isOneBitSet - Return true if there is exactly one bit set in the specified
2671 // constant.
2672 static bool isOneBitSet(const ConstantInt *CI) {
2673   uint64_t V = CI->getZExtValue();
2674   return V && (V & (V-1)) == 0;
2675 }
2676
2677 #if 0   // Currently unused
2678 // isLowOnes - Return true if the constant is of the form 0+1+.
2679 static bool isLowOnes(const ConstantInt *CI) {
2680   uint64_t V = CI->getZExtValue();
2681
2682   // There won't be bits set in parts that the type doesn't contain.
2683   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2684
2685   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2686   return U && V && (U & V) == 0;
2687 }
2688 #endif
2689
2690 // isHighOnes - Return true if the constant is of the form 1+0+.
2691 // This is the same as lowones(~X).
2692 static bool isHighOnes(const ConstantInt *CI) {
2693   uint64_t V = ~CI->getZExtValue();
2694   if (~V == 0) return false;  // 0's does not match "1+"
2695
2696   // There won't be bits set in parts that the type doesn't contain.
2697   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2698
2699   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2700   return U && V && (U & V) == 0;
2701 }
2702
2703 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2704 /// are carefully arranged to allow folding of expressions such as:
2705 ///
2706 ///      (A < B) | (A > B) --> (A != B)
2707 ///
2708 /// Note that this is only valid if the first and second predicates have the
2709 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2710 ///
2711 /// Three bits are used to represent the condition, as follows:
2712 ///   0  A > B
2713 ///   1  A == B
2714 ///   2  A < B
2715 ///
2716 /// <=>  Value  Definition
2717 /// 000     0   Always false
2718 /// 001     1   A >  B
2719 /// 010     2   A == B
2720 /// 011     3   A >= B
2721 /// 100     4   A <  B
2722 /// 101     5   A != B
2723 /// 110     6   A <= B
2724 /// 111     7   Always true
2725 ///  
2726 static unsigned getICmpCode(const ICmpInst *ICI) {
2727   switch (ICI->getPredicate()) {
2728     // False -> 0
2729   case ICmpInst::ICMP_UGT: return 1;  // 001
2730   case ICmpInst::ICMP_SGT: return 1;  // 001
2731   case ICmpInst::ICMP_EQ:  return 2;  // 010
2732   case ICmpInst::ICMP_UGE: return 3;  // 011
2733   case ICmpInst::ICMP_SGE: return 3;  // 011
2734   case ICmpInst::ICMP_ULT: return 4;  // 100
2735   case ICmpInst::ICMP_SLT: return 4;  // 100
2736   case ICmpInst::ICMP_NE:  return 5;  // 101
2737   case ICmpInst::ICMP_ULE: return 6;  // 110
2738   case ICmpInst::ICMP_SLE: return 6;  // 110
2739     // True -> 7
2740   default:
2741     assert(0 && "Invalid ICmp predicate!");
2742     return 0;
2743   }
2744 }
2745
2746 /// getICmpValue - This is the complement of getICmpCode, which turns an
2747 /// opcode and two operands into either a constant true or false, or a brand 
2748 /// new /// ICmp instruction. The sign is passed in to determine which kind
2749 /// of predicate to use in new icmp instructions.
2750 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2751   switch (code) {
2752   default: assert(0 && "Illegal ICmp code!");
2753   case  0: return ConstantInt::getFalse();
2754   case  1: 
2755     if (sign)
2756       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2757     else
2758       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2759   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2760   case  3: 
2761     if (sign)
2762       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2763     else
2764       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2765   case  4: 
2766     if (sign)
2767       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2768     else
2769       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2770   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2771   case  6: 
2772     if (sign)
2773       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2774     else
2775       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2776   case  7: return ConstantInt::getTrue();
2777   }
2778 }
2779
2780 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2781   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2782     (ICmpInst::isSignedPredicate(p1) && 
2783      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2784     (ICmpInst::isSignedPredicate(p2) && 
2785      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2786 }
2787
2788 namespace { 
2789 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2790 struct FoldICmpLogical {
2791   InstCombiner &IC;
2792   Value *LHS, *RHS;
2793   ICmpInst::Predicate pred;
2794   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2795     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2796       pred(ICI->getPredicate()) {}
2797   bool shouldApply(Value *V) const {
2798     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2799       if (PredicatesFoldable(pred, ICI->getPredicate()))
2800         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2801                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2802     return false;
2803   }
2804   Instruction *apply(Instruction &Log) const {
2805     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2806     if (ICI->getOperand(0) != LHS) {
2807       assert(ICI->getOperand(1) == LHS);
2808       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2809     }
2810
2811     unsigned LHSCode = getICmpCode(ICI);
2812     unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2813     unsigned Code;
2814     switch (Log.getOpcode()) {
2815     case Instruction::And: Code = LHSCode & RHSCode; break;
2816     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2817     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2818     default: assert(0 && "Illegal logical opcode!"); return 0;
2819     }
2820
2821     Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2822     if (Instruction *I = dyn_cast<Instruction>(RV))
2823       return I;
2824     // Otherwise, it's a constant boolean value...
2825     return IC.ReplaceInstUsesWith(Log, RV);
2826   }
2827 };
2828 } // end anonymous namespace
2829
2830 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2831 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2832 // guaranteed to be a binary operator.
2833 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2834                                     ConstantInt *OpRHS,
2835                                     ConstantInt *AndRHS,
2836                                     BinaryOperator &TheAnd) {
2837   Value *X = Op->getOperand(0);
2838   Constant *Together = 0;
2839   if (!Op->isShift())
2840     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2841
2842   switch (Op->getOpcode()) {
2843   case Instruction::Xor:
2844     if (Op->hasOneUse()) {
2845       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2846       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
2847       InsertNewInstBefore(And, TheAnd);
2848       And->takeName(Op);
2849       return BinaryOperator::createXor(And, Together);
2850     }
2851     break;
2852   case Instruction::Or:
2853     if (Together == AndRHS) // (X | C) & C --> C
2854       return ReplaceInstUsesWith(TheAnd, AndRHS);
2855
2856     if (Op->hasOneUse() && Together != OpRHS) {
2857       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2858       Instruction *Or = BinaryOperator::createOr(X, Together);
2859       InsertNewInstBefore(Or, TheAnd);
2860       Or->takeName(Op);
2861       return BinaryOperator::createAnd(Or, AndRHS);
2862     }
2863     break;
2864   case Instruction::Add:
2865     if (Op->hasOneUse()) {
2866       // Adding a one to a single bit bit-field should be turned into an XOR
2867       // of the bit.  First thing to check is to see if this AND is with a
2868       // single bit constant.
2869       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2870
2871       // Clear bits that are not part of the constant.
2872       AndRHSV &= AndRHS->getType()->getBitMask();
2873
2874       // If there is only one bit set...
2875       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2876         // Ok, at this point, we know that we are masking the result of the
2877         // ADD down to exactly one bit.  If the constant we are adding has
2878         // no bits set below this bit, then we can eliminate the ADD.
2879         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2880
2881         // Check to see if any bits below the one bit set in AndRHSV are set.
2882         if ((AddRHS & (AndRHSV-1)) == 0) {
2883           // If not, the only thing that can effect the output of the AND is
2884           // the bit specified by AndRHSV.  If that bit is set, the effect of
2885           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2886           // no effect.
2887           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2888             TheAnd.setOperand(0, X);
2889             return &TheAnd;
2890           } else {
2891             // Pull the XOR out of the AND.
2892             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
2893             InsertNewInstBefore(NewAnd, TheAnd);
2894             NewAnd->takeName(Op);
2895             return BinaryOperator::createXor(NewAnd, AndRHS);
2896           }
2897         }
2898       }
2899     }
2900     break;
2901
2902   case Instruction::Shl: {
2903     // We know that the AND will not produce any of the bits shifted in, so if
2904     // the anded constant includes them, clear them now!
2905     //
2906     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2907     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2908     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2909
2910     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2911       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2912     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2913       TheAnd.setOperand(1, CI);
2914       return &TheAnd;
2915     }
2916     break;
2917   }
2918   case Instruction::LShr:
2919   {
2920     // We know that the AND will not produce any of the bits shifted in, so if
2921     // the anded constant includes them, clear them now!  This only applies to
2922     // unsigned shifts, because a signed shr may bring in set bits!
2923     //
2924     Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2925     Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2926     Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2927
2928     if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2929       return ReplaceInstUsesWith(TheAnd, Op);
2930     } else if (CI != AndRHS) {
2931       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2932       return &TheAnd;
2933     }
2934     break;
2935   }
2936   case Instruction::AShr:
2937     // Signed shr.
2938     // See if this is shifting in some sign extension, then masking it out
2939     // with an and.
2940     if (Op->hasOneUse()) {
2941       Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2942       Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2943       Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2944       if (C == AndRHS) {          // Masking out bits shifted in.
2945         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2946         // Make the argument unsigned.
2947         Value *ShVal = Op->getOperand(0);
2948         ShVal = InsertNewInstBefore(
2949             BinaryOperator::createLShr(ShVal, OpRHS, 
2950                                    Op->getName()), TheAnd);
2951         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2952       }
2953     }
2954     break;
2955   }
2956   return 0;
2957 }
2958
2959
2960 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2961 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2962 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
2963 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2964 /// insert new instructions.
2965 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2966                                            bool isSigned, bool Inside, 
2967                                            Instruction &IB) {
2968   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
2969             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2970          "Lo is not <= Hi in range emission code!");
2971     
2972   if (Inside) {
2973     if (Lo == Hi)  // Trivially false.
2974       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2975
2976     // V >= Min && V < Hi --> V < Hi
2977     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2978     ICmpInst::Predicate pred = (isSigned ? 
2979         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2980       return new ICmpInst(pred, V, Hi);
2981     }
2982
2983     // Emit V-Lo <u Hi-Lo
2984     Constant *NegLo = ConstantExpr::getNeg(Lo);
2985     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2986     InsertNewInstBefore(Add, IB);
2987     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2988     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2989   }
2990
2991   if (Lo == Hi)  // Trivially true.
2992     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2993
2994   // V < Min || V >= Hi ->'V > Hi-1'
2995   Hi = SubOne(cast<ConstantInt>(Hi));
2996   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2997     ICmpInst::Predicate pred = (isSigned ? 
2998         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2999     return new ICmpInst(pred, V, Hi);
3000   }
3001
3002   // Emit V-Lo > Hi-1-Lo
3003   Constant *NegLo = ConstantExpr::getNeg(Lo);
3004   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3005   InsertNewInstBefore(Add, IB);
3006   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3007   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3008 }
3009
3010 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3011 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3012 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3013 // not, since all 1s are not contiguous.
3014 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
3015   uint64_t V = Val->getZExtValue();
3016   if (!isShiftedMask_64(V)) return false;
3017
3018   // look for the first zero bit after the run of ones
3019   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
3020   // look for the first non-zero bit
3021   ME = 64-CountLeadingZeros_64(V);
3022   return true;
3023 }
3024
3025
3026
3027 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3028 /// where isSub determines whether the operator is a sub.  If we can fold one of
3029 /// the following xforms:
3030 /// 
3031 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3032 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3033 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3034 ///
3035 /// return (A +/- B).
3036 ///
3037 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3038                                         ConstantInt *Mask, bool isSub,
3039                                         Instruction &I) {
3040   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3041   if (!LHSI || LHSI->getNumOperands() != 2 ||
3042       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3043
3044   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3045
3046   switch (LHSI->getOpcode()) {
3047   default: return 0;
3048   case Instruction::And:
3049     if (ConstantExpr::getAnd(N, Mask) == Mask) {
3050       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3051       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3052         break;
3053
3054       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3055       // part, we don't need any explicit masks to take them out of A.  If that
3056       // is all N is, ignore it.
3057       unsigned MB, ME;
3058       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3059         uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3060         Mask >>= 64-MB+1;
3061         if (MaskedValueIsZero(RHS, Mask))
3062           break;
3063       }
3064     }
3065     return 0;
3066   case Instruction::Or:
3067   case Instruction::Xor:
3068     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3069     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3070         ConstantExpr::getAnd(N, Mask)->isNullValue())
3071       break;
3072     return 0;
3073   }
3074   
3075   Instruction *New;
3076   if (isSub)
3077     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3078   else
3079     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3080   return InsertNewInstBefore(New, I);
3081 }
3082
3083 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3084   bool Changed = SimplifyCommutative(I);
3085   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3086
3087   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3088     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3089
3090   // and X, X = X
3091   if (Op0 == Op1)
3092     return ReplaceInstUsesWith(I, Op1);
3093
3094   // See if we can simplify any instructions used by the instruction whose sole 
3095   // purpose is to compute bits we don't care about.
3096   uint64_t KnownZero, KnownOne;
3097   if (!isa<VectorType>(I.getType())) {
3098     if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3099                              KnownZero, KnownOne))
3100     return &I;
3101   } else {
3102     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3103       if (CP->isAllOnesValue())
3104         return ReplaceInstUsesWith(I, I.getOperand(0));
3105     }
3106   }
3107   
3108   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3109     uint64_t AndRHSMask = AndRHS->getZExtValue();
3110     uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3111     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3112
3113     // Optimize a variety of ((val OP C1) & C2) combinations...
3114     if (isa<BinaryOperator>(Op0)) {
3115       Instruction *Op0I = cast<Instruction>(Op0);
3116       Value *Op0LHS = Op0I->getOperand(0);
3117       Value *Op0RHS = Op0I->getOperand(1);
3118       switch (Op0I->getOpcode()) {
3119       case Instruction::Xor:
3120       case Instruction::Or:
3121         // If the mask is only needed on one incoming arm, push it up.
3122         if (Op0I->hasOneUse()) {
3123           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3124             // Not masking anything out for the LHS, move to RHS.
3125             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3126                                                    Op0RHS->getName()+".masked");
3127             InsertNewInstBefore(NewRHS, I);
3128             return BinaryOperator::create(
3129                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3130           }
3131           if (!isa<Constant>(Op0RHS) &&
3132               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3133             // Not masking anything out for the RHS, move to LHS.
3134             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3135                                                    Op0LHS->getName()+".masked");
3136             InsertNewInstBefore(NewLHS, I);
3137             return BinaryOperator::create(
3138                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3139           }
3140         }
3141
3142         break;
3143       case Instruction::Add:
3144         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3145         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3146         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3147         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3148           return BinaryOperator::createAnd(V, AndRHS);
3149         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3150           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3151         break;
3152
3153       case Instruction::Sub:
3154         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3155         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3156         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3157         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3158           return BinaryOperator::createAnd(V, AndRHS);
3159         break;
3160       }
3161
3162       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3163         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3164           return Res;
3165     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3166       // If this is an integer truncation or change from signed-to-unsigned, and
3167       // if the source is an and/or with immediate, transform it.  This
3168       // frequently occurs for bitfield accesses.
3169       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3170         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3171             CastOp->getNumOperands() == 2)
3172           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3173             if (CastOp->getOpcode() == Instruction::And) {
3174               // Change: and (cast (and X, C1) to T), C2
3175               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3176               // This will fold the two constants together, which may allow 
3177               // other simplifications.
3178               Instruction *NewCast = CastInst::createTruncOrBitCast(
3179                 CastOp->getOperand(0), I.getType(), 
3180                 CastOp->getName()+".shrunk");
3181               NewCast = InsertNewInstBefore(NewCast, I);
3182               // trunc_or_bitcast(C1)&C2
3183               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3184               C3 = ConstantExpr::getAnd(C3, AndRHS);
3185               return BinaryOperator::createAnd(NewCast, C3);
3186             } else if (CastOp->getOpcode() == Instruction::Or) {
3187               // Change: and (cast (or X, C1) to T), C2
3188               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3189               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3190               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3191                 return ReplaceInstUsesWith(I, AndRHS);
3192             }
3193       }
3194     }
3195
3196     // Try to fold constant and into select arguments.
3197     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3198       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3199         return R;
3200     if (isa<PHINode>(Op0))
3201       if (Instruction *NV = FoldOpIntoPhi(I))
3202         return NV;
3203   }
3204
3205   Value *Op0NotVal = dyn_castNotVal(Op0);
3206   Value *Op1NotVal = dyn_castNotVal(Op1);
3207
3208   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3209     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3210
3211   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3212   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3213     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3214                                                I.getName()+".demorgan");
3215     InsertNewInstBefore(Or, I);
3216     return BinaryOperator::createNot(Or);
3217   }
3218   
3219   {
3220     Value *A = 0, *B = 0;
3221     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3222       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3223         return ReplaceInstUsesWith(I, Op1);
3224     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3225       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3226         return ReplaceInstUsesWith(I, Op0);
3227     
3228     if (Op0->hasOneUse() &&
3229         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3230       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3231         I.swapOperands();     // Simplify below
3232         std::swap(Op0, Op1);
3233       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3234         cast<BinaryOperator>(Op0)->swapOperands();
3235         I.swapOperands();     // Simplify below
3236         std::swap(Op0, Op1);
3237       }
3238     }
3239     if (Op1->hasOneUse() &&
3240         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3241       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3242         cast<BinaryOperator>(Op1)->swapOperands();
3243         std::swap(A, B);
3244       }
3245       if (A == Op0) {                                // A&(A^B) -> A & ~B
3246         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3247         InsertNewInstBefore(NotB, I);
3248         return BinaryOperator::createAnd(A, NotB);
3249       }
3250     }
3251   }
3252   
3253   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3254     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3255     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3256       return R;
3257
3258     Value *LHSVal, *RHSVal;
3259     ConstantInt *LHSCst, *RHSCst;
3260     ICmpInst::Predicate LHSCC, RHSCC;
3261     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3262       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3263         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3264             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3265             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3266             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3267             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3268             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3269           // Ensure that the larger constant is on the RHS.
3270           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3271             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3272           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3273           ICmpInst *LHS = cast<ICmpInst>(Op0);
3274           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3275             std::swap(LHS, RHS);
3276             std::swap(LHSCst, RHSCst);
3277             std::swap(LHSCC, RHSCC);
3278           }
3279
3280           // At this point, we know we have have two icmp instructions
3281           // comparing a value against two constants and and'ing the result
3282           // together.  Because of the above check, we know that we only have
3283           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3284           // (from the FoldICmpLogical check above), that the two constants 
3285           // are not equal and that the larger constant is on the RHS
3286           assert(LHSCst != RHSCst && "Compares not folded above?");
3287
3288           switch (LHSCC) {
3289           default: assert(0 && "Unknown integer condition code!");
3290           case ICmpInst::ICMP_EQ:
3291             switch (RHSCC) {
3292             default: assert(0 && "Unknown integer condition code!");
3293             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3294             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3295             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3296               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3297             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3298             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3299             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3300               return ReplaceInstUsesWith(I, LHS);
3301             }
3302           case ICmpInst::ICMP_NE:
3303             switch (RHSCC) {
3304             default: assert(0 && "Unknown integer condition code!");
3305             case ICmpInst::ICMP_ULT:
3306               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3307                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3308               break;                        // (X != 13 & X u< 15) -> no change
3309             case ICmpInst::ICMP_SLT:
3310               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3311                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3312               break;                        // (X != 13 & X s< 15) -> no change
3313             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3314             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3315             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3316               return ReplaceInstUsesWith(I, RHS);
3317             case ICmpInst::ICMP_NE:
3318               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3319                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3320                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3321                                                       LHSVal->getName()+".off");
3322                 InsertNewInstBefore(Add, I);
3323                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3324                                     ConstantInt::get(Add->getType(), 1));
3325               }
3326               break;                        // (X != 13 & X != 15) -> no change
3327             }
3328             break;
3329           case ICmpInst::ICMP_ULT:
3330             switch (RHSCC) {
3331             default: assert(0 && "Unknown integer condition code!");
3332             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3333             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3334               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3335             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3336               break;
3337             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3338             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3339               return ReplaceInstUsesWith(I, LHS);
3340             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3341               break;
3342             }
3343             break;
3344           case ICmpInst::ICMP_SLT:
3345             switch (RHSCC) {
3346             default: assert(0 && "Unknown integer condition code!");
3347             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3348             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3349               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3350             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3351               break;
3352             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3353             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3354               return ReplaceInstUsesWith(I, LHS);
3355             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3356               break;
3357             }
3358             break;
3359           case ICmpInst::ICMP_UGT:
3360             switch (RHSCC) {
3361             default: assert(0 && "Unknown integer condition code!");
3362             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3363               return ReplaceInstUsesWith(I, LHS);
3364             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3365               return ReplaceInstUsesWith(I, RHS);
3366             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3367               break;
3368             case ICmpInst::ICMP_NE:
3369               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3370                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3371               break;                        // (X u> 13 & X != 15) -> no change
3372             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3373               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3374                                      true, I);
3375             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3376               break;
3377             }
3378             break;
3379           case ICmpInst::ICMP_SGT:
3380             switch (RHSCC) {
3381             default: assert(0 && "Unknown integer condition code!");
3382             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X s> 13
3383               return ReplaceInstUsesWith(I, LHS);
3384             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3385               return ReplaceInstUsesWith(I, RHS);
3386             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3387               break;
3388             case ICmpInst::ICMP_NE:
3389               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3390                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3391               break;                        // (X s> 13 & X != 15) -> no change
3392             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3393               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3394                                      true, I);
3395             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3396               break;
3397             }
3398             break;
3399           }
3400         }
3401   }
3402
3403   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3404   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3405     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3406       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3407         const Type *SrcTy = Op0C->getOperand(0)->getType();
3408         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3409             // Only do this if the casts both really cause code to be generated.
3410             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3411                               I.getType(), TD) &&
3412             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3413                               I.getType(), TD)) {
3414           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3415                                                          Op1C->getOperand(0),
3416                                                          I.getName());
3417           InsertNewInstBefore(NewOp, I);
3418           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3419         }
3420       }
3421     
3422   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3423   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3424     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3425       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3426           SI0->getOperand(1) == SI1->getOperand(1) &&
3427           (SI0->hasOneUse() || SI1->hasOneUse())) {
3428         Instruction *NewOp =
3429           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3430                                                         SI1->getOperand(0),
3431                                                         SI0->getName()), I);
3432         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3433                                       SI1->getOperand(1));
3434       }
3435   }
3436
3437   return Changed ? &I : 0;
3438 }
3439
3440 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3441 /// in the result.  If it does, and if the specified byte hasn't been filled in
3442 /// yet, fill it in and return false.
3443 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3444   Instruction *I = dyn_cast<Instruction>(V);
3445   if (I == 0) return true;
3446
3447   // If this is an or instruction, it is an inner node of the bswap.
3448   if (I->getOpcode() == Instruction::Or)
3449     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3450            CollectBSwapParts(I->getOperand(1), ByteValues);
3451   
3452   // If this is a shift by a constant int, and it is "24", then its operand
3453   // defines a byte.  We only handle unsigned types here.
3454   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3455     // Not shifting the entire input by N-1 bytes?
3456     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3457         8*(ByteValues.size()-1))
3458       return true;
3459     
3460     unsigned DestNo;
3461     if (I->getOpcode() == Instruction::Shl) {
3462       // X << 24 defines the top byte with the lowest of the input bytes.
3463       DestNo = ByteValues.size()-1;
3464     } else {
3465       // X >>u 24 defines the low byte with the highest of the input bytes.
3466       DestNo = 0;
3467     }
3468     
3469     // If the destination byte value is already defined, the values are or'd
3470     // together, which isn't a bswap (unless it's an or of the same bits).
3471     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3472       return true;
3473     ByteValues[DestNo] = I->getOperand(0);
3474     return false;
3475   }
3476   
3477   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3478   // don't have this.
3479   Value *Shift = 0, *ShiftLHS = 0;
3480   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3481   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3482       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3483     return true;
3484   Instruction *SI = cast<Instruction>(Shift);
3485
3486   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3487   if (ShiftAmt->getZExtValue() & 7 ||
3488       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3489     return true;
3490   
3491   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3492   unsigned DestByte;
3493   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3494     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3495       break;
3496   // Unknown mask for bswap.
3497   if (DestByte == ByteValues.size()) return true;
3498   
3499   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3500   unsigned SrcByte;
3501   if (SI->getOpcode() == Instruction::Shl)
3502     SrcByte = DestByte - ShiftBytes;
3503   else
3504     SrcByte = DestByte + ShiftBytes;
3505   
3506   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3507   if (SrcByte != ByteValues.size()-DestByte-1)
3508     return true;
3509   
3510   // If the destination byte value is already defined, the values are or'd
3511   // together, which isn't a bswap (unless it's an or of the same bits).
3512   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3513     return true;
3514   ByteValues[DestByte] = SI->getOperand(0);
3515   return false;
3516 }
3517
3518 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3519 /// If so, insert the new bswap intrinsic and return it.
3520 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3521   // We cannot bswap one byte.
3522   if (I.getType() == Type::Int8Ty)
3523     return 0;
3524   
3525   /// ByteValues - For each byte of the result, we keep track of which value
3526   /// defines each byte.
3527   SmallVector<Value*, 8> ByteValues;
3528   ByteValues.resize(TD->getTypeSize(I.getType()));
3529     
3530   // Try to find all the pieces corresponding to the bswap.
3531   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3532       CollectBSwapParts(I.getOperand(1), ByteValues))
3533     return 0;
3534   
3535   // Check to see if all of the bytes come from the same value.
3536   Value *V = ByteValues[0];
3537   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3538   
3539   // Check to make sure that all of the bytes come from the same value.
3540   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3541     if (ByteValues[i] != V)
3542       return 0;
3543     
3544   // If they do then *success* we can turn this into a bswap.  Figure out what
3545   // bswap to make it into.
3546   Module *M = I.getParent()->getParent()->getParent();
3547   const char *FnName = 0;
3548   if (I.getType() == Type::Int16Ty)
3549     FnName = "llvm.bswap.i16";
3550   else if (I.getType() == Type::Int32Ty)
3551     FnName = "llvm.bswap.i32";
3552   else if (I.getType() == Type::Int64Ty)
3553     FnName = "llvm.bswap.i64";
3554   else
3555     assert(0 && "Unknown integer type!");
3556   Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3557   return new CallInst(F, V);
3558 }
3559
3560
3561 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3562   bool Changed = SimplifyCommutative(I);
3563   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3564
3565   if (isa<UndefValue>(Op1))
3566     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3567                                ConstantInt::getAllOnesValue(I.getType()));
3568
3569   // or X, X = X
3570   if (Op0 == Op1)
3571     return ReplaceInstUsesWith(I, Op0);
3572
3573   // See if we can simplify any instructions used by the instruction whose sole 
3574   // purpose is to compute bits we don't care about.
3575   uint64_t KnownZero, KnownOne;
3576   if (!isa<VectorType>(I.getType()) &&
3577       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3578                            KnownZero, KnownOne))
3579     return &I;
3580   
3581   // or X, -1 == -1
3582   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3583     ConstantInt *C1 = 0; Value *X = 0;
3584     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3585     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3586       Instruction *Or = BinaryOperator::createOr(X, RHS);
3587       InsertNewInstBefore(Or, I);
3588       Or->takeName(Op0);
3589       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3590     }
3591
3592     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3593     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3594       Instruction *Or = BinaryOperator::createOr(X, RHS);
3595       InsertNewInstBefore(Or, I);
3596       Or->takeName(Op0);
3597       return BinaryOperator::createXor(Or,
3598                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3599     }
3600
3601     // Try to fold constant and into select arguments.
3602     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3603       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3604         return R;
3605     if (isa<PHINode>(Op0))
3606       if (Instruction *NV = FoldOpIntoPhi(I))
3607         return NV;
3608   }
3609
3610   Value *A = 0, *B = 0;
3611   ConstantInt *C1 = 0, *C2 = 0;
3612
3613   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3614     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3615       return ReplaceInstUsesWith(I, Op1);
3616   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3617     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3618       return ReplaceInstUsesWith(I, Op0);
3619
3620   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3621   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3622   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3623       match(Op1, m_Or(m_Value(), m_Value())) ||
3624       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3625        match(Op1, m_Shift(m_Value(), m_Value())))) {
3626     if (Instruction *BSwap = MatchBSwap(I))
3627       return BSwap;
3628   }
3629   
3630   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3631   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3632       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3633     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3634     InsertNewInstBefore(NOr, I);
3635     NOr->takeName(Op0);
3636     return BinaryOperator::createXor(NOr, C1);
3637   }
3638
3639   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3640   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3641       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3642     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3643     InsertNewInstBefore(NOr, I);
3644     NOr->takeName(Op0);
3645     return BinaryOperator::createXor(NOr, C1);
3646   }
3647
3648   // (A & C1)|(B & C2)
3649   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3650       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3651
3652     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3653       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3654
3655
3656     // If we have: ((V + N) & C1) | (V & C2)
3657     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3658     // replace with V+N.
3659     if (C1 == ConstantExpr::getNot(C2)) {
3660       Value *V1 = 0, *V2 = 0;
3661       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3662           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3663         // Add commutes, try both ways.
3664         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3665           return ReplaceInstUsesWith(I, A);
3666         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3667           return ReplaceInstUsesWith(I, A);
3668       }
3669       // Or commutes, try both ways.
3670       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3671           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3672         // Add commutes, try both ways.
3673         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3674           return ReplaceInstUsesWith(I, B);
3675         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3676           return ReplaceInstUsesWith(I, B);
3677       }
3678     }
3679   }
3680   
3681   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3682   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3683     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3684       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3685           SI0->getOperand(1) == SI1->getOperand(1) &&
3686           (SI0->hasOneUse() || SI1->hasOneUse())) {
3687         Instruction *NewOp =
3688         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3689                                                      SI1->getOperand(0),
3690                                                      SI0->getName()), I);
3691         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3692                                       SI1->getOperand(1));
3693       }
3694   }
3695
3696   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3697     if (A == Op1)   // ~A | A == -1
3698       return ReplaceInstUsesWith(I,
3699                                 ConstantInt::getAllOnesValue(I.getType()));
3700   } else {
3701     A = 0;
3702   }
3703   // Note, A is still live here!
3704   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3705     if (Op0 == B)
3706       return ReplaceInstUsesWith(I,
3707                                 ConstantInt::getAllOnesValue(I.getType()));
3708
3709     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3710     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3711       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3712                                               I.getName()+".demorgan"), I);
3713       return BinaryOperator::createNot(And);
3714     }
3715   }
3716
3717   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3718   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3719     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3720       return R;
3721
3722     Value *LHSVal, *RHSVal;
3723     ConstantInt *LHSCst, *RHSCst;
3724     ICmpInst::Predicate LHSCC, RHSCC;
3725     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3726       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3727         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3728             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3729             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3730             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3731             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3732             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3733           // Ensure that the larger constant is on the RHS.
3734           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3735             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3736           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3737           ICmpInst *LHS = cast<ICmpInst>(Op0);
3738           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3739             std::swap(LHS, RHS);
3740             std::swap(LHSCst, RHSCst);
3741             std::swap(LHSCC, RHSCC);
3742           }
3743
3744           // At this point, we know we have have two icmp instructions
3745           // comparing a value against two constants and or'ing the result
3746           // together.  Because of the above check, we know that we only have
3747           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3748           // FoldICmpLogical check above), that the two constants are not
3749           // equal.
3750           assert(LHSCst != RHSCst && "Compares not folded above?");
3751
3752           switch (LHSCC) {
3753           default: assert(0 && "Unknown integer condition code!");
3754           case ICmpInst::ICMP_EQ:
3755             switch (RHSCC) {
3756             default: assert(0 && "Unknown integer condition code!");
3757             case ICmpInst::ICMP_EQ:
3758               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3759                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3760                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3761                                                       LHSVal->getName()+".off");
3762                 InsertNewInstBefore(Add, I);
3763                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3764                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3765               }
3766               break;                         // (X == 13 | X == 15) -> no change
3767             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
3768             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
3769               break;
3770             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
3771             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
3772             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
3773               return ReplaceInstUsesWith(I, RHS);
3774             }
3775             break;
3776           case ICmpInst::ICMP_NE:
3777             switch (RHSCC) {
3778             default: assert(0 && "Unknown integer condition code!");
3779             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
3780             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
3781             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
3782               return ReplaceInstUsesWith(I, LHS);
3783             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
3784             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
3785             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
3786               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3787             }
3788             break;
3789           case ICmpInst::ICMP_ULT:
3790             switch (RHSCC) {
3791             default: assert(0 && "Unknown integer condition code!");
3792             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
3793               break;
3794             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
3795               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
3796                                      false, I);
3797             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
3798               break;
3799             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
3800             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
3801               return ReplaceInstUsesWith(I, RHS);
3802             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
3803               break;
3804             }
3805             break;
3806           case ICmpInst::ICMP_SLT:
3807             switch (RHSCC) {
3808             default: assert(0 && "Unknown integer condition code!");
3809             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
3810               break;
3811             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
3812               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
3813                                      false, I);
3814             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
3815               break;
3816             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
3817             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
3818               return ReplaceInstUsesWith(I, RHS);
3819             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
3820               break;
3821             }
3822             break;
3823           case ICmpInst::ICMP_UGT:
3824             switch (RHSCC) {
3825             default: assert(0 && "Unknown integer condition code!");
3826             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
3827             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
3828               return ReplaceInstUsesWith(I, LHS);
3829             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
3830               break;
3831             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
3832             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
3833               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3834             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
3835               break;
3836             }
3837             break;
3838           case ICmpInst::ICMP_SGT:
3839             switch (RHSCC) {
3840             default: assert(0 && "Unknown integer condition code!");
3841             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
3842             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
3843               return ReplaceInstUsesWith(I, LHS);
3844             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
3845               break;
3846             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
3847             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
3848               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3849             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
3850               break;
3851             }
3852             break;
3853           }
3854         }
3855   }
3856     
3857   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3858   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3859     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3860       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3861         const Type *SrcTy = Op0C->getOperand(0)->getType();
3862         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3863             // Only do this if the casts both really cause code to be generated.
3864             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3865                               I.getType(), TD) &&
3866             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3867                               I.getType(), TD)) {
3868           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3869                                                         Op1C->getOperand(0),
3870                                                         I.getName());
3871           InsertNewInstBefore(NewOp, I);
3872           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3873         }
3874       }
3875       
3876
3877   return Changed ? &I : 0;
3878 }
3879
3880 // XorSelf - Implements: X ^ X --> 0
3881 struct XorSelf {
3882   Value *RHS;
3883   XorSelf(Value *rhs) : RHS(rhs) {}
3884   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3885   Instruction *apply(BinaryOperator &Xor) const {
3886     return &Xor;
3887   }
3888 };
3889
3890
3891 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3892   bool Changed = SimplifyCommutative(I);
3893   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3894
3895   if (isa<UndefValue>(Op1))
3896     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3897
3898   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3899   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3900     assert(Result == &I && "AssociativeOpt didn't work?");
3901     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3902   }
3903   
3904   // See if we can simplify any instructions used by the instruction whose sole 
3905   // purpose is to compute bits we don't care about.
3906   uint64_t KnownZero, KnownOne;
3907   if (!isa<VectorType>(I.getType()) &&
3908       SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3909                            KnownZero, KnownOne))
3910     return &I;
3911
3912   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3913     // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3914     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3915       if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3916         return new ICmpInst(ICI->getInversePredicate(),
3917                             ICI->getOperand(0), ICI->getOperand(1));
3918
3919     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3920       // ~(c-X) == X-c-1 == X+(-c-1)
3921       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3922         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3923           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3924           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3925                                               ConstantInt::get(I.getType(), 1));
3926           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3927         }
3928
3929       // ~(~X & Y) --> (X | ~Y)
3930       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3931         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3932         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3933           Instruction *NotY =
3934             BinaryOperator::createNot(Op0I->getOperand(1),
3935                                       Op0I->getOperand(1)->getName()+".not");
3936           InsertNewInstBefore(NotY, I);
3937           return BinaryOperator::createOr(Op0NotVal, NotY);
3938         }
3939       }
3940
3941       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3942         if (Op0I->getOpcode() == Instruction::Add) {
3943           // ~(X-c) --> (-c-1)-X
3944           if (RHS->isAllOnesValue()) {
3945             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3946             return BinaryOperator::createSub(
3947                            ConstantExpr::getSub(NegOp0CI,
3948                                              ConstantInt::get(I.getType(), 1)),
3949                                           Op0I->getOperand(0));
3950           }
3951         } else if (Op0I->getOpcode() == Instruction::Or) {
3952           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3953           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3954             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3955             // Anything in both C1 and C2 is known to be zero, remove it from
3956             // NewRHS.
3957             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3958             NewRHS = ConstantExpr::getAnd(NewRHS, 
3959                                           ConstantExpr::getNot(CommonBits));
3960             AddToWorkList(Op0I);
3961             I.setOperand(0, Op0I->getOperand(0));
3962             I.setOperand(1, NewRHS);
3963             return &I;
3964           }
3965         }
3966     }
3967
3968     // Try to fold constant and into select arguments.
3969     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3970       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3971         return R;
3972     if (isa<PHINode>(Op0))
3973       if (Instruction *NV = FoldOpIntoPhi(I))
3974         return NV;
3975   }
3976
3977   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3978     if (X == Op1)
3979       return ReplaceInstUsesWith(I,
3980                                 ConstantInt::getAllOnesValue(I.getType()));
3981
3982   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3983     if (X == Op0)
3984       return ReplaceInstUsesWith(I,
3985                                 ConstantInt::getAllOnesValue(I.getType()));
3986
3987   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3988     if (Op1I->getOpcode() == Instruction::Or) {
3989       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3990         Op1I->swapOperands();
3991         I.swapOperands();
3992         std::swap(Op0, Op1);
3993       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3994         I.swapOperands();     // Simplified below.
3995         std::swap(Op0, Op1);
3996       }
3997     } else if (Op1I->getOpcode() == Instruction::Xor) {
3998       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3999         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
4000       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
4001         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
4002     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
4003       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
4004         Op1I->swapOperands();
4005       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
4006         I.swapOperands();     // Simplified below.
4007         std::swap(Op0, Op1);
4008       }
4009     }
4010
4011   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
4012     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
4013       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
4014         Op0I->swapOperands();
4015       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
4016         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
4017         InsertNewInstBefore(NotB, I);
4018         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
4019       }
4020     } else if (Op0I->getOpcode() == Instruction::Xor) {
4021       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
4022         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
4023       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
4024         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
4025     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
4026       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
4027         Op0I->swapOperands();
4028       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
4029           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4030         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
4031         InsertNewInstBefore(N, I);
4032         return BinaryOperator::createAnd(N, Op1);
4033       }
4034     }
4035
4036   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4037   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4038     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4039       return R;
4040
4041   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4042   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) 
4043     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4044       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4045         const Type *SrcTy = Op0C->getOperand(0)->getType();
4046         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4047             // Only do this if the casts both really cause code to be generated.
4048             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4049                               I.getType(), TD) &&
4050             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4051                               I.getType(), TD)) {
4052           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4053                                                          Op1C->getOperand(0),
4054                                                          I.getName());
4055           InsertNewInstBefore(NewOp, I);
4056           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4057         }
4058       }
4059
4060   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4061   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4062     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4063       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4064           SI0->getOperand(1) == SI1->getOperand(1) &&
4065           (SI0->hasOneUse() || SI1->hasOneUse())) {
4066         Instruction *NewOp =
4067         InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4068                                                       SI1->getOperand(0),
4069                                                       SI0->getName()), I);
4070         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4071                                       SI1->getOperand(1));
4072       }
4073   }
4074     
4075   return Changed ? &I : 0;
4076 }
4077
4078 static bool isPositive(ConstantInt *C) {
4079   return C->getSExtValue() >= 0;
4080 }
4081
4082 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4083 /// overflowed for this type.
4084 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4085                             ConstantInt *In2) {
4086   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4087
4088   return cast<ConstantInt>(Result)->getZExtValue() <
4089          cast<ConstantInt>(In1)->getZExtValue();
4090 }
4091
4092 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4093 /// code necessary to compute the offset from the base pointer (without adding
4094 /// in the base pointer).  Return the result as a signed integer of intptr size.
4095 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4096   TargetData &TD = IC.getTargetData();
4097   gep_type_iterator GTI = gep_type_begin(GEP);
4098   const Type *IntPtrTy = TD.getIntPtrType();
4099   Value *Result = Constant::getNullValue(IntPtrTy);
4100
4101   // Build a mask for high order bits.
4102   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4103
4104   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4105     Value *Op = GEP->getOperand(i);
4106     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4107     Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4108     if (Constant *OpC = dyn_cast<Constant>(Op)) {
4109       if (!OpC->isNullValue()) {
4110         OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4111         Scale = ConstantExpr::getMul(OpC, Scale);
4112         if (Constant *RC = dyn_cast<Constant>(Result))
4113           Result = ConstantExpr::getAdd(RC, Scale);
4114         else {
4115           // Emit an add instruction.
4116           Result = IC.InsertNewInstBefore(
4117              BinaryOperator::createAdd(Result, Scale,
4118                                        GEP->getName()+".offs"), I);
4119         }
4120       }
4121     } else {
4122       // Convert to correct type.
4123       Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4124                                                Op->getName()+".c"), I);
4125       if (Size != 1)
4126         // We'll let instcombine(mul) convert this to a shl if possible.
4127         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4128                                                     GEP->getName()+".idx"), I);
4129
4130       // Emit an add instruction.
4131       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4132                                                     GEP->getName()+".offs"), I);
4133     }
4134   }
4135   return Result;
4136 }
4137
4138 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4139 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4140 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4141                                        ICmpInst::Predicate Cond,
4142                                        Instruction &I) {
4143   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4144
4145   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4146     if (isa<PointerType>(CI->getOperand(0)->getType()))
4147       RHS = CI->getOperand(0);
4148
4149   Value *PtrBase = GEPLHS->getOperand(0);
4150   if (PtrBase == RHS) {
4151     // As an optimization, we don't actually have to compute the actual value of
4152     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4153     // each index is zero or not.
4154     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4155       Instruction *InVal = 0;
4156       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4157       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4158         bool EmitIt = true;
4159         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4160           if (isa<UndefValue>(C))  // undef index -> undef.
4161             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4162           if (C->isNullValue())
4163             EmitIt = false;
4164           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4165             EmitIt = false;  // This is indexing into a zero sized array?
4166           } else if (isa<ConstantInt>(C))
4167             return ReplaceInstUsesWith(I, // No comparison is needed here.
4168                                  ConstantInt::get(Type::Int1Ty, 
4169                                                   Cond == ICmpInst::ICMP_NE));
4170         }
4171
4172         if (EmitIt) {
4173           Instruction *Comp =
4174             new ICmpInst(Cond, GEPLHS->getOperand(i),
4175                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4176           if (InVal == 0)
4177             InVal = Comp;
4178           else {
4179             InVal = InsertNewInstBefore(InVal, I);
4180             InsertNewInstBefore(Comp, I);
4181             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4182               InVal = BinaryOperator::createOr(InVal, Comp);
4183             else                              // True if all are equal
4184               InVal = BinaryOperator::createAnd(InVal, Comp);
4185           }
4186         }
4187       }
4188
4189       if (InVal)
4190         return InVal;
4191       else
4192         // No comparison is needed here, all indexes = 0
4193         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4194                                                 Cond == ICmpInst::ICMP_EQ));
4195     }
4196
4197     // Only lower this if the icmp is the only user of the GEP or if we expect
4198     // the result to fold to a constant!
4199     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4200       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4201       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4202       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4203                           Constant::getNullValue(Offset->getType()));
4204     }
4205   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4206     // If the base pointers are different, but the indices are the same, just
4207     // compare the base pointer.
4208     if (PtrBase != GEPRHS->getOperand(0)) {
4209       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4210       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4211                         GEPRHS->getOperand(0)->getType();
4212       if (IndicesTheSame)
4213         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4214           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4215             IndicesTheSame = false;
4216             break;
4217           }
4218
4219       // If all indices are the same, just compare the base pointers.
4220       if (IndicesTheSame)
4221         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4222                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4223
4224       // Otherwise, the base pointers are different and the indices are
4225       // different, bail out.
4226       return 0;
4227     }
4228
4229     // If one of the GEPs has all zero indices, recurse.
4230     bool AllZeros = true;
4231     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4232       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4233           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4234         AllZeros = false;
4235         break;
4236       }
4237     if (AllZeros)
4238       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4239                           ICmpInst::getSwappedPredicate(Cond), I);
4240
4241     // If the other GEP has all zero indices, recurse.
4242     AllZeros = true;
4243     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4244       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4245           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4246         AllZeros = false;
4247         break;
4248       }
4249     if (AllZeros)
4250       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4251
4252     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4253       // If the GEPs only differ by one index, compare it.
4254       unsigned NumDifferences = 0;  // Keep track of # differences.
4255       unsigned DiffOperand = 0;     // The operand that differs.
4256       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4257         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4258           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4259                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4260             // Irreconcilable differences.
4261             NumDifferences = 2;
4262             break;
4263           } else {
4264             if (NumDifferences++) break;
4265             DiffOperand = i;
4266           }
4267         }
4268
4269       if (NumDifferences == 0)   // SAME GEP?
4270         return ReplaceInstUsesWith(I, // No comparison is needed here.
4271                                    ConstantInt::get(Type::Int1Ty, 
4272                                                     Cond == ICmpInst::ICMP_EQ));
4273       else if (NumDifferences == 1) {
4274         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4275         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4276         // Make sure we do a signed comparison here.
4277         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4278       }
4279     }
4280
4281     // Only lower this if the icmp is the only user of the GEP or if we expect
4282     // the result to fold to a constant!
4283     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4284         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4285       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4286       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4287       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4288       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4289     }
4290   }
4291   return 0;
4292 }
4293
4294 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4295   bool Changed = SimplifyCompare(I);
4296   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4297
4298   // Fold trivial predicates.
4299   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4300     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4301   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4302     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4303   
4304   // Simplify 'fcmp pred X, X'
4305   if (Op0 == Op1) {
4306     switch (I.getPredicate()) {
4307     default: assert(0 && "Unknown predicate!");
4308     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4309     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4310     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4311       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4312     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4313     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4314     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4315       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4316       
4317     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4318     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4319     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4320     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4321       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4322       I.setPredicate(FCmpInst::FCMP_UNO);
4323       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4324       return &I;
4325       
4326     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4327     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4328     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4329     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4330       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4331       I.setPredicate(FCmpInst::FCMP_ORD);
4332       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4333       return &I;
4334     }
4335   }
4336     
4337   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4338     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4339
4340   // Handle fcmp with constant RHS
4341   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4342     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4343       switch (LHSI->getOpcode()) {
4344       case Instruction::PHI:
4345         if (Instruction *NV = FoldOpIntoPhi(I))
4346           return NV;
4347         break;
4348       case Instruction::Select:
4349         // If either operand of the select is a constant, we can fold the
4350         // comparison into the select arms, which will cause one to be
4351         // constant folded and the select turned into a bitwise or.
4352         Value *Op1 = 0, *Op2 = 0;
4353         if (LHSI->hasOneUse()) {
4354           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4355             // Fold the known value into the constant operand.
4356             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4357             // Insert a new FCmp of the other select operand.
4358             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4359                                                       LHSI->getOperand(2), RHSC,
4360                                                       I.getName()), I);
4361           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4362             // Fold the known value into the constant operand.
4363             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4364             // Insert a new FCmp of the other select operand.
4365             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4366                                                       LHSI->getOperand(1), RHSC,
4367                                                       I.getName()), I);
4368           }
4369         }
4370
4371         if (Op1)
4372           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4373         break;
4374       }
4375   }
4376
4377   return Changed ? &I : 0;
4378 }
4379
4380 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4381   bool Changed = SimplifyCompare(I);
4382   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4383   const Type *Ty = Op0->getType();
4384
4385   // icmp X, X
4386   if (Op0 == Op1)
4387     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4388                                                    isTrueWhenEqual(I)));
4389
4390   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4391     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4392
4393   // icmp of GlobalValues can never equal each other as long as they aren't
4394   // external weak linkage type.
4395   if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4396     if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4397       if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4398         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4399                                                        !isTrueWhenEqual(I)));
4400
4401   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4402   // addresses never equal each other!  We already know that Op0 != Op1.
4403   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4404        isa<ConstantPointerNull>(Op0)) &&
4405       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4406        isa<ConstantPointerNull>(Op1)))
4407     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4408                                                    !isTrueWhenEqual(I)));
4409
4410   // icmp's with boolean values can always be turned into bitwise operations
4411   if (Ty == Type::Int1Ty) {
4412     switch (I.getPredicate()) {
4413     default: assert(0 && "Invalid icmp instruction!");
4414     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4415       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4416       InsertNewInstBefore(Xor, I);
4417       return BinaryOperator::createNot(Xor);
4418     }
4419     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4420       return BinaryOperator::createXor(Op0, Op1);
4421
4422     case ICmpInst::ICMP_UGT:
4423     case ICmpInst::ICMP_SGT:
4424       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4425       // FALL THROUGH
4426     case ICmpInst::ICMP_ULT:
4427     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4428       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4429       InsertNewInstBefore(Not, I);
4430       return BinaryOperator::createAnd(Not, Op1);
4431     }
4432     case ICmpInst::ICMP_UGE:
4433     case ICmpInst::ICMP_SGE:
4434       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4435       // FALL THROUGH
4436     case ICmpInst::ICMP_ULE:
4437     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4438       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4439       InsertNewInstBefore(Not, I);
4440       return BinaryOperator::createOr(Not, Op1);
4441     }
4442     }
4443   }
4444
4445   // See if we are doing a comparison between a constant and an instruction that
4446   // can be folded into the comparison.
4447   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4448     switch (I.getPredicate()) {
4449     default: break;
4450     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4451       if (CI->isMinValue(false))
4452         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4453       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4454         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4455       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4456         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4457       break;
4458
4459     case ICmpInst::ICMP_SLT:
4460       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4461         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4462       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4463         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4464       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4465         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4466       break;
4467
4468     case ICmpInst::ICMP_UGT:
4469       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4470         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4471       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4472         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4473       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4474         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4475       break;
4476
4477     case ICmpInst::ICMP_SGT:
4478       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4479         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4480       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4481         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4482       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4483         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4484       break;
4485
4486     case ICmpInst::ICMP_ULE:
4487       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4488         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4489       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4490         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4491       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4492         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4493       break;
4494
4495     case ICmpInst::ICMP_SLE:
4496       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4497         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4498       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4499         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4500       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4501         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4502       break;
4503
4504     case ICmpInst::ICMP_UGE:
4505       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4506         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4507       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4508         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4509       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4510         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4511       break;
4512
4513     case ICmpInst::ICMP_SGE:
4514       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4515         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4516       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4517         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4518       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4519         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4520       break;
4521     }
4522
4523     // If we still have a icmp le or icmp ge instruction, turn it into the
4524     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4525     // already been handled above, this requires little checking.
4526     //
4527     if (I.getPredicate() == ICmpInst::ICMP_ULE)
4528       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4529     if (I.getPredicate() == ICmpInst::ICMP_SLE)
4530       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4531     if (I.getPredicate() == ICmpInst::ICMP_UGE)
4532       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4533     if (I.getPredicate() == ICmpInst::ICMP_SGE)
4534       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4535     
4536     // See if we can fold the comparison based on bits known to be zero or one
4537     // in the input.
4538     uint64_t KnownZero, KnownOne;
4539     if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
4540                              KnownZero, KnownOne, 0))
4541       return &I;
4542         
4543     // Given the known and unknown bits, compute a range that the LHS could be
4544     // in.
4545     if (KnownOne | KnownZero) {
4546       // Compute the Min, Max and RHS values based on the known bits. For the
4547       // EQ and NE we use unsigned values.
4548       uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4549       int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4550       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4551         SRHSVal = CI->getSExtValue();
4552         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin, 
4553                                                SMax);
4554       } else {
4555         URHSVal = CI->getZExtValue();
4556         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin, 
4557                                                  UMax);
4558       }
4559       switch (I.getPredicate()) {  // LE/GE have been folded already.
4560       default: assert(0 && "Unknown icmp opcode!");
4561       case ICmpInst::ICMP_EQ:
4562         if (UMax < URHSVal || UMin > URHSVal)
4563           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4564         break;
4565       case ICmpInst::ICMP_NE:
4566         if (UMax < URHSVal || UMin > URHSVal)
4567           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4568         break;
4569       case ICmpInst::ICMP_ULT:
4570         if (UMax < URHSVal)
4571           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4572         if (UMin > URHSVal)
4573           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4574         break;
4575       case ICmpInst::ICMP_UGT:
4576         if (UMin > URHSVal)
4577           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4578         if (UMax < URHSVal)
4579           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4580         break;
4581       case ICmpInst::ICMP_SLT:
4582         if (SMax < SRHSVal)
4583           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4584         if (SMin > SRHSVal)
4585           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4586         break;
4587       case ICmpInst::ICMP_SGT: 
4588         if (SMin > SRHSVal)
4589           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4590         if (SMax < SRHSVal)
4591           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4592         break;
4593       }
4594     }
4595           
4596     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4597     // instruction, see if that instruction also has constants so that the 
4598     // instruction can be folded into the icmp 
4599     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4600       switch (LHSI->getOpcode()) {
4601       case Instruction::And:
4602         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4603             LHSI->getOperand(0)->hasOneUse()) {
4604           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4605
4606           // If the LHS is an AND of a truncating cast, we can widen the
4607           // and/compare to be the input width without changing the value
4608           // produced, eliminating a cast.
4609           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4610             // We can do this transformation if either the AND constant does not
4611             // have its sign bit set or if it is an equality comparison. 
4612             // Extending a relational comparison when we're checking the sign
4613             // bit would not work.
4614             if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4615                 (I.isEquality() ||
4616                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4617                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4618               ConstantInt *NewCST;
4619               ConstantInt *NewCI;
4620               NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4621                                          AndCST->getZExtValue());
4622               NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4623                                         CI->getZExtValue());
4624               Instruction *NewAnd = 
4625                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4626                                           LHSI->getName());
4627               InsertNewInstBefore(NewAnd, I);
4628               return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4629             }
4630           }
4631           
4632           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4633           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4634           // happens a LOT in code produced by the C front-end, for bitfield
4635           // access.
4636           BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
4637           if (Shift && !Shift->isShift())
4638             Shift = 0;
4639
4640           ConstantInt *ShAmt;
4641           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4642           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4643           const Type *AndTy = AndCST->getType();          // Type of the and.
4644
4645           // We can fold this as long as we can't shift unknown bits
4646           // into the mask.  This can only happen with signed shift
4647           // rights, as they sign-extend.
4648           if (ShAmt) {
4649             bool CanFold = Shift->isLogicalShift();
4650             if (!CanFold) {
4651               // To test for the bad case of the signed shr, see if any
4652               // of the bits shifted in could be tested after the mask.
4653               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4654               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4655
4656               Constant *OShAmt = ConstantInt::get(AndTy, ShAmtVal);
4657               Constant *ShVal =
4658                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4659                                      OShAmt);
4660               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4661                 CanFold = true;
4662             }
4663
4664             if (CanFold) {
4665               Constant *NewCst;
4666               if (Shift->getOpcode() == Instruction::Shl)
4667                 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4668               else
4669                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4670
4671               // Check to see if we are shifting out any of the bits being
4672               // compared.
4673               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4674                 // If we shifted bits out, the fold is not going to work out.
4675                 // As a special case, check to see if this means that the
4676                 // result is always true or false now.
4677                 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4678                   return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4679                 if (I.getPredicate() == ICmpInst::ICMP_NE)
4680                   return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4681               } else {
4682                 I.setOperand(1, NewCst);
4683                 Constant *NewAndCST;
4684                 if (Shift->getOpcode() == Instruction::Shl)
4685                   NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4686                 else
4687                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4688                 LHSI->setOperand(1, NewAndCST);
4689                 LHSI->setOperand(0, Shift->getOperand(0));
4690                 AddToWorkList(Shift); // Shift is dead.
4691                 AddUsesToWorkList(I);
4692                 return &I;
4693               }
4694             }
4695           }
4696           
4697           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4698           // preferable because it allows the C<<Y expression to be hoisted out
4699           // of a loop if Y is invariant and X is not.
4700           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4701               I.isEquality() && !Shift->isArithmeticShift() &&
4702               isa<Instruction>(Shift->getOperand(0))) {
4703             // Compute C << Y.
4704             Value *NS;
4705             if (Shift->getOpcode() == Instruction::LShr) {
4706               NS = BinaryOperator::createShl(AndCST, 
4707                                           Shift->getOperand(1), "tmp");
4708             } else {
4709               // Insert a logical shift.
4710               NS = BinaryOperator::createLShr(AndCST,
4711                                           Shift->getOperand(1), "tmp");
4712             }
4713             InsertNewInstBefore(cast<Instruction>(NS), I);
4714
4715             // Compute X & (C << Y).
4716             Instruction *NewAnd = BinaryOperator::createAnd(
4717                 Shift->getOperand(0), NS, LHSI->getName());
4718             InsertNewInstBefore(NewAnd, I);
4719             
4720             I.setOperand(0, NewAnd);
4721             return &I;
4722           }
4723         }
4724         break;
4725
4726       case Instruction::Shl:         // (icmp pred (shl X, ShAmt), CI)
4727         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4728           if (I.isEquality()) {
4729             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4730
4731             // Check that the shift amount is in range.  If not, don't perform
4732             // undefined shifts.  When the shift is visited it will be
4733             // simplified.
4734             if (ShAmt->getZExtValue() >= TypeBits)
4735               break;
4736
4737             // If we are comparing against bits always shifted out, the
4738             // comparison cannot succeed.
4739             Constant *Comp =
4740               ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4741             if (Comp != CI) {// Comparing against a bit that we know is zero.
4742               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4743               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4744               return ReplaceInstUsesWith(I, Cst);
4745             }
4746
4747             if (LHSI->hasOneUse()) {
4748               // Otherwise strength reduce the shift into an and.
4749               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4750               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4751               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4752
4753               Instruction *AndI =
4754                 BinaryOperator::createAnd(LHSI->getOperand(0),
4755                                           Mask, LHSI->getName()+".mask");
4756               Value *And = InsertNewInstBefore(AndI, I);
4757               return new ICmpInst(I.getPredicate(), And,
4758                                      ConstantExpr::getLShr(CI, ShAmt));
4759             }
4760           }
4761         }
4762         break;
4763
4764       case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
4765       case Instruction::AShr:
4766         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4767           if (I.isEquality()) {
4768             // Check that the shift amount is in range.  If not, don't perform
4769             // undefined shifts.  When the shift is visited it will be
4770             // simplified.
4771             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4772             if (ShAmt->getZExtValue() >= TypeBits)
4773               break;
4774
4775             // If we are comparing against bits always shifted out, the
4776             // comparison cannot succeed.
4777             Constant *Comp;
4778             if (LHSI->getOpcode() == Instruction::LShr) 
4779               Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt), 
4780                                            ShAmt);
4781             else
4782               Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt), 
4783                                            ShAmt);
4784
4785             if (Comp != CI) {// Comparing against a bit that we know is zero.
4786               bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4787               Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4788               return ReplaceInstUsesWith(I, Cst);
4789             }
4790
4791             if (LHSI->hasOneUse() || CI->isNullValue()) {
4792               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4793
4794               // Otherwise strength reduce the shift into an and.
4795               uint64_t Val = ~0ULL;          // All ones.
4796               Val <<= ShAmtVal;              // Shift over to the right spot.
4797               Val &= ~0ULL >> (64-TypeBits);
4798               Constant *Mask = ConstantInt::get(CI->getType(), Val);
4799
4800               Instruction *AndI =
4801                 BinaryOperator::createAnd(LHSI->getOperand(0),
4802                                           Mask, LHSI->getName()+".mask");
4803               Value *And = InsertNewInstBefore(AndI, I);
4804               return new ICmpInst(I.getPredicate(), And,
4805                                      ConstantExpr::getShl(CI, ShAmt));
4806             }
4807           }
4808         }
4809         break;
4810
4811       case Instruction::SDiv:
4812       case Instruction::UDiv:
4813         // Fold: icmp pred ([us]div X, C1), C2 -> range test
4814         // Fold this div into the comparison, producing a range check. 
4815         // Determine, based on the divide type, what the range is being 
4816         // checked.  If there is an overflow on the low or high side, remember 
4817         // it, otherwise compute the range [low, hi) bounding the new value.
4818         // See: InsertRangeTest above for the kinds of replacements possible.
4819         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4820           // FIXME: If the operand types don't match the type of the divide 
4821           // then don't attempt this transform. The code below doesn't have the
4822           // logic to deal with a signed divide and an unsigned compare (and
4823           // vice versa). This is because (x /s C1) <s C2  produces different 
4824           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4825           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4826           // work. :(  The if statement below tests that condition and bails 
4827           // if it finds it. 
4828           bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4829           if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4830             break;
4831
4832           // Initialize the variables that will indicate the nature of the
4833           // range check.
4834           bool LoOverflow = false, HiOverflow = false;
4835           ConstantInt *LoBound = 0, *HiBound = 0;
4836
4837           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4838           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4839           // C2 (CI). By solving for X we can turn this into a range check 
4840           // instead of computing a divide. 
4841           ConstantInt *Prod = 
4842             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4843
4844           // Determine if the product overflows by seeing if the product is
4845           // not equal to the divide. Make sure we do the same kind of divide
4846           // as in the LHS instruction that we're folding. 
4847           bool ProdOV = !DivRHS->isNullValue() && 
4848             (DivIsSigned ?  ConstantExpr::getSDiv(Prod, DivRHS) :
4849               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4850
4851           // Get the ICmp opcode
4852           ICmpInst::Predicate predicate = I.getPredicate();
4853
4854           if (DivRHS->isNullValue()) {  
4855             // Don't hack on divide by zeros!
4856           } else if (!DivIsSigned) {  // udiv
4857             LoBound = Prod;
4858             LoOverflow = ProdOV;
4859             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4860           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4861             if (CI->isNullValue()) {       // (X / pos) op 0
4862               // Can't overflow.
4863               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4864               HiBound = DivRHS;
4865             } else if (isPositive(CI)) {   // (X / pos) op pos
4866               LoBound = Prod;
4867               LoOverflow = ProdOV;
4868               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4869             } else {                       // (X / pos) op neg
4870               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4871               LoOverflow = AddWithOverflow(LoBound, Prod,
4872                                            cast<ConstantInt>(DivRHSH));
4873               HiBound = Prod;
4874               HiOverflow = ProdOV;
4875             }
4876           } else {                         // Divisor is < 0.
4877             if (CI->isNullValue()) {       // (X / neg) op 0
4878               LoBound = AddOne(DivRHS);
4879               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4880               if (HiBound == DivRHS)
4881                 LoBound = 0;               // - INTMIN = INTMIN
4882             } else if (isPositive(CI)) {   // (X / neg) op pos
4883               HiOverflow = LoOverflow = ProdOV;
4884               if (!LoOverflow)
4885                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4886               HiBound = AddOne(Prod);
4887             } else {                       // (X / neg) op neg
4888               LoBound = Prod;
4889               LoOverflow = HiOverflow = ProdOV;
4890               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4891             }
4892
4893             // Dividing by a negate swaps the condition.
4894             predicate = ICmpInst::getSwappedPredicate(predicate);
4895           }
4896
4897           if (LoBound) {
4898             Value *X = LHSI->getOperand(0);
4899             switch (predicate) {
4900             default: assert(0 && "Unhandled icmp opcode!");
4901             case ICmpInst::ICMP_EQ:
4902               if (LoOverflow && HiOverflow)
4903                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4904               else if (HiOverflow)
4905                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SGE : 
4906                                     ICmpInst::ICMP_UGE, X, LoBound);
4907               else if (LoOverflow)
4908                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
4909                                     ICmpInst::ICMP_ULT, X, HiBound);
4910               else
4911                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4912                                        true, I);
4913             case ICmpInst::ICMP_NE:
4914               if (LoOverflow && HiOverflow)
4915                 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4916               else if (HiOverflow)
4917                 return new ICmpInst(DivIsSigned ?  ICmpInst::ICMP_SLT : 
4918                                     ICmpInst::ICMP_ULT, X, LoBound);
4919               else if (LoOverflow)
4920                 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
4921                                     ICmpInst::ICMP_UGE, X, HiBound);
4922               else
4923                 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, 
4924                                        false, I);
4925             case ICmpInst::ICMP_ULT:
4926             case ICmpInst::ICMP_SLT:
4927               if (LoOverflow)
4928                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4929               return new ICmpInst(predicate, X, LoBound);
4930             case ICmpInst::ICMP_UGT:
4931             case ICmpInst::ICMP_SGT:
4932               if (HiOverflow)
4933                 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4934               if (predicate == ICmpInst::ICMP_UGT)
4935                 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4936               else
4937                 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4938             }
4939           }
4940         }
4941         break;
4942       }
4943
4944     // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4945     if (I.isEquality()) {
4946       bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4947
4948       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4949       // the second operand is a constant, simplify a bit.
4950       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4951         switch (BO->getOpcode()) {
4952         case Instruction::SRem:
4953           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4954           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4955               BO->hasOneUse()) {
4956             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4957             if (V > 1 && isPowerOf2_64(V)) {
4958               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4959                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4960               return new ICmpInst(I.getPredicate(), NewRem, 
4961                                   Constant::getNullValue(BO->getType()));
4962             }
4963           }
4964           break;
4965         case Instruction::Add:
4966           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4967           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4968             if (BO->hasOneUse())
4969               return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4970                                   ConstantExpr::getSub(CI, BOp1C));
4971           } else if (CI->isNullValue()) {
4972             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4973             // efficiently invertible, or if the add has just this one use.
4974             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4975
4976             if (Value *NegVal = dyn_castNegVal(BOp1))
4977               return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4978             else if (Value *NegVal = dyn_castNegVal(BOp0))
4979               return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4980             else if (BO->hasOneUse()) {
4981               Instruction *Neg = BinaryOperator::createNeg(BOp1);
4982               InsertNewInstBefore(Neg, I);
4983               Neg->takeName(BO);
4984               return new ICmpInst(I.getPredicate(), BOp0, Neg);
4985             }
4986           }
4987           break;
4988         case Instruction::Xor:
4989           // For the xor case, we can xor two constants together, eliminating
4990           // the explicit xor.
4991           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4992             return new ICmpInst(I.getPredicate(), BO->getOperand(0), 
4993                                 ConstantExpr::getXor(CI, BOC));
4994
4995           // FALLTHROUGH
4996         case Instruction::Sub:
4997           // Replace (([sub|xor] A, B) != 0) with (A != B)
4998           if (CI->isNullValue())
4999             return new ICmpInst(I.getPredicate(), BO->getOperand(0),
5000                                 BO->getOperand(1));
5001           break;
5002
5003         case Instruction::Or:
5004           // If bits are being or'd in that are not present in the constant we
5005           // are comparing against, then the comparison could never succeed!
5006           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5007             Constant *NotCI = ConstantExpr::getNot(CI);
5008             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5009               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5010                                                              isICMP_NE));
5011           }
5012           break;
5013
5014         case Instruction::And:
5015           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5016             // If bits are being compared against that are and'd out, then the
5017             // comparison can never succeed!
5018             if (!ConstantExpr::getAnd(CI,
5019                                       ConstantExpr::getNot(BOC))->isNullValue())
5020               return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5021                                                              isICMP_NE));
5022
5023             // If we have ((X & C) == C), turn it into ((X & C) != 0).
5024             if (CI == BOC && isOneBitSet(CI))
5025               return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5026                                   ICmpInst::ICMP_NE, Op0,
5027                                   Constant::getNullValue(CI->getType()));
5028
5029             // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5030             if (isSignBit(BOC)) {
5031               Value *X = BO->getOperand(0);
5032               Constant *Zero = Constant::getNullValue(X->getType());
5033               ICmpInst::Predicate pred = isICMP_NE ? 
5034                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5035               return new ICmpInst(pred, X, Zero);
5036             }
5037
5038             // ((X & ~7) == 0) --> X < 8
5039             if (CI->isNullValue() && isHighOnes(BOC)) {
5040               Value *X = BO->getOperand(0);
5041               Constant *NegX = ConstantExpr::getNeg(BOC);
5042               ICmpInst::Predicate pred = isICMP_NE ? 
5043                 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5044               return new ICmpInst(pred, X, NegX);
5045             }
5046
5047           }
5048         default: break;
5049         }
5050       } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5051         // Handle set{eq|ne} <intrinsic>, intcst.
5052         switch (II->getIntrinsicID()) {
5053         default: break;
5054         case Intrinsic::bswap_i16: 
5055           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5056           AddToWorkList(II);  // Dead?
5057           I.setOperand(0, II->getOperand(1));
5058           I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5059                                            ByteSwap_16(CI->getZExtValue())));
5060           return &I;
5061         case Intrinsic::bswap_i32:   
5062           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5063           AddToWorkList(II);  // Dead?
5064           I.setOperand(0, II->getOperand(1));
5065           I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5066                                            ByteSwap_32(CI->getZExtValue())));
5067           return &I;
5068         case Intrinsic::bswap_i64:   
5069           // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5070           AddToWorkList(II);  // Dead?
5071           I.setOperand(0, II->getOperand(1));
5072           I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5073                                            ByteSwap_64(CI->getZExtValue())));
5074           return &I;
5075         }
5076       }
5077     } else {  // Not a ICMP_EQ/ICMP_NE
5078       // If the LHS is a cast from an integral value of the same size, then 
5079       // since we know the RHS is a constant, try to simlify.
5080       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5081         Value *CastOp = Cast->getOperand(0);
5082         const Type *SrcTy = CastOp->getType();
5083         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5084         if (SrcTy->isInteger() && 
5085             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5086           // If this is an unsigned comparison, try to make the comparison use
5087           // smaller constant values.
5088           switch (I.getPredicate()) {
5089             default: break;
5090             case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5091               ConstantInt *CUI = cast<ConstantInt>(CI);
5092               if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5093                 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5094                                     ConstantInt::get(SrcTy, -1ULL));
5095               break;
5096             }
5097             case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5098               ConstantInt *CUI = cast<ConstantInt>(CI);
5099               if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5100                 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5101                                     Constant::getNullValue(SrcTy));
5102               break;
5103             }
5104           }
5105
5106         }
5107       }
5108     }
5109   }
5110
5111   // Handle icmp with constant RHS
5112   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5113     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5114       switch (LHSI->getOpcode()) {
5115       case Instruction::GetElementPtr:
5116         if (RHSC->isNullValue()) {
5117           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5118           bool isAllZeros = true;
5119           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5120             if (!isa<Constant>(LHSI->getOperand(i)) ||
5121                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5122               isAllZeros = false;
5123               break;
5124             }
5125           if (isAllZeros)
5126             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5127                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5128         }
5129         break;
5130
5131       case Instruction::PHI:
5132         if (Instruction *NV = FoldOpIntoPhi(I))
5133           return NV;
5134         break;
5135       case Instruction::Select:
5136         // If either operand of the select is a constant, we can fold the
5137         // comparison into the select arms, which will cause one to be
5138         // constant folded and the select turned into a bitwise or.
5139         Value *Op1 = 0, *Op2 = 0;
5140         if (LHSI->hasOneUse()) {
5141           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5142             // Fold the known value into the constant operand.
5143             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5144             // Insert a new ICmp of the other select operand.
5145             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5146                                                    LHSI->getOperand(2), RHSC,
5147                                                    I.getName()), I);
5148           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5149             // Fold the known value into the constant operand.
5150             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5151             // Insert a new ICmp of the other select operand.
5152             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5153                                                    LHSI->getOperand(1), RHSC,
5154                                                    I.getName()), I);
5155           }
5156         }
5157
5158         if (Op1)
5159           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5160         break;
5161       }
5162   }
5163
5164   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5165   if (User *GEP = dyn_castGetElementPtr(Op0))
5166     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5167       return NI;
5168   if (User *GEP = dyn_castGetElementPtr(Op1))
5169     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5170                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5171       return NI;
5172
5173   // Test to see if the operands of the icmp are casted versions of other
5174   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5175   // now.
5176   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5177     if (isa<PointerType>(Op0->getType()) && 
5178         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5179       // We keep moving the cast from the left operand over to the right
5180       // operand, where it can often be eliminated completely.
5181       Op0 = CI->getOperand(0);
5182
5183       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5184       // so eliminate it as well.
5185       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5186         Op1 = CI2->getOperand(0);
5187
5188       // If Op1 is a constant, we can fold the cast into the constant.
5189       if (Op0->getType() != Op1->getType())
5190         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5191           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5192         } else {
5193           // Otherwise, cast the RHS right before the icmp
5194           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5195         }
5196       return new ICmpInst(I.getPredicate(), Op0, Op1);
5197     }
5198   }
5199   
5200   if (isa<CastInst>(Op0)) {
5201     // Handle the special case of: icmp (cast bool to X), <cst>
5202     // This comes up when you have code like
5203     //   int X = A < B;
5204     //   if (X) ...
5205     // For generality, we handle any zero-extension of any operand comparison
5206     // with a constant or another cast from the same type.
5207     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5208       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5209         return R;
5210   }
5211   
5212   if (I.isEquality()) {
5213     Value *A, *B, *C, *D;
5214     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5215       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5216         Value *OtherVal = A == Op1 ? B : A;
5217         return new ICmpInst(I.getPredicate(), OtherVal,
5218                             Constant::getNullValue(A->getType()));
5219       }
5220
5221       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5222         // A^c1 == C^c2 --> A == C^(c1^c2)
5223         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5224           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5225             if (Op1->hasOneUse()) {
5226               Constant *NC = ConstantExpr::getXor(C1, C2);
5227               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5228               return new ICmpInst(I.getPredicate(), A,
5229                                   InsertNewInstBefore(Xor, I));
5230             }
5231         
5232         // A^B == A^D -> B == D
5233         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5234         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5235         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5236         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5237       }
5238     }
5239     
5240     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5241         (A == Op0 || B == Op0)) {
5242       // A == (A^B)  ->  B == 0
5243       Value *OtherVal = A == Op0 ? B : A;
5244       return new ICmpInst(I.getPredicate(), OtherVal,
5245                           Constant::getNullValue(A->getType()));
5246     }
5247     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5248       // (A-B) == A  ->  B == 0
5249       return new ICmpInst(I.getPredicate(), B,
5250                           Constant::getNullValue(B->getType()));
5251     }
5252     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5253       // A == (A-B)  ->  B == 0
5254       return new ICmpInst(I.getPredicate(), B,
5255                           Constant::getNullValue(B->getType()));
5256     }
5257     
5258     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5259     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5260         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5261         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5262       Value *X = 0, *Y = 0, *Z = 0;
5263       
5264       if (A == C) {
5265         X = B; Y = D; Z = A;
5266       } else if (A == D) {
5267         X = B; Y = C; Z = A;
5268       } else if (B == C) {
5269         X = A; Y = D; Z = B;
5270       } else if (B == D) {
5271         X = A; Y = C; Z = B;
5272       }
5273       
5274       if (X) {   // Build (X^Y) & Z
5275         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5276         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5277         I.setOperand(0, Op1);
5278         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5279         return &I;
5280       }
5281     }
5282   }
5283   return Changed ? &I : 0;
5284 }
5285
5286 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5287 // We only handle extending casts so far.
5288 //
5289 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5290   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5291   Value *LHSCIOp        = LHSCI->getOperand(0);
5292   const Type *SrcTy     = LHSCIOp->getType();
5293   const Type *DestTy    = LHSCI->getType();
5294   Value *RHSCIOp;
5295
5296   // We only handle extension cast instructions, so far. Enforce this.
5297   if (LHSCI->getOpcode() != Instruction::ZExt &&
5298       LHSCI->getOpcode() != Instruction::SExt)
5299     return 0;
5300
5301   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5302   bool isSignedCmp = ICI.isSignedPredicate();
5303
5304   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5305     // Not an extension from the same type?
5306     RHSCIOp = CI->getOperand(0);
5307     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5308       return 0;
5309     
5310     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5311     // and the other is a zext), then we can't handle this.
5312     if (CI->getOpcode() != LHSCI->getOpcode())
5313       return 0;
5314
5315     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5316     // then we can't handle this.
5317     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5318       return 0;
5319     
5320     // Okay, just insert a compare of the reduced operands now!
5321     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5322   }
5323
5324   // If we aren't dealing with a constant on the RHS, exit early
5325   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5326   if (!CI)
5327     return 0;
5328
5329   // Compute the constant that would happen if we truncated to SrcTy then
5330   // reextended to DestTy.
5331   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5332   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5333
5334   // If the re-extended constant didn't change...
5335   if (Res2 == CI) {
5336     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5337     // For example, we might have:
5338     //    %A = sext short %X to uint
5339     //    %B = icmp ugt uint %A, 1330
5340     // It is incorrect to transform this into 
5341     //    %B = icmp ugt short %X, 1330 
5342     // because %A may have negative value. 
5343     //
5344     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5345     // OR operation is EQ/NE.
5346     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5347       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5348     else
5349       return 0;
5350   }
5351
5352   // The re-extended constant changed so the constant cannot be represented 
5353   // in the shorter type. Consequently, we cannot emit a simple comparison.
5354
5355   // First, handle some easy cases. We know the result cannot be equal at this
5356   // point so handle the ICI.isEquality() cases
5357   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5358     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5359   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5360     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5361
5362   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5363   // should have been folded away previously and not enter in here.
5364   Value *Result;
5365   if (isSignedCmp) {
5366     // We're performing a signed comparison.
5367     if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5368       Result = ConstantInt::getFalse();          // X < (small) --> false
5369     else
5370       Result = ConstantInt::getTrue();           // X < (large) --> true
5371   } else {
5372     // We're performing an unsigned comparison.
5373     if (isSignedExt) {
5374       // We're performing an unsigned comp with a sign extended value.
5375       // This is true if the input is >= 0. [aka >s -1]
5376       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5377       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5378                                    NegOne, ICI.getName()), ICI);
5379     } else {
5380       // Unsigned extend & unsigned compare -> always true.
5381       Result = ConstantInt::getTrue();
5382     }
5383   }
5384
5385   // Finally, return the value computed.
5386   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5387       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5388     return ReplaceInstUsesWith(ICI, Result);
5389   } else {
5390     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5391             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5392            "ICmp should be folded!");
5393     if (Constant *CI = dyn_cast<Constant>(Result))
5394       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5395     else
5396       return BinaryOperator::createNot(Result);
5397   }
5398 }
5399
5400 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5401   return commonShiftTransforms(I);
5402 }
5403
5404 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5405   return commonShiftTransforms(I);
5406 }
5407
5408 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5409   return commonShiftTransforms(I);
5410 }
5411
5412 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5413   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5414   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5415
5416   // shl X, 0 == X and shr X, 0 == X
5417   // shl 0, X == 0 and shr 0, X == 0
5418   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5419       Op0 == Constant::getNullValue(Op0->getType()))
5420     return ReplaceInstUsesWith(I, Op0);
5421   
5422   if (isa<UndefValue>(Op0)) {            
5423     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5424       return ReplaceInstUsesWith(I, Op0);
5425     else                                    // undef << X -> 0, undef >>u X -> 0
5426       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5427   }
5428   if (isa<UndefValue>(Op1)) {
5429     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5430       return ReplaceInstUsesWith(I, Op0);          
5431     else                                     // X << undef, X >>u undef -> 0
5432       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5433   }
5434
5435   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5436   if (I.getOpcode() == Instruction::AShr)
5437     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5438       if (CSI->isAllOnesValue())
5439         return ReplaceInstUsesWith(I, CSI);
5440
5441   // Try to fold constant and into select arguments.
5442   if (isa<Constant>(Op0))
5443     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5444       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5445         return R;
5446
5447   // See if we can turn a signed shr into an unsigned shr.
5448   if (I.isArithmeticShift()) {
5449     if (MaskedValueIsZero(Op0,
5450                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5451       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5452     }
5453   }
5454
5455   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5456     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5457       return Res;
5458   return 0;
5459 }
5460
5461 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5462                                                BinaryOperator &I) {
5463   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5464
5465   // See if we can simplify any instructions used by the instruction whose sole 
5466   // purpose is to compute bits we don't care about.
5467   uint64_t KnownZero, KnownOne;
5468   if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
5469                            KnownZero, KnownOne))
5470     return &I;
5471   
5472   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5473   // of a signed value.
5474   //
5475   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5476   if (Op1->getZExtValue() >= TypeBits) {
5477     if (I.getOpcode() != Instruction::AShr)
5478       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5479     else {
5480       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5481       return &I;
5482     }
5483   }
5484   
5485   // ((X*C1) << C2) == (X * (C1 << C2))
5486   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5487     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5488       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5489         return BinaryOperator::createMul(BO->getOperand(0),
5490                                          ConstantExpr::getShl(BOOp, Op1));
5491   
5492   // Try to fold constant and into select arguments.
5493   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5494     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5495       return R;
5496   if (isa<PHINode>(Op0))
5497     if (Instruction *NV = FoldOpIntoPhi(I))
5498       return NV;
5499   
5500   if (Op0->hasOneUse()) {
5501     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5502       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5503       Value *V1, *V2;
5504       ConstantInt *CC;
5505       switch (Op0BO->getOpcode()) {
5506         default: break;
5507         case Instruction::Add:
5508         case Instruction::And:
5509         case Instruction::Or:
5510         case Instruction::Xor: {
5511           // These operators commute.
5512           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5513           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5514               match(Op0BO->getOperand(1),
5515                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5516             Instruction *YS = BinaryOperator::createShl(
5517                                             Op0BO->getOperand(0), Op1,
5518                                             Op0BO->getName());
5519             InsertNewInstBefore(YS, I); // (Y << C)
5520             Instruction *X = 
5521               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5522                                      Op0BO->getOperand(1)->getName());
5523             InsertNewInstBefore(X, I);  // (X + (Y << C))
5524             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5525             C2 = ConstantExpr::getShl(C2, Op1);
5526             return BinaryOperator::createAnd(X, C2);
5527           }
5528           
5529           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5530           Value *Op0BOOp1 = Op0BO->getOperand(1);
5531           if (isLeftShift && Op0BOOp1->hasOneUse() && V2 == Op1 &&
5532               match(Op0BOOp1, 
5533                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5534               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)-> hasOneUse()) {
5535             Instruction *YS = BinaryOperator::createShl(
5536                                                      Op0BO->getOperand(0), Op1,
5537                                                      Op0BO->getName());
5538             InsertNewInstBefore(YS, I); // (Y << C)
5539             Instruction *XM =
5540               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5541                                         V1->getName()+".mask");
5542             InsertNewInstBefore(XM, I); // X & (CC << C)
5543             
5544             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5545           }
5546         }
5547           
5548         // FALL THROUGH.
5549         case Instruction::Sub: {
5550           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5551           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5552               match(Op0BO->getOperand(0),
5553                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5554             Instruction *YS = BinaryOperator::createShl(
5555                                                      Op0BO->getOperand(1), Op1,
5556                                                      Op0BO->getName());
5557             InsertNewInstBefore(YS, I); // (Y << C)
5558             Instruction *X =
5559               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5560                                      Op0BO->getOperand(0)->getName());
5561             InsertNewInstBefore(X, I);  // (X + (Y << C))
5562             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5563             C2 = ConstantExpr::getShl(C2, Op1);
5564             return BinaryOperator::createAnd(X, C2);
5565           }
5566           
5567           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5568           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5569               match(Op0BO->getOperand(0),
5570                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5571                           m_ConstantInt(CC))) && V2 == Op1 &&
5572               cast<BinaryOperator>(Op0BO->getOperand(0))
5573                   ->getOperand(0)->hasOneUse()) {
5574             Instruction *YS = BinaryOperator::createShl(
5575                                                      Op0BO->getOperand(1), Op1,
5576                                                      Op0BO->getName());
5577             InsertNewInstBefore(YS, I); // (Y << C)
5578             Instruction *XM =
5579               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5580                                         V1->getName()+".mask");
5581             InsertNewInstBefore(XM, I); // X & (CC << C)
5582             
5583             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5584           }
5585           
5586           break;
5587         }
5588       }
5589       
5590       
5591       // If the operand is an bitwise operator with a constant RHS, and the
5592       // shift is the only use, we can pull it out of the shift.
5593       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5594         bool isValid = true;     // Valid only for And, Or, Xor
5595         bool highBitSet = false; // Transform if high bit of constant set?
5596         
5597         switch (Op0BO->getOpcode()) {
5598           default: isValid = false; break;   // Do not perform transform!
5599           case Instruction::Add:
5600             isValid = isLeftShift;
5601             break;
5602           case Instruction::Or:
5603           case Instruction::Xor:
5604             highBitSet = false;
5605             break;
5606           case Instruction::And:
5607             highBitSet = true;
5608             break;
5609         }
5610         
5611         // If this is a signed shift right, and the high bit is modified
5612         // by the logical operation, do not perform the transformation.
5613         // The highBitSet boolean indicates the value of the high bit of
5614         // the constant which would cause it to be modified for this
5615         // operation.
5616         //
5617         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
5618           uint64_t Val = Op0C->getZExtValue();
5619           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5620         }
5621         
5622         if (isValid) {
5623           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5624           
5625           Instruction *NewShift =
5626             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
5627           InsertNewInstBefore(NewShift, I);
5628           NewShift->takeName(Op0BO);
5629           
5630           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5631                                         NewRHS);
5632         }
5633       }
5634     }
5635   }
5636   
5637   // Find out if this is a shift of a shift by a constant.
5638   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5639   if (ShiftOp && !ShiftOp->isShift())
5640     ShiftOp = 0;
5641   
5642   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5643     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5644     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5645     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5646     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5647     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
5648     Value *X = ShiftOp->getOperand(0);
5649     
5650     unsigned AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5651     if (AmtSum > I.getType()->getPrimitiveSizeInBits())
5652       AmtSum = I.getType()->getPrimitiveSizeInBits();
5653     
5654     const IntegerType *Ty = cast<IntegerType>(I.getType());
5655     
5656     // Check for (X << c1) << c2  and  (X >> c1) >> c2
5657     if (I.getOpcode() == ShiftOp->getOpcode()) {
5658       return BinaryOperator::create(I.getOpcode(), X,
5659                                     ConstantInt::get(Ty, AmtSum));
5660     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5661                I.getOpcode() == Instruction::AShr) {
5662       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
5663       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5664     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5665                I.getOpcode() == Instruction::LShr) {
5666       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5667       Instruction *Shift =
5668         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5669       InsertNewInstBefore(Shift, I);
5670
5671       uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5672       return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5673     }
5674     
5675     // Okay, if we get here, one shift must be left, and the other shift must be
5676     // right.  See if the amounts are equal.
5677     if (ShiftAmt1 == ShiftAmt2) {
5678       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5679       if (I.getOpcode() == Instruction::Shl) {
5680         uint64_t Mask = Ty->getBitMask() << ShiftAmt1;
5681         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5682       }
5683       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5684       if (I.getOpcode() == Instruction::LShr) {
5685         uint64_t Mask = Ty->getBitMask() >> ShiftAmt1;
5686         return BinaryOperator::createAnd(X, ConstantInt::get(Ty, Mask));
5687       }
5688       // We can simplify ((X << C) >>s C) into a trunc + sext.
5689       // NOTE: we could do this for any C, but that would make 'unusual' integer
5690       // types.  For now, just stick to ones well-supported by the code
5691       // generators.
5692       const Type *SExtType = 0;
5693       switch (Ty->getBitWidth() - ShiftAmt1) {
5694       case 8 : SExtType = Type::Int8Ty; break;
5695       case 16: SExtType = Type::Int16Ty; break;
5696       case 32: SExtType = Type::Int32Ty; break;
5697       default: break;
5698       }
5699       if (SExtType) {
5700         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5701         InsertNewInstBefore(NewTrunc, I);
5702         return new SExtInst(NewTrunc, Ty);
5703       }
5704       // Otherwise, we can't handle it yet.
5705     } else if (ShiftAmt1 < ShiftAmt2) {
5706       unsigned ShiftDiff = ShiftAmt2-ShiftAmt1;
5707       
5708       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
5709       if (I.getOpcode() == Instruction::Shl) {
5710         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5711                ShiftOp->getOpcode() == Instruction::AShr);
5712         Instruction *Shift =
5713           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5714         InsertNewInstBefore(Shift, I);
5715         
5716         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5717         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5718       }
5719       
5720       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
5721       if (I.getOpcode() == Instruction::LShr) {
5722         assert(ShiftOp->getOpcode() == Instruction::Shl);
5723         Instruction *Shift =
5724           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5725         InsertNewInstBefore(Shift, I);
5726         
5727         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5728         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5729       }
5730       
5731       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
5732     } else {
5733       assert(ShiftAmt2 < ShiftAmt1);
5734       unsigned ShiftDiff = ShiftAmt1-ShiftAmt2;
5735
5736       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
5737       if (I.getOpcode() == Instruction::Shl) {
5738         assert(ShiftOp->getOpcode() == Instruction::LShr ||
5739                ShiftOp->getOpcode() == Instruction::AShr);
5740         Instruction *Shift =
5741           BinaryOperator::create(ShiftOp->getOpcode(), X,
5742                                  ConstantInt::get(Ty, ShiftDiff));
5743         InsertNewInstBefore(Shift, I);
5744         
5745         uint64_t Mask = Ty->getBitMask() << ShiftAmt2;
5746         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5747       }
5748       
5749       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
5750       if (I.getOpcode() == Instruction::LShr) {
5751         assert(ShiftOp->getOpcode() == Instruction::Shl);
5752         Instruction *Shift =
5753           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5754         InsertNewInstBefore(Shift, I);
5755         
5756         uint64_t Mask = Ty->getBitMask() >> ShiftAmt2;
5757         return BinaryOperator::createAnd(Shift, ConstantInt::get(Ty, Mask));
5758       }
5759       
5760       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
5761     }
5762   }
5763   return 0;
5764 }
5765
5766
5767 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5768 /// expression.  If so, decompose it, returning some value X, such that Val is
5769 /// X*Scale+Offset.
5770 ///
5771 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5772                                         unsigned &Offset) {
5773   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5774   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5775     Offset = CI->getZExtValue();
5776     Scale  = 1;
5777     return ConstantInt::get(Type::Int32Ty, 0);
5778   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5779     if (I->getNumOperands() == 2) {
5780       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5781         if (I->getOpcode() == Instruction::Shl) {
5782           // This is a value scaled by '1 << the shift amt'.
5783           Scale = 1U << CUI->getZExtValue();
5784           Offset = 0;
5785           return I->getOperand(0);
5786         } else if (I->getOpcode() == Instruction::Mul) {
5787           // This value is scaled by 'CUI'.
5788           Scale = CUI->getZExtValue();
5789           Offset = 0;
5790           return I->getOperand(0);
5791         } else if (I->getOpcode() == Instruction::Add) {
5792           // We have X+C.  Check to see if we really have (X*C2)+C1, 
5793           // where C1 is divisible by C2.
5794           unsigned SubScale;
5795           Value *SubVal = 
5796             DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5797           Offset += CUI->getZExtValue();
5798           if (SubScale > 1 && (Offset % SubScale == 0)) {
5799             Scale = SubScale;
5800             return SubVal;
5801           }
5802         }
5803       }
5804     }
5805   }
5806
5807   // Otherwise, we can't look past this.
5808   Scale = 1;
5809   Offset = 0;
5810   return Val;
5811 }
5812
5813
5814 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5815 /// try to eliminate the cast by moving the type information into the alloc.
5816 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5817                                                    AllocationInst &AI) {
5818   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5819   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5820   
5821   // Remove any uses of AI that are dead.
5822   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5823   
5824   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5825     Instruction *User = cast<Instruction>(*UI++);
5826     if (isInstructionTriviallyDead(User)) {
5827       while (UI != E && *UI == User)
5828         ++UI; // If this instruction uses AI more than once, don't break UI.
5829       
5830       ++NumDeadInst;
5831       DOUT << "IC: DCE: " << *User;
5832       EraseInstFromFunction(*User);
5833     }
5834   }
5835   
5836   // Get the type really allocated and the type casted to.
5837   const Type *AllocElTy = AI.getAllocatedType();
5838   const Type *CastElTy = PTy->getElementType();
5839   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5840
5841   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
5842   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
5843   if (CastElTyAlign < AllocElTyAlign) return 0;
5844
5845   // If the allocation has multiple uses, only promote it if we are strictly
5846   // increasing the alignment of the resultant allocation.  If we keep it the
5847   // same, we open the door to infinite loops of various kinds.
5848   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5849
5850   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5851   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5852   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5853
5854   // See if we can satisfy the modulus by pulling a scale out of the array
5855   // size argument.
5856   unsigned ArraySizeScale, ArrayOffset;
5857   Value *NumElements = // See if the array size is a decomposable linear expr.
5858     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5859  
5860   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5861   // do the xform.
5862   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5863       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5864
5865   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5866   Value *Amt = 0;
5867   if (Scale == 1) {
5868     Amt = NumElements;
5869   } else {
5870     // If the allocation size is constant, form a constant mul expression
5871     Amt = ConstantInt::get(Type::Int32Ty, Scale);
5872     if (isa<ConstantInt>(NumElements))
5873       Amt = ConstantExpr::getMul(
5874               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5875     // otherwise multiply the amount and the number of elements
5876     else if (Scale != 1) {
5877       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5878       Amt = InsertNewInstBefore(Tmp, AI);
5879     }
5880   }
5881   
5882   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5883     Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5884     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5885     Amt = InsertNewInstBefore(Tmp, AI);
5886   }
5887   
5888   AllocationInst *New;
5889   if (isa<MallocInst>(AI))
5890     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
5891   else
5892     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
5893   InsertNewInstBefore(New, AI);
5894   New->takeName(&AI);
5895   
5896   // If the allocation has multiple uses, insert a cast and change all things
5897   // that used it to use the new cast.  This will also hack on CI, but it will
5898   // die soon.
5899   if (!AI.hasOneUse()) {
5900     AddUsesToWorkList(AI);
5901     // New is the allocation instruction, pointer typed. AI is the original
5902     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5903     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5904     InsertNewInstBefore(NewCast, AI);
5905     AI.replaceAllUsesWith(NewCast);
5906   }
5907   return ReplaceInstUsesWith(CI, New);
5908 }
5909
5910 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5911 /// and return it without inserting any new casts.  This is used by code that
5912 /// tries to decide whether promoting or shrinking integer operations to wider
5913 /// or smaller types will allow us to eliminate a truncate or extend.
5914 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5915                                        int &NumCastsRemoved) {
5916   if (isa<Constant>(V)) return true;
5917   
5918   Instruction *I = dyn_cast<Instruction>(V);
5919   if (!I || !I->hasOneUse()) return false;
5920   
5921   switch (I->getOpcode()) {
5922   case Instruction::And:
5923   case Instruction::Or:
5924   case Instruction::Xor:
5925     // These operators can all arbitrarily be extended or truncated.
5926     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5927            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5928   case Instruction::AShr:
5929   case Instruction::LShr:
5930   case Instruction::Shl:
5931     // If this is just a bitcast changing the sign of the operation, we can
5932     // convert if the operand can be converted.
5933     if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5934       return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5935     break;
5936   case Instruction::Trunc:
5937   case Instruction::ZExt:
5938   case Instruction::SExt:
5939   case Instruction::BitCast:
5940     // If this is a cast from the destination type, we can trivially eliminate
5941     // it, and this will remove a cast overall.
5942     if (I->getOperand(0)->getType() == Ty) {
5943       // If the first operand is itself a cast, and is eliminable, do not count
5944       // this as an eliminable cast.  We would prefer to eliminate those two
5945       // casts first.
5946       if (isa<CastInst>(I->getOperand(0)))
5947         return true;
5948       
5949       ++NumCastsRemoved;
5950       return true;
5951     }
5952     break;
5953   default:
5954     // TODO: Can handle more cases here.
5955     break;
5956   }
5957   
5958   return false;
5959 }
5960
5961 /// EvaluateInDifferentType - Given an expression that 
5962 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5963 /// evaluate the expression.
5964 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
5965                                              bool isSigned ) {
5966   if (Constant *C = dyn_cast<Constant>(V))
5967     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5968
5969   // Otherwise, it must be an instruction.
5970   Instruction *I = cast<Instruction>(V);
5971   Instruction *Res = 0;
5972   switch (I->getOpcode()) {
5973   case Instruction::And:
5974   case Instruction::Or:
5975   case Instruction::Xor: {
5976     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5977     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5978     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5979                                  LHS, RHS, I->getName());
5980     break;
5981   }
5982   case Instruction::AShr:
5983   case Instruction::LShr:
5984   case Instruction::Shl: {
5985     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5986     Res = BinaryOperator::create(Instruction::BinaryOps(I->getOpcode()), LHS, 
5987                                  I->getOperand(1), I->getName());
5988     break;
5989   }    
5990   case Instruction::Trunc:
5991   case Instruction::ZExt:
5992   case Instruction::SExt:
5993   case Instruction::BitCast:
5994     // If the source type of the cast is the type we're trying for then we can
5995     // just return the source. There's no need to insert it because its not new.
5996     if (I->getOperand(0)->getType() == Ty)
5997       return I->getOperand(0);
5998     
5999     // Some other kind of cast, which shouldn't happen, so just ..
6000     // FALL THROUGH
6001   default: 
6002     // TODO: Can handle more cases here.
6003     assert(0 && "Unreachable!");
6004     break;
6005   }
6006   
6007   return InsertNewInstBefore(Res, *I);
6008 }
6009
6010 /// @brief Implement the transforms common to all CastInst visitors.
6011 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6012   Value *Src = CI.getOperand(0);
6013
6014   // Casting undef to anything results in undef so might as just replace it and
6015   // get rid of the cast.
6016   if (isa<UndefValue>(Src))   // cast undef -> undef
6017     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6018
6019   // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6020   // eliminate it now.
6021   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6022     if (Instruction::CastOps opc = 
6023         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6024       // The first cast (CSrc) is eliminable so we need to fix up or replace
6025       // the second cast (CI). CSrc will then have a good chance of being dead.
6026       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6027     }
6028   }
6029
6030   // If casting the result of a getelementptr instruction with no offset, turn
6031   // this into a cast of the original pointer!
6032   //
6033   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6034     bool AllZeroOperands = true;
6035     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
6036       if (!isa<Constant>(GEP->getOperand(i)) ||
6037           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
6038         AllZeroOperands = false;
6039         break;
6040       }
6041     if (AllZeroOperands) {
6042       // Changing the cast operand is usually not a good idea but it is safe
6043       // here because the pointer operand is being replaced with another 
6044       // pointer operand so the opcode doesn't need to change.
6045       CI.setOperand(0, GEP->getOperand(0));
6046       return &CI;
6047     }
6048   }
6049     
6050   // If we are casting a malloc or alloca to a pointer to a type of the same
6051   // size, rewrite the allocation instruction to allocate the "right" type.
6052   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6053     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6054       return V;
6055
6056   // If we are casting a select then fold the cast into the select
6057   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6058     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6059       return NV;
6060
6061   // If we are casting a PHI then fold the cast into the PHI
6062   if (isa<PHINode>(Src))
6063     if (Instruction *NV = FoldOpIntoPhi(CI))
6064       return NV;
6065   
6066   return 0;
6067 }
6068
6069 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6070 /// integers. This function implements the common transforms for all those
6071 /// cases.
6072 /// @brief Implement the transforms common to CastInst with integer operands
6073 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6074   if (Instruction *Result = commonCastTransforms(CI))
6075     return Result;
6076
6077   Value *Src = CI.getOperand(0);
6078   const Type *SrcTy = Src->getType();
6079   const Type *DestTy = CI.getType();
6080   unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6081   unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6082
6083   // See if we can simplify any instructions used by the LHS whose sole 
6084   // purpose is to compute bits we don't care about.
6085   uint64_t KnownZero = 0, KnownOne = 0;
6086   if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6087                            KnownZero, KnownOne))
6088     return &CI;
6089
6090   // If the source isn't an instruction or has more than one use then we
6091   // can't do anything more. 
6092   Instruction *SrcI = dyn_cast<Instruction>(Src);
6093   if (!SrcI || !Src->hasOneUse())
6094     return 0;
6095
6096   // Attempt to propagate the cast into the instruction.
6097   int NumCastsRemoved = 0;
6098   if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6099     // If this cast is a truncate, evaluting in a different type always
6100     // eliminates the cast, so it is always a win.  If this is a noop-cast
6101     // this just removes a noop cast which isn't pointful, but simplifies
6102     // the code.  If this is a zero-extension, we need to do an AND to
6103     // maintain the clear top-part of the computation, so we require that
6104     // the input have eliminated at least one cast.  If this is a sign
6105     // extension, we insert two new casts (to do the extension) so we
6106     // require that two casts have been eliminated.
6107     bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6108     if (!DoXForm) {
6109       switch (CI.getOpcode()) {
6110         case Instruction::Trunc:
6111           DoXForm = true;
6112           break;
6113         case Instruction::ZExt:
6114           DoXForm = NumCastsRemoved >= 1;
6115           break;
6116         case Instruction::SExt:
6117           DoXForm = NumCastsRemoved >= 2;
6118           break;
6119         case Instruction::BitCast:
6120           DoXForm = false;
6121           break;
6122         default:
6123           // All the others use floating point so we shouldn't actually 
6124           // get here because of the check above.
6125           assert(!"Unknown cast type .. unreachable");
6126           break;
6127       }
6128     }
6129     
6130     if (DoXForm) {
6131       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6132                                            CI.getOpcode() == Instruction::SExt);
6133       assert(Res->getType() == DestTy);
6134       switch (CI.getOpcode()) {
6135       default: assert(0 && "Unknown cast type!");
6136       case Instruction::Trunc:
6137       case Instruction::BitCast:
6138         // Just replace this cast with the result.
6139         return ReplaceInstUsesWith(CI, Res);
6140       case Instruction::ZExt: {
6141         // We need to emit an AND to clear the high bits.
6142         assert(SrcBitSize < DestBitSize && "Not a zext?");
6143         Constant *C = 
6144           ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6145         if (DestBitSize < 64)
6146           C = ConstantExpr::getTrunc(C, DestTy);
6147         return BinaryOperator::createAnd(Res, C);
6148       }
6149       case Instruction::SExt:
6150         // We need to emit a cast to truncate, then a cast to sext.
6151         return CastInst::create(Instruction::SExt,
6152             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6153                              CI), DestTy);
6154       }
6155     }
6156   }
6157   
6158   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6159   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6160
6161   switch (SrcI->getOpcode()) {
6162   case Instruction::Add:
6163   case Instruction::Mul:
6164   case Instruction::And:
6165   case Instruction::Or:
6166   case Instruction::Xor:
6167     // If we are discarding information, or just changing the sign, 
6168     // rewrite.
6169     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6170       // Don't insert two casts if they cannot be eliminated.  We allow 
6171       // two casts to be inserted if the sizes are the same.  This could 
6172       // only be converting signedness, which is a noop.
6173       if (DestBitSize == SrcBitSize || 
6174           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6175           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6176         Instruction::CastOps opcode = CI.getOpcode();
6177         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6178         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6179         return BinaryOperator::create(
6180             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6181       }
6182     }
6183
6184     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6185     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6186         SrcI->getOpcode() == Instruction::Xor &&
6187         Op1 == ConstantInt::getTrue() &&
6188         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6189       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6190       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6191     }
6192     break;
6193   case Instruction::SDiv:
6194   case Instruction::UDiv:
6195   case Instruction::SRem:
6196   case Instruction::URem:
6197     // If we are just changing the sign, rewrite.
6198     if (DestBitSize == SrcBitSize) {
6199       // Don't insert two casts if they cannot be eliminated.  We allow 
6200       // two casts to be inserted if the sizes are the same.  This could 
6201       // only be converting signedness, which is a noop.
6202       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6203           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6204         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6205                                               Op0, DestTy, SrcI);
6206         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6207                                               Op1, DestTy, SrcI);
6208         return BinaryOperator::create(
6209           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6210       }
6211     }
6212     break;
6213
6214   case Instruction::Shl:
6215     // Allow changing the sign of the source operand.  Do not allow 
6216     // changing the size of the shift, UNLESS the shift amount is a 
6217     // constant.  We must not change variable sized shifts to a smaller 
6218     // size, because it is undefined to shift more bits out than exist 
6219     // in the value.
6220     if (DestBitSize == SrcBitSize ||
6221         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6222       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6223           Instruction::BitCast : Instruction::Trunc);
6224       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6225       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6226       return BinaryOperator::createShl(Op0c, Op1c);
6227     }
6228     break;
6229   case Instruction::AShr:
6230     // If this is a signed shr, and if all bits shifted in are about to be
6231     // truncated off, turn it into an unsigned shr to allow greater
6232     // simplifications.
6233     if (DestBitSize < SrcBitSize &&
6234         isa<ConstantInt>(Op1)) {
6235       unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6236       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6237         // Insert the new logical shift right.
6238         return BinaryOperator::createLShr(Op0, Op1);
6239       }
6240     }
6241     break;
6242
6243   case Instruction::ICmp:
6244     // If we are just checking for a icmp eq of a single bit and casting it
6245     // to an integer, then shift the bit to the appropriate place and then
6246     // cast to integer to avoid the comparison.
6247     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6248       uint64_t Op1CV = Op1C->getZExtValue();
6249       // cast (X == 0) to int --> X^1      iff X has only the low bit set.
6250       // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6251       // cast (X == 1) to int --> X        iff X has only the low bit set.
6252       // cast (X == 2) to int --> X>>1     iff X has only the 2nd bit set.
6253       // cast (X != 0) to int --> X        iff X has only the low bit set.
6254       // cast (X != 0) to int --> X>>1     iff X has only the 2nd bit set.
6255       // cast (X != 1) to int --> X^1      iff X has only the low bit set.
6256       // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6257       if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6258         // If Op1C some other power of two, convert:
6259         uint64_t KnownZero, KnownOne;
6260         uint64_t TypeMask = Op1C->getType()->getBitMask();
6261         ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6262
6263         // This only works for EQ and NE
6264         ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6265         if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6266           break;
6267         
6268         if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6269           bool isNE = pred == ICmpInst::ICMP_NE;
6270           if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6271             // (X&4) == 2 --> false
6272             // (X&4) != 2 --> true
6273             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6274             Res = ConstantExpr::getZExt(Res, CI.getType());
6275             return ReplaceInstUsesWith(CI, Res);
6276           }
6277           
6278           unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6279           Value *In = Op0;
6280           if (ShiftAmt) {
6281             // Perform a logical shr by shiftamt.
6282             // Insert the shift to put the result in the low bit.
6283             In = InsertNewInstBefore(
6284               BinaryOperator::createLShr(In,
6285                                      ConstantInt::get(In->getType(), ShiftAmt),
6286                                      In->getName()+".lobit"), CI);
6287           }
6288           
6289           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6290             Constant *One = ConstantInt::get(In->getType(), 1);
6291             In = BinaryOperator::createXor(In, One, "tmp");
6292             InsertNewInstBefore(cast<Instruction>(In), CI);
6293           }
6294           
6295           if (CI.getType() == In->getType())
6296             return ReplaceInstUsesWith(CI, In);
6297           else
6298             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6299         }
6300       }
6301     }
6302     break;
6303   }
6304   return 0;
6305 }
6306
6307 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6308   if (Instruction *Result = commonIntCastTransforms(CI))
6309     return Result;
6310   
6311   Value *Src = CI.getOperand(0);
6312   const Type *Ty = CI.getType();
6313   unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6314   
6315   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6316     switch (SrcI->getOpcode()) {
6317     default: break;
6318     case Instruction::LShr:
6319       // We can shrink lshr to something smaller if we know the bits shifted in
6320       // are already zeros.
6321       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6322         unsigned ShAmt = ShAmtV->getZExtValue();
6323         
6324         // Get a mask for the bits shifting in.
6325         uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6326         Value* SrcIOp0 = SrcI->getOperand(0);
6327         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6328           if (ShAmt >= DestBitWidth)        // All zeros.
6329             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6330
6331           // Okay, we can shrink this.  Truncate the input, then return a new
6332           // shift.
6333           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6334           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6335                                        Ty, CI);
6336           return BinaryOperator::createLShr(V1, V2);
6337         }
6338       } else {     // This is a variable shr.
6339         
6340         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6341         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6342         // loop-invariant and CSE'd.
6343         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6344           Value *One = ConstantInt::get(SrcI->getType(), 1);
6345
6346           Value *V = InsertNewInstBefore(
6347               BinaryOperator::createShl(One, SrcI->getOperand(1),
6348                                      "tmp"), CI);
6349           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6350                                                             SrcI->getOperand(0),
6351                                                             "tmp"), CI);
6352           Value *Zero = Constant::getNullValue(V->getType());
6353           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6354         }
6355       }
6356       break;
6357     }
6358   }
6359   
6360   return 0;
6361 }
6362
6363 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6364   // If one of the common conversion will work ..
6365   if (Instruction *Result = commonIntCastTransforms(CI))
6366     return Result;
6367
6368   Value *Src = CI.getOperand(0);
6369
6370   // If this is a cast of a cast
6371   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6372     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6373     // types and if the sizes are just right we can convert this into a logical
6374     // 'and' which will be much cheaper than the pair of casts.
6375     if (isa<TruncInst>(CSrc)) {
6376       // Get the sizes of the types involved
6377       Value *A = CSrc->getOperand(0);
6378       unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6379       unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6380       unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6381       // If we're actually extending zero bits and the trunc is a no-op
6382       if (MidSize < DstSize && SrcSize == DstSize) {
6383         // Replace both of the casts with an And of the type mask.
6384         uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
6385         Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6386         Instruction *And = 
6387           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6388         // Unfortunately, if the type changed, we need to cast it back.
6389         if (And->getType() != CI.getType()) {
6390           And->setName(CSrc->getName()+".mask");
6391           InsertNewInstBefore(And, CI);
6392           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6393         }
6394         return And;
6395       }
6396     }
6397   }
6398
6399   return 0;
6400 }
6401
6402 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6403   return commonIntCastTransforms(CI);
6404 }
6405
6406 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6407   return commonCastTransforms(CI);
6408 }
6409
6410 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6411   return commonCastTransforms(CI);
6412 }
6413
6414 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6415   return commonCastTransforms(CI);
6416 }
6417
6418 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6419   return commonCastTransforms(CI);
6420 }
6421
6422 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6423   return commonCastTransforms(CI);
6424 }
6425
6426 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6427   return commonCastTransforms(CI);
6428 }
6429
6430 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6431   return commonCastTransforms(CI);
6432 }
6433
6434 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6435   return commonCastTransforms(CI);
6436 }
6437
6438 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6439
6440   // If the operands are integer typed then apply the integer transforms,
6441   // otherwise just apply the common ones.
6442   Value *Src = CI.getOperand(0);
6443   const Type *SrcTy = Src->getType();
6444   const Type *DestTy = CI.getType();
6445
6446   if (SrcTy->isInteger() && DestTy->isInteger()) {
6447     if (Instruction *Result = commonIntCastTransforms(CI))
6448       return Result;
6449   } else {
6450     if (Instruction *Result = commonCastTransforms(CI))
6451       return Result;
6452   }
6453
6454
6455   // Get rid of casts from one type to the same type. These are useless and can
6456   // be replaced by the operand.
6457   if (DestTy == Src->getType())
6458     return ReplaceInstUsesWith(CI, Src);
6459
6460   // If the source and destination are pointers, and this cast is equivalent to
6461   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
6462   // This can enhance SROA and other transforms that want type-safe pointers.
6463   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6464     if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6465       const Type *DstElTy = DstPTy->getElementType();
6466       const Type *SrcElTy = SrcPTy->getElementType();
6467       
6468       Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6469       unsigned NumZeros = 0;
6470       while (SrcElTy != DstElTy && 
6471              isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6472              SrcElTy->getNumContainedTypes() /* not "{}" */) {
6473         SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6474         ++NumZeros;
6475       }
6476
6477       // If we found a path from the src to dest, create the getelementptr now.
6478       if (SrcElTy == DstElTy) {
6479         SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6480         return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6481       }
6482     }
6483   }
6484
6485   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6486     if (SVI->hasOneUse()) {
6487       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
6488       // a bitconvert to a vector with the same # elts.
6489       if (isa<VectorType>(DestTy) && 
6490           cast<VectorType>(DestTy)->getNumElements() == 
6491                 SVI->getType()->getNumElements()) {
6492         CastInst *Tmp;
6493         // If either of the operands is a cast from CI.getType(), then
6494         // evaluating the shuffle in the casted destination's type will allow
6495         // us to eliminate at least one cast.
6496         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
6497              Tmp->getOperand(0)->getType() == DestTy) ||
6498             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
6499              Tmp->getOperand(0)->getType() == DestTy)) {
6500           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6501                                                SVI->getOperand(0), DestTy, &CI);
6502           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6503                                                SVI->getOperand(1), DestTy, &CI);
6504           // Return a new shuffle vector.  Use the same element ID's, as we
6505           // know the vector types match #elts.
6506           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6507         }
6508       }
6509     }
6510   }
6511   return 0;
6512 }
6513
6514 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6515 ///   %C = or %A, %B
6516 ///   %D = select %cond, %C, %A
6517 /// into:
6518 ///   %C = select %cond, %B, 0
6519 ///   %D = or %A, %C
6520 ///
6521 /// Assuming that the specified instruction is an operand to the select, return
6522 /// a bitmask indicating which operands of this instruction are foldable if they
6523 /// equal the other incoming value of the select.
6524 ///
6525 static unsigned GetSelectFoldableOperands(Instruction *I) {
6526   switch (I->getOpcode()) {
6527   case Instruction::Add:
6528   case Instruction::Mul:
6529   case Instruction::And:
6530   case Instruction::Or:
6531   case Instruction::Xor:
6532     return 3;              // Can fold through either operand.
6533   case Instruction::Sub:   // Can only fold on the amount subtracted.
6534   case Instruction::Shl:   // Can only fold on the shift amount.
6535   case Instruction::LShr:
6536   case Instruction::AShr:
6537     return 1;
6538   default:
6539     return 0;              // Cannot fold
6540   }
6541 }
6542
6543 /// GetSelectFoldableConstant - For the same transformation as the previous
6544 /// function, return the identity constant that goes into the select.
6545 static Constant *GetSelectFoldableConstant(Instruction *I) {
6546   switch (I->getOpcode()) {
6547   default: assert(0 && "This cannot happen!"); abort();
6548   case Instruction::Add:
6549   case Instruction::Sub:
6550   case Instruction::Or:
6551   case Instruction::Xor:
6552   case Instruction::Shl:
6553   case Instruction::LShr:
6554   case Instruction::AShr:
6555     return Constant::getNullValue(I->getType());
6556   case Instruction::And:
6557     return ConstantInt::getAllOnesValue(I->getType());
6558   case Instruction::Mul:
6559     return ConstantInt::get(I->getType(), 1);
6560   }
6561 }
6562
6563 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6564 /// have the same opcode and only one use each.  Try to simplify this.
6565 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6566                                           Instruction *FI) {
6567   if (TI->getNumOperands() == 1) {
6568     // If this is a non-volatile load or a cast from the same type,
6569     // merge.
6570     if (TI->isCast()) {
6571       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6572         return 0;
6573     } else {
6574       return 0;  // unknown unary op.
6575     }
6576
6577     // Fold this by inserting a select from the input values.
6578     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6579                                        FI->getOperand(0), SI.getName()+".v");
6580     InsertNewInstBefore(NewSI, SI);
6581     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
6582                             TI->getType());
6583   }
6584
6585   // Only handle binary operators here.
6586   if (!isa<BinaryOperator>(TI))
6587     return 0;
6588
6589   // Figure out if the operations have any operands in common.
6590   Value *MatchOp, *OtherOpT, *OtherOpF;
6591   bool MatchIsOpZero;
6592   if (TI->getOperand(0) == FI->getOperand(0)) {
6593     MatchOp  = TI->getOperand(0);
6594     OtherOpT = TI->getOperand(1);
6595     OtherOpF = FI->getOperand(1);
6596     MatchIsOpZero = true;
6597   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6598     MatchOp  = TI->getOperand(1);
6599     OtherOpT = TI->getOperand(0);
6600     OtherOpF = FI->getOperand(0);
6601     MatchIsOpZero = false;
6602   } else if (!TI->isCommutative()) {
6603     return 0;
6604   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6605     MatchOp  = TI->getOperand(0);
6606     OtherOpT = TI->getOperand(1);
6607     OtherOpF = FI->getOperand(0);
6608     MatchIsOpZero = true;
6609   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6610     MatchOp  = TI->getOperand(1);
6611     OtherOpT = TI->getOperand(0);
6612     OtherOpF = FI->getOperand(1);
6613     MatchIsOpZero = true;
6614   } else {
6615     return 0;
6616   }
6617
6618   // If we reach here, they do have operations in common.
6619   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6620                                      OtherOpF, SI.getName()+".v");
6621   InsertNewInstBefore(NewSI, SI);
6622
6623   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6624     if (MatchIsOpZero)
6625       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6626     else
6627       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6628   }
6629   assert(0 && "Shouldn't get here");
6630   return 0;
6631 }
6632
6633 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6634   Value *CondVal = SI.getCondition();
6635   Value *TrueVal = SI.getTrueValue();
6636   Value *FalseVal = SI.getFalseValue();
6637
6638   // select true, X, Y  -> X
6639   // select false, X, Y -> Y
6640   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6641     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6642
6643   // select C, X, X -> X
6644   if (TrueVal == FalseVal)
6645     return ReplaceInstUsesWith(SI, TrueVal);
6646
6647   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6648     return ReplaceInstUsesWith(SI, FalseVal);
6649   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6650     return ReplaceInstUsesWith(SI, TrueVal);
6651   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6652     if (isa<Constant>(TrueVal))
6653       return ReplaceInstUsesWith(SI, TrueVal);
6654     else
6655       return ReplaceInstUsesWith(SI, FalseVal);
6656   }
6657
6658   if (SI.getType() == Type::Int1Ty) {
6659     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6660       if (C->getZExtValue()) {
6661         // Change: A = select B, true, C --> A = or B, C
6662         return BinaryOperator::createOr(CondVal, FalseVal);
6663       } else {
6664         // Change: A = select B, false, C --> A = and !B, C
6665         Value *NotCond =
6666           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6667                                              "not."+CondVal->getName()), SI);
6668         return BinaryOperator::createAnd(NotCond, FalseVal);
6669       }
6670     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6671       if (C->getZExtValue() == false) {
6672         // Change: A = select B, C, false --> A = and B, C
6673         return BinaryOperator::createAnd(CondVal, TrueVal);
6674       } else {
6675         // Change: A = select B, C, true --> A = or !B, C
6676         Value *NotCond =
6677           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6678                                              "not."+CondVal->getName()), SI);
6679         return BinaryOperator::createOr(NotCond, TrueVal);
6680       }
6681     }
6682   }
6683
6684   // Selecting between two integer constants?
6685   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6686     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6687       // select C, 1, 0 -> cast C to int
6688       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6689         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6690       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6691         // select C, 0, 1 -> cast !C to int
6692         Value *NotCond =
6693           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6694                                                "not."+CondVal->getName()), SI);
6695         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6696       }
6697
6698       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6699
6700         // (x <s 0) ? -1 : 0 -> ashr x, 31
6701         // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6702         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6703           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6704             bool CanXForm = false;
6705             if (IC->isSignedPredicate())
6706               CanXForm = CmpCst->isNullValue() && 
6707                          IC->getPredicate() == ICmpInst::ICMP_SLT;
6708             else {
6709               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6710               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6711                          IC->getPredicate() == ICmpInst::ICMP_UGT;
6712             }
6713             
6714             if (CanXForm) {
6715               // The comparison constant and the result are not neccessarily the
6716               // same width. Make an all-ones value by inserting a AShr.
6717               Value *X = IC->getOperand(0);
6718               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6719               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
6720               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
6721                                                         ShAmt, "ones");
6722               InsertNewInstBefore(SRA, SI);
6723               
6724               // Finally, convert to the type of the select RHS.  We figure out
6725               // if this requires a SExt, Trunc or BitCast based on the sizes.
6726               Instruction::CastOps opc = Instruction::BitCast;
6727               unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6728               unsigned SISize  = SI.getType()->getPrimitiveSizeInBits();
6729               if (SRASize < SISize)
6730                 opc = Instruction::SExt;
6731               else if (SRASize > SISize)
6732                 opc = Instruction::Trunc;
6733               return CastInst::create(opc, SRA, SI.getType());
6734             }
6735           }
6736
6737
6738         // If one of the constants is zero (we know they can't both be) and we
6739         // have a fcmp instruction with zero, and we have an 'and' with the
6740         // non-constant value, eliminate this whole mess.  This corresponds to
6741         // cases like this: ((X & 27) ? 27 : 0)
6742         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6743           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6744               cast<Constant>(IC->getOperand(1))->isNullValue())
6745             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6746               if (ICA->getOpcode() == Instruction::And &&
6747                   isa<ConstantInt>(ICA->getOperand(1)) &&
6748                   (ICA->getOperand(1) == TrueValC ||
6749                    ICA->getOperand(1) == FalseValC) &&
6750                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6751                 // Okay, now we know that everything is set up, we just don't
6752                 // know whether we have a icmp_ne or icmp_eq and whether the 
6753                 // true or false val is the zero.
6754                 bool ShouldNotVal = !TrueValC->isNullValue();
6755                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6756                 Value *V = ICA;
6757                 if (ShouldNotVal)
6758                   V = InsertNewInstBefore(BinaryOperator::create(
6759                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6760                 return ReplaceInstUsesWith(SI, V);
6761               }
6762       }
6763     }
6764
6765   // See if we are selecting two values based on a comparison of the two values.
6766   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6767     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6768       // Transform (X == Y) ? X : Y  -> Y
6769       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6770         return ReplaceInstUsesWith(SI, FalseVal);
6771       // Transform (X != Y) ? X : Y  -> X
6772       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6773         return ReplaceInstUsesWith(SI, TrueVal);
6774       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6775
6776     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6777       // Transform (X == Y) ? Y : X  -> X
6778       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6779         return ReplaceInstUsesWith(SI, FalseVal);
6780       // Transform (X != Y) ? Y : X  -> Y
6781       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6782         return ReplaceInstUsesWith(SI, TrueVal);
6783       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6784     }
6785   }
6786
6787   // See if we are selecting two values based on a comparison of the two values.
6788   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6789     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6790       // Transform (X == Y) ? X : Y  -> Y
6791       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6792         return ReplaceInstUsesWith(SI, FalseVal);
6793       // Transform (X != Y) ? X : Y  -> X
6794       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6795         return ReplaceInstUsesWith(SI, TrueVal);
6796       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6797
6798     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6799       // Transform (X == Y) ? Y : X  -> X
6800       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6801         return ReplaceInstUsesWith(SI, FalseVal);
6802       // Transform (X != Y) ? Y : X  -> Y
6803       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6804         return ReplaceInstUsesWith(SI, TrueVal);
6805       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6806     }
6807   }
6808
6809   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6810     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6811       if (TI->hasOneUse() && FI->hasOneUse()) {
6812         Instruction *AddOp = 0, *SubOp = 0;
6813
6814         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6815         if (TI->getOpcode() == FI->getOpcode())
6816           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6817             return IV;
6818
6819         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6820         // even legal for FP.
6821         if (TI->getOpcode() == Instruction::Sub &&
6822             FI->getOpcode() == Instruction::Add) {
6823           AddOp = FI; SubOp = TI;
6824         } else if (FI->getOpcode() == Instruction::Sub &&
6825                    TI->getOpcode() == Instruction::Add) {
6826           AddOp = TI; SubOp = FI;
6827         }
6828
6829         if (AddOp) {
6830           Value *OtherAddOp = 0;
6831           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6832             OtherAddOp = AddOp->getOperand(1);
6833           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6834             OtherAddOp = AddOp->getOperand(0);
6835           }
6836
6837           if (OtherAddOp) {
6838             // So at this point we know we have (Y -> OtherAddOp):
6839             //        select C, (add X, Y), (sub X, Z)
6840             Value *NegVal;  // Compute -Z
6841             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6842               NegVal = ConstantExpr::getNeg(C);
6843             } else {
6844               NegVal = InsertNewInstBefore(
6845                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6846             }
6847
6848             Value *NewTrueOp = OtherAddOp;
6849             Value *NewFalseOp = NegVal;
6850             if (AddOp != TI)
6851               std::swap(NewTrueOp, NewFalseOp);
6852             Instruction *NewSel =
6853               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6854
6855             NewSel = InsertNewInstBefore(NewSel, SI);
6856             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6857           }
6858         }
6859       }
6860
6861   // See if we can fold the select into one of our operands.
6862   if (SI.getType()->isInteger()) {
6863     // See the comment above GetSelectFoldableOperands for a description of the
6864     // transformation we are doing here.
6865     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6866       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6867           !isa<Constant>(FalseVal))
6868         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6869           unsigned OpToFold = 0;
6870           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6871             OpToFold = 1;
6872           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6873             OpToFold = 2;
6874           }
6875
6876           if (OpToFold) {
6877             Constant *C = GetSelectFoldableConstant(TVI);
6878             Instruction *NewSel =
6879               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
6880             InsertNewInstBefore(NewSel, SI);
6881             NewSel->takeName(TVI);
6882             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6883               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6884             else {
6885               assert(0 && "Unknown instruction!!");
6886             }
6887           }
6888         }
6889
6890     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6891       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6892           !isa<Constant>(TrueVal))
6893         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6894           unsigned OpToFold = 0;
6895           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6896             OpToFold = 1;
6897           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6898             OpToFold = 2;
6899           }
6900
6901           if (OpToFold) {
6902             Constant *C = GetSelectFoldableConstant(FVI);
6903             Instruction *NewSel =
6904               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
6905             InsertNewInstBefore(NewSel, SI);
6906             NewSel->takeName(FVI);
6907             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6908               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6909             else
6910               assert(0 && "Unknown instruction!!");
6911           }
6912         }
6913   }
6914
6915   if (BinaryOperator::isNot(CondVal)) {
6916     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6917     SI.setOperand(1, FalseVal);
6918     SI.setOperand(2, TrueVal);
6919     return &SI;
6920   }
6921
6922   return 0;
6923 }
6924
6925 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6926 /// determine, return it, otherwise return 0.
6927 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6928   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6929     unsigned Align = GV->getAlignment();
6930     if (Align == 0 && TD) 
6931       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
6932     return Align;
6933   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6934     unsigned Align = AI->getAlignment();
6935     if (Align == 0 && TD) {
6936       if (isa<AllocaInst>(AI))
6937         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
6938       else if (isa<MallocInst>(AI)) {
6939         // Malloc returns maximally aligned memory.
6940         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
6941         Align =
6942           std::max(Align,
6943                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
6944         Align =
6945           std::max(Align,
6946                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
6947       }
6948     }
6949     return Align;
6950   } else if (isa<BitCastInst>(V) ||
6951              (isa<ConstantExpr>(V) && 
6952               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6953     User *CI = cast<User>(V);
6954     if (isa<PointerType>(CI->getOperand(0)->getType()))
6955       return GetKnownAlignment(CI->getOperand(0), TD);
6956     return 0;
6957   } else if (isa<GetElementPtrInst>(V) ||
6958              (isa<ConstantExpr>(V) && 
6959               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6960     User *GEPI = cast<User>(V);
6961     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6962     if (BaseAlignment == 0) return 0;
6963     
6964     // If all indexes are zero, it is just the alignment of the base pointer.
6965     bool AllZeroOperands = true;
6966     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6967       if (!isa<Constant>(GEPI->getOperand(i)) ||
6968           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6969         AllZeroOperands = false;
6970         break;
6971       }
6972     if (AllZeroOperands)
6973       return BaseAlignment;
6974     
6975     // Otherwise, if the base alignment is >= the alignment we expect for the
6976     // base pointer type, then we know that the resultant pointer is aligned at
6977     // least as much as its type requires.
6978     if (!TD) return 0;
6979
6980     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6981     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
6982     if (TD->getABITypeAlignment(PtrTy->getElementType())
6983         <= BaseAlignment) {
6984       const Type *GEPTy = GEPI->getType();
6985       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
6986       return TD->getABITypeAlignment(GEPPtrTy->getElementType());
6987     }
6988     return 0;
6989   }
6990   return 0;
6991 }
6992
6993
6994 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6995 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6996 /// the heavy lifting.
6997 ///
6998 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6999   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7000   if (!II) return visitCallSite(&CI);
7001   
7002   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7003   // visitCallSite.
7004   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7005     bool Changed = false;
7006
7007     // memmove/cpy/set of zero bytes is a noop.
7008     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7009       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7010
7011       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7012         if (CI->getZExtValue() == 1) {
7013           // Replace the instruction with just byte operations.  We would
7014           // transform other cases to loads/stores, but we don't know if
7015           // alignment is sufficient.
7016         }
7017     }
7018
7019     // If we have a memmove and the source operation is a constant global,
7020     // then the source and dest pointers can't alias, so we can change this
7021     // into a call to memcpy.
7022     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7023       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7024         if (GVSrc->isConstant()) {
7025           Module *M = CI.getParent()->getParent()->getParent();
7026           const char *Name;
7027           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7028               Type::Int32Ty)
7029             Name = "llvm.memcpy.i32";
7030           else
7031             Name = "llvm.memcpy.i64";
7032           Constant *MemCpy = M->getOrInsertFunction(Name,
7033                                      CI.getCalledFunction()->getFunctionType());
7034           CI.setOperand(0, MemCpy);
7035           Changed = true;
7036         }
7037     }
7038
7039     // If we can determine a pointer alignment that is bigger than currently
7040     // set, update the alignment.
7041     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7042       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7043       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7044       unsigned Align = std::min(Alignment1, Alignment2);
7045       if (MI->getAlignment()->getZExtValue() < Align) {
7046         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7047         Changed = true;
7048       }
7049     } else if (isa<MemSetInst>(MI)) {
7050       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7051       if (MI->getAlignment()->getZExtValue() < Alignment) {
7052         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7053         Changed = true;
7054       }
7055     }
7056           
7057     if (Changed) return II;
7058   } else {
7059     switch (II->getIntrinsicID()) {
7060     default: break;
7061     case Intrinsic::ppc_altivec_lvx:
7062     case Intrinsic::ppc_altivec_lvxl:
7063     case Intrinsic::x86_sse_loadu_ps:
7064     case Intrinsic::x86_sse2_loadu_pd:
7065     case Intrinsic::x86_sse2_loadu_dq:
7066       // Turn PPC lvx     -> load if the pointer is known aligned.
7067       // Turn X86 loadups -> load if the pointer is known aligned.
7068       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7069         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7070                                       PointerType::get(II->getType()), CI);
7071         return new LoadInst(Ptr);
7072       }
7073       break;
7074     case Intrinsic::ppc_altivec_stvx:
7075     case Intrinsic::ppc_altivec_stvxl:
7076       // Turn stvx -> store if the pointer is known aligned.
7077       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7078         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7079         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7080                                       OpPtrTy, CI);
7081         return new StoreInst(II->getOperand(1), Ptr);
7082       }
7083       break;
7084     case Intrinsic::x86_sse_storeu_ps:
7085     case Intrinsic::x86_sse2_storeu_pd:
7086     case Intrinsic::x86_sse2_storeu_dq:
7087     case Intrinsic::x86_sse2_storel_dq:
7088       // Turn X86 storeu -> store if the pointer is known aligned.
7089       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7090         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7091         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7092                                       OpPtrTy, CI);
7093         return new StoreInst(II->getOperand(2), Ptr);
7094       }
7095       break;
7096       
7097     case Intrinsic::x86_sse_cvttss2si: {
7098       // These intrinsics only demands the 0th element of its input vector.  If
7099       // we can simplify the input based on that, do so now.
7100       uint64_t UndefElts;
7101       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7102                                                 UndefElts)) {
7103         II->setOperand(1, V);
7104         return II;
7105       }
7106       break;
7107     }
7108       
7109     case Intrinsic::ppc_altivec_vperm:
7110       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7111       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7112         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7113         
7114         // Check that all of the elements are integer constants or undefs.
7115         bool AllEltsOk = true;
7116         for (unsigned i = 0; i != 16; ++i) {
7117           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7118               !isa<UndefValue>(Mask->getOperand(i))) {
7119             AllEltsOk = false;
7120             break;
7121           }
7122         }
7123         
7124         if (AllEltsOk) {
7125           // Cast the input vectors to byte vectors.
7126           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7127                                         II->getOperand(1), Mask->getType(), CI);
7128           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7129                                         II->getOperand(2), Mask->getType(), CI);
7130           Value *Result = UndefValue::get(Op0->getType());
7131           
7132           // Only extract each element once.
7133           Value *ExtractedElts[32];
7134           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7135           
7136           for (unsigned i = 0; i != 16; ++i) {
7137             if (isa<UndefValue>(Mask->getOperand(i)))
7138               continue;
7139             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7140             Idx &= 31;  // Match the hardware behavior.
7141             
7142             if (ExtractedElts[Idx] == 0) {
7143               Instruction *Elt = 
7144                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7145               InsertNewInstBefore(Elt, CI);
7146               ExtractedElts[Idx] = Elt;
7147             }
7148           
7149             // Insert this value into the result vector.
7150             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7151             InsertNewInstBefore(cast<Instruction>(Result), CI);
7152           }
7153           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7154         }
7155       }
7156       break;
7157
7158     case Intrinsic::stackrestore: {
7159       // If the save is right next to the restore, remove the restore.  This can
7160       // happen when variable allocas are DCE'd.
7161       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7162         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7163           BasicBlock::iterator BI = SS;
7164           if (&*++BI == II)
7165             return EraseInstFromFunction(CI);
7166         }
7167       }
7168       
7169       // If the stack restore is in a return/unwind block and if there are no
7170       // allocas or calls between the restore and the return, nuke the restore.
7171       TerminatorInst *TI = II->getParent()->getTerminator();
7172       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7173         BasicBlock::iterator BI = II;
7174         bool CannotRemove = false;
7175         for (++BI; &*BI != TI; ++BI) {
7176           if (isa<AllocaInst>(BI) ||
7177               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7178             CannotRemove = true;
7179             break;
7180           }
7181         }
7182         if (!CannotRemove)
7183           return EraseInstFromFunction(CI);
7184       }
7185       break;
7186     }
7187     }
7188   }
7189
7190   return visitCallSite(II);
7191 }
7192
7193 // InvokeInst simplification
7194 //
7195 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7196   return visitCallSite(&II);
7197 }
7198
7199 // visitCallSite - Improvements for call and invoke instructions.
7200 //
7201 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7202   bool Changed = false;
7203
7204   // If the callee is a constexpr cast of a function, attempt to move the cast
7205   // to the arguments of the call/invoke.
7206   if (transformConstExprCastCall(CS)) return 0;
7207
7208   Value *Callee = CS.getCalledValue();
7209
7210   if (Function *CalleeF = dyn_cast<Function>(Callee))
7211     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7212       Instruction *OldCall = CS.getInstruction();
7213       // If the call and callee calling conventions don't match, this call must
7214       // be unreachable, as the call is undefined.
7215       new StoreInst(ConstantInt::getTrue(),
7216                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7217       if (!OldCall->use_empty())
7218         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7219       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7220         return EraseInstFromFunction(*OldCall);
7221       return 0;
7222     }
7223
7224   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7225     // This instruction is not reachable, just remove it.  We insert a store to
7226     // undef so that we know that this code is not reachable, despite the fact
7227     // that we can't modify the CFG here.
7228     new StoreInst(ConstantInt::getTrue(),
7229                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7230                   CS.getInstruction());
7231
7232     if (!CS.getInstruction()->use_empty())
7233       CS.getInstruction()->
7234         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7235
7236     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7237       // Don't break the CFG, insert a dummy cond branch.
7238       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7239                      ConstantInt::getTrue(), II);
7240     }
7241     return EraseInstFromFunction(*CS.getInstruction());
7242   }
7243
7244   const PointerType *PTy = cast<PointerType>(Callee->getType());
7245   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7246   if (FTy->isVarArg()) {
7247     // See if we can optimize any arguments passed through the varargs area of
7248     // the call.
7249     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7250            E = CS.arg_end(); I != E; ++I)
7251       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7252         // If this cast does not effect the value passed through the varargs
7253         // area, we can eliminate the use of the cast.
7254         Value *Op = CI->getOperand(0);
7255         if (CI->isLosslessCast()) {
7256           *I = Op;
7257           Changed = true;
7258         }
7259       }
7260   }
7261
7262   return Changed ? CS.getInstruction() : 0;
7263 }
7264
7265 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7266 // attempt to move the cast to the arguments of the call/invoke.
7267 //
7268 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7269   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7270   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7271   if (CE->getOpcode() != Instruction::BitCast || 
7272       !isa<Function>(CE->getOperand(0)))
7273     return false;
7274   Function *Callee = cast<Function>(CE->getOperand(0));
7275   Instruction *Caller = CS.getInstruction();
7276
7277   // Okay, this is a cast from a function to a different type.  Unless doing so
7278   // would cause a type conversion of one of our arguments, change this call to
7279   // be a direct call with arguments casted to the appropriate types.
7280   //
7281   const FunctionType *FT = Callee->getFunctionType();
7282   const Type *OldRetTy = Caller->getType();
7283
7284   // Check to see if we are changing the return type...
7285   if (OldRetTy != FT->getReturnType()) {
7286     if (Callee->isDeclaration() && !Caller->use_empty() && 
7287         OldRetTy != FT->getReturnType() &&
7288         // Conversion is ok if changing from pointer to int of same size.
7289         !(isa<PointerType>(FT->getReturnType()) &&
7290           TD->getIntPtrType() == OldRetTy))
7291       return false;   // Cannot transform this return value.
7292
7293     // If the callsite is an invoke instruction, and the return value is used by
7294     // a PHI node in a successor, we cannot change the return type of the call
7295     // because there is no place to put the cast instruction (without breaking
7296     // the critical edge).  Bail out in this case.
7297     if (!Caller->use_empty())
7298       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7299         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7300              UI != E; ++UI)
7301           if (PHINode *PN = dyn_cast<PHINode>(*UI))
7302             if (PN->getParent() == II->getNormalDest() ||
7303                 PN->getParent() == II->getUnwindDest())
7304               return false;
7305   }
7306
7307   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7308   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7309
7310   CallSite::arg_iterator AI = CS.arg_begin();
7311   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7312     const Type *ParamTy = FT->getParamType(i);
7313     const Type *ActTy = (*AI)->getType();
7314     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7315     //Either we can cast directly, or we can upconvert the argument
7316     bool isConvertible = ActTy == ParamTy ||
7317       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7318       (ParamTy->isInteger() && ActTy->isInteger() &&
7319        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7320       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7321        && c->getSExtValue() > 0);
7322     if (Callee->isDeclaration() && !isConvertible) return false;
7323   }
7324
7325   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7326       Callee->isDeclaration())
7327     return false;   // Do not delete arguments unless we have a function body...
7328
7329   // Okay, we decided that this is a safe thing to do: go ahead and start
7330   // inserting cast instructions as necessary...
7331   std::vector<Value*> Args;
7332   Args.reserve(NumActualArgs);
7333
7334   AI = CS.arg_begin();
7335   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7336     const Type *ParamTy = FT->getParamType(i);
7337     if ((*AI)->getType() == ParamTy) {
7338       Args.push_back(*AI);
7339     } else {
7340       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7341           false, ParamTy, false);
7342       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7343       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7344     }
7345   }
7346
7347   // If the function takes more arguments than the call was taking, add them
7348   // now...
7349   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7350     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7351
7352   // If we are removing arguments to the function, emit an obnoxious warning...
7353   if (FT->getNumParams() < NumActualArgs)
7354     if (!FT->isVarArg()) {
7355       cerr << "WARNING: While resolving call to function '"
7356            << Callee->getName() << "' arguments were dropped!\n";
7357     } else {
7358       // Add all of the arguments in their promoted form to the arg list...
7359       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7360         const Type *PTy = getPromotedType((*AI)->getType());
7361         if (PTy != (*AI)->getType()) {
7362           // Must promote to pass through va_arg area!
7363           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
7364                                                                 PTy, false);
7365           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7366           InsertNewInstBefore(Cast, *Caller);
7367           Args.push_back(Cast);
7368         } else {
7369           Args.push_back(*AI);
7370         }
7371       }
7372     }
7373
7374   if (FT->getReturnType() == Type::VoidTy)
7375     Caller->setName("");   // Void type should not have a name.
7376
7377   Instruction *NC;
7378   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7379     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7380                         &Args[0], Args.size(), Caller->getName(), Caller);
7381     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7382   } else {
7383     NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
7384     if (cast<CallInst>(Caller)->isTailCall())
7385       cast<CallInst>(NC)->setTailCall();
7386    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7387   }
7388
7389   // Insert a cast of the return type as necessary.
7390   Value *NV = NC;
7391   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7392     if (NV->getType() != Type::VoidTy) {
7393       const Type *CallerTy = Caller->getType();
7394       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
7395                                                             CallerTy, false);
7396       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7397
7398       // If this is an invoke instruction, we should insert it after the first
7399       // non-phi, instruction in the normal successor block.
7400       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7401         BasicBlock::iterator I = II->getNormalDest()->begin();
7402         while (isa<PHINode>(I)) ++I;
7403         InsertNewInstBefore(NC, *I);
7404       } else {
7405         // Otherwise, it's a call, just insert cast right after the call instr
7406         InsertNewInstBefore(NC, *Caller);
7407       }
7408       AddUsersToWorkList(*Caller);
7409     } else {
7410       NV = UndefValue::get(Caller->getType());
7411     }
7412   }
7413
7414   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7415     Caller->replaceAllUsesWith(NV);
7416   Caller->eraseFromParent();
7417   RemoveFromWorkList(Caller);
7418   return true;
7419 }
7420
7421 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7422 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7423 /// and a single binop.
7424 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7425   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7426   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7427          isa<CmpInst>(FirstInst));
7428   unsigned Opc = FirstInst->getOpcode();
7429   Value *LHSVal = FirstInst->getOperand(0);
7430   Value *RHSVal = FirstInst->getOperand(1);
7431     
7432   const Type *LHSType = LHSVal->getType();
7433   const Type *RHSType = RHSVal->getType();
7434   
7435   // Scan to see if all operands are the same opcode, all have one use, and all
7436   // kill their operands (i.e. the operands have one use).
7437   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7438     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7439     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7440         // Verify type of the LHS matches so we don't fold cmp's of different
7441         // types or GEP's with different index types.
7442         I->getOperand(0)->getType() != LHSType ||
7443         I->getOperand(1)->getType() != RHSType)
7444       return 0;
7445
7446     // If they are CmpInst instructions, check their predicates
7447     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7448       if (cast<CmpInst>(I)->getPredicate() !=
7449           cast<CmpInst>(FirstInst)->getPredicate())
7450         return 0;
7451     
7452     // Keep track of which operand needs a phi node.
7453     if (I->getOperand(0) != LHSVal) LHSVal = 0;
7454     if (I->getOperand(1) != RHSVal) RHSVal = 0;
7455   }
7456   
7457   // Otherwise, this is safe to transform, determine if it is profitable.
7458
7459   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7460   // Indexes are often folded into load/store instructions, so we don't want to
7461   // hide them behind a phi.
7462   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7463     return 0;
7464   
7465   Value *InLHS = FirstInst->getOperand(0);
7466   Value *InRHS = FirstInst->getOperand(1);
7467   PHINode *NewLHS = 0, *NewRHS = 0;
7468   if (LHSVal == 0) {
7469     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7470     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7471     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7472     InsertNewInstBefore(NewLHS, PN);
7473     LHSVal = NewLHS;
7474   }
7475   
7476   if (RHSVal == 0) {
7477     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7478     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7479     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7480     InsertNewInstBefore(NewRHS, PN);
7481     RHSVal = NewRHS;
7482   }
7483   
7484   // Add all operands to the new PHIs.
7485   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7486     if (NewLHS) {
7487       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7488       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7489     }
7490     if (NewRHS) {
7491       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7492       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7493     }
7494   }
7495     
7496   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7497     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7498   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7499     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
7500                            RHSVal);
7501   else {
7502     assert(isa<GetElementPtrInst>(FirstInst));
7503     return new GetElementPtrInst(LHSVal, RHSVal);
7504   }
7505 }
7506
7507 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7508 /// of the block that defines it.  This means that it must be obvious the value
7509 /// of the load is not changed from the point of the load to the end of the
7510 /// block it is in.
7511 ///
7512 /// Finally, it is safe, but not profitable, to sink a load targetting a
7513 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
7514 /// to a register.
7515 static bool isSafeToSinkLoad(LoadInst *L) {
7516   BasicBlock::iterator BBI = L, E = L->getParent()->end();
7517   
7518   for (++BBI; BBI != E; ++BBI)
7519     if (BBI->mayWriteToMemory())
7520       return false;
7521   
7522   // Check for non-address taken alloca.  If not address-taken already, it isn't
7523   // profitable to do this xform.
7524   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7525     bool isAddressTaken = false;
7526     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7527          UI != E; ++UI) {
7528       if (isa<LoadInst>(UI)) continue;
7529       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7530         // If storing TO the alloca, then the address isn't taken.
7531         if (SI->getOperand(1) == AI) continue;
7532       }
7533       isAddressTaken = true;
7534       break;
7535     }
7536     
7537     if (!isAddressTaken)
7538       return false;
7539   }
7540   
7541   return true;
7542 }
7543
7544
7545 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7546 // operator and they all are only used by the PHI, PHI together their
7547 // inputs, and do the operation once, to the result of the PHI.
7548 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7549   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7550
7551   // Scan the instruction, looking for input operations that can be folded away.
7552   // If all input operands to the phi are the same instruction (e.g. a cast from
7553   // the same type or "+42") we can pull the operation through the PHI, reducing
7554   // code size and simplifying code.
7555   Constant *ConstantOp = 0;
7556   const Type *CastSrcTy = 0;
7557   bool isVolatile = false;
7558   if (isa<CastInst>(FirstInst)) {
7559     CastSrcTy = FirstInst->getOperand(0)->getType();
7560   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
7561     // Can fold binop, compare or shift here if the RHS is a constant, 
7562     // otherwise call FoldPHIArgBinOpIntoPHI.
7563     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7564     if (ConstantOp == 0)
7565       return FoldPHIArgBinOpIntoPHI(PN);
7566   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7567     isVolatile = LI->isVolatile();
7568     // We can't sink the load if the loaded value could be modified between the
7569     // load and the PHI.
7570     if (LI->getParent() != PN.getIncomingBlock(0) ||
7571         !isSafeToSinkLoad(LI))
7572       return 0;
7573   } else if (isa<GetElementPtrInst>(FirstInst)) {
7574     if (FirstInst->getNumOperands() == 2)
7575       return FoldPHIArgBinOpIntoPHI(PN);
7576     // Can't handle general GEPs yet.
7577     return 0;
7578   } else {
7579     return 0;  // Cannot fold this operation.
7580   }
7581
7582   // Check to see if all arguments are the same operation.
7583   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7584     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7585     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7586     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7587       return 0;
7588     if (CastSrcTy) {
7589       if (I->getOperand(0)->getType() != CastSrcTy)
7590         return 0;  // Cast operation must match.
7591     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7592       // We can't sink the load if the loaded value could be modified between 
7593       // the load and the PHI.
7594       if (LI->isVolatile() != isVolatile ||
7595           LI->getParent() != PN.getIncomingBlock(i) ||
7596           !isSafeToSinkLoad(LI))
7597         return 0;
7598     } else if (I->getOperand(1) != ConstantOp) {
7599       return 0;
7600     }
7601   }
7602
7603   // Okay, they are all the same operation.  Create a new PHI node of the
7604   // correct type, and PHI together all of the LHS's of the instructions.
7605   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7606                                PN.getName()+".in");
7607   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7608
7609   Value *InVal = FirstInst->getOperand(0);
7610   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7611
7612   // Add all operands to the new PHI.
7613   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7614     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7615     if (NewInVal != InVal)
7616       InVal = 0;
7617     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7618   }
7619
7620   Value *PhiVal;
7621   if (InVal) {
7622     // The new PHI unions all of the same values together.  This is really
7623     // common, so we handle it intelligently here for compile-time speed.
7624     PhiVal = InVal;
7625     delete NewPN;
7626   } else {
7627     InsertNewInstBefore(NewPN, PN);
7628     PhiVal = NewPN;
7629   }
7630
7631   // Insert and return the new operation.
7632   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7633     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7634   else if (isa<LoadInst>(FirstInst))
7635     return new LoadInst(PhiVal, "", isVolatile);
7636   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7637     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7638   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7639     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
7640                            PhiVal, ConstantOp);
7641   else
7642     assert(0 && "Unknown operation");
7643 }
7644
7645 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7646 /// that is dead.
7647 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7648   if (PN->use_empty()) return true;
7649   if (!PN->hasOneUse()) return false;
7650
7651   // Remember this node, and if we find the cycle, return.
7652   if (!PotentiallyDeadPHIs.insert(PN).second)
7653     return true;
7654
7655   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7656     return DeadPHICycle(PU, PotentiallyDeadPHIs);
7657
7658   return false;
7659 }
7660
7661 // PHINode simplification
7662 //
7663 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7664   // If LCSSA is around, don't mess with Phi nodes
7665   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7666   
7667   if (Value *V = PN.hasConstantValue())
7668     return ReplaceInstUsesWith(PN, V);
7669
7670   // If all PHI operands are the same operation, pull them through the PHI,
7671   // reducing code size.
7672   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7673       PN.getIncomingValue(0)->hasOneUse())
7674     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7675       return Result;
7676
7677   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7678   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7679   // PHI)... break the cycle.
7680   if (PN.hasOneUse()) {
7681     Instruction *PHIUser = cast<Instruction>(PN.use_back());
7682     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7683       std::set<PHINode*> PotentiallyDeadPHIs;
7684       PotentiallyDeadPHIs.insert(&PN);
7685       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7686         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7687     }
7688    
7689     // If this phi has a single use, and if that use just computes a value for
7690     // the next iteration of a loop, delete the phi.  This occurs with unused
7691     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
7692     // common case here is good because the only other things that catch this
7693     // are induction variable analysis (sometimes) and ADCE, which is only run
7694     // late.
7695     if (PHIUser->hasOneUse() &&
7696         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7697         PHIUser->use_back() == &PN) {
7698       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7699     }
7700   }
7701
7702   return 0;
7703 }
7704
7705 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7706                                    Instruction *InsertPoint,
7707                                    InstCombiner *IC) {
7708   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7709   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7710   // We must cast correctly to the pointer type. Ensure that we
7711   // sign extend the integer value if it is smaller as this is
7712   // used for address computation.
7713   Instruction::CastOps opcode = 
7714      (VTySize < PtrSize ? Instruction::SExt :
7715       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7716   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7717 }
7718
7719
7720 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7721   Value *PtrOp = GEP.getOperand(0);
7722   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7723   // If so, eliminate the noop.
7724   if (GEP.getNumOperands() == 1)
7725     return ReplaceInstUsesWith(GEP, PtrOp);
7726
7727   if (isa<UndefValue>(GEP.getOperand(0)))
7728     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7729
7730   bool HasZeroPointerIndex = false;
7731   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7732     HasZeroPointerIndex = C->isNullValue();
7733
7734   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7735     return ReplaceInstUsesWith(GEP, PtrOp);
7736
7737   // Eliminate unneeded casts for indices.
7738   bool MadeChange = false;
7739   gep_type_iterator GTI = gep_type_begin(GEP);
7740   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7741     if (isa<SequentialType>(*GTI)) {
7742       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7743         if (CI->getOpcode() == Instruction::ZExt ||
7744             CI->getOpcode() == Instruction::SExt) {
7745           const Type *SrcTy = CI->getOperand(0)->getType();
7746           // We can eliminate a cast from i32 to i64 iff the target 
7747           // is a 32-bit pointer target.
7748           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7749             MadeChange = true;
7750             GEP.setOperand(i, CI->getOperand(0));
7751           }
7752         }
7753       }
7754       // If we are using a wider index than needed for this platform, shrink it
7755       // to what we need.  If the incoming value needs a cast instruction,
7756       // insert it.  This explicit cast can make subsequent optimizations more
7757       // obvious.
7758       Value *Op = GEP.getOperand(i);
7759       if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7760         if (Constant *C = dyn_cast<Constant>(Op)) {
7761           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7762           MadeChange = true;
7763         } else {
7764           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7765                                 GEP);
7766           GEP.setOperand(i, Op);
7767           MadeChange = true;
7768         }
7769     }
7770   if (MadeChange) return &GEP;
7771
7772   // Combine Indices - If the source pointer to this getelementptr instruction
7773   // is a getelementptr instruction, combine the indices of the two
7774   // getelementptr instructions into a single instruction.
7775   //
7776   SmallVector<Value*, 8> SrcGEPOperands;
7777   if (User *Src = dyn_castGetElementPtr(PtrOp))
7778     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
7779
7780   if (!SrcGEPOperands.empty()) {
7781     // Note that if our source is a gep chain itself that we wait for that
7782     // chain to be resolved before we perform this transformation.  This
7783     // avoids us creating a TON of code in some cases.
7784     //
7785     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7786         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7787       return 0;   // Wait until our source is folded to completion.
7788
7789     SmallVector<Value*, 8> Indices;
7790
7791     // Find out whether the last index in the source GEP is a sequential idx.
7792     bool EndsWithSequential = false;
7793     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7794            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7795       EndsWithSequential = !isa<StructType>(*I);
7796
7797     // Can we combine the two pointer arithmetics offsets?
7798     if (EndsWithSequential) {
7799       // Replace: gep (gep %P, long B), long A, ...
7800       // With:    T = long A+B; gep %P, T, ...
7801       //
7802       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7803       if (SO1 == Constant::getNullValue(SO1->getType())) {
7804         Sum = GO1;
7805       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7806         Sum = SO1;
7807       } else {
7808         // If they aren't the same type, convert both to an integer of the
7809         // target's pointer size.
7810         if (SO1->getType() != GO1->getType()) {
7811           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7812             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7813           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7814             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7815           } else {
7816             unsigned PS = TD->getPointerSize();
7817             if (TD->getTypeSize(SO1->getType()) == PS) {
7818               // Convert GO1 to SO1's type.
7819               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7820
7821             } else if (TD->getTypeSize(GO1->getType()) == PS) {
7822               // Convert SO1 to GO1's type.
7823               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7824             } else {
7825               const Type *PT = TD->getIntPtrType();
7826               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7827               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7828             }
7829           }
7830         }
7831         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7832           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7833         else {
7834           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7835           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7836         }
7837       }
7838
7839       // Recycle the GEP we already have if possible.
7840       if (SrcGEPOperands.size() == 2) {
7841         GEP.setOperand(0, SrcGEPOperands[0]);
7842         GEP.setOperand(1, Sum);
7843         return &GEP;
7844       } else {
7845         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7846                        SrcGEPOperands.end()-1);
7847         Indices.push_back(Sum);
7848         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7849       }
7850     } else if (isa<Constant>(*GEP.idx_begin()) &&
7851                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7852                SrcGEPOperands.size() != 1) {
7853       // Otherwise we can do the fold if the first index of the GEP is a zero
7854       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7855                      SrcGEPOperands.end());
7856       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7857     }
7858
7859     if (!Indices.empty())
7860       return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
7861                                    Indices.size(), GEP.getName());
7862
7863   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7864     // GEP of global variable.  If all of the indices for this GEP are
7865     // constants, we can promote this to a constexpr instead of an instruction.
7866
7867     // Scan for nonconstants...
7868     SmallVector<Constant*, 8> Indices;
7869     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7870     for (; I != E && isa<Constant>(*I); ++I)
7871       Indices.push_back(cast<Constant>(*I));
7872
7873     if (I == E) {  // If they are all constants...
7874       Constant *CE = ConstantExpr::getGetElementPtr(GV,
7875                                                     &Indices[0],Indices.size());
7876
7877       // Replace all uses of the GEP with the new constexpr...
7878       return ReplaceInstUsesWith(GEP, CE);
7879     }
7880   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
7881     if (!isa<PointerType>(X->getType())) {
7882       // Not interesting.  Source pointer must be a cast from pointer.
7883     } else if (HasZeroPointerIndex) {
7884       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7885       // into     : GEP [10 x ubyte]* X, long 0, ...
7886       //
7887       // This occurs when the program declares an array extern like "int X[];"
7888       //
7889       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7890       const PointerType *XTy = cast<PointerType>(X->getType());
7891       if (const ArrayType *XATy =
7892           dyn_cast<ArrayType>(XTy->getElementType()))
7893         if (const ArrayType *CATy =
7894             dyn_cast<ArrayType>(CPTy->getElementType()))
7895           if (CATy->getElementType() == XATy->getElementType()) {
7896             // At this point, we know that the cast source type is a pointer
7897             // to an array of the same type as the destination pointer
7898             // array.  Because the array type is never stepped over (there
7899             // is a leading zero) we can fold the cast into this GEP.
7900             GEP.setOperand(0, X);
7901             return &GEP;
7902           }
7903     } else if (GEP.getNumOperands() == 2) {
7904       // Transform things like:
7905       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7906       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7907       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7908       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7909       if (isa<ArrayType>(SrcElTy) &&
7910           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7911           TD->getTypeSize(ResElTy)) {
7912         Value *V = InsertNewInstBefore(
7913                new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7914                                      GEP.getOperand(1), GEP.getName()), GEP);
7915         // V and GEP are both pointer types --> BitCast
7916         return new BitCastInst(V, GEP.getType());
7917       }
7918       
7919       // Transform things like:
7920       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7921       //   (where tmp = 8*tmp2) into:
7922       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7923       
7924       if (isa<ArrayType>(SrcElTy) &&
7925           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7926         uint64_t ArrayEltSize =
7927             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7928         
7929         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7930         // allow either a mul, shift, or constant here.
7931         Value *NewIdx = 0;
7932         ConstantInt *Scale = 0;
7933         if (ArrayEltSize == 1) {
7934           NewIdx = GEP.getOperand(1);
7935           Scale = ConstantInt::get(NewIdx->getType(), 1);
7936         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7937           NewIdx = ConstantInt::get(CI->getType(), 1);
7938           Scale = CI;
7939         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7940           if (Inst->getOpcode() == Instruction::Shl &&
7941               isa<ConstantInt>(Inst->getOperand(1))) {
7942             unsigned ShAmt =
7943               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7944             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7945             NewIdx = Inst->getOperand(0);
7946           } else if (Inst->getOpcode() == Instruction::Mul &&
7947                      isa<ConstantInt>(Inst->getOperand(1))) {
7948             Scale = cast<ConstantInt>(Inst->getOperand(1));
7949             NewIdx = Inst->getOperand(0);
7950           }
7951         }
7952
7953         // If the index will be to exactly the right offset with the scale taken
7954         // out, perform the transformation.
7955         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7956           if (isa<ConstantInt>(Scale))
7957             Scale = ConstantInt::get(Scale->getType(),
7958                                       Scale->getZExtValue() / ArrayEltSize);
7959           if (Scale->getZExtValue() != 1) {
7960             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7961                                                        true /*SExt*/);
7962             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7963             NewIdx = InsertNewInstBefore(Sc, GEP);
7964           }
7965
7966           // Insert the new GEP instruction.
7967           Instruction *NewGEP =
7968             new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7969                                   NewIdx, GEP.getName());
7970           NewGEP = InsertNewInstBefore(NewGEP, GEP);
7971           // The NewGEP must be pointer typed, so must the old one -> BitCast
7972           return new BitCastInst(NewGEP, GEP.getType());
7973         }
7974       }
7975     }
7976   }
7977
7978   return 0;
7979 }
7980
7981 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7982   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7983   if (AI.isArrayAllocation())    // Check C != 1
7984     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7985       const Type *NewTy = 
7986         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7987       AllocationInst *New = 0;
7988
7989       // Create and insert the replacement instruction...
7990       if (isa<MallocInst>(AI))
7991         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7992       else {
7993         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7994         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7995       }
7996
7997       InsertNewInstBefore(New, AI);
7998
7999       // Scan to the end of the allocation instructions, to skip over a block of
8000       // allocas if possible...
8001       //
8002       BasicBlock::iterator It = New;
8003       while (isa<AllocationInst>(*It)) ++It;
8004
8005       // Now that I is pointing to the first non-allocation-inst in the block,
8006       // insert our getelementptr instruction...
8007       //
8008       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8009       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8010                                        New->getName()+".sub", It);
8011
8012       // Now make everything use the getelementptr instead of the original
8013       // allocation.
8014       return ReplaceInstUsesWith(AI, V);
8015     } else if (isa<UndefValue>(AI.getArraySize())) {
8016       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8017     }
8018
8019   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8020   // Note that we only do this for alloca's, because malloc should allocate and
8021   // return a unique pointer, even for a zero byte allocation.
8022   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8023       TD->getTypeSize(AI.getAllocatedType()) == 0)
8024     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8025
8026   return 0;
8027 }
8028
8029 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8030   Value *Op = FI.getOperand(0);
8031
8032   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8033   if (CastInst *CI = dyn_cast<CastInst>(Op))
8034     if (isa<PointerType>(CI->getOperand(0)->getType())) {
8035       FI.setOperand(0, CI->getOperand(0));
8036       return &FI;
8037     }
8038
8039   // free undef -> unreachable.
8040   if (isa<UndefValue>(Op)) {
8041     // Insert a new store to null because we cannot modify the CFG here.
8042     new StoreInst(ConstantInt::getTrue(),
8043                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8044     return EraseInstFromFunction(FI);
8045   }
8046
8047   // If we have 'free null' delete the instruction.  This can happen in stl code
8048   // when lots of inlining happens.
8049   if (isa<ConstantPointerNull>(Op))
8050     return EraseInstFromFunction(FI);
8051
8052   return 0;
8053 }
8054
8055
8056 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8057 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8058   User *CI = cast<User>(LI.getOperand(0));
8059   Value *CastOp = CI->getOperand(0);
8060
8061   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8062   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8063     const Type *SrcPTy = SrcTy->getElementType();
8064
8065     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
8066          isa<VectorType>(DestPTy)) {
8067       // If the source is an array, the code below will not succeed.  Check to
8068       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8069       // constants.
8070       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8071         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8072           if (ASrcTy->getNumElements() != 0) {
8073             Value *Idxs[2];
8074             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8075             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8076             SrcTy = cast<PointerType>(CastOp->getType());
8077             SrcPTy = SrcTy->getElementType();
8078           }
8079
8080       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
8081             isa<VectorType>(SrcPTy)) &&
8082           // Do not allow turning this into a load of an integer, which is then
8083           // casted to a pointer, this pessimizes pointer analysis a lot.
8084           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8085           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8086                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8087
8088         // Okay, we are casting from one integer or pointer type to another of
8089         // the same size.  Instead of casting the pointer before the load, cast
8090         // the result of the loaded value.
8091         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8092                                                              CI->getName(),
8093                                                          LI.isVolatile()),LI);
8094         // Now cast the result of the load.
8095         return new BitCastInst(NewLoad, LI.getType());
8096       }
8097     }
8098   }
8099   return 0;
8100 }
8101
8102 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8103 /// from this value cannot trap.  If it is not obviously safe to load from the
8104 /// specified pointer, we do a quick local scan of the basic block containing
8105 /// ScanFrom, to determine if the address is already accessed.
8106 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8107   // If it is an alloca or global variable, it is always safe to load from.
8108   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8109
8110   // Otherwise, be a little bit agressive by scanning the local block where we
8111   // want to check to see if the pointer is already being loaded or stored
8112   // from/to.  If so, the previous load or store would have already trapped,
8113   // so there is no harm doing an extra load (also, CSE will later eliminate
8114   // the load entirely).
8115   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8116
8117   while (BBI != E) {
8118     --BBI;
8119
8120     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8121       if (LI->getOperand(0) == V) return true;
8122     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8123       if (SI->getOperand(1) == V) return true;
8124
8125   }
8126   return false;
8127 }
8128
8129 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8130   Value *Op = LI.getOperand(0);
8131
8132   // load (cast X) --> cast (load X) iff safe
8133   if (isa<CastInst>(Op))
8134     if (Instruction *Res = InstCombineLoadCast(*this, LI))
8135       return Res;
8136
8137   // None of the following transforms are legal for volatile loads.
8138   if (LI.isVolatile()) return 0;
8139   
8140   if (&LI.getParent()->front() != &LI) {
8141     BasicBlock::iterator BBI = &LI; --BBI;
8142     // If the instruction immediately before this is a store to the same
8143     // address, do a simple form of store->load forwarding.
8144     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8145       if (SI->getOperand(1) == LI.getOperand(0))
8146         return ReplaceInstUsesWith(LI, SI->getOperand(0));
8147     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8148       if (LIB->getOperand(0) == LI.getOperand(0))
8149         return ReplaceInstUsesWith(LI, LIB);
8150   }
8151
8152   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8153     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8154         isa<UndefValue>(GEPI->getOperand(0))) {
8155       // Insert a new store to null instruction before the load to indicate
8156       // that this code is not reachable.  We do this instead of inserting
8157       // an unreachable instruction directly because we cannot modify the
8158       // CFG.
8159       new StoreInst(UndefValue::get(LI.getType()),
8160                     Constant::getNullValue(Op->getType()), &LI);
8161       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8162     }
8163
8164   if (Constant *C = dyn_cast<Constant>(Op)) {
8165     // load null/undef -> undef
8166     if ((C->isNullValue() || isa<UndefValue>(C))) {
8167       // Insert a new store to null instruction before the load to indicate that
8168       // this code is not reachable.  We do this instead of inserting an
8169       // unreachable instruction directly because we cannot modify the CFG.
8170       new StoreInst(UndefValue::get(LI.getType()),
8171                     Constant::getNullValue(Op->getType()), &LI);
8172       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8173     }
8174
8175     // Instcombine load (constant global) into the value loaded.
8176     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8177       if (GV->isConstant() && !GV->isDeclaration())
8178         return ReplaceInstUsesWith(LI, GV->getInitializer());
8179
8180     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8181     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8182       if (CE->getOpcode() == Instruction::GetElementPtr) {
8183         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8184           if (GV->isConstant() && !GV->isDeclaration())
8185             if (Constant *V = 
8186                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8187               return ReplaceInstUsesWith(LI, V);
8188         if (CE->getOperand(0)->isNullValue()) {
8189           // Insert a new store to null instruction before the load to indicate
8190           // that this code is not reachable.  We do this instead of inserting
8191           // an unreachable instruction directly because we cannot modify the
8192           // CFG.
8193           new StoreInst(UndefValue::get(LI.getType()),
8194                         Constant::getNullValue(Op->getType()), &LI);
8195           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8196         }
8197
8198       } else if (CE->isCast()) {
8199         if (Instruction *Res = InstCombineLoadCast(*this, LI))
8200           return Res;
8201       }
8202   }
8203
8204   if (Op->hasOneUse()) {
8205     // Change select and PHI nodes to select values instead of addresses: this
8206     // helps alias analysis out a lot, allows many others simplifications, and
8207     // exposes redundancy in the code.
8208     //
8209     // Note that we cannot do the transformation unless we know that the
8210     // introduced loads cannot trap!  Something like this is valid as long as
8211     // the condition is always false: load (select bool %C, int* null, int* %G),
8212     // but it would not be valid if we transformed it to load from null
8213     // unconditionally.
8214     //
8215     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8216       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
8217       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8218           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8219         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8220                                      SI->getOperand(1)->getName()+".val"), LI);
8221         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8222                                      SI->getOperand(2)->getName()+".val"), LI);
8223         return new SelectInst(SI->getCondition(), V1, V2);
8224       }
8225
8226       // load (select (cond, null, P)) -> load P
8227       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8228         if (C->isNullValue()) {
8229           LI.setOperand(0, SI->getOperand(2));
8230           return &LI;
8231         }
8232
8233       // load (select (cond, P, null)) -> load P
8234       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8235         if (C->isNullValue()) {
8236           LI.setOperand(0, SI->getOperand(1));
8237           return &LI;
8238         }
8239     }
8240   }
8241   return 0;
8242 }
8243
8244 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8245 /// when possible.
8246 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8247   User *CI = cast<User>(SI.getOperand(1));
8248   Value *CastOp = CI->getOperand(0);
8249
8250   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8251   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8252     const Type *SrcPTy = SrcTy->getElementType();
8253
8254     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8255       // If the source is an array, the code below will not succeed.  Check to
8256       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
8257       // constants.
8258       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8259         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8260           if (ASrcTy->getNumElements() != 0) {
8261             Value* Idxs[2];
8262             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8263             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8264             SrcTy = cast<PointerType>(CastOp->getType());
8265             SrcPTy = SrcTy->getElementType();
8266           }
8267
8268       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8269           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8270                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8271
8272         // Okay, we are casting from one integer or pointer type to another of
8273         // the same size.  Instead of casting the pointer before 
8274         // the store, cast the value to be stored.
8275         Value *NewCast;
8276         Value *SIOp0 = SI.getOperand(0);
8277         Instruction::CastOps opcode = Instruction::BitCast;
8278         const Type* CastSrcTy = SIOp0->getType();
8279         const Type* CastDstTy = SrcPTy;
8280         if (isa<PointerType>(CastDstTy)) {
8281           if (CastSrcTy->isInteger())
8282             opcode = Instruction::IntToPtr;
8283         } else if (isa<IntegerType>(CastDstTy)) {
8284           if (isa<PointerType>(SIOp0->getType()))
8285             opcode = Instruction::PtrToInt;
8286         }
8287         if (Constant *C = dyn_cast<Constant>(SIOp0))
8288           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8289         else
8290           NewCast = IC.InsertNewInstBefore(
8291             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
8292             SI);
8293         return new StoreInst(NewCast, CastOp);
8294       }
8295     }
8296   }
8297   return 0;
8298 }
8299
8300 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8301   Value *Val = SI.getOperand(0);
8302   Value *Ptr = SI.getOperand(1);
8303
8304   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
8305     EraseInstFromFunction(SI);
8306     ++NumCombined;
8307     return 0;
8308   }
8309   
8310   // If the RHS is an alloca with a single use, zapify the store, making the
8311   // alloca dead.
8312   if (Ptr->hasOneUse()) {
8313     if (isa<AllocaInst>(Ptr)) {
8314       EraseInstFromFunction(SI);
8315       ++NumCombined;
8316       return 0;
8317     }
8318     
8319     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8320       if (isa<AllocaInst>(GEP->getOperand(0)) &&
8321           GEP->getOperand(0)->hasOneUse()) {
8322         EraseInstFromFunction(SI);
8323         ++NumCombined;
8324         return 0;
8325       }
8326   }
8327
8328   // Do really simple DSE, to catch cases where there are several consequtive
8329   // stores to the same location, separated by a few arithmetic operations. This
8330   // situation often occurs with bitfield accesses.
8331   BasicBlock::iterator BBI = &SI;
8332   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8333        --ScanInsts) {
8334     --BBI;
8335     
8336     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8337       // Prev store isn't volatile, and stores to the same location?
8338       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8339         ++NumDeadStore;
8340         ++BBI;
8341         EraseInstFromFunction(*PrevSI);
8342         continue;
8343       }
8344       break;
8345     }
8346     
8347     // If this is a load, we have to stop.  However, if the loaded value is from
8348     // the pointer we're loading and is producing the pointer we're storing,
8349     // then *this* store is dead (X = load P; store X -> P).
8350     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8351       if (LI == Val && LI->getOperand(0) == Ptr) {
8352         EraseInstFromFunction(SI);
8353         ++NumCombined;
8354         return 0;
8355       }
8356       // Otherwise, this is a load from some other location.  Stores before it
8357       // may not be dead.
8358       break;
8359     }
8360     
8361     // Don't skip over loads or things that can modify memory.
8362     if (BBI->mayWriteToMemory())
8363       break;
8364   }
8365   
8366   
8367   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
8368
8369   // store X, null    -> turns into 'unreachable' in SimplifyCFG
8370   if (isa<ConstantPointerNull>(Ptr)) {
8371     if (!isa<UndefValue>(Val)) {
8372       SI.setOperand(0, UndefValue::get(Val->getType()));
8373       if (Instruction *U = dyn_cast<Instruction>(Val))
8374         AddToWorkList(U);  // Dropped a use.
8375       ++NumCombined;
8376     }
8377     return 0;  // Do not modify these!
8378   }
8379
8380   // store undef, Ptr -> noop
8381   if (isa<UndefValue>(Val)) {
8382     EraseInstFromFunction(SI);
8383     ++NumCombined;
8384     return 0;
8385   }
8386
8387   // If the pointer destination is a cast, see if we can fold the cast into the
8388   // source instead.
8389   if (isa<CastInst>(Ptr))
8390     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8391       return Res;
8392   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8393     if (CE->isCast())
8394       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8395         return Res;
8396
8397   
8398   // If this store is the last instruction in the basic block, and if the block
8399   // ends with an unconditional branch, try to move it to the successor block.
8400   BBI = &SI; ++BBI;
8401   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8402     if (BI->isUnconditional()) {
8403       // Check to see if the successor block has exactly two incoming edges.  If
8404       // so, see if the other predecessor contains a store to the same location.
8405       // if so, insert a PHI node (if needed) and move the stores down.
8406       BasicBlock *Dest = BI->getSuccessor(0);
8407
8408       pred_iterator PI = pred_begin(Dest);
8409       BasicBlock *Other = 0;
8410       if (*PI != BI->getParent())
8411         Other = *PI;
8412       ++PI;
8413       if (PI != pred_end(Dest)) {
8414         if (*PI != BI->getParent())
8415           if (Other)
8416             Other = 0;
8417           else
8418             Other = *PI;
8419         if (++PI != pred_end(Dest))
8420           Other = 0;
8421       }
8422       if (Other) {  // If only one other pred...
8423         BBI = Other->getTerminator();
8424         // Make sure this other block ends in an unconditional branch and that
8425         // there is an instruction before the branch.
8426         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8427             BBI != Other->begin()) {
8428           --BBI;
8429           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8430           
8431           // If this instruction is a store to the same location.
8432           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8433             // Okay, we know we can perform this transformation.  Insert a PHI
8434             // node now if we need it.
8435             Value *MergedVal = OtherStore->getOperand(0);
8436             if (MergedVal != SI.getOperand(0)) {
8437               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8438               PN->reserveOperandSpace(2);
8439               PN->addIncoming(SI.getOperand(0), SI.getParent());
8440               PN->addIncoming(OtherStore->getOperand(0), Other);
8441               MergedVal = InsertNewInstBefore(PN, Dest->front());
8442             }
8443             
8444             // Advance to a place where it is safe to insert the new store and
8445             // insert it.
8446             BBI = Dest->begin();
8447             while (isa<PHINode>(BBI)) ++BBI;
8448             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8449                                               OtherStore->isVolatile()), *BBI);
8450
8451             // Nuke the old stores.
8452             EraseInstFromFunction(SI);
8453             EraseInstFromFunction(*OtherStore);
8454             ++NumCombined;
8455             return 0;
8456           }
8457         }
8458       }
8459     }
8460   
8461   return 0;
8462 }
8463
8464
8465 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8466   // Change br (not X), label True, label False to: br X, label False, True
8467   Value *X = 0;
8468   BasicBlock *TrueDest;
8469   BasicBlock *FalseDest;
8470   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8471       !isa<Constant>(X)) {
8472     // Swap Destinations and condition...
8473     BI.setCondition(X);
8474     BI.setSuccessor(0, FalseDest);
8475     BI.setSuccessor(1, TrueDest);
8476     return &BI;
8477   }
8478
8479   // Cannonicalize fcmp_one -> fcmp_oeq
8480   FCmpInst::Predicate FPred; Value *Y;
8481   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
8482                              TrueDest, FalseDest)))
8483     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8484          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8485       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8486       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8487       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8488       NewSCC->takeName(I);
8489       // Swap Destinations and condition...
8490       BI.setCondition(NewSCC);
8491       BI.setSuccessor(0, FalseDest);
8492       BI.setSuccessor(1, TrueDest);
8493       RemoveFromWorkList(I);
8494       I->eraseFromParent();
8495       AddToWorkList(NewSCC);
8496       return &BI;
8497     }
8498
8499   // Cannonicalize icmp_ne -> icmp_eq
8500   ICmpInst::Predicate IPred;
8501   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8502                       TrueDest, FalseDest)))
8503     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
8504          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8505          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8506       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8507       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8508       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8509       NewSCC->takeName(I);
8510       // Swap Destinations and condition...
8511       BI.setCondition(NewSCC);
8512       BI.setSuccessor(0, FalseDest);
8513       BI.setSuccessor(1, TrueDest);
8514       RemoveFromWorkList(I);
8515       I->eraseFromParent();;
8516       AddToWorkList(NewSCC);
8517       return &BI;
8518     }
8519
8520   return 0;
8521 }
8522
8523 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8524   Value *Cond = SI.getCondition();
8525   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8526     if (I->getOpcode() == Instruction::Add)
8527       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8528         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8529         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8530           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8531                                                 AddRHS));
8532         SI.setOperand(0, I->getOperand(0));
8533         AddToWorkList(I);
8534         return &SI;
8535       }
8536   }
8537   return 0;
8538 }
8539
8540 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8541 /// is to leave as a vector operation.
8542 static bool CheapToScalarize(Value *V, bool isConstant) {
8543   if (isa<ConstantAggregateZero>(V)) 
8544     return true;
8545   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
8546     if (isConstant) return true;
8547     // If all elts are the same, we can extract.
8548     Constant *Op0 = C->getOperand(0);
8549     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8550       if (C->getOperand(i) != Op0)
8551         return false;
8552     return true;
8553   }
8554   Instruction *I = dyn_cast<Instruction>(V);
8555   if (!I) return false;
8556   
8557   // Insert element gets simplified to the inserted element or is deleted if
8558   // this is constant idx extract element and its a constant idx insertelt.
8559   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8560       isa<ConstantInt>(I->getOperand(2)))
8561     return true;
8562   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8563     return true;
8564   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8565     if (BO->hasOneUse() &&
8566         (CheapToScalarize(BO->getOperand(0), isConstant) ||
8567          CheapToScalarize(BO->getOperand(1), isConstant)))
8568       return true;
8569   if (CmpInst *CI = dyn_cast<CmpInst>(I))
8570     if (CI->hasOneUse() &&
8571         (CheapToScalarize(CI->getOperand(0), isConstant) ||
8572          CheapToScalarize(CI->getOperand(1), isConstant)))
8573       return true;
8574   
8575   return false;
8576 }
8577
8578 /// Read and decode a shufflevector mask.
8579 ///
8580 /// It turns undef elements into values that are larger than the number of
8581 /// elements in the input.
8582 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8583   unsigned NElts = SVI->getType()->getNumElements();
8584   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8585     return std::vector<unsigned>(NElts, 0);
8586   if (isa<UndefValue>(SVI->getOperand(2)))
8587     return std::vector<unsigned>(NElts, 2*NElts);
8588
8589   std::vector<unsigned> Result;
8590   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
8591   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8592     if (isa<UndefValue>(CP->getOperand(i)))
8593       Result.push_back(NElts*2);  // undef -> 8
8594     else
8595       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8596   return Result;
8597 }
8598
8599 /// FindScalarElement - Given a vector and an element number, see if the scalar
8600 /// value is already around as a register, for example if it were inserted then
8601 /// extracted from the vector.
8602 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8603   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
8604   const VectorType *PTy = cast<VectorType>(V->getType());
8605   unsigned Width = PTy->getNumElements();
8606   if (EltNo >= Width)  // Out of range access.
8607     return UndefValue::get(PTy->getElementType());
8608   
8609   if (isa<UndefValue>(V))
8610     return UndefValue::get(PTy->getElementType());
8611   else if (isa<ConstantAggregateZero>(V))
8612     return Constant::getNullValue(PTy->getElementType());
8613   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
8614     return CP->getOperand(EltNo);
8615   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8616     // If this is an insert to a variable element, we don't know what it is.
8617     if (!isa<ConstantInt>(III->getOperand(2))) 
8618       return 0;
8619     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8620     
8621     // If this is an insert to the element we are looking for, return the
8622     // inserted value.
8623     if (EltNo == IIElt) 
8624       return III->getOperand(1);
8625     
8626     // Otherwise, the insertelement doesn't modify the value, recurse on its
8627     // vector input.
8628     return FindScalarElement(III->getOperand(0), EltNo);
8629   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8630     unsigned InEl = getShuffleMask(SVI)[EltNo];
8631     if (InEl < Width)
8632       return FindScalarElement(SVI->getOperand(0), InEl);
8633     else if (InEl < Width*2)
8634       return FindScalarElement(SVI->getOperand(1), InEl - Width);
8635     else
8636       return UndefValue::get(PTy->getElementType());
8637   }
8638   
8639   // Otherwise, we don't know.
8640   return 0;
8641 }
8642
8643 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8644
8645   // If packed val is undef, replace extract with scalar undef.
8646   if (isa<UndefValue>(EI.getOperand(0)))
8647     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8648
8649   // If packed val is constant 0, replace extract with scalar 0.
8650   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8651     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8652   
8653   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
8654     // If packed val is constant with uniform operands, replace EI
8655     // with that operand
8656     Constant *op0 = C->getOperand(0);
8657     for (unsigned i = 1; i < C->getNumOperands(); ++i)
8658       if (C->getOperand(i) != op0) {
8659         op0 = 0; 
8660         break;
8661       }
8662     if (op0)
8663       return ReplaceInstUsesWith(EI, op0);
8664   }
8665   
8666   // If extracting a specified index from the vector, see if we can recursively
8667   // find a previously computed scalar that was inserted into the vector.
8668   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8669     // This instruction only demands the single element from the input vector.
8670     // If the input vector has a single use, simplify it based on this use
8671     // property.
8672     uint64_t IndexVal = IdxC->getZExtValue();
8673     if (EI.getOperand(0)->hasOneUse()) {
8674       uint64_t UndefElts;
8675       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8676                                                 1 << IndexVal,
8677                                                 UndefElts)) {
8678         EI.setOperand(0, V);
8679         return &EI;
8680       }
8681     }
8682     
8683     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8684       return ReplaceInstUsesWith(EI, Elt);
8685   }
8686   
8687   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8688     if (I->hasOneUse()) {
8689       // Push extractelement into predecessor operation if legal and
8690       // profitable to do so
8691       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8692         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8693         if (CheapToScalarize(BO, isConstantElt)) {
8694           ExtractElementInst *newEI0 = 
8695             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8696                                    EI.getName()+".lhs");
8697           ExtractElementInst *newEI1 =
8698             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8699                                    EI.getName()+".rhs");
8700           InsertNewInstBefore(newEI0, EI);
8701           InsertNewInstBefore(newEI1, EI);
8702           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8703         }
8704       } else if (isa<LoadInst>(I)) {
8705         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8706                                       PointerType::get(EI.getType()), EI);
8707         GetElementPtrInst *GEP = 
8708           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8709         InsertNewInstBefore(GEP, EI);
8710         return new LoadInst(GEP);
8711       }
8712     }
8713     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8714       // Extracting the inserted element?
8715       if (IE->getOperand(2) == EI.getOperand(1))
8716         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8717       // If the inserted and extracted elements are constants, they must not
8718       // be the same value, extract from the pre-inserted value instead.
8719       if (isa<Constant>(IE->getOperand(2)) &&
8720           isa<Constant>(EI.getOperand(1))) {
8721         AddUsesToWorkList(EI);
8722         EI.setOperand(0, IE->getOperand(0));
8723         return &EI;
8724       }
8725     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8726       // If this is extracting an element from a shufflevector, figure out where
8727       // it came from and extract from the appropriate input element instead.
8728       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8729         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8730         Value *Src;
8731         if (SrcIdx < SVI->getType()->getNumElements())
8732           Src = SVI->getOperand(0);
8733         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8734           SrcIdx -= SVI->getType()->getNumElements();
8735           Src = SVI->getOperand(1);
8736         } else {
8737           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8738         }
8739         return new ExtractElementInst(Src, SrcIdx);
8740       }
8741     }
8742   }
8743   return 0;
8744 }
8745
8746 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8747 /// elements from either LHS or RHS, return the shuffle mask and true. 
8748 /// Otherwise, return false.
8749 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8750                                          std::vector<Constant*> &Mask) {
8751   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8752          "Invalid CollectSingleShuffleElements");
8753   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
8754
8755   if (isa<UndefValue>(V)) {
8756     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8757     return true;
8758   } else if (V == LHS) {
8759     for (unsigned i = 0; i != NumElts; ++i)
8760       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8761     return true;
8762   } else if (V == RHS) {
8763     for (unsigned i = 0; i != NumElts; ++i)
8764       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8765     return true;
8766   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8767     // If this is an insert of an extract from some other vector, include it.
8768     Value *VecOp    = IEI->getOperand(0);
8769     Value *ScalarOp = IEI->getOperand(1);
8770     Value *IdxOp    = IEI->getOperand(2);
8771     
8772     if (!isa<ConstantInt>(IdxOp))
8773       return false;
8774     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8775     
8776     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8777       // Okay, we can handle this if the vector we are insertinting into is
8778       // transitively ok.
8779       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8780         // If so, update the mask to reflect the inserted undef.
8781         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8782         return true;
8783       }      
8784     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8785       if (isa<ConstantInt>(EI->getOperand(1)) &&
8786           EI->getOperand(0)->getType() == V->getType()) {
8787         unsigned ExtractedIdx =
8788           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8789         
8790         // This must be extracting from either LHS or RHS.
8791         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8792           // Okay, we can handle this if the vector we are insertinting into is
8793           // transitively ok.
8794           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8795             // If so, update the mask to reflect the inserted value.
8796             if (EI->getOperand(0) == LHS) {
8797               Mask[InsertedIdx & (NumElts-1)] = 
8798                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8799             } else {
8800               assert(EI->getOperand(0) == RHS);
8801               Mask[InsertedIdx & (NumElts-1)] = 
8802                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8803               
8804             }
8805             return true;
8806           }
8807         }
8808       }
8809     }
8810   }
8811   // TODO: Handle shufflevector here!
8812   
8813   return false;
8814 }
8815
8816 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8817 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8818 /// that computes V and the LHS value of the shuffle.
8819 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8820                                      Value *&RHS) {
8821   assert(isa<VectorType>(V->getType()) && 
8822          (RHS == 0 || V->getType() == RHS->getType()) &&
8823          "Invalid shuffle!");
8824   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
8825
8826   if (isa<UndefValue>(V)) {
8827     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8828     return V;
8829   } else if (isa<ConstantAggregateZero>(V)) {
8830     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8831     return V;
8832   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8833     // If this is an insert of an extract from some other vector, include it.
8834     Value *VecOp    = IEI->getOperand(0);
8835     Value *ScalarOp = IEI->getOperand(1);
8836     Value *IdxOp    = IEI->getOperand(2);
8837     
8838     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8839       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8840           EI->getOperand(0)->getType() == V->getType()) {
8841         unsigned ExtractedIdx =
8842           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8843         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8844         
8845         // Either the extracted from or inserted into vector must be RHSVec,
8846         // otherwise we'd end up with a shuffle of three inputs.
8847         if (EI->getOperand(0) == RHS || RHS == 0) {
8848           RHS = EI->getOperand(0);
8849           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8850           Mask[InsertedIdx & (NumElts-1)] = 
8851             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8852           return V;
8853         }
8854         
8855         if (VecOp == RHS) {
8856           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8857           // Everything but the extracted element is replaced with the RHS.
8858           for (unsigned i = 0; i != NumElts; ++i) {
8859             if (i != InsertedIdx)
8860               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8861           }
8862           return V;
8863         }
8864         
8865         // If this insertelement is a chain that comes from exactly these two
8866         // vectors, return the vector and the effective shuffle.
8867         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8868           return EI->getOperand(0);
8869         
8870       }
8871     }
8872   }
8873   // TODO: Handle shufflevector here!
8874   
8875   // Otherwise, can't do anything fancy.  Return an identity vector.
8876   for (unsigned i = 0; i != NumElts; ++i)
8877     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8878   return V;
8879 }
8880
8881 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8882   Value *VecOp    = IE.getOperand(0);
8883   Value *ScalarOp = IE.getOperand(1);
8884   Value *IdxOp    = IE.getOperand(2);
8885   
8886   // If the inserted element was extracted from some other vector, and if the 
8887   // indexes are constant, try to turn this into a shufflevector operation.
8888   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8889     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8890         EI->getOperand(0)->getType() == IE.getType()) {
8891       unsigned NumVectorElts = IE.getType()->getNumElements();
8892       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8893       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8894       
8895       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8896         return ReplaceInstUsesWith(IE, VecOp);
8897       
8898       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8899         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8900       
8901       // If we are extracting a value from a vector, then inserting it right
8902       // back into the same place, just use the input vector.
8903       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8904         return ReplaceInstUsesWith(IE, VecOp);      
8905       
8906       // We could theoretically do this for ANY input.  However, doing so could
8907       // turn chains of insertelement instructions into a chain of shufflevector
8908       // instructions, and right now we do not merge shufflevectors.  As such,
8909       // only do this in a situation where it is clear that there is benefit.
8910       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8911         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8912         // the values of VecOp, except then one read from EIOp0.
8913         // Build a new shuffle mask.
8914         std::vector<Constant*> Mask;
8915         if (isa<UndefValue>(VecOp))
8916           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8917         else {
8918           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8919           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8920                                                        NumVectorElts));
8921         } 
8922         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8923         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8924                                      ConstantVector::get(Mask));
8925       }
8926       
8927       // If this insertelement isn't used by some other insertelement, turn it
8928       // (and any insertelements it points to), into one big shuffle.
8929       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8930         std::vector<Constant*> Mask;
8931         Value *RHS = 0;
8932         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8933         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8934         // We now have a shuffle of LHS, RHS, Mask.
8935         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
8936       }
8937     }
8938   }
8939
8940   return 0;
8941 }
8942
8943
8944 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8945   Value *LHS = SVI.getOperand(0);
8946   Value *RHS = SVI.getOperand(1);
8947   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8948
8949   bool MadeChange = false;
8950   
8951   // Undefined shuffle mask -> undefined value.
8952   if (isa<UndefValue>(SVI.getOperand(2)))
8953     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8954   
8955   // If we have shuffle(x, undef, mask) and any elements of mask refer to
8956   // the undef, change them to undefs.
8957   if (isa<UndefValue>(SVI.getOperand(1))) {
8958     // Scan to see if there are any references to the RHS.  If so, replace them
8959     // with undef element refs and set MadeChange to true.
8960     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8961       if (Mask[i] >= e && Mask[i] != 2*e) {
8962         Mask[i] = 2*e;
8963         MadeChange = true;
8964       }
8965     }
8966     
8967     if (MadeChange) {
8968       // Remap any references to RHS to use LHS.
8969       std::vector<Constant*> Elts;
8970       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8971         if (Mask[i] == 2*e)
8972           Elts.push_back(UndefValue::get(Type::Int32Ty));
8973         else
8974           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8975       }
8976       SVI.setOperand(2, ConstantVector::get(Elts));
8977     }
8978   }
8979   
8980   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8981   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8982   if (LHS == RHS || isa<UndefValue>(LHS)) {
8983     if (isa<UndefValue>(LHS) && LHS == RHS) {
8984       // shuffle(undef,undef,mask) -> undef.
8985       return ReplaceInstUsesWith(SVI, LHS);
8986     }
8987     
8988     // Remap any references to RHS to use LHS.
8989     std::vector<Constant*> Elts;
8990     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8991       if (Mask[i] >= 2*e)
8992         Elts.push_back(UndefValue::get(Type::Int32Ty));
8993       else {
8994         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8995             (Mask[i] <  e && isa<UndefValue>(LHS)))
8996           Mask[i] = 2*e;     // Turn into undef.
8997         else
8998           Mask[i] &= (e-1);  // Force to LHS.
8999         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9000       }
9001     }
9002     SVI.setOperand(0, SVI.getOperand(1));
9003     SVI.setOperand(1, UndefValue::get(RHS->getType()));
9004     SVI.setOperand(2, ConstantVector::get(Elts));
9005     LHS = SVI.getOperand(0);
9006     RHS = SVI.getOperand(1);
9007     MadeChange = true;
9008   }
9009   
9010   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9011   bool isLHSID = true, isRHSID = true;
9012     
9013   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9014     if (Mask[i] >= e*2) continue;  // Ignore undef values.
9015     // Is this an identity shuffle of the LHS value?
9016     isLHSID &= (Mask[i] == i);
9017       
9018     // Is this an identity shuffle of the RHS value?
9019     isRHSID &= (Mask[i]-e == i);
9020   }
9021
9022   // Eliminate identity shuffles.
9023   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9024   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9025   
9026   // If the LHS is a shufflevector itself, see if we can combine it with this
9027   // one without producing an unusual shuffle.  Here we are really conservative:
9028   // we are absolutely afraid of producing a shuffle mask not in the input
9029   // program, because the code gen may not be smart enough to turn a merged
9030   // shuffle into two specific shuffles: it may produce worse code.  As such,
9031   // we only merge two shuffles if the result is one of the two input shuffle
9032   // masks.  In this case, merging the shuffles just removes one instruction,
9033   // which we know is safe.  This is good for things like turning:
9034   // (splat(splat)) -> splat.
9035   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9036     if (isa<UndefValue>(RHS)) {
9037       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9038
9039       std::vector<unsigned> NewMask;
9040       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9041         if (Mask[i] >= 2*e)
9042           NewMask.push_back(2*e);
9043         else
9044           NewMask.push_back(LHSMask[Mask[i]]);
9045       
9046       // If the result mask is equal to the src shuffle or this shuffle mask, do
9047       // the replacement.
9048       if (NewMask == LHSMask || NewMask == Mask) {
9049         std::vector<Constant*> Elts;
9050         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9051           if (NewMask[i] >= e*2) {
9052             Elts.push_back(UndefValue::get(Type::Int32Ty));
9053           } else {
9054             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9055           }
9056         }
9057         return new ShuffleVectorInst(LHSSVI->getOperand(0),
9058                                      LHSSVI->getOperand(1),
9059                                      ConstantVector::get(Elts));
9060       }
9061     }
9062   }
9063
9064   return MadeChange ? &SVI : 0;
9065 }
9066
9067
9068
9069
9070 /// TryToSinkInstruction - Try to move the specified instruction from its
9071 /// current block into the beginning of DestBlock, which can only happen if it's
9072 /// safe to move the instruction past all of the instructions between it and the
9073 /// end of its block.
9074 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9075   assert(I->hasOneUse() && "Invariants didn't hold!");
9076
9077   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9078   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9079
9080   // Do not sink alloca instructions out of the entry block.
9081   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9082     return false;
9083
9084   // We can only sink load instructions if there is nothing between the load and
9085   // the end of block that could change the value.
9086   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9087     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9088          Scan != E; ++Scan)
9089       if (Scan->mayWriteToMemory())
9090         return false;
9091   }
9092
9093   BasicBlock::iterator InsertPos = DestBlock->begin();
9094   while (isa<PHINode>(InsertPos)) ++InsertPos;
9095
9096   I->moveBefore(InsertPos);
9097   ++NumSunkInst;
9098   return true;
9099 }
9100
9101
9102 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9103 /// all reachable code to the worklist.
9104 ///
9105 /// This has a couple of tricks to make the code faster and more powerful.  In
9106 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9107 /// them to the worklist (this significantly speeds up instcombine on code where
9108 /// many instructions are dead or constant).  Additionally, if we find a branch
9109 /// whose condition is a known constant, we only visit the reachable successors.
9110 ///
9111 static void AddReachableCodeToWorklist(BasicBlock *BB, 
9112                                        SmallPtrSet<BasicBlock*, 64> &Visited,
9113                                        InstCombiner &IC,
9114                                        const TargetData *TD) {
9115   // We have now visited this block!  If we've already been here, bail out.
9116   if (!Visited.insert(BB)) return;
9117     
9118   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9119     Instruction *Inst = BBI++;
9120     
9121     // DCE instruction if trivially dead.
9122     if (isInstructionTriviallyDead(Inst)) {
9123       ++NumDeadInst;
9124       DOUT << "IC: DCE: " << *Inst;
9125       Inst->eraseFromParent();
9126       continue;
9127     }
9128     
9129     // ConstantProp instruction if trivially constant.
9130     if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9131       DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9132       Inst->replaceAllUsesWith(C);
9133       ++NumConstProp;
9134       Inst->eraseFromParent();
9135       continue;
9136     }
9137     
9138     IC.AddToWorkList(Inst);
9139   }
9140
9141   // Recursively visit successors.  If this is a branch or switch on a constant,
9142   // only visit the reachable successor.
9143   TerminatorInst *TI = BB->getTerminator();
9144   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9145     if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9146       bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9147       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, IC, TD);
9148       return;
9149     }
9150   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9151     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9152       // See if this is an explicit destination.
9153       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9154         if (SI->getCaseValue(i) == Cond) {
9155           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, IC, TD);
9156           return;
9157         }
9158       
9159       // Otherwise it is the default destination.
9160       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, IC, TD);
9161       return;
9162     }
9163   }
9164   
9165   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9166     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, IC, TD);
9167 }
9168
9169 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
9170   bool Changed = false;
9171   TD = &getAnalysis<TargetData>();
9172   
9173   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9174              << F.getNameStr() << "\n");
9175
9176   {
9177     // Do a depth-first traversal of the function, populate the worklist with
9178     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
9179     // track of which blocks we visit.
9180     SmallPtrSet<BasicBlock*, 64> Visited;
9181     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
9182
9183     // Do a quick scan over the function.  If we find any blocks that are
9184     // unreachable, remove any instructions inside of them.  This prevents
9185     // the instcombine code from having to deal with some bad special cases.
9186     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9187       if (!Visited.count(BB)) {
9188         Instruction *Term = BB->getTerminator();
9189         while (Term != BB->begin()) {   // Remove instrs bottom-up
9190           BasicBlock::iterator I = Term; --I;
9191
9192           DOUT << "IC: DCE: " << *I;
9193           ++NumDeadInst;
9194
9195           if (!I->use_empty())
9196             I->replaceAllUsesWith(UndefValue::get(I->getType()));
9197           I->eraseFromParent();
9198         }
9199       }
9200   }
9201
9202   while (!Worklist.empty()) {
9203     Instruction *I = RemoveOneFromWorkList();
9204     if (I == 0) continue;  // skip null values.
9205
9206     // Check to see if we can DCE the instruction.
9207     if (isInstructionTriviallyDead(I)) {
9208       // Add operands to the worklist.
9209       if (I->getNumOperands() < 4)
9210         AddUsesToWorkList(*I);
9211       ++NumDeadInst;
9212
9213       DOUT << "IC: DCE: " << *I;
9214
9215       I->eraseFromParent();
9216       RemoveFromWorkList(I);
9217       continue;
9218     }
9219
9220     // Instruction isn't dead, see if we can constant propagate it.
9221     if (Constant *C = ConstantFoldInstruction(I, TD)) {
9222       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9223
9224       // Add operands to the worklist.
9225       AddUsesToWorkList(*I);
9226       ReplaceInstUsesWith(*I, C);
9227
9228       ++NumConstProp;
9229       I->eraseFromParent();
9230       RemoveFromWorkList(I);
9231       continue;
9232     }
9233
9234     // See if we can trivially sink this instruction to a successor basic block.
9235     if (I->hasOneUse()) {
9236       BasicBlock *BB = I->getParent();
9237       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9238       if (UserParent != BB) {
9239         bool UserIsSuccessor = false;
9240         // See if the user is one of our successors.
9241         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9242           if (*SI == UserParent) {
9243             UserIsSuccessor = true;
9244             break;
9245           }
9246
9247         // If the user is one of our immediate successors, and if that successor
9248         // only has us as a predecessors (we'd have to split the critical edge
9249         // otherwise), we can keep going.
9250         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9251             next(pred_begin(UserParent)) == pred_end(UserParent))
9252           // Okay, the CFG is simple enough, try to sink this instruction.
9253           Changed |= TryToSinkInstruction(I, UserParent);
9254       }
9255     }
9256
9257     // Now that we have an instruction, try combining it to simplify it...
9258     if (Instruction *Result = visit(*I)) {
9259       ++NumCombined;
9260       // Should we replace the old instruction with a new one?
9261       if (Result != I) {
9262         DOUT << "IC: Old = " << *I
9263              << "    New = " << *Result;
9264
9265         // Everything uses the new instruction now.
9266         I->replaceAllUsesWith(Result);
9267
9268         // Push the new instruction and any users onto the worklist.
9269         AddToWorkList(Result);
9270         AddUsersToWorkList(*Result);
9271
9272         // Move the name to the new instruction first.
9273         Result->takeName(I);
9274
9275         // Insert the new instruction into the basic block...
9276         BasicBlock *InstParent = I->getParent();
9277         BasicBlock::iterator InsertPos = I;
9278
9279         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
9280           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9281             ++InsertPos;
9282
9283         InstParent->getInstList().insert(InsertPos, Result);
9284
9285         // Make sure that we reprocess all operands now that we reduced their
9286         // use counts.
9287         AddUsesToWorkList(*I);
9288
9289         // Instructions can end up on the worklist more than once.  Make sure
9290         // we do not process an instruction that has been deleted.
9291         RemoveFromWorkList(I);
9292
9293         // Erase the old instruction.
9294         InstParent->getInstList().erase(I);
9295       } else {
9296         DOUT << "IC: MOD = " << *I;
9297
9298         // If the instruction was modified, it's possible that it is now dead.
9299         // if so, remove it.
9300         if (isInstructionTriviallyDead(I)) {
9301           // Make sure we process all operands now that we are reducing their
9302           // use counts.
9303           AddUsesToWorkList(*I);
9304
9305           // Instructions may end up in the worklist more than once.  Erase all
9306           // occurrences of this instruction.
9307           RemoveFromWorkList(I);
9308           I->eraseFromParent();
9309         } else {
9310           AddToWorkList(I);
9311           AddUsersToWorkList(*I);
9312         }
9313       }
9314       Changed = true;
9315     }
9316   }
9317
9318   assert(WorklistMap.empty() && "Worklist empty, but map not?");
9319   return Changed;
9320 }
9321
9322
9323 bool InstCombiner::runOnFunction(Function &F) {
9324   bool EverMadeChange = false;
9325
9326   // Iterate while there is work to do.
9327   unsigned Iteration = 0;
9328   while (DoOneIteration(F, Iteration++)) 
9329     EverMadeChange = true;
9330   return EverMadeChange;
9331 }
9332
9333 FunctionPass *llvm::createInstructionCombiningPass() {
9334   return new InstCombiner();
9335 }
9336