typo
[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 i32 %X, 1
16 //    %Z = add i32 %Y, 1
17 // into:
18 //    %Z = add i32 %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/ParameterAttributes.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include <algorithm>
60 #include <sstream>
61 using namespace llvm;
62 using namespace llvm::PatternMatch;
63
64 STATISTIC(NumCombined , "Number of insts combined");
65 STATISTIC(NumConstProp, "Number of constant folds");
66 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68 STATISTIC(NumSunkInst , "Number of instructions sunk");
69
70 namespace {
71   class VISIBILITY_HIDDEN InstCombiner
72     : public FunctionPass,
73       public InstVisitor<InstCombiner, Instruction*> {
74     // Worklist of all of the instructions that need to be simplified.
75     std::vector<Instruction*> Worklist;
76     DenseMap<Instruction*, unsigned> WorklistMap;
77     TargetData *TD;
78     bool MustPreserveLCSSA;
79   public:
80     static char ID; // Pass identification, replacement for typeid
81     InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
83     /// AddToWorkList - Add the specified instruction to the worklist if it
84     /// isn't already in it.
85     void AddToWorkList(Instruction *I) {
86       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87         Worklist.push_back(I);
88     }
89     
90     // RemoveFromWorkList - remove I from the worklist if it exists.
91     void RemoveFromWorkList(Instruction *I) {
92       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93       if (It == WorklistMap.end()) return; // Not in worklist.
94       
95       // Don't bother moving everything down, just null out the slot.
96       Worklist[It->second] = 0;
97       
98       WorklistMap.erase(It);
99     }
100     
101     Instruction *RemoveOneFromWorkList() {
102       Instruction *I = Worklist.back();
103       Worklist.pop_back();
104       WorklistMap.erase(I);
105       return I;
106     }
107
108     
109     /// AddUsersToWorkList - When an instruction is simplified, add all users of
110     /// the instruction to the work lists because they might get more simplified
111     /// now.
112     ///
113     void AddUsersToWorkList(Value &I) {
114       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
115            UI != UE; ++UI)
116         AddToWorkList(cast<Instruction>(*UI));
117     }
118
119     /// AddUsesToWorkList - When an instruction is simplified, add operands to
120     /// the work lists because they might get more simplified now.
121     ///
122     void AddUsesToWorkList(Instruction &I) {
123       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
125           AddToWorkList(Op);
126     }
127     
128     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129     /// dead.  Add all of its operands to the worklist, turning them into
130     /// undef's to reduce the number of uses of those instructions.
131     ///
132     /// Return the specified operand before it is turned into an undef.
133     ///
134     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135       Value *R = I.getOperand(op);
136       
137       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
139           AddToWorkList(Op);
140           // Set the operand to undef to drop the use.
141           I.setOperand(i, UndefValue::get(Op->getType()));
142         }
143       
144       return R;
145     }
146
147   public:
148     virtual bool runOnFunction(Function &F);
149     
150     bool DoOneIteration(Function &F, unsigned ItNum);
151
152     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153       AU.addRequired<TargetData>();
154       AU.addPreservedID(LCSSAID);
155       AU.setPreservesCFG();
156     }
157
158     TargetData &getTargetData() const { return *TD; }
159
160     // Visitation implementation - Implement instruction combining for different
161     // instruction types.  The semantics are as follows:
162     // Return Value:
163     //    null        - No change was made
164     //     I          - Change was made, I is still valid, I may be dead though
165     //   otherwise    - Change was made, replace I with returned instruction
166     //
167     Instruction *visitAdd(BinaryOperator &I);
168     Instruction *visitSub(BinaryOperator &I);
169     Instruction *visitMul(BinaryOperator &I);
170     Instruction *visitURem(BinaryOperator &I);
171     Instruction *visitSRem(BinaryOperator &I);
172     Instruction *visitFRem(BinaryOperator &I);
173     Instruction *commonRemTransforms(BinaryOperator &I);
174     Instruction *commonIRemTransforms(BinaryOperator &I);
175     Instruction *commonDivTransforms(BinaryOperator &I);
176     Instruction *commonIDivTransforms(BinaryOperator &I);
177     Instruction *visitUDiv(BinaryOperator &I);
178     Instruction *visitSDiv(BinaryOperator &I);
179     Instruction *visitFDiv(BinaryOperator &I);
180     Instruction *visitAnd(BinaryOperator &I);
181     Instruction *visitOr (BinaryOperator &I);
182     Instruction *visitXor(BinaryOperator &I);
183     Instruction *visitShl(BinaryOperator &I);
184     Instruction *visitAShr(BinaryOperator &I);
185     Instruction *visitLShr(BinaryOperator &I);
186     Instruction *commonShiftTransforms(BinaryOperator &I);
187     Instruction *visitFCmpInst(FCmpInst &I);
188     Instruction *visitICmpInst(ICmpInst &I);
189     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
190     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191                                                 Instruction *LHS,
192                                                 ConstantInt *RHS);
193     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194                                 ConstantInt *DivRHS);
195
196     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197                              ICmpInst::Predicate Cond, Instruction &I);
198     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
199                                      BinaryOperator &I);
200     Instruction *commonCastTransforms(CastInst &CI);
201     Instruction *commonIntCastTransforms(CastInst &CI);
202     Instruction *commonPointerCastTransforms(CastInst &CI);
203     Instruction *visitTrunc(TruncInst &CI);
204     Instruction *visitZExt(ZExtInst &CI);
205     Instruction *visitSExt(SExtInst &CI);
206     Instruction *visitFPTrunc(CastInst &CI);
207     Instruction *visitFPExt(CastInst &CI);
208     Instruction *visitFPToUI(CastInst &CI);
209     Instruction *visitFPToSI(CastInst &CI);
210     Instruction *visitUIToFP(CastInst &CI);
211     Instruction *visitSIToFP(CastInst &CI);
212     Instruction *visitPtrToInt(CastInst &CI);
213     Instruction *visitIntToPtr(CastInst &CI);
214     Instruction *visitBitCast(BitCastInst &CI);
215     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216                                 Instruction *FI);
217     Instruction *visitSelectInst(SelectInst &CI);
218     Instruction *visitCallInst(CallInst &CI);
219     Instruction *visitInvokeInst(InvokeInst &II);
220     Instruction *visitPHINode(PHINode &PN);
221     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
222     Instruction *visitAllocationInst(AllocationInst &AI);
223     Instruction *visitFreeInst(FreeInst &FI);
224     Instruction *visitLoadInst(LoadInst &LI);
225     Instruction *visitStoreInst(StoreInst &SI);
226     Instruction *visitBranchInst(BranchInst &BI);
227     Instruction *visitSwitchInst(SwitchInst &SI);
228     Instruction *visitInsertElementInst(InsertElementInst &IE);
229     Instruction *visitExtractElementInst(ExtractElementInst &EI);
230     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
231
232     // visitInstruction - Specify what to return for unhandled instructions...
233     Instruction *visitInstruction(Instruction &I) { return 0; }
234
235   private:
236     Instruction *visitCallSite(CallSite CS);
237     bool transformConstExprCastCall(CallSite CS);
238     Instruction *transformCallThroughTrampoline(CallSite CS);
239
240   public:
241     // InsertNewInstBefore - insert an instruction New before instruction Old
242     // in the program.  Add the new instruction to the worklist.
243     //
244     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
245       assert(New && New->getParent() == 0 &&
246              "New instruction already inserted into a basic block!");
247       BasicBlock *BB = Old.getParent();
248       BB->getInstList().insert(&Old, New);  // Insert inst
249       AddToWorkList(New);
250       return New;
251     }
252
253     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254     /// This also adds the cast to the worklist.  Finally, this returns the
255     /// cast.
256     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257                             Instruction &Pos) {
258       if (V->getType() == Ty) return V;
259
260       if (Constant *CV = dyn_cast<Constant>(V))
261         return ConstantExpr::getCast(opc, CV, Ty);
262       
263       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
264       AddToWorkList(C);
265       return C;
266     }
267
268     // ReplaceInstUsesWith - This method is to be used when an instruction is
269     // found to be dead, replacable with another preexisting expression.  Here
270     // we add all uses of I to the worklist, replace all uses of I with the new
271     // value, then return I, so that the inst combiner will know that I was
272     // modified.
273     //
274     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
275       AddUsersToWorkList(I);         // Add all modified instrs to worklist
276       if (&I != V) {
277         I.replaceAllUsesWith(V);
278         return &I;
279       } else {
280         // If we are replacing the instruction with itself, this must be in a
281         // segment of unreachable code, so just clobber the instruction.
282         I.replaceAllUsesWith(UndefValue::get(I.getType()));
283         return &I;
284       }
285     }
286
287     // UpdateValueUsesWith - This method is to be used when an value is
288     // found to be replacable with another preexisting expression or was
289     // updated.  Here we add all uses of I to the worklist, replace all uses of
290     // I with the new value (unless the instruction was just updated), then
291     // return true, so that the inst combiner will know that I was modified.
292     //
293     bool UpdateValueUsesWith(Value *Old, Value *New) {
294       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
295       if (Old != New)
296         Old->replaceAllUsesWith(New);
297       if (Instruction *I = dyn_cast<Instruction>(Old))
298         AddToWorkList(I);
299       if (Instruction *I = dyn_cast<Instruction>(New))
300         AddToWorkList(I);
301       return true;
302     }
303     
304     // EraseInstFromFunction - When dealing with an instruction that has side
305     // effects or produces a void value, we can't rely on DCE to delete the
306     // instruction.  Instead, visit methods should return the value returned by
307     // this function.
308     Instruction *EraseInstFromFunction(Instruction &I) {
309       assert(I.use_empty() && "Cannot erase instruction that is used!");
310       AddUsesToWorkList(I);
311       RemoveFromWorkList(&I);
312       I.eraseFromParent();
313       return 0;  // Don't do anything with FI
314     }
315
316   private:
317     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
318     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
319     /// casts that are known to not do anything...
320     ///
321     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
322                                    Value *V, const Type *DestTy,
323                                    Instruction *InsertBefore);
324
325     /// SimplifyCommutative - This performs a few simplifications for 
326     /// commutative operators.
327     bool SimplifyCommutative(BinaryOperator &I);
328
329     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
330     /// most-complex to least-complex order.
331     bool SimplifyCompare(CmpInst &I);
332
333     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
334     /// on the demanded bits.
335     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
336                               APInt& KnownZero, APInt& KnownOne,
337                               unsigned Depth = 0);
338
339     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
340                                       uint64_t &UndefElts, unsigned Depth = 0);
341       
342     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
343     // PHI node as operand #0, see if we can fold the instruction into the PHI
344     // (which is only possible if all operands to the PHI are constants).
345     Instruction *FoldOpIntoPhi(Instruction &I);
346
347     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
348     // operator and they all are only used by the PHI, PHI together their
349     // inputs, and do the operation once, to the result of the PHI.
350     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
351     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
352     
353     
354     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
355                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
356     
357     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
358                               bool isSub, Instruction &I);
359     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
360                                  bool isSigned, bool Inside, Instruction &IB);
361     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
362     Instruction *MatchBSwap(BinaryOperator &I);
363     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
364
365     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
366   };
367
368   char InstCombiner::ID = 0;
369   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
370 }
371
372 // getComplexity:  Assign a complexity or rank value to LLVM Values...
373 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
374 static unsigned getComplexity(Value *V) {
375   if (isa<Instruction>(V)) {
376     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
377       return 3;
378     return 4;
379   }
380   if (isa<Argument>(V)) return 3;
381   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
382 }
383
384 // isOnlyUse - Return true if this instruction will be deleted if we stop using
385 // it.
386 static bool isOnlyUse(Value *V) {
387   return V->hasOneUse() || isa<Constant>(V);
388 }
389
390 // getPromotedType - Return the specified type promoted as it would be to pass
391 // though a va_arg area...
392 static const Type *getPromotedType(const Type *Ty) {
393   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
394     if (ITy->getBitWidth() < 32)
395       return Type::Int32Ty;
396   }
397   return Ty;
398 }
399
400 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
401 /// expression bitcast,  return the operand value, otherwise return null.
402 static Value *getBitCastOperand(Value *V) {
403   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
404     return I->getOperand(0);
405   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
406     if (CE->getOpcode() == Instruction::BitCast)
407       return CE->getOperand(0);
408   return 0;
409 }
410
411 /// This function is a wrapper around CastInst::isEliminableCastPair. It
412 /// simply extracts arguments and returns what that function returns.
413 static Instruction::CastOps 
414 isEliminableCastPair(
415   const CastInst *CI, ///< The first cast instruction
416   unsigned opcode,       ///< The opcode of the second cast instruction
417   const Type *DstTy,     ///< The target type for the second cast instruction
418   TargetData *TD         ///< The target data for pointer size
419 ) {
420   
421   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
422   const Type *MidTy = CI->getType();                  // B from above
423
424   // Get the opcodes of the two Cast instructions
425   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
426   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
427
428   return Instruction::CastOps(
429       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
430                                      DstTy, TD->getIntPtrType()));
431 }
432
433 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
434 /// in any code being generated.  It does not require codegen if V is simple
435 /// enough or if the cast can be folded into other casts.
436 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
437                               const Type *Ty, TargetData *TD) {
438   if (V->getType() == Ty || isa<Constant>(V)) return false;
439   
440   // If this is another cast that can be eliminated, it isn't codegen either.
441   if (const CastInst *CI = dyn_cast<CastInst>(V))
442     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
443       return false;
444   return true;
445 }
446
447 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
448 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
449 /// casts that are known to not do anything...
450 ///
451 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
452                                              Value *V, const Type *DestTy,
453                                              Instruction *InsertBefore) {
454   if (V->getType() == DestTy) return V;
455   if (Constant *C = dyn_cast<Constant>(V))
456     return ConstantExpr::getCast(opcode, C, DestTy);
457   
458   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
459 }
460
461 // SimplifyCommutative - This performs a few simplifications for commutative
462 // operators:
463 //
464 //  1. Order operands such that they are listed from right (least complex) to
465 //     left (most complex).  This puts constants before unary operators before
466 //     binary operators.
467 //
468 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
469 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
470 //
471 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
472   bool Changed = false;
473   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
474     Changed = !I.swapOperands();
475
476   if (!I.isAssociative()) return Changed;
477   Instruction::BinaryOps Opcode = I.getOpcode();
478   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
479     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
480       if (isa<Constant>(I.getOperand(1))) {
481         Constant *Folded = ConstantExpr::get(I.getOpcode(),
482                                              cast<Constant>(I.getOperand(1)),
483                                              cast<Constant>(Op->getOperand(1)));
484         I.setOperand(0, Op->getOperand(0));
485         I.setOperand(1, Folded);
486         return true;
487       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
488         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
489             isOnlyUse(Op) && isOnlyUse(Op1)) {
490           Constant *C1 = cast<Constant>(Op->getOperand(1));
491           Constant *C2 = cast<Constant>(Op1->getOperand(1));
492
493           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
494           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
495           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
496                                                     Op1->getOperand(0),
497                                                     Op1->getName(), &I);
498           AddToWorkList(New);
499           I.setOperand(0, New);
500           I.setOperand(1, Folded);
501           return true;
502         }
503     }
504   return Changed;
505 }
506
507 /// SimplifyCompare - For a CmpInst this function just orders the operands
508 /// so that theyare listed from right (least complex) to left (most complex).
509 /// This puts constants before unary operators before binary operators.
510 bool InstCombiner::SimplifyCompare(CmpInst &I) {
511   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
512     return false;
513   I.swapOperands();
514   // Compare instructions are not associative so there's nothing else we can do.
515   return true;
516 }
517
518 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
519 // if the LHS is a constant zero (which is the 'negate' form).
520 //
521 static inline Value *dyn_castNegVal(Value *V) {
522   if (BinaryOperator::isNeg(V))
523     return BinaryOperator::getNegArgument(V);
524
525   // Constants can be considered to be negated values if they can be folded.
526   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
527     return ConstantExpr::getNeg(C);
528   return 0;
529 }
530
531 static inline Value *dyn_castNotVal(Value *V) {
532   if (BinaryOperator::isNot(V))
533     return BinaryOperator::getNotArgument(V);
534
535   // Constants can be considered to be not'ed values...
536   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
537     return ConstantInt::get(~C->getValue());
538   return 0;
539 }
540
541 // dyn_castFoldableMul - If this value is a multiply that can be folded into
542 // other computations (because it has a constant operand), return the
543 // non-constant operand of the multiply, and set CST to point to the multiplier.
544 // Otherwise, return null.
545 //
546 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
547   if (V->hasOneUse() && V->getType()->isInteger())
548     if (Instruction *I = dyn_cast<Instruction>(V)) {
549       if (I->getOpcode() == Instruction::Mul)
550         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
551           return I->getOperand(0);
552       if (I->getOpcode() == Instruction::Shl)
553         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
554           // The multiplier is really 1 << CST.
555           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
556           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
557           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
558           return I->getOperand(0);
559         }
560     }
561   return 0;
562 }
563
564 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565 /// expression, return it.
566 static User *dyn_castGetElementPtr(Value *V) {
567   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569     if (CE->getOpcode() == Instruction::GetElementPtr)
570       return cast<User>(V);
571   return false;
572 }
573
574 /// AddOne - Add one to a ConstantInt
575 static ConstantInt *AddOne(ConstantInt *C) {
576   APInt Val(C->getValue());
577   return ConstantInt::get(++Val);
578 }
579 /// SubOne - Subtract one from a ConstantInt
580 static ConstantInt *SubOne(ConstantInt *C) {
581   APInt Val(C->getValue());
582   return ConstantInt::get(--Val);
583 }
584 /// Add - Add two ConstantInts together
585 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
586   return ConstantInt::get(C1->getValue() + C2->getValue());
587 }
588 /// And - Bitwise AND two ConstantInts together
589 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
590   return ConstantInt::get(C1->getValue() & C2->getValue());
591 }
592 /// Subtract - Subtract one ConstantInt from another
593 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
594   return ConstantInt::get(C1->getValue() - C2->getValue());
595 }
596 /// Multiply - Multiply two ConstantInts together
597 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
598   return ConstantInt::get(C1->getValue() * C2->getValue());
599 }
600
601 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
602 /// known to be either zero or one and return them in the KnownZero/KnownOne
603 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
604 /// processing.
605 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
606 /// we cannot optimize based on the assumption that it is zero without changing
607 /// it to be an explicit zero.  If we don't change it to zero, other code could
608 /// optimized based on the contradictory assumption that it is non-zero.
609 /// Because instcombine aggressively folds operations with undef args anyway,
610 /// this won't lose us code quality.
611 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
612                               APInt& KnownOne, unsigned Depth = 0) {
613   assert(V && "No Value?");
614   assert(Depth <= 6 && "Limit Search Depth");
615   uint32_t BitWidth = Mask.getBitWidth();
616   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
617          KnownZero.getBitWidth() == BitWidth && 
618          KnownOne.getBitWidth() == BitWidth &&
619          "V, Mask, KnownOne and KnownZero should have same BitWidth");
620   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
621     // We know all of the bits for a constant!
622     KnownOne = CI->getValue() & Mask;
623     KnownZero = ~KnownOne & Mask;
624     return;
625   }
626
627   if (Depth == 6 || Mask == 0)
628     return;  // Limit search depth.
629
630   Instruction *I = dyn_cast<Instruction>(V);
631   if (!I) return;
632
633   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
634   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
635   
636   switch (I->getOpcode()) {
637   case Instruction::And: {
638     // If either the LHS or the RHS are Zero, the result is zero.
639     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
640     APInt Mask2(Mask & ~KnownZero);
641     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
642     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
643     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
644     
645     // Output known-1 bits are only known if set in both the LHS & RHS.
646     KnownOne &= KnownOne2;
647     // Output known-0 are known to be clear if zero in either the LHS | RHS.
648     KnownZero |= KnownZero2;
649     return;
650   }
651   case Instruction::Or: {
652     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
653     APInt Mask2(Mask & ~KnownOne);
654     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
655     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
656     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
657     
658     // Output known-0 bits are only known if clear in both the LHS & RHS.
659     KnownZero &= KnownZero2;
660     // Output known-1 are known to be set if set in either the LHS | RHS.
661     KnownOne |= KnownOne2;
662     return;
663   }
664   case Instruction::Xor: {
665     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
666     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
667     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
668     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
669     
670     // Output known-0 bits are known if clear or set in both the LHS & RHS.
671     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
672     // Output known-1 are known to be set if set in only one of the LHS, RHS.
673     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
674     KnownZero = KnownZeroOut;
675     return;
676   }
677   case Instruction::Select:
678     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
679     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
680     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
681     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
682
683     // Only known if known in both the LHS and RHS.
684     KnownOne &= KnownOne2;
685     KnownZero &= KnownZero2;
686     return;
687   case Instruction::FPTrunc:
688   case Instruction::FPExt:
689   case Instruction::FPToUI:
690   case Instruction::FPToSI:
691   case Instruction::SIToFP:
692   case Instruction::PtrToInt:
693   case Instruction::UIToFP:
694   case Instruction::IntToPtr:
695     return; // Can't work with floating point or pointers
696   case Instruction::Trunc: {
697     // All these have integer operands
698     uint32_t SrcBitWidth = 
699       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
700     APInt MaskIn(Mask);
701     MaskIn.zext(SrcBitWidth);
702     KnownZero.zext(SrcBitWidth);
703     KnownOne.zext(SrcBitWidth);
704     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
705     KnownZero.trunc(BitWidth);
706     KnownOne.trunc(BitWidth);
707     return;
708   }
709   case Instruction::BitCast: {
710     const Type *SrcTy = I->getOperand(0)->getType();
711     if (SrcTy->isInteger()) {
712       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
713       return;
714     }
715     break;
716   }
717   case Instruction::ZExt:  {
718     // Compute the bits in the result that are not present in the input.
719     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
720     uint32_t SrcBitWidth = SrcTy->getBitWidth();
721       
722     APInt MaskIn(Mask);
723     MaskIn.trunc(SrcBitWidth);
724     KnownZero.trunc(SrcBitWidth);
725     KnownOne.trunc(SrcBitWidth);
726     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
727     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
728     // The top bits are known to be zero.
729     KnownZero.zext(BitWidth);
730     KnownOne.zext(BitWidth);
731     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
732     return;
733   }
734   case Instruction::SExt: {
735     // Compute the bits in the result that are not present in the input.
736     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
737     uint32_t SrcBitWidth = SrcTy->getBitWidth();
738       
739     APInt MaskIn(Mask); 
740     MaskIn.trunc(SrcBitWidth);
741     KnownZero.trunc(SrcBitWidth);
742     KnownOne.trunc(SrcBitWidth);
743     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
744     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
745     KnownZero.zext(BitWidth);
746     KnownOne.zext(BitWidth);
747
748     // If the sign bit of the input is known set or clear, then we know the
749     // top bits of the result.
750     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
751       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
752     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
753       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
754     return;
755   }
756   case Instruction::Shl:
757     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
758     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
759       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
760       APInt Mask2(Mask.lshr(ShiftAmt));
761       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
762       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
763       KnownZero <<= ShiftAmt;
764       KnownOne  <<= ShiftAmt;
765       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
766       return;
767     }
768     break;
769   case Instruction::LShr:
770     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
771     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
772       // Compute the new bits that are at the top now.
773       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
774       
775       // Unsigned shift right.
776       APInt Mask2(Mask.shl(ShiftAmt));
777       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
778       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
779       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
780       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
781       // high bits known zero.
782       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
783       return;
784     }
785     break;
786   case Instruction::AShr:
787     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
788     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
789       // Compute the new bits that are at the top now.
790       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
791       
792       // Signed shift right.
793       APInt Mask2(Mask.shl(ShiftAmt));
794       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
795       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
796       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
797       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
798         
799       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
800       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
801         KnownZero |= HighBits;
802       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
803         KnownOne |= HighBits;
804       return;
805     }
806     break;
807   }
808 }
809
810 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
811 /// this predicate to simplify operations downstream.  Mask is known to be zero
812 /// for bits that V cannot have.
813 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
814   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
815   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
816   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
817   return (KnownZero & Mask) == Mask;
818 }
819
820 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
821 /// specified instruction is a constant integer.  If so, check to see if there
822 /// are any bits set in the constant that are not demanded.  If so, shrink the
823 /// constant and return true.
824 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
825                                    APInt Demanded) {
826   assert(I && "No instruction?");
827   assert(OpNo < I->getNumOperands() && "Operand index too large");
828
829   // If the operand is not a constant integer, nothing to do.
830   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
831   if (!OpC) return false;
832
833   // If there are no bits set that aren't demanded, nothing to do.
834   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
835   if ((~Demanded & OpC->getValue()) == 0)
836     return false;
837
838   // This instruction is producing bits that are not demanded. Shrink the RHS.
839   Demanded &= OpC->getValue();
840   I->setOperand(OpNo, ConstantInt::get(Demanded));
841   return true;
842 }
843
844 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
845 // set of known zero and one bits, compute the maximum and minimum values that
846 // could have the specified known zero and known one bits, returning them in
847 // min/max.
848 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
849                                                    const APInt& KnownZero,
850                                                    const APInt& KnownOne,
851                                                    APInt& Min, APInt& Max) {
852   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
853   assert(KnownZero.getBitWidth() == BitWidth && 
854          KnownOne.getBitWidth() == BitWidth &&
855          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
856          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
857   APInt UnknownBits = ~(KnownZero|KnownOne);
858
859   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
860   // bit if it is unknown.
861   Min = KnownOne;
862   Max = KnownOne|UnknownBits;
863   
864   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
865     Min.set(BitWidth-1);
866     Max.clear(BitWidth-1);
867   }
868 }
869
870 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
871 // a set of known zero and one bits, compute the maximum and minimum values that
872 // could have the specified known zero and known one bits, returning them in
873 // min/max.
874 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
875                                                      const APInt &KnownZero,
876                                                      const APInt &KnownOne,
877                                                      APInt &Min, APInt &Max) {
878   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
879   assert(KnownZero.getBitWidth() == BitWidth && 
880          KnownOne.getBitWidth() == BitWidth &&
881          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
882          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
883   APInt UnknownBits = ~(KnownZero|KnownOne);
884   
885   // The minimum value is when the unknown bits are all zeros.
886   Min = KnownOne;
887   // The maximum value is when the unknown bits are all ones.
888   Max = KnownOne|UnknownBits;
889 }
890
891 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
892 /// value based on the demanded bits. When this function is called, it is known
893 /// that only the bits set in DemandedMask of the result of V are ever used
894 /// downstream. Consequently, depending on the mask and V, it may be possible
895 /// to replace V with a constant or one of its operands. In such cases, this
896 /// function does the replacement and returns true. In all other cases, it
897 /// returns false after analyzing the expression and setting KnownOne and known
898 /// to be one in the expression. KnownZero contains all the bits that are known
899 /// to be zero in the expression. These are provided to potentially allow the
900 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
901 /// the expression. KnownOne and KnownZero always follow the invariant that 
902 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
903 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
904 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
905 /// and KnownOne must all be the same.
906 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
907                                         APInt& KnownZero, APInt& KnownOne,
908                                         unsigned Depth) {
909   assert(V != 0 && "Null pointer of Value???");
910   assert(Depth <= 6 && "Limit Search Depth");
911   uint32_t BitWidth = DemandedMask.getBitWidth();
912   const IntegerType *VTy = cast<IntegerType>(V->getType());
913   assert(VTy->getBitWidth() == BitWidth && 
914          KnownZero.getBitWidth() == BitWidth && 
915          KnownOne.getBitWidth() == BitWidth &&
916          "Value *V, DemandedMask, KnownZero and KnownOne \
917           must have same BitWidth");
918   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
919     // We know all of the bits for a constant!
920     KnownOne = CI->getValue() & DemandedMask;
921     KnownZero = ~KnownOne & DemandedMask;
922     return false;
923   }
924   
925   KnownZero.clear(); 
926   KnownOne.clear();
927   if (!V->hasOneUse()) {    // Other users may use these bits.
928     if (Depth != 0) {       // Not at the root.
929       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
930       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
931       return false;
932     }
933     // If this is the root being simplified, allow it to have multiple uses,
934     // just set the DemandedMask to all bits.
935     DemandedMask = APInt::getAllOnesValue(BitWidth);
936   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
937     if (V != UndefValue::get(VTy))
938       return UpdateValueUsesWith(V, UndefValue::get(VTy));
939     return false;
940   } else if (Depth == 6) {        // Limit search depth.
941     return false;
942   }
943   
944   Instruction *I = dyn_cast<Instruction>(V);
945   if (!I) return false;        // Only analyze instructions.
946
947   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
948   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
949   switch (I->getOpcode()) {
950   default: break;
951   case Instruction::And:
952     // If either the LHS or the RHS are Zero, the result is zero.
953     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
954                              RHSKnownZero, RHSKnownOne, Depth+1))
955       return true;
956     assert((RHSKnownZero & RHSKnownOne) == 0 && 
957            "Bits known to be one AND zero?"); 
958
959     // If something is known zero on the RHS, the bits aren't demanded on the
960     // LHS.
961     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
962                              LHSKnownZero, LHSKnownOne, Depth+1))
963       return true;
964     assert((LHSKnownZero & LHSKnownOne) == 0 && 
965            "Bits known to be one AND zero?"); 
966
967     // If all of the demanded bits are known 1 on one side, return the other.
968     // These bits cannot contribute to the result of the 'and'.
969     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
970         (DemandedMask & ~LHSKnownZero))
971       return UpdateValueUsesWith(I, I->getOperand(0));
972     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
973         (DemandedMask & ~RHSKnownZero))
974       return UpdateValueUsesWith(I, I->getOperand(1));
975     
976     // If all of the demanded bits in the inputs are known zeros, return zero.
977     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
978       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
979       
980     // If the RHS is a constant, see if we can simplify it.
981     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
982       return UpdateValueUsesWith(I, I);
983       
984     // Output known-1 bits are only known if set in both the LHS & RHS.
985     RHSKnownOne &= LHSKnownOne;
986     // Output known-0 are known to be clear if zero in either the LHS | RHS.
987     RHSKnownZero |= LHSKnownZero;
988     break;
989   case Instruction::Or:
990     // If either the LHS or the RHS are One, the result is One.
991     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
992                              RHSKnownZero, RHSKnownOne, Depth+1))
993       return true;
994     assert((RHSKnownZero & RHSKnownOne) == 0 && 
995            "Bits known to be one AND zero?"); 
996     // If something is known one on the RHS, the bits aren't demanded on the
997     // LHS.
998     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
999                              LHSKnownZero, LHSKnownOne, Depth+1))
1000       return true;
1001     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1002            "Bits known to be one AND zero?"); 
1003     
1004     // If all of the demanded bits are known zero on one side, return the other.
1005     // These bits cannot contribute to the result of the 'or'.
1006     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1007         (DemandedMask & ~LHSKnownOne))
1008       return UpdateValueUsesWith(I, I->getOperand(0));
1009     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1010         (DemandedMask & ~RHSKnownOne))
1011       return UpdateValueUsesWith(I, I->getOperand(1));
1012
1013     // If all of the potentially set bits on one side are known to be set on
1014     // the other side, just use the 'other' side.
1015     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1016         (DemandedMask & (~RHSKnownZero)))
1017       return UpdateValueUsesWith(I, I->getOperand(0));
1018     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1019         (DemandedMask & (~LHSKnownZero)))
1020       return UpdateValueUsesWith(I, I->getOperand(1));
1021         
1022     // If the RHS is a constant, see if we can simplify it.
1023     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1024       return UpdateValueUsesWith(I, I);
1025           
1026     // Output known-0 bits are only known if clear in both the LHS & RHS.
1027     RHSKnownZero &= LHSKnownZero;
1028     // Output known-1 are known to be set if set in either the LHS | RHS.
1029     RHSKnownOne |= LHSKnownOne;
1030     break;
1031   case Instruction::Xor: {
1032     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1033                              RHSKnownZero, RHSKnownOne, Depth+1))
1034       return true;
1035     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1036            "Bits known to be one AND zero?"); 
1037     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1038                              LHSKnownZero, LHSKnownOne, Depth+1))
1039       return true;
1040     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1041            "Bits known to be one AND zero?"); 
1042     
1043     // If all of the demanded bits are known zero on one side, return the other.
1044     // These bits cannot contribute to the result of the 'xor'.
1045     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1046       return UpdateValueUsesWith(I, I->getOperand(0));
1047     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1048       return UpdateValueUsesWith(I, I->getOperand(1));
1049     
1050     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1051     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1052                          (RHSKnownOne & LHSKnownOne);
1053     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1054     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1055                         (RHSKnownOne & LHSKnownZero);
1056     
1057     // If all of the demanded bits are known to be zero on one side or the
1058     // other, turn this into an *inclusive* or.
1059     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1060     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1061       Instruction *Or =
1062         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1063                                  I->getName());
1064       InsertNewInstBefore(Or, *I);
1065       return UpdateValueUsesWith(I, Or);
1066     }
1067     
1068     // If all of the demanded bits on one side are known, and all of the set
1069     // bits on that side are also known to be set on the other side, turn this
1070     // into an AND, as we know the bits will be cleared.
1071     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1072     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1073       // all known
1074       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1075         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1076         Instruction *And = 
1077           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1078         InsertNewInstBefore(And, *I);
1079         return UpdateValueUsesWith(I, And);
1080       }
1081     }
1082     
1083     // If the RHS is a constant, see if we can simplify it.
1084     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1085     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1086       return UpdateValueUsesWith(I, I);
1087     
1088     RHSKnownZero = KnownZeroOut;
1089     RHSKnownOne  = KnownOneOut;
1090     break;
1091   }
1092   case Instruction::Select:
1093     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1094                              RHSKnownZero, RHSKnownOne, Depth+1))
1095       return true;
1096     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1097                              LHSKnownZero, LHSKnownOne, Depth+1))
1098       return true;
1099     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1100            "Bits known to be one AND zero?"); 
1101     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1102            "Bits known to be one AND zero?"); 
1103     
1104     // If the operands are constants, see if we can simplify them.
1105     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1106       return UpdateValueUsesWith(I, I);
1107     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1108       return UpdateValueUsesWith(I, I);
1109     
1110     // Only known if known in both the LHS and RHS.
1111     RHSKnownOne &= LHSKnownOne;
1112     RHSKnownZero &= LHSKnownZero;
1113     break;
1114   case Instruction::Trunc: {
1115     uint32_t truncBf = 
1116       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1117     DemandedMask.zext(truncBf);
1118     RHSKnownZero.zext(truncBf);
1119     RHSKnownOne.zext(truncBf);
1120     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1121                              RHSKnownZero, RHSKnownOne, Depth+1))
1122       return true;
1123     DemandedMask.trunc(BitWidth);
1124     RHSKnownZero.trunc(BitWidth);
1125     RHSKnownOne.trunc(BitWidth);
1126     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1127            "Bits known to be one AND zero?"); 
1128     break;
1129   }
1130   case Instruction::BitCast:
1131     if (!I->getOperand(0)->getType()->isInteger())
1132       return false;
1133       
1134     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1135                              RHSKnownZero, RHSKnownOne, Depth+1))
1136       return true;
1137     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1138            "Bits known to be one AND zero?"); 
1139     break;
1140   case Instruction::ZExt: {
1141     // Compute the bits in the result that are not present in the input.
1142     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1143     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1144     
1145     DemandedMask.trunc(SrcBitWidth);
1146     RHSKnownZero.trunc(SrcBitWidth);
1147     RHSKnownOne.trunc(SrcBitWidth);
1148     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1149                              RHSKnownZero, RHSKnownOne, Depth+1))
1150       return true;
1151     DemandedMask.zext(BitWidth);
1152     RHSKnownZero.zext(BitWidth);
1153     RHSKnownOne.zext(BitWidth);
1154     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1155            "Bits known to be one AND zero?"); 
1156     // The top bits are known to be zero.
1157     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1158     break;
1159   }
1160   case Instruction::SExt: {
1161     // Compute the bits in the result that are not present in the input.
1162     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1163     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1164     
1165     APInt InputDemandedBits = DemandedMask & 
1166                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1167
1168     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1169     // If any of the sign extended bits are demanded, we know that the sign
1170     // bit is demanded.
1171     if ((NewBits & DemandedMask) != 0)
1172       InputDemandedBits.set(SrcBitWidth-1);
1173       
1174     InputDemandedBits.trunc(SrcBitWidth);
1175     RHSKnownZero.trunc(SrcBitWidth);
1176     RHSKnownOne.trunc(SrcBitWidth);
1177     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1178                              RHSKnownZero, RHSKnownOne, Depth+1))
1179       return true;
1180     InputDemandedBits.zext(BitWidth);
1181     RHSKnownZero.zext(BitWidth);
1182     RHSKnownOne.zext(BitWidth);
1183     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1184            "Bits known to be one AND zero?"); 
1185       
1186     // If the sign bit of the input is known set or clear, then we know the
1187     // top bits of the result.
1188
1189     // If the input sign bit is known zero, or if the NewBits are not demanded
1190     // convert this into a zero extension.
1191     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1192     {
1193       // Convert to ZExt cast
1194       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1195       return UpdateValueUsesWith(I, NewCast);
1196     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1197       RHSKnownOne |= NewBits;
1198     }
1199     break;
1200   }
1201   case Instruction::Add: {
1202     // Figure out what the input bits are.  If the top bits of the and result
1203     // are not demanded, then the add doesn't demand them from its input
1204     // either.
1205     uint32_t NLZ = DemandedMask.countLeadingZeros();
1206       
1207     // If there is a constant on the RHS, there are a variety of xformations
1208     // we can do.
1209     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1210       // If null, this should be simplified elsewhere.  Some of the xforms here
1211       // won't work if the RHS is zero.
1212       if (RHS->isZero())
1213         break;
1214       
1215       // If the top bit of the output is demanded, demand everything from the
1216       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1217       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1218
1219       // Find information about known zero/one bits in the input.
1220       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1221                                LHSKnownZero, LHSKnownOne, Depth+1))
1222         return true;
1223
1224       // If the RHS of the add has bits set that can't affect the input, reduce
1225       // the constant.
1226       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1227         return UpdateValueUsesWith(I, I);
1228       
1229       // Avoid excess work.
1230       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1231         break;
1232       
1233       // Turn it into OR if input bits are zero.
1234       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1235         Instruction *Or =
1236           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1237                                    I->getName());
1238         InsertNewInstBefore(Or, *I);
1239         return UpdateValueUsesWith(I, Or);
1240       }
1241       
1242       // We can say something about the output known-zero and known-one bits,
1243       // depending on potential carries from the input constant and the
1244       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1245       // bits set and the RHS constant is 0x01001, then we know we have a known
1246       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1247       
1248       // To compute this, we first compute the potential carry bits.  These are
1249       // the bits which may be modified.  I'm not aware of a better way to do
1250       // this scan.
1251       const APInt& RHSVal = RHS->getValue();
1252       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1253       
1254       // Now that we know which bits have carries, compute the known-1/0 sets.
1255       
1256       // Bits are known one if they are known zero in one operand and one in the
1257       // other, and there is no input carry.
1258       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1259                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1260       
1261       // Bits are known zero if they are known zero in both operands and there
1262       // is no input carry.
1263       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1264     } else {
1265       // If the high-bits of this ADD are not demanded, then it does not demand
1266       // the high bits of its LHS or RHS.
1267       if (DemandedMask[BitWidth-1] == 0) {
1268         // Right fill the mask of bits for this ADD to demand the most
1269         // significant bit and all those below it.
1270         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1271         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1272                                  LHSKnownZero, LHSKnownOne, Depth+1))
1273           return true;
1274         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1275                                  LHSKnownZero, LHSKnownOne, Depth+1))
1276           return true;
1277       }
1278     }
1279     break;
1280   }
1281   case Instruction::Sub:
1282     // If the high-bits of this SUB are not demanded, then it does not demand
1283     // the high bits of its LHS or RHS.
1284     if (DemandedMask[BitWidth-1] == 0) {
1285       // Right fill the mask of bits for this SUB to demand the most
1286       // significant bit and all those below it.
1287       uint32_t NLZ = DemandedMask.countLeadingZeros();
1288       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1289       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1290                                LHSKnownZero, LHSKnownOne, Depth+1))
1291         return true;
1292       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1293                                LHSKnownZero, LHSKnownOne, Depth+1))
1294         return true;
1295     }
1296     break;
1297   case Instruction::Shl:
1298     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1299       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1300       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1301       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1302                                RHSKnownZero, RHSKnownOne, Depth+1))
1303         return true;
1304       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1305              "Bits known to be one AND zero?"); 
1306       RHSKnownZero <<= ShiftAmt;
1307       RHSKnownOne  <<= ShiftAmt;
1308       // low bits known zero.
1309       if (ShiftAmt)
1310         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1311     }
1312     break;
1313   case Instruction::LShr:
1314     // For a logical shift right
1315     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1316       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1317       
1318       // Unsigned shift right.
1319       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1320       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1321                                RHSKnownZero, RHSKnownOne, Depth+1))
1322         return true;
1323       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1324              "Bits known to be one AND zero?"); 
1325       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1326       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1327       if (ShiftAmt) {
1328         // Compute the new bits that are at the top now.
1329         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1330         RHSKnownZero |= HighBits;  // high bits known zero.
1331       }
1332     }
1333     break;
1334   case Instruction::AShr:
1335     // If this is an arithmetic shift right and only the low-bit is set, we can
1336     // always convert this into a logical shr, even if the shift amount is
1337     // variable.  The low bit of the shift cannot be an input sign bit unless
1338     // the shift amount is >= the size of the datatype, which is undefined.
1339     if (DemandedMask == 1) {
1340       // Perform the logical shift right.
1341       Value *NewVal = BinaryOperator::createLShr(
1342                         I->getOperand(0), I->getOperand(1), I->getName());
1343       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1344       return UpdateValueUsesWith(I, NewVal);
1345     }    
1346
1347     // If the sign bit is the only bit demanded by this ashr, then there is no
1348     // need to do it, the shift doesn't change the high bit.
1349     if (DemandedMask.isSignBit())
1350       return UpdateValueUsesWith(I, I->getOperand(0));
1351     
1352     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1353       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1354       
1355       // Signed shift right.
1356       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1357       // If any of the "high bits" are demanded, we should set the sign bit as
1358       // demanded.
1359       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1360         DemandedMaskIn.set(BitWidth-1);
1361       if (SimplifyDemandedBits(I->getOperand(0),
1362                                DemandedMaskIn,
1363                                RHSKnownZero, RHSKnownOne, Depth+1))
1364         return true;
1365       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1366              "Bits known to be one AND zero?"); 
1367       // Compute the new bits that are at the top now.
1368       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1369       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1370       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1371         
1372       // Handle the sign bits.
1373       APInt SignBit(APInt::getSignBit(BitWidth));
1374       // Adjust to where it is now in the mask.
1375       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1376         
1377       // If the input sign bit is known to be zero, or if none of the top bits
1378       // are demanded, turn this into an unsigned shift right.
1379       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1380           (HighBits & ~DemandedMask) == HighBits) {
1381         // Perform the logical shift right.
1382         Value *NewVal = BinaryOperator::createLShr(
1383                           I->getOperand(0), SA, I->getName());
1384         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1385         return UpdateValueUsesWith(I, NewVal);
1386       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1387         RHSKnownOne |= HighBits;
1388       }
1389     }
1390     break;
1391   }
1392   
1393   // If the client is only demanding bits that we know, return the known
1394   // constant.
1395   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1396     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1397   return false;
1398 }
1399
1400
1401 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1402 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1403 /// actually used by the caller.  This method analyzes which elements of the
1404 /// operand are undef and returns that information in UndefElts.
1405 ///
1406 /// If the information about demanded elements can be used to simplify the
1407 /// operation, the operation is simplified, then the resultant value is
1408 /// returned.  This returns null if no change was made.
1409 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1410                                                 uint64_t &UndefElts,
1411                                                 unsigned Depth) {
1412   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1413   assert(VWidth <= 64 && "Vector too wide to analyze!");
1414   uint64_t EltMask = ~0ULL >> (64-VWidth);
1415   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1416          "Invalid DemandedElts!");
1417
1418   if (isa<UndefValue>(V)) {
1419     // If the entire vector is undefined, just return this info.
1420     UndefElts = EltMask;
1421     return 0;
1422   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1423     UndefElts = EltMask;
1424     return UndefValue::get(V->getType());
1425   }
1426   
1427   UndefElts = 0;
1428   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1429     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1430     Constant *Undef = UndefValue::get(EltTy);
1431
1432     std::vector<Constant*> Elts;
1433     for (unsigned i = 0; i != VWidth; ++i)
1434       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1435         Elts.push_back(Undef);
1436         UndefElts |= (1ULL << i);
1437       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1438         Elts.push_back(Undef);
1439         UndefElts |= (1ULL << i);
1440       } else {                               // Otherwise, defined.
1441         Elts.push_back(CP->getOperand(i));
1442       }
1443         
1444     // If we changed the constant, return it.
1445     Constant *NewCP = ConstantVector::get(Elts);
1446     return NewCP != CP ? NewCP : 0;
1447   } else if (isa<ConstantAggregateZero>(V)) {
1448     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1449     // set to undef.
1450     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1451     Constant *Zero = Constant::getNullValue(EltTy);
1452     Constant *Undef = UndefValue::get(EltTy);
1453     std::vector<Constant*> Elts;
1454     for (unsigned i = 0; i != VWidth; ++i)
1455       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1456     UndefElts = DemandedElts ^ EltMask;
1457     return ConstantVector::get(Elts);
1458   }
1459   
1460   if (!V->hasOneUse()) {    // Other users may use these bits.
1461     if (Depth != 0) {       // Not at the root.
1462       // TODO: Just compute the UndefElts information recursively.
1463       return false;
1464     }
1465     return false;
1466   } else if (Depth == 10) {        // Limit search depth.
1467     return false;
1468   }
1469   
1470   Instruction *I = dyn_cast<Instruction>(V);
1471   if (!I) return false;        // Only analyze instructions.
1472   
1473   bool MadeChange = false;
1474   uint64_t UndefElts2;
1475   Value *TmpV;
1476   switch (I->getOpcode()) {
1477   default: break;
1478     
1479   case Instruction::InsertElement: {
1480     // If this is a variable index, we don't know which element it overwrites.
1481     // demand exactly the same input as we produce.
1482     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1483     if (Idx == 0) {
1484       // Note that we can't propagate undef elt info, because we don't know
1485       // which elt is getting updated.
1486       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1487                                         UndefElts2, Depth+1);
1488       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1489       break;
1490     }
1491     
1492     // If this is inserting an element that isn't demanded, remove this
1493     // insertelement.
1494     unsigned IdxNo = Idx->getZExtValue();
1495     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1496       return AddSoonDeadInstToWorklist(*I, 0);
1497     
1498     // Otherwise, the element inserted overwrites whatever was there, so the
1499     // input demanded set is simpler than the output set.
1500     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1501                                       DemandedElts & ~(1ULL << IdxNo),
1502                                       UndefElts, Depth+1);
1503     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1504
1505     // The inserted element is defined.
1506     UndefElts |= 1ULL << IdxNo;
1507     break;
1508   }
1509   case Instruction::BitCast: {
1510     // Vector->vector casts only.
1511     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1512     if (!VTy) break;
1513     unsigned InVWidth = VTy->getNumElements();
1514     uint64_t InputDemandedElts = 0;
1515     unsigned Ratio;
1516
1517     if (VWidth == InVWidth) {
1518       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1519       // elements as are demanded of us.
1520       Ratio = 1;
1521       InputDemandedElts = DemandedElts;
1522     } else if (VWidth > InVWidth) {
1523       // Untested so far.
1524       break;
1525       
1526       // If there are more elements in the result than there are in the source,
1527       // then an input element is live if any of the corresponding output
1528       // elements are live.
1529       Ratio = VWidth/InVWidth;
1530       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1531         if (DemandedElts & (1ULL << OutIdx))
1532           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1533       }
1534     } else {
1535       // Untested so far.
1536       break;
1537       
1538       // If there are more elements in the source than there are in the result,
1539       // then an input element is live if the corresponding output element is
1540       // live.
1541       Ratio = InVWidth/VWidth;
1542       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1543         if (DemandedElts & (1ULL << InIdx/Ratio))
1544           InputDemandedElts |= 1ULL << InIdx;
1545     }
1546     
1547     // div/rem demand all inputs, because they don't want divide by zero.
1548     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1549                                       UndefElts2, Depth+1);
1550     if (TmpV) {
1551       I->setOperand(0, TmpV);
1552       MadeChange = true;
1553     }
1554     
1555     UndefElts = UndefElts2;
1556     if (VWidth > InVWidth) {
1557       assert(0 && "Unimp");
1558       // If there are more elements in the result than there are in the source,
1559       // then an output element is undef if the corresponding input element is
1560       // undef.
1561       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1562         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1563           UndefElts |= 1ULL << OutIdx;
1564     } else if (VWidth < InVWidth) {
1565       assert(0 && "Unimp");
1566       // If there are more elements in the source than there are in the result,
1567       // then a result element is undef if all of the corresponding input
1568       // elements are undef.
1569       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1570       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1571         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1572           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1573     }
1574     break;
1575   }
1576   case Instruction::And:
1577   case Instruction::Or:
1578   case Instruction::Xor:
1579   case Instruction::Add:
1580   case Instruction::Sub:
1581   case Instruction::Mul:
1582     // div/rem demand all inputs, because they don't want divide by zero.
1583     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1584                                       UndefElts, Depth+1);
1585     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1586     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1587                                       UndefElts2, Depth+1);
1588     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1589       
1590     // Output elements are undefined if both are undefined.  Consider things
1591     // like undef&0.  The result is known zero, not undef.
1592     UndefElts &= UndefElts2;
1593     break;
1594     
1595   case Instruction::Call: {
1596     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1597     if (!II) break;
1598     switch (II->getIntrinsicID()) {
1599     default: break;
1600       
1601     // Binary vector operations that work column-wise.  A dest element is a
1602     // function of the corresponding input elements from the two inputs.
1603     case Intrinsic::x86_sse_sub_ss:
1604     case Intrinsic::x86_sse_mul_ss:
1605     case Intrinsic::x86_sse_min_ss:
1606     case Intrinsic::x86_sse_max_ss:
1607     case Intrinsic::x86_sse2_sub_sd:
1608     case Intrinsic::x86_sse2_mul_sd:
1609     case Intrinsic::x86_sse2_min_sd:
1610     case Intrinsic::x86_sse2_max_sd:
1611       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1612                                         UndefElts, Depth+1);
1613       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1614       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1615                                         UndefElts2, Depth+1);
1616       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1617
1618       // If only the low elt is demanded and this is a scalarizable intrinsic,
1619       // scalarize it now.
1620       if (DemandedElts == 1) {
1621         switch (II->getIntrinsicID()) {
1622         default: break;
1623         case Intrinsic::x86_sse_sub_ss:
1624         case Intrinsic::x86_sse_mul_ss:
1625         case Intrinsic::x86_sse2_sub_sd:
1626         case Intrinsic::x86_sse2_mul_sd:
1627           // TODO: Lower MIN/MAX/ABS/etc
1628           Value *LHS = II->getOperand(1);
1629           Value *RHS = II->getOperand(2);
1630           // Extract the element as scalars.
1631           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1632           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1633           
1634           switch (II->getIntrinsicID()) {
1635           default: assert(0 && "Case stmts out of sync!");
1636           case Intrinsic::x86_sse_sub_ss:
1637           case Intrinsic::x86_sse2_sub_sd:
1638             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1639                                                         II->getName()), *II);
1640             break;
1641           case Intrinsic::x86_sse_mul_ss:
1642           case Intrinsic::x86_sse2_mul_sd:
1643             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1644                                                          II->getName()), *II);
1645             break;
1646           }
1647           
1648           Instruction *New =
1649             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1650                                   II->getName());
1651           InsertNewInstBefore(New, *II);
1652           AddSoonDeadInstToWorklist(*II, 0);
1653           return New;
1654         }            
1655       }
1656         
1657       // Output elements are undefined if both are undefined.  Consider things
1658       // like undef&0.  The result is known zero, not undef.
1659       UndefElts &= UndefElts2;
1660       break;
1661     }
1662     break;
1663   }
1664   }
1665   return MadeChange ? I : 0;
1666 }
1667
1668 /// @returns true if the specified compare predicate is
1669 /// true when both operands are equal...
1670 /// @brief Determine if the icmp Predicate is true when both operands are equal
1671 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1672   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1673          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1674          pred == ICmpInst::ICMP_SLE;
1675 }
1676
1677 /// @returns true if the specified compare instruction is
1678 /// true when both operands are equal...
1679 /// @brief Determine if the ICmpInst returns true when both operands are equal
1680 static bool isTrueWhenEqual(ICmpInst &ICI) {
1681   return isTrueWhenEqual(ICI.getPredicate());
1682 }
1683
1684 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1685 /// function is designed to check a chain of associative operators for a
1686 /// potential to apply a certain optimization.  Since the optimization may be
1687 /// applicable if the expression was reassociated, this checks the chain, then
1688 /// reassociates the expression as necessary to expose the optimization
1689 /// opportunity.  This makes use of a special Functor, which must define
1690 /// 'shouldApply' and 'apply' methods.
1691 ///
1692 template<typename Functor>
1693 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1694   unsigned Opcode = Root.getOpcode();
1695   Value *LHS = Root.getOperand(0);
1696
1697   // Quick check, see if the immediate LHS matches...
1698   if (F.shouldApply(LHS))
1699     return F.apply(Root);
1700
1701   // Otherwise, if the LHS is not of the same opcode as the root, return.
1702   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1703   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1704     // Should we apply this transform to the RHS?
1705     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1706
1707     // If not to the RHS, check to see if we should apply to the LHS...
1708     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1709       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1710       ShouldApply = true;
1711     }
1712
1713     // If the functor wants to apply the optimization to the RHS of LHSI,
1714     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1715     if (ShouldApply) {
1716       BasicBlock *BB = Root.getParent();
1717
1718       // Now all of the instructions are in the current basic block, go ahead
1719       // and perform the reassociation.
1720       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1721
1722       // First move the selected RHS to the LHS of the root...
1723       Root.setOperand(0, LHSI->getOperand(1));
1724
1725       // Make what used to be the LHS of the root be the user of the root...
1726       Value *ExtraOperand = TmpLHSI->getOperand(1);
1727       if (&Root == TmpLHSI) {
1728         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1729         return 0;
1730       }
1731       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1732       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1733       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1734       BasicBlock::iterator ARI = &Root; ++ARI;
1735       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1736       ARI = Root;
1737
1738       // Now propagate the ExtraOperand down the chain of instructions until we
1739       // get to LHSI.
1740       while (TmpLHSI != LHSI) {
1741         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1742         // Move the instruction to immediately before the chain we are
1743         // constructing to avoid breaking dominance properties.
1744         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1745         BB->getInstList().insert(ARI, NextLHSI);
1746         ARI = NextLHSI;
1747
1748         Value *NextOp = NextLHSI->getOperand(1);
1749         NextLHSI->setOperand(1, ExtraOperand);
1750         TmpLHSI = NextLHSI;
1751         ExtraOperand = NextOp;
1752       }
1753
1754       // Now that the instructions are reassociated, have the functor perform
1755       // the transformation...
1756       return F.apply(Root);
1757     }
1758
1759     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1760   }
1761   return 0;
1762 }
1763
1764
1765 // AddRHS - Implements: X + X --> X << 1
1766 struct AddRHS {
1767   Value *RHS;
1768   AddRHS(Value *rhs) : RHS(rhs) {}
1769   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1770   Instruction *apply(BinaryOperator &Add) const {
1771     return BinaryOperator::createShl(Add.getOperand(0),
1772                                   ConstantInt::get(Add.getType(), 1));
1773   }
1774 };
1775
1776 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1777 //                 iff C1&C2 == 0
1778 struct AddMaskingAnd {
1779   Constant *C2;
1780   AddMaskingAnd(Constant *c) : C2(c) {}
1781   bool shouldApply(Value *LHS) const {
1782     ConstantInt *C1;
1783     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1784            ConstantExpr::getAnd(C1, C2)->isNullValue();
1785   }
1786   Instruction *apply(BinaryOperator &Add) const {
1787     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1788   }
1789 };
1790
1791 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1792                                              InstCombiner *IC) {
1793   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1794     if (Constant *SOC = dyn_cast<Constant>(SO))
1795       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1796
1797     return IC->InsertNewInstBefore(CastInst::create(
1798           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1799   }
1800
1801   // Figure out if the constant is the left or the right argument.
1802   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1803   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1804
1805   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1806     if (ConstIsRHS)
1807       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1808     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1809   }
1810
1811   Value *Op0 = SO, *Op1 = ConstOperand;
1812   if (!ConstIsRHS)
1813     std::swap(Op0, Op1);
1814   Instruction *New;
1815   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1816     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1817   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1818     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1819                           SO->getName()+".cmp");
1820   else {
1821     assert(0 && "Unknown binary instruction type!");
1822     abort();
1823   }
1824   return IC->InsertNewInstBefore(New, I);
1825 }
1826
1827 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1828 // constant as the other operand, try to fold the binary operator into the
1829 // select arguments.  This also works for Cast instructions, which obviously do
1830 // not have a second operand.
1831 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1832                                      InstCombiner *IC) {
1833   // Don't modify shared select instructions
1834   if (!SI->hasOneUse()) return 0;
1835   Value *TV = SI->getOperand(1);
1836   Value *FV = SI->getOperand(2);
1837
1838   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1839     // Bool selects with constant operands can be folded to logical ops.
1840     if (SI->getType() == Type::Int1Ty) return 0;
1841
1842     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1843     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1844
1845     return new SelectInst(SI->getCondition(), SelectTrueVal,
1846                           SelectFalseVal);
1847   }
1848   return 0;
1849 }
1850
1851
1852 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1853 /// node as operand #0, see if we can fold the instruction into the PHI (which
1854 /// is only possible if all operands to the PHI are constants).
1855 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1856   PHINode *PN = cast<PHINode>(I.getOperand(0));
1857   unsigned NumPHIValues = PN->getNumIncomingValues();
1858   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1859
1860   // Check to see if all of the operands of the PHI are constants.  If there is
1861   // one non-constant value, remember the BB it is.  If there is more than one
1862   // or if *it* is a PHI, bail out.
1863   BasicBlock *NonConstBB = 0;
1864   for (unsigned i = 0; i != NumPHIValues; ++i)
1865     if (!isa<Constant>(PN->getIncomingValue(i))) {
1866       if (NonConstBB) return 0;  // More than one non-const value.
1867       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1868       NonConstBB = PN->getIncomingBlock(i);
1869       
1870       // If the incoming non-constant value is in I's block, we have an infinite
1871       // loop.
1872       if (NonConstBB == I.getParent())
1873         return 0;
1874     }
1875   
1876   // If there is exactly one non-constant value, we can insert a copy of the
1877   // operation in that block.  However, if this is a critical edge, we would be
1878   // inserting the computation one some other paths (e.g. inside a loop).  Only
1879   // do this if the pred block is unconditionally branching into the phi block.
1880   if (NonConstBB) {
1881     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1882     if (!BI || !BI->isUnconditional()) return 0;
1883   }
1884
1885   // Okay, we can do the transformation: create the new PHI node.
1886   PHINode *NewPN = new PHINode(I.getType(), "");
1887   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1888   InsertNewInstBefore(NewPN, *PN);
1889   NewPN->takeName(PN);
1890
1891   // Next, add all of the operands to the PHI.
1892   if (I.getNumOperands() == 2) {
1893     Constant *C = cast<Constant>(I.getOperand(1));
1894     for (unsigned i = 0; i != NumPHIValues; ++i) {
1895       Value *InV = 0;
1896       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1897         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1898           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1899         else
1900           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1901       } else {
1902         assert(PN->getIncomingBlock(i) == NonConstBB);
1903         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1904           InV = BinaryOperator::create(BO->getOpcode(),
1905                                        PN->getIncomingValue(i), C, "phitmp",
1906                                        NonConstBB->getTerminator());
1907         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1908           InV = CmpInst::create(CI->getOpcode(), 
1909                                 CI->getPredicate(),
1910                                 PN->getIncomingValue(i), C, "phitmp",
1911                                 NonConstBB->getTerminator());
1912         else
1913           assert(0 && "Unknown binop!");
1914         
1915         AddToWorkList(cast<Instruction>(InV));
1916       }
1917       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1918     }
1919   } else { 
1920     CastInst *CI = cast<CastInst>(&I);
1921     const Type *RetTy = CI->getType();
1922     for (unsigned i = 0; i != NumPHIValues; ++i) {
1923       Value *InV;
1924       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1925         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1926       } else {
1927         assert(PN->getIncomingBlock(i) == NonConstBB);
1928         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1929                                I.getType(), "phitmp", 
1930                                NonConstBB->getTerminator());
1931         AddToWorkList(cast<Instruction>(InV));
1932       }
1933       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1934     }
1935   }
1936   return ReplaceInstUsesWith(I, NewPN);
1937 }
1938
1939 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1940   bool Changed = SimplifyCommutative(I);
1941   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1942
1943   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1944     // X + undef -> undef
1945     if (isa<UndefValue>(RHS))
1946       return ReplaceInstUsesWith(I, RHS);
1947
1948     // X + 0 --> X
1949     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1950       if (RHSC->isNullValue())
1951         return ReplaceInstUsesWith(I, LHS);
1952     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1953       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1954                               (I.getType())->getValueAPF()))
1955         return ReplaceInstUsesWith(I, LHS);
1956     }
1957
1958     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1959       // X + (signbit) --> X ^ signbit
1960       const APInt& Val = CI->getValue();
1961       uint32_t BitWidth = Val.getBitWidth();
1962       if (Val == APInt::getSignBit(BitWidth))
1963         return BinaryOperator::createXor(LHS, RHS);
1964       
1965       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1966       // (X & 254)+1 -> (X&254)|1
1967       if (!isa<VectorType>(I.getType())) {
1968         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1969         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1970                                  KnownZero, KnownOne))
1971           return &I;
1972       }
1973     }
1974
1975     if (isa<PHINode>(LHS))
1976       if (Instruction *NV = FoldOpIntoPhi(I))
1977         return NV;
1978     
1979     ConstantInt *XorRHS = 0;
1980     Value *XorLHS = 0;
1981     if (isa<ConstantInt>(RHSC) &&
1982         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1983       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1984       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1985       
1986       uint32_t Size = TySizeBits / 2;
1987       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1988       APInt CFF80Val(-C0080Val);
1989       do {
1990         if (TySizeBits > Size) {
1991           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1992           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1993           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1994               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1995             // This is a sign extend if the top bits are known zero.
1996             if (!MaskedValueIsZero(XorLHS, 
1997                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1998               Size = 0;  // Not a sign ext, but can't be any others either.
1999             break;
2000           }
2001         }
2002         Size >>= 1;
2003         C0080Val = APIntOps::lshr(C0080Val, Size);
2004         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2005       } while (Size >= 1);
2006       
2007       // FIXME: This shouldn't be necessary. When the backends can handle types
2008       // with funny bit widths then this whole cascade of if statements should
2009       // be removed. It is just here to get the size of the "middle" type back
2010       // up to something that the back ends can handle.
2011       const Type *MiddleType = 0;
2012       switch (Size) {
2013         default: break;
2014         case 32: MiddleType = Type::Int32Ty; break;
2015         case 16: MiddleType = Type::Int16Ty; break;
2016         case  8: MiddleType = Type::Int8Ty; break;
2017       }
2018       if (MiddleType) {
2019         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2020         InsertNewInstBefore(NewTrunc, I);
2021         return new SExtInst(NewTrunc, I.getType(), I.getName());
2022       }
2023     }
2024   }
2025
2026   // X + X --> X << 1
2027   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2028     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2029
2030     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2031       if (RHSI->getOpcode() == Instruction::Sub)
2032         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2033           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2034     }
2035     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2036       if (LHSI->getOpcode() == Instruction::Sub)
2037         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2038           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2039     }
2040   }
2041
2042   // -A + B  -->  B - A
2043   if (Value *V = dyn_castNegVal(LHS))
2044     return BinaryOperator::createSub(RHS, V);
2045
2046   // A + -B  -->  A - B
2047   if (!isa<Constant>(RHS))
2048     if (Value *V = dyn_castNegVal(RHS))
2049       return BinaryOperator::createSub(LHS, V);
2050
2051
2052   ConstantInt *C2;
2053   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2054     if (X == RHS)   // X*C + X --> X * (C+1)
2055       return BinaryOperator::createMul(RHS, AddOne(C2));
2056
2057     // X*C1 + X*C2 --> X * (C1+C2)
2058     ConstantInt *C1;
2059     if (X == dyn_castFoldableMul(RHS, C1))
2060       return BinaryOperator::createMul(X, Add(C1, C2));
2061   }
2062
2063   // X + X*C --> X * (C+1)
2064   if (dyn_castFoldableMul(RHS, C2) == LHS)
2065     return BinaryOperator::createMul(LHS, AddOne(C2));
2066
2067   // X + ~X --> -1   since   ~X = -X-1
2068   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2069     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2070   
2071
2072   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2073   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2074     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2075       return R;
2076
2077   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2078     Value *X = 0;
2079     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2080       return BinaryOperator::createSub(SubOne(CRHS), X);
2081
2082     // (X & FF00) + xx00  -> (X+xx00) & FF00
2083     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2084       Constant *Anded = And(CRHS, C2);
2085       if (Anded == CRHS) {
2086         // See if all bits from the first bit set in the Add RHS up are included
2087         // in the mask.  First, get the rightmost bit.
2088         const APInt& AddRHSV = CRHS->getValue();
2089
2090         // Form a mask of all bits from the lowest bit added through the top.
2091         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2092
2093         // See if the and mask includes all of these bits.
2094         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2095
2096         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2097           // Okay, the xform is safe.  Insert the new add pronto.
2098           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2099                                                             LHS->getName()), I);
2100           return BinaryOperator::createAnd(NewAdd, C2);
2101         }
2102       }
2103     }
2104
2105     // Try to fold constant add into select arguments.
2106     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2107       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2108         return R;
2109   }
2110
2111   // add (cast *A to intptrtype) B -> 
2112   //   cast (GEP (cast *A to sbyte*) B) -> 
2113   //     intptrtype
2114   {
2115     CastInst *CI = dyn_cast<CastInst>(LHS);
2116     Value *Other = RHS;
2117     if (!CI) {
2118       CI = dyn_cast<CastInst>(RHS);
2119       Other = LHS;
2120     }
2121     if (CI && CI->getType()->isSized() && 
2122         (CI->getType()->getPrimitiveSizeInBits() == 
2123          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2124         && isa<PointerType>(CI->getOperand(0)->getType())) {
2125       Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2126                                    PointerType::get(Type::Int8Ty), I);
2127       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2128       return new PtrToIntInst(I2, CI->getType());
2129     }
2130   }
2131
2132   return Changed ? &I : 0;
2133 }
2134
2135 // isSignBit - Return true if the value represented by the constant only has the
2136 // highest order bit set.
2137 static bool isSignBit(ConstantInt *CI) {
2138   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2139   return CI->getValue() == APInt::getSignBit(NumBits);
2140 }
2141
2142 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2143   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2144
2145   if (Op0 == Op1)         // sub X, X  -> 0
2146     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2147
2148   // If this is a 'B = x-(-A)', change to B = x+A...
2149   if (Value *V = dyn_castNegVal(Op1))
2150     return BinaryOperator::createAdd(Op0, V);
2151
2152   if (isa<UndefValue>(Op0))
2153     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2154   if (isa<UndefValue>(Op1))
2155     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2156
2157   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2158     // Replace (-1 - A) with (~A)...
2159     if (C->isAllOnesValue())
2160       return BinaryOperator::createNot(Op1);
2161
2162     // C - ~X == X + (1+C)
2163     Value *X = 0;
2164     if (match(Op1, m_Not(m_Value(X))))
2165       return BinaryOperator::createAdd(X, AddOne(C));
2166
2167     // -(X >>u 31) -> (X >>s 31)
2168     // -(X >>s 31) -> (X >>u 31)
2169     if (C->isZero()) {
2170       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2171         if (SI->getOpcode() == Instruction::LShr) {
2172           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2173             // Check to see if we are shifting out everything but the sign bit.
2174             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2175                 SI->getType()->getPrimitiveSizeInBits()-1) {
2176               // Ok, the transformation is safe.  Insert AShr.
2177               return BinaryOperator::create(Instruction::AShr, 
2178                                           SI->getOperand(0), CU, SI->getName());
2179             }
2180           }
2181         }
2182         else if (SI->getOpcode() == Instruction::AShr) {
2183           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2184             // Check to see if we are shifting out everything but the sign bit.
2185             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2186                 SI->getType()->getPrimitiveSizeInBits()-1) {
2187               // Ok, the transformation is safe.  Insert LShr. 
2188               return BinaryOperator::createLShr(
2189                                           SI->getOperand(0), CU, SI->getName());
2190             }
2191           }
2192         } 
2193     }
2194
2195     // Try to fold constant sub into select arguments.
2196     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2197       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2198         return R;
2199
2200     if (isa<PHINode>(Op0))
2201       if (Instruction *NV = FoldOpIntoPhi(I))
2202         return NV;
2203   }
2204
2205   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2206     if (Op1I->getOpcode() == Instruction::Add &&
2207         !Op0->getType()->isFPOrFPVector()) {
2208       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2209         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2210       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2211         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2212       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2213         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2214           // C1-(X+C2) --> (C1-C2)-X
2215           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2216                                            Op1I->getOperand(0));
2217       }
2218     }
2219
2220     if (Op1I->hasOneUse()) {
2221       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2222       // is not used by anyone else...
2223       //
2224       if (Op1I->getOpcode() == Instruction::Sub &&
2225           !Op1I->getType()->isFPOrFPVector()) {
2226         // Swap the two operands of the subexpr...
2227         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2228         Op1I->setOperand(0, IIOp1);
2229         Op1I->setOperand(1, IIOp0);
2230
2231         // Create the new top level add instruction...
2232         return BinaryOperator::createAdd(Op0, Op1);
2233       }
2234
2235       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2236       //
2237       if (Op1I->getOpcode() == Instruction::And &&
2238           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2239         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2240
2241         Value *NewNot =
2242           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2243         return BinaryOperator::createAnd(Op0, NewNot);
2244       }
2245
2246       // 0 - (X sdiv C)  -> (X sdiv -C)
2247       if (Op1I->getOpcode() == Instruction::SDiv)
2248         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2249           if (CSI->isZero())
2250             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2251               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2252                                                ConstantExpr::getNeg(DivRHS));
2253
2254       // X - X*C --> X * (1-C)
2255       ConstantInt *C2 = 0;
2256       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2257         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2258         return BinaryOperator::createMul(Op0, CP1);
2259       }
2260
2261       // X - ((X / Y) * Y) --> X % Y
2262       if (Op1I->getOpcode() == Instruction::Mul)
2263         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2264           if (Op0 == I->getOperand(0) &&
2265               Op1I->getOperand(1) == I->getOperand(1)) {
2266             if (I->getOpcode() == Instruction::SDiv)
2267               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2268             if (I->getOpcode() == Instruction::UDiv)
2269               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2270           }
2271     }
2272   }
2273
2274   if (!Op0->getType()->isFPOrFPVector())
2275     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2276       if (Op0I->getOpcode() == Instruction::Add) {
2277         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2278           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2279         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2280           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2281       } else if (Op0I->getOpcode() == Instruction::Sub) {
2282         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2283           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2284       }
2285
2286   ConstantInt *C1;
2287   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2288     if (X == Op1)  // X*C - X --> X * (C-1)
2289       return BinaryOperator::createMul(Op1, SubOne(C1));
2290
2291     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2292     if (X == dyn_castFoldableMul(Op1, C2))
2293       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2294   }
2295   return 0;
2296 }
2297
2298 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2299 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2300 /// TrueIfSigned if the result of the comparison is true when the input value is
2301 /// signed.
2302 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2303                            bool &TrueIfSigned) {
2304   switch (pred) {
2305   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2306     TrueIfSigned = true;
2307     return RHS->isZero();
2308   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2309     TrueIfSigned = true;
2310     return RHS->isAllOnesValue();
2311   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2312     TrueIfSigned = false;
2313     return RHS->isAllOnesValue();
2314   case ICmpInst::ICMP_UGT:
2315     // True if LHS u> RHS and RHS == high-bit-mask - 1
2316     TrueIfSigned = true;
2317     return RHS->getValue() ==
2318       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2319   case ICmpInst::ICMP_UGE: 
2320     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2321     TrueIfSigned = true;
2322     return RHS->getValue() == 
2323       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2324   default:
2325     return false;
2326   }
2327 }
2328
2329 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2330   bool Changed = SimplifyCommutative(I);
2331   Value *Op0 = I.getOperand(0);
2332
2333   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2334     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2335
2336   // Simplify mul instructions with a constant RHS...
2337   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2338     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2339
2340       // ((X << C1)*C2) == (X * (C2 << C1))
2341       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2342         if (SI->getOpcode() == Instruction::Shl)
2343           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2344             return BinaryOperator::createMul(SI->getOperand(0),
2345                                              ConstantExpr::getShl(CI, ShOp));
2346
2347       if (CI->isZero())
2348         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2349       if (CI->equalsInt(1))                  // X * 1  == X
2350         return ReplaceInstUsesWith(I, Op0);
2351       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2352         return BinaryOperator::createNeg(Op0, I.getName());
2353
2354       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2355       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2356         return BinaryOperator::createShl(Op0,
2357                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2358       }
2359     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2360       if (Op1F->isNullValue())
2361         return ReplaceInstUsesWith(I, Op1);
2362
2363       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2364       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2365       // We need a better interface for long double here.
2366       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2367         if (Op1F->isExactlyValue(1.0))
2368           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2369     }
2370     
2371     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2372       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2373           isa<ConstantInt>(Op0I->getOperand(1))) {
2374         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2375         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2376                                                      Op1, "tmp");
2377         InsertNewInstBefore(Add, I);
2378         Value *C1C2 = ConstantExpr::getMul(Op1, 
2379                                            cast<Constant>(Op0I->getOperand(1)));
2380         return BinaryOperator::createAdd(Add, C1C2);
2381         
2382       }
2383
2384     // Try to fold constant mul into select arguments.
2385     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2386       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2387         return R;
2388
2389     if (isa<PHINode>(Op0))
2390       if (Instruction *NV = FoldOpIntoPhi(I))
2391         return NV;
2392   }
2393
2394   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2395     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2396       return BinaryOperator::createMul(Op0v, Op1v);
2397
2398   // If one of the operands of the multiply is a cast from a boolean value, then
2399   // we know the bool is either zero or one, so this is a 'masking' multiply.
2400   // See if we can simplify things based on how the boolean was originally
2401   // formed.
2402   CastInst *BoolCast = 0;
2403   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2404     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2405       BoolCast = CI;
2406   if (!BoolCast)
2407     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2408       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2409         BoolCast = CI;
2410   if (BoolCast) {
2411     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2412       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2413       const Type *SCOpTy = SCIOp0->getType();
2414       bool TIS = false;
2415       
2416       // If the icmp is true iff the sign bit of X is set, then convert this
2417       // multiply into a shift/and combination.
2418       if (isa<ConstantInt>(SCIOp1) &&
2419           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2420           TIS) {
2421         // Shift the X value right to turn it into "all signbits".
2422         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2423                                           SCOpTy->getPrimitiveSizeInBits()-1);
2424         Value *V =
2425           InsertNewInstBefore(
2426             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2427                                             BoolCast->getOperand(0)->getName()+
2428                                             ".mask"), I);
2429
2430         // If the multiply type is not the same as the source type, sign extend
2431         // or truncate to the multiply type.
2432         if (I.getType() != V->getType()) {
2433           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2434           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2435           Instruction::CastOps opcode = 
2436             (SrcBits == DstBits ? Instruction::BitCast : 
2437              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2438           V = InsertCastBefore(opcode, V, I.getType(), I);
2439         }
2440
2441         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2442         return BinaryOperator::createAnd(V, OtherOp);
2443       }
2444     }
2445   }
2446
2447   return Changed ? &I : 0;
2448 }
2449
2450 /// This function implements the transforms on div instructions that work
2451 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2452 /// used by the visitors to those instructions.
2453 /// @brief Transforms common to all three div instructions
2454 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2455   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2456
2457   // undef / X -> 0
2458   if (isa<UndefValue>(Op0))
2459     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2460
2461   // X / undef -> undef
2462   if (isa<UndefValue>(Op1))
2463     return ReplaceInstUsesWith(I, Op1);
2464
2465   // Handle cases involving: div X, (select Cond, Y, Z)
2466   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2467     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2468     // same basic block, then we replace the select with Y, and the condition 
2469     // of the select with false (if the cond value is in the same BB).  If the
2470     // select has uses other than the div, this allows them to be simplified
2471     // also. Note that div X, Y is just as good as div X, 0 (undef)
2472     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2473       if (ST->isNullValue()) {
2474         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2475         if (CondI && CondI->getParent() == I.getParent())
2476           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2477         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2478           I.setOperand(1, SI->getOperand(2));
2479         else
2480           UpdateValueUsesWith(SI, SI->getOperand(2));
2481         return &I;
2482       }
2483
2484     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2485     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2486       if (ST->isNullValue()) {
2487         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2488         if (CondI && CondI->getParent() == I.getParent())
2489           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2490         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2491           I.setOperand(1, SI->getOperand(1));
2492         else
2493           UpdateValueUsesWith(SI, SI->getOperand(1));
2494         return &I;
2495       }
2496   }
2497
2498   return 0;
2499 }
2500
2501 /// This function implements the transforms common to both integer division
2502 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2503 /// division instructions.
2504 /// @brief Common integer divide transforms
2505 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2506   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2507
2508   if (Instruction *Common = commonDivTransforms(I))
2509     return Common;
2510
2511   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2512     // div X, 1 == X
2513     if (RHS->equalsInt(1))
2514       return ReplaceInstUsesWith(I, Op0);
2515
2516     // (X / C1) / C2  -> X / (C1*C2)
2517     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2518       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2519         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2520           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2521                                         Multiply(RHS, LHSRHS));
2522         }
2523
2524     if (!RHS->isZero()) { // avoid X udiv 0
2525       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2526         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2527           return R;
2528       if (isa<PHINode>(Op0))
2529         if (Instruction *NV = FoldOpIntoPhi(I))
2530           return NV;
2531     }
2532   }
2533
2534   // 0 / X == 0, we don't need to preserve faults!
2535   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2536     if (LHS->equalsInt(0))
2537       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2538
2539   return 0;
2540 }
2541
2542 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2543   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2544
2545   // Handle the integer div common cases
2546   if (Instruction *Common = commonIDivTransforms(I))
2547     return Common;
2548
2549   // X udiv C^2 -> X >> C
2550   // Check to see if this is an unsigned division with an exact power of 2,
2551   // if so, convert to a right shift.
2552   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2553     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2554       return BinaryOperator::createLShr(Op0, 
2555                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2556   }
2557
2558   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2559   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2560     if (RHSI->getOpcode() == Instruction::Shl &&
2561         isa<ConstantInt>(RHSI->getOperand(0))) {
2562       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2563       if (C1.isPowerOf2()) {
2564         Value *N = RHSI->getOperand(1);
2565         const Type *NTy = N->getType();
2566         if (uint32_t C2 = C1.logBase2()) {
2567           Constant *C2V = ConstantInt::get(NTy, C2);
2568           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2569         }
2570         return BinaryOperator::createLShr(Op0, N);
2571       }
2572     }
2573   }
2574   
2575   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2576   // where C1&C2 are powers of two.
2577   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2578     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2579       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2580         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2581         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2582           // Compute the shift amounts
2583           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2584           // Construct the "on true" case of the select
2585           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2586           Instruction *TSI = BinaryOperator::createLShr(
2587                                                  Op0, TC, SI->getName()+".t");
2588           TSI = InsertNewInstBefore(TSI, I);
2589   
2590           // Construct the "on false" case of the select
2591           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2592           Instruction *FSI = BinaryOperator::createLShr(
2593                                                  Op0, FC, SI->getName()+".f");
2594           FSI = InsertNewInstBefore(FSI, I);
2595
2596           // construct the select instruction and return it.
2597           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2598         }
2599       }
2600   return 0;
2601 }
2602
2603 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2604   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2605
2606   // Handle the integer div common cases
2607   if (Instruction *Common = commonIDivTransforms(I))
2608     return Common;
2609
2610   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2611     // sdiv X, -1 == -X
2612     if (RHS->isAllOnesValue())
2613       return BinaryOperator::createNeg(Op0);
2614
2615     // -X/C -> X/-C
2616     if (Value *LHSNeg = dyn_castNegVal(Op0))
2617       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2618   }
2619
2620   // If the sign bits of both operands are zero (i.e. we can prove they are
2621   // unsigned inputs), turn this into a udiv.
2622   if (I.getType()->isInteger()) {
2623     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2624     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2625       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2626       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2627     }
2628   }      
2629   
2630   return 0;
2631 }
2632
2633 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2634   return commonDivTransforms(I);
2635 }
2636
2637 /// GetFactor - If we can prove that the specified value is at least a multiple
2638 /// of some factor, return that factor.
2639 static Constant *GetFactor(Value *V) {
2640   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2641     return CI;
2642   
2643   // Unless we can be tricky, we know this is a multiple of 1.
2644   Constant *Result = ConstantInt::get(V->getType(), 1);
2645   
2646   Instruction *I = dyn_cast<Instruction>(V);
2647   if (!I) return Result;
2648   
2649   if (I->getOpcode() == Instruction::Mul) {
2650     // Handle multiplies by a constant, etc.
2651     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2652                                 GetFactor(I->getOperand(1)));
2653   } else if (I->getOpcode() == Instruction::Shl) {
2654     // (X<<C) -> X * (1 << C)
2655     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2656       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2657       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2658     }
2659   } else if (I->getOpcode() == Instruction::And) {
2660     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2661       // X & 0xFFF0 is known to be a multiple of 16.
2662       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2663       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2664         return ConstantExpr::getShl(Result, 
2665                                     ConstantInt::get(Result->getType(), Zeros));
2666     }
2667   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2668     // Only handle int->int casts.
2669     if (!CI->isIntegerCast())
2670       return Result;
2671     Value *Op = CI->getOperand(0);
2672     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2673   }    
2674   return Result;
2675 }
2676
2677 /// This function implements the transforms on rem instructions that work
2678 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2679 /// is used by the visitors to those instructions.
2680 /// @brief Transforms common to all three rem instructions
2681 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2682   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2683
2684   // 0 % X == 0, we don't need to preserve faults!
2685   if (Constant *LHS = dyn_cast<Constant>(Op0))
2686     if (LHS->isNullValue())
2687       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2688
2689   if (isa<UndefValue>(Op0))              // undef % X -> 0
2690     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2691   if (isa<UndefValue>(Op1))
2692     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2693
2694   // Handle cases involving: rem X, (select Cond, Y, Z)
2695   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2696     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2697     // the same basic block, then we replace the select with Y, and the
2698     // condition of the select with false (if the cond value is in the same
2699     // BB).  If the select has uses other than the div, this allows them to be
2700     // simplified also.
2701     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2702       if (ST->isNullValue()) {
2703         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2704         if (CondI && CondI->getParent() == I.getParent())
2705           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2706         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2707           I.setOperand(1, SI->getOperand(2));
2708         else
2709           UpdateValueUsesWith(SI, SI->getOperand(2));
2710         return &I;
2711       }
2712     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2713     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2714       if (ST->isNullValue()) {
2715         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2716         if (CondI && CondI->getParent() == I.getParent())
2717           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2718         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2719           I.setOperand(1, SI->getOperand(1));
2720         else
2721           UpdateValueUsesWith(SI, SI->getOperand(1));
2722         return &I;
2723       }
2724   }
2725
2726   return 0;
2727 }
2728
2729 /// This function implements the transforms common to both integer remainder
2730 /// instructions (urem and srem). It is called by the visitors to those integer
2731 /// remainder instructions.
2732 /// @brief Common integer remainder transforms
2733 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2734   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2735
2736   if (Instruction *common = commonRemTransforms(I))
2737     return common;
2738
2739   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2740     // X % 0 == undef, we don't need to preserve faults!
2741     if (RHS->equalsInt(0))
2742       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2743     
2744     if (RHS->equalsInt(1))  // X % 1 == 0
2745       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2746
2747     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2748       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2749         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2750           return R;
2751       } else if (isa<PHINode>(Op0I)) {
2752         if (Instruction *NV = FoldOpIntoPhi(I))
2753           return NV;
2754       }
2755       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2756       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2757         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2758     }
2759   }
2760
2761   return 0;
2762 }
2763
2764 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2765   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2766
2767   if (Instruction *common = commonIRemTransforms(I))
2768     return common;
2769   
2770   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2771     // X urem C^2 -> X and C
2772     // Check to see if this is an unsigned remainder with an exact power of 2,
2773     // if so, convert to a bitwise and.
2774     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2775       if (C->getValue().isPowerOf2())
2776         return BinaryOperator::createAnd(Op0, SubOne(C));
2777   }
2778
2779   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2780     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2781     if (RHSI->getOpcode() == Instruction::Shl &&
2782         isa<ConstantInt>(RHSI->getOperand(0))) {
2783       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2784         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2785         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2786                                                                    "tmp"), I);
2787         return BinaryOperator::createAnd(Op0, Add);
2788       }
2789     }
2790   }
2791
2792   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2793   // where C1&C2 are powers of two.
2794   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2795     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2796       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2797         // STO == 0 and SFO == 0 handled above.
2798         if ((STO->getValue().isPowerOf2()) && 
2799             (SFO->getValue().isPowerOf2())) {
2800           Value *TrueAnd = InsertNewInstBefore(
2801             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2802           Value *FalseAnd = InsertNewInstBefore(
2803             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2804           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2805         }
2806       }
2807   }
2808   
2809   return 0;
2810 }
2811
2812 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2813   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2814
2815   // Handle the integer rem common cases
2816   if (Instruction *common = commonIRemTransforms(I))
2817     return common;
2818   
2819   if (Value *RHSNeg = dyn_castNegVal(Op1))
2820     if (!isa<ConstantInt>(RHSNeg) || 
2821         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2822       // X % -Y -> X % Y
2823       AddUsesToWorkList(I);
2824       I.setOperand(1, RHSNeg);
2825       return &I;
2826     }
2827  
2828   // If the sign bits of both operands are zero (i.e. we can prove they are
2829   // unsigned inputs), turn this into a urem.
2830   if (I.getType()->isInteger()) {
2831     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2832     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2833       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2834       return BinaryOperator::createURem(Op0, Op1, I.getName());
2835     }
2836   }
2837
2838   return 0;
2839 }
2840
2841 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2842   return commonRemTransforms(I);
2843 }
2844
2845 // isMaxValueMinusOne - return true if this is Max-1
2846 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2847   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2848   if (!isSigned)
2849     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2850   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2851 }
2852
2853 // isMinValuePlusOne - return true if this is Min+1
2854 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2855   if (!isSigned)
2856     return C->getValue() == 1; // unsigned
2857     
2858   // Calculate 1111111111000000000000
2859   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2860   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2861 }
2862
2863 // isOneBitSet - Return true if there is exactly one bit set in the specified
2864 // constant.
2865 static bool isOneBitSet(const ConstantInt *CI) {
2866   return CI->getValue().isPowerOf2();
2867 }
2868
2869 // isHighOnes - Return true if the constant is of the form 1+0+.
2870 // This is the same as lowones(~X).
2871 static bool isHighOnes(const ConstantInt *CI) {
2872   return (~CI->getValue() + 1).isPowerOf2();
2873 }
2874
2875 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2876 /// are carefully arranged to allow folding of expressions such as:
2877 ///
2878 ///      (A < B) | (A > B) --> (A != B)
2879 ///
2880 /// Note that this is only valid if the first and second predicates have the
2881 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2882 ///
2883 /// Three bits are used to represent the condition, as follows:
2884 ///   0  A > B
2885 ///   1  A == B
2886 ///   2  A < B
2887 ///
2888 /// <=>  Value  Definition
2889 /// 000     0   Always false
2890 /// 001     1   A >  B
2891 /// 010     2   A == B
2892 /// 011     3   A >= B
2893 /// 100     4   A <  B
2894 /// 101     5   A != B
2895 /// 110     6   A <= B
2896 /// 111     7   Always true
2897 ///  
2898 static unsigned getICmpCode(const ICmpInst *ICI) {
2899   switch (ICI->getPredicate()) {
2900     // False -> 0
2901   case ICmpInst::ICMP_UGT: return 1;  // 001
2902   case ICmpInst::ICMP_SGT: return 1;  // 001
2903   case ICmpInst::ICMP_EQ:  return 2;  // 010
2904   case ICmpInst::ICMP_UGE: return 3;  // 011
2905   case ICmpInst::ICMP_SGE: return 3;  // 011
2906   case ICmpInst::ICMP_ULT: return 4;  // 100
2907   case ICmpInst::ICMP_SLT: return 4;  // 100
2908   case ICmpInst::ICMP_NE:  return 5;  // 101
2909   case ICmpInst::ICMP_ULE: return 6;  // 110
2910   case ICmpInst::ICMP_SLE: return 6;  // 110
2911     // True -> 7
2912   default:
2913     assert(0 && "Invalid ICmp predicate!");
2914     return 0;
2915   }
2916 }
2917
2918 /// getICmpValue - This is the complement of getICmpCode, which turns an
2919 /// opcode and two operands into either a constant true or false, or a brand 
2920 /// new ICmp instruction. The sign is passed in to determine which kind
2921 /// of predicate to use in new icmp instructions.
2922 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2923   switch (code) {
2924   default: assert(0 && "Illegal ICmp code!");
2925   case  0: return ConstantInt::getFalse();
2926   case  1: 
2927     if (sign)
2928       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2929     else
2930       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2931   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
2932   case  3: 
2933     if (sign)
2934       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2935     else
2936       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2937   case  4: 
2938     if (sign)
2939       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2940     else
2941       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2942   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
2943   case  6: 
2944     if (sign)
2945       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2946     else
2947       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2948   case  7: return ConstantInt::getTrue();
2949   }
2950 }
2951
2952 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2953   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2954     (ICmpInst::isSignedPredicate(p1) && 
2955      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2956     (ICmpInst::isSignedPredicate(p2) && 
2957      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2958 }
2959
2960 namespace { 
2961 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2962 struct FoldICmpLogical {
2963   InstCombiner &IC;
2964   Value *LHS, *RHS;
2965   ICmpInst::Predicate pred;
2966   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2967     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2968       pred(ICI->getPredicate()) {}
2969   bool shouldApply(Value *V) const {
2970     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2971       if (PredicatesFoldable(pred, ICI->getPredicate()))
2972         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2973                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2974     return false;
2975   }
2976   Instruction *apply(Instruction &Log) const {
2977     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2978     if (ICI->getOperand(0) != LHS) {
2979       assert(ICI->getOperand(1) == LHS);
2980       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
2981     }
2982
2983     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2984     unsigned LHSCode = getICmpCode(ICI);
2985     unsigned RHSCode = getICmpCode(RHSICI);
2986     unsigned Code;
2987     switch (Log.getOpcode()) {
2988     case Instruction::And: Code = LHSCode & RHSCode; break;
2989     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2990     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2991     default: assert(0 && "Illegal logical opcode!"); return 0;
2992     }
2993
2994     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
2995                     ICmpInst::isSignedPredicate(ICI->getPredicate());
2996       
2997     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
2998     if (Instruction *I = dyn_cast<Instruction>(RV))
2999       return I;
3000     // Otherwise, it's a constant boolean value...
3001     return IC.ReplaceInstUsesWith(Log, RV);
3002   }
3003 };
3004 } // end anonymous namespace
3005
3006 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3007 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3008 // guaranteed to be a binary operator.
3009 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3010                                     ConstantInt *OpRHS,
3011                                     ConstantInt *AndRHS,
3012                                     BinaryOperator &TheAnd) {
3013   Value *X = Op->getOperand(0);
3014   Constant *Together = 0;
3015   if (!Op->isShift())
3016     Together = And(AndRHS, OpRHS);
3017
3018   switch (Op->getOpcode()) {
3019   case Instruction::Xor:
3020     if (Op->hasOneUse()) {
3021       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3022       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3023       InsertNewInstBefore(And, TheAnd);
3024       And->takeName(Op);
3025       return BinaryOperator::createXor(And, Together);
3026     }
3027     break;
3028   case Instruction::Or:
3029     if (Together == AndRHS) // (X | C) & C --> C
3030       return ReplaceInstUsesWith(TheAnd, AndRHS);
3031
3032     if (Op->hasOneUse() && Together != OpRHS) {
3033       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3034       Instruction *Or = BinaryOperator::createOr(X, Together);
3035       InsertNewInstBefore(Or, TheAnd);
3036       Or->takeName(Op);
3037       return BinaryOperator::createAnd(Or, AndRHS);
3038     }
3039     break;
3040   case Instruction::Add:
3041     if (Op->hasOneUse()) {
3042       // Adding a one to a single bit bit-field should be turned into an XOR
3043       // of the bit.  First thing to check is to see if this AND is with a
3044       // single bit constant.
3045       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3046
3047       // If there is only one bit set...
3048       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3049         // Ok, at this point, we know that we are masking the result of the
3050         // ADD down to exactly one bit.  If the constant we are adding has
3051         // no bits set below this bit, then we can eliminate the ADD.
3052         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3053
3054         // Check to see if any bits below the one bit set in AndRHSV are set.
3055         if ((AddRHS & (AndRHSV-1)) == 0) {
3056           // If not, the only thing that can effect the output of the AND is
3057           // the bit specified by AndRHSV.  If that bit is set, the effect of
3058           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3059           // no effect.
3060           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3061             TheAnd.setOperand(0, X);
3062             return &TheAnd;
3063           } else {
3064             // Pull the XOR out of the AND.
3065             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3066             InsertNewInstBefore(NewAnd, TheAnd);
3067             NewAnd->takeName(Op);
3068             return BinaryOperator::createXor(NewAnd, AndRHS);
3069           }
3070         }
3071       }
3072     }
3073     break;
3074
3075   case Instruction::Shl: {
3076     // We know that the AND will not produce any of the bits shifted in, so if
3077     // the anded constant includes them, clear them now!
3078     //
3079     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3080     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3081     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3082     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3083
3084     if (CI->getValue() == ShlMask) { 
3085     // Masking out bits that the shift already masks
3086       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3087     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3088       TheAnd.setOperand(1, CI);
3089       return &TheAnd;
3090     }
3091     break;
3092   }
3093   case Instruction::LShr:
3094   {
3095     // We know that the AND will not produce any of the bits shifted in, so if
3096     // the anded constant includes them, clear them now!  This only applies to
3097     // unsigned shifts, because a signed shr may bring in set bits!
3098     //
3099     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3100     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3101     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3102     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3103
3104     if (CI->getValue() == ShrMask) {   
3105     // Masking out bits that the shift already masks.
3106       return ReplaceInstUsesWith(TheAnd, Op);
3107     } else if (CI != AndRHS) {
3108       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3109       return &TheAnd;
3110     }
3111     break;
3112   }
3113   case Instruction::AShr:
3114     // Signed shr.
3115     // See if this is shifting in some sign extension, then masking it out
3116     // with an and.
3117     if (Op->hasOneUse()) {
3118       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3119       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3120       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3121       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3122       if (C == AndRHS) {          // Masking out bits shifted in.
3123         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3124         // Make the argument unsigned.
3125         Value *ShVal = Op->getOperand(0);
3126         ShVal = InsertNewInstBefore(
3127             BinaryOperator::createLShr(ShVal, OpRHS, 
3128                                    Op->getName()), TheAnd);
3129         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3130       }
3131     }
3132     break;
3133   }
3134   return 0;
3135 }
3136
3137
3138 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3139 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3140 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3141 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3142 /// insert new instructions.
3143 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3144                                            bool isSigned, bool Inside, 
3145                                            Instruction &IB) {
3146   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3147             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3148          "Lo is not <= Hi in range emission code!");
3149     
3150   if (Inside) {
3151     if (Lo == Hi)  // Trivially false.
3152       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3153
3154     // V >= Min && V < Hi --> V < Hi
3155     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3156       ICmpInst::Predicate pred = (isSigned ? 
3157         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3158       return new ICmpInst(pred, V, Hi);
3159     }
3160
3161     // Emit V-Lo <u Hi-Lo
3162     Constant *NegLo = ConstantExpr::getNeg(Lo);
3163     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3164     InsertNewInstBefore(Add, IB);
3165     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3166     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3167   }
3168
3169   if (Lo == Hi)  // Trivially true.
3170     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3171
3172   // V < Min || V >= Hi -> V > Hi-1
3173   Hi = SubOne(cast<ConstantInt>(Hi));
3174   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3175     ICmpInst::Predicate pred = (isSigned ? 
3176         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3177     return new ICmpInst(pred, V, Hi);
3178   }
3179
3180   // Emit V-Lo >u Hi-1-Lo
3181   // Note that Hi has already had one subtracted from it, above.
3182   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3183   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3184   InsertNewInstBefore(Add, IB);
3185   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3186   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3187 }
3188
3189 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3190 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3191 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3192 // not, since all 1s are not contiguous.
3193 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3194   const APInt& V = Val->getValue();
3195   uint32_t BitWidth = Val->getType()->getBitWidth();
3196   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3197
3198   // look for the first zero bit after the run of ones
3199   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3200   // look for the first non-zero bit
3201   ME = V.getActiveBits(); 
3202   return true;
3203 }
3204
3205 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3206 /// where isSub determines whether the operator is a sub.  If we can fold one of
3207 /// the following xforms:
3208 /// 
3209 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3210 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3211 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3212 ///
3213 /// return (A +/- B).
3214 ///
3215 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3216                                         ConstantInt *Mask, bool isSub,
3217                                         Instruction &I) {
3218   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3219   if (!LHSI || LHSI->getNumOperands() != 2 ||
3220       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3221
3222   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3223
3224   switch (LHSI->getOpcode()) {
3225   default: return 0;
3226   case Instruction::And:
3227     if (And(N, Mask) == Mask) {
3228       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3229       if ((Mask->getValue().countLeadingZeros() + 
3230            Mask->getValue().countPopulation()) == 
3231           Mask->getValue().getBitWidth())
3232         break;
3233
3234       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3235       // part, we don't need any explicit masks to take them out of A.  If that
3236       // is all N is, ignore it.
3237       uint32_t MB = 0, ME = 0;
3238       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3239         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3240         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3241         if (MaskedValueIsZero(RHS, Mask))
3242           break;
3243       }
3244     }
3245     return 0;
3246   case Instruction::Or:
3247   case Instruction::Xor:
3248     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3249     if ((Mask->getValue().countLeadingZeros() + 
3250          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3251         && And(N, Mask)->isZero())
3252       break;
3253     return 0;
3254   }
3255   
3256   Instruction *New;
3257   if (isSub)
3258     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3259   else
3260     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3261   return InsertNewInstBefore(New, I);
3262 }
3263
3264 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3265   bool Changed = SimplifyCommutative(I);
3266   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3267
3268   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3269     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3270
3271   // and X, X = X
3272   if (Op0 == Op1)
3273     return ReplaceInstUsesWith(I, Op1);
3274
3275   // See if we can simplify any instructions used by the instruction whose sole 
3276   // purpose is to compute bits we don't care about.
3277   if (!isa<VectorType>(I.getType())) {
3278     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3279     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3280     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3281                              KnownZero, KnownOne))
3282       return &I;
3283   } else {
3284     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3285       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3286         return ReplaceInstUsesWith(I, I.getOperand(0));
3287     } else if (isa<ConstantAggregateZero>(Op1)) {
3288       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3289     }
3290   }
3291   
3292   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3293     const APInt& AndRHSMask = AndRHS->getValue();
3294     APInt NotAndRHS(~AndRHSMask);
3295
3296     // Optimize a variety of ((val OP C1) & C2) combinations...
3297     if (isa<BinaryOperator>(Op0)) {
3298       Instruction *Op0I = cast<Instruction>(Op0);
3299       Value *Op0LHS = Op0I->getOperand(0);
3300       Value *Op0RHS = Op0I->getOperand(1);
3301       switch (Op0I->getOpcode()) {
3302       case Instruction::Xor:
3303       case Instruction::Or:
3304         // If the mask is only needed on one incoming arm, push it up.
3305         if (Op0I->hasOneUse()) {
3306           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3307             // Not masking anything out for the LHS, move to RHS.
3308             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3309                                                    Op0RHS->getName()+".masked");
3310             InsertNewInstBefore(NewRHS, I);
3311             return BinaryOperator::create(
3312                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3313           }
3314           if (!isa<Constant>(Op0RHS) &&
3315               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3316             // Not masking anything out for the RHS, move to LHS.
3317             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3318                                                    Op0LHS->getName()+".masked");
3319             InsertNewInstBefore(NewLHS, I);
3320             return BinaryOperator::create(
3321                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3322           }
3323         }
3324
3325         break;
3326       case Instruction::Add:
3327         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3328         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3329         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3330         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3331           return BinaryOperator::createAnd(V, AndRHS);
3332         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3333           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3334         break;
3335
3336       case Instruction::Sub:
3337         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3338         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3339         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3340         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3341           return BinaryOperator::createAnd(V, AndRHS);
3342         break;
3343       }
3344
3345       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3346         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3347           return Res;
3348     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3349       // If this is an integer truncation or change from signed-to-unsigned, and
3350       // if the source is an and/or with immediate, transform it.  This
3351       // frequently occurs for bitfield accesses.
3352       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3353         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3354             CastOp->getNumOperands() == 2)
3355           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3356             if (CastOp->getOpcode() == Instruction::And) {
3357               // Change: and (cast (and X, C1) to T), C2
3358               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3359               // This will fold the two constants together, which may allow 
3360               // other simplifications.
3361               Instruction *NewCast = CastInst::createTruncOrBitCast(
3362                 CastOp->getOperand(0), I.getType(), 
3363                 CastOp->getName()+".shrunk");
3364               NewCast = InsertNewInstBefore(NewCast, I);
3365               // trunc_or_bitcast(C1)&C2
3366               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3367               C3 = ConstantExpr::getAnd(C3, AndRHS);
3368               return BinaryOperator::createAnd(NewCast, C3);
3369             } else if (CastOp->getOpcode() == Instruction::Or) {
3370               // Change: and (cast (or X, C1) to T), C2
3371               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3372               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3373               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3374                 return ReplaceInstUsesWith(I, AndRHS);
3375             }
3376       }
3377     }
3378
3379     // Try to fold constant and into select arguments.
3380     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3381       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3382         return R;
3383     if (isa<PHINode>(Op0))
3384       if (Instruction *NV = FoldOpIntoPhi(I))
3385         return NV;
3386   }
3387
3388   Value *Op0NotVal = dyn_castNotVal(Op0);
3389   Value *Op1NotVal = dyn_castNotVal(Op1);
3390
3391   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3392     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3393
3394   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3395   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3396     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3397                                                I.getName()+".demorgan");
3398     InsertNewInstBefore(Or, I);
3399     return BinaryOperator::createNot(Or);
3400   }
3401   
3402   {
3403     Value *A = 0, *B = 0, *C = 0, *D = 0;
3404     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3405       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3406         return ReplaceInstUsesWith(I, Op1);
3407     
3408       // (A|B) & ~(A&B) -> A^B
3409       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3410         if ((A == C && B == D) || (A == D && B == C))
3411           return BinaryOperator::createXor(A, B);
3412       }
3413     }
3414     
3415     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3416       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3417         return ReplaceInstUsesWith(I, Op0);
3418
3419       // ~(A&B) & (A|B) -> A^B
3420       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3421         if ((A == C && B == D) || (A == D && B == C))
3422           return BinaryOperator::createXor(A, B);
3423       }
3424     }
3425     
3426     if (Op0->hasOneUse() &&
3427         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3428       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3429         I.swapOperands();     // Simplify below
3430         std::swap(Op0, Op1);
3431       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3432         cast<BinaryOperator>(Op0)->swapOperands();
3433         I.swapOperands();     // Simplify below
3434         std::swap(Op0, Op1);
3435       }
3436     }
3437     if (Op1->hasOneUse() &&
3438         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3439       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3440         cast<BinaryOperator>(Op1)->swapOperands();
3441         std::swap(A, B);
3442       }
3443       if (A == Op0) {                                // A&(A^B) -> A & ~B
3444         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3445         InsertNewInstBefore(NotB, I);
3446         return BinaryOperator::createAnd(A, NotB);
3447       }
3448     }
3449   }
3450   
3451   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3452     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3453     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3454       return R;
3455
3456     Value *LHSVal, *RHSVal;
3457     ConstantInt *LHSCst, *RHSCst;
3458     ICmpInst::Predicate LHSCC, RHSCC;
3459     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3460       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3461         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3462             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3463             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3464             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3465             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3466             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3467           // Ensure that the larger constant is on the RHS.
3468           ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ? 
3469             ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3470           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3471           ICmpInst *LHS = cast<ICmpInst>(Op0);
3472           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3473             std::swap(LHS, RHS);
3474             std::swap(LHSCst, RHSCst);
3475             std::swap(LHSCC, RHSCC);
3476           }
3477
3478           // At this point, we know we have have two icmp instructions
3479           // comparing a value against two constants and and'ing the result
3480           // together.  Because of the above check, we know that we only have
3481           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3482           // (from the FoldICmpLogical check above), that the two constants 
3483           // are not equal and that the larger constant is on the RHS
3484           assert(LHSCst != RHSCst && "Compares not folded above?");
3485
3486           switch (LHSCC) {
3487           default: assert(0 && "Unknown integer condition code!");
3488           case ICmpInst::ICMP_EQ:
3489             switch (RHSCC) {
3490             default: assert(0 && "Unknown integer condition code!");
3491             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3492             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3493             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3494               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3495             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3496             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3497             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3498               return ReplaceInstUsesWith(I, LHS);
3499             }
3500           case ICmpInst::ICMP_NE:
3501             switch (RHSCC) {
3502             default: assert(0 && "Unknown integer condition code!");
3503             case ICmpInst::ICMP_ULT:
3504               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3505                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3506               break;                        // (X != 13 & X u< 15) -> no change
3507             case ICmpInst::ICMP_SLT:
3508               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3509                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3510               break;                        // (X != 13 & X s< 15) -> no change
3511             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3512             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3513             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3514               return ReplaceInstUsesWith(I, RHS);
3515             case ICmpInst::ICMP_NE:
3516               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3517                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3518                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3519                                                       LHSVal->getName()+".off");
3520                 InsertNewInstBefore(Add, I);
3521                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3522                                     ConstantInt::get(Add->getType(), 1));
3523               }
3524               break;                        // (X != 13 & X != 15) -> no change
3525             }
3526             break;
3527           case ICmpInst::ICMP_ULT:
3528             switch (RHSCC) {
3529             default: assert(0 && "Unknown integer condition code!");
3530             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3531             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3532               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3533             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3534               break;
3535             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3536             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3537               return ReplaceInstUsesWith(I, LHS);
3538             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3539               break;
3540             }
3541             break;
3542           case ICmpInst::ICMP_SLT:
3543             switch (RHSCC) {
3544             default: assert(0 && "Unknown integer condition code!");
3545             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3546             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3547               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3548             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3549               break;
3550             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3551             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3552               return ReplaceInstUsesWith(I, LHS);
3553             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3554               break;
3555             }
3556             break;
3557           case ICmpInst::ICMP_UGT:
3558             switch (RHSCC) {
3559             default: assert(0 && "Unknown integer condition code!");
3560             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3561               return ReplaceInstUsesWith(I, LHS);
3562             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3563               return ReplaceInstUsesWith(I, RHS);
3564             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3565               break;
3566             case ICmpInst::ICMP_NE:
3567               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3568                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3569               break;                        // (X u> 13 & X != 15) -> no change
3570             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3571               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3572                                      true, I);
3573             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3574               break;
3575             }
3576             break;
3577           case ICmpInst::ICMP_SGT:
3578             switch (RHSCC) {
3579             default: assert(0 && "Unknown integer condition code!");
3580             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3581             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3582               return ReplaceInstUsesWith(I, RHS);
3583             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3584               break;
3585             case ICmpInst::ICMP_NE:
3586               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3587                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3588               break;                        // (X s> 13 & X != 15) -> no change
3589             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3590               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3591                                      true, I);
3592             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3593               break;
3594             }
3595             break;
3596           }
3597         }
3598   }
3599
3600   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3601   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3602     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3603       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3604         const Type *SrcTy = Op0C->getOperand(0)->getType();
3605         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3606             // Only do this if the casts both really cause code to be generated.
3607             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3608                               I.getType(), TD) &&
3609             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3610                               I.getType(), TD)) {
3611           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3612                                                          Op1C->getOperand(0),
3613                                                          I.getName());
3614           InsertNewInstBefore(NewOp, I);
3615           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3616         }
3617       }
3618     
3619   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3620   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3621     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3622       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3623           SI0->getOperand(1) == SI1->getOperand(1) &&
3624           (SI0->hasOneUse() || SI1->hasOneUse())) {
3625         Instruction *NewOp =
3626           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3627                                                         SI1->getOperand(0),
3628                                                         SI0->getName()), I);
3629         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3630                                       SI1->getOperand(1));
3631       }
3632   }
3633
3634   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3635   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3636     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3637       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3638           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3639         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3640           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3641             // If either of the constants are nans, then the whole thing returns
3642             // false.
3643             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3644               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3645             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3646                                 RHS->getOperand(0));
3647           }
3648     }
3649   }
3650       
3651   return Changed ? &I : 0;
3652 }
3653
3654 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3655 /// in the result.  If it does, and if the specified byte hasn't been filled in
3656 /// yet, fill it in and return false.
3657 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3658   Instruction *I = dyn_cast<Instruction>(V);
3659   if (I == 0) return true;
3660
3661   // If this is an or instruction, it is an inner node of the bswap.
3662   if (I->getOpcode() == Instruction::Or)
3663     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3664            CollectBSwapParts(I->getOperand(1), ByteValues);
3665   
3666   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3667   // If this is a shift by a constant int, and it is "24", then its operand
3668   // defines a byte.  We only handle unsigned types here.
3669   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3670     // Not shifting the entire input by N-1 bytes?
3671     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3672         8*(ByteValues.size()-1))
3673       return true;
3674     
3675     unsigned DestNo;
3676     if (I->getOpcode() == Instruction::Shl) {
3677       // X << 24 defines the top byte with the lowest of the input bytes.
3678       DestNo = ByteValues.size()-1;
3679     } else {
3680       // X >>u 24 defines the low byte with the highest of the input bytes.
3681       DestNo = 0;
3682     }
3683     
3684     // If the destination byte value is already defined, the values are or'd
3685     // together, which isn't a bswap (unless it's an or of the same bits).
3686     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3687       return true;
3688     ByteValues[DestNo] = I->getOperand(0);
3689     return false;
3690   }
3691   
3692   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3693   // don't have this.
3694   Value *Shift = 0, *ShiftLHS = 0;
3695   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3696   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3697       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3698     return true;
3699   Instruction *SI = cast<Instruction>(Shift);
3700
3701   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3702   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3703       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3704     return true;
3705   
3706   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3707   unsigned DestByte;
3708   if (AndAmt->getValue().getActiveBits() > 64)
3709     return true;
3710   uint64_t AndAmtVal = AndAmt->getZExtValue();
3711   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3712     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3713       break;
3714   // Unknown mask for bswap.
3715   if (DestByte == ByteValues.size()) return true;
3716   
3717   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3718   unsigned SrcByte;
3719   if (SI->getOpcode() == Instruction::Shl)
3720     SrcByte = DestByte - ShiftBytes;
3721   else
3722     SrcByte = DestByte + ShiftBytes;
3723   
3724   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3725   if (SrcByte != ByteValues.size()-DestByte-1)
3726     return true;
3727   
3728   // If the destination byte value is already defined, the values are or'd
3729   // together, which isn't a bswap (unless it's an or of the same bits).
3730   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3731     return true;
3732   ByteValues[DestByte] = SI->getOperand(0);
3733   return false;
3734 }
3735
3736 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3737 /// If so, insert the new bswap intrinsic and return it.
3738 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3739   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3740   if (!ITy || ITy->getBitWidth() % 16) 
3741     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3742   
3743   /// ByteValues - For each byte of the result, we keep track of which value
3744   /// defines each byte.
3745   SmallVector<Value*, 8> ByteValues;
3746   ByteValues.resize(ITy->getBitWidth()/8);
3747     
3748   // Try to find all the pieces corresponding to the bswap.
3749   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3750       CollectBSwapParts(I.getOperand(1), ByteValues))
3751     return 0;
3752   
3753   // Check to see if all of the bytes come from the same value.
3754   Value *V = ByteValues[0];
3755   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3756   
3757   // Check to make sure that all of the bytes come from the same value.
3758   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3759     if (ByteValues[i] != V)
3760       return 0;
3761   const Type *Tys[] = { ITy };
3762   Module *M = I.getParent()->getParent()->getParent();
3763   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3764   return new CallInst(F, V);
3765 }
3766
3767
3768 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3769   bool Changed = SimplifyCommutative(I);
3770   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3771
3772   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3773     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3774
3775   // or X, X = X
3776   if (Op0 == Op1)
3777     return ReplaceInstUsesWith(I, Op0);
3778
3779   // See if we can simplify any instructions used by the instruction whose sole 
3780   // purpose is to compute bits we don't care about.
3781   if (!isa<VectorType>(I.getType())) {
3782     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3783     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3784     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3785                              KnownZero, KnownOne))
3786       return &I;
3787   } else if (isa<ConstantAggregateZero>(Op1)) {
3788     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3789   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3790     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3791       return ReplaceInstUsesWith(I, I.getOperand(1));
3792   }
3793     
3794
3795   
3796   // or X, -1 == -1
3797   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3798     ConstantInt *C1 = 0; Value *X = 0;
3799     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3800     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3801       Instruction *Or = BinaryOperator::createOr(X, RHS);
3802       InsertNewInstBefore(Or, I);
3803       Or->takeName(Op0);
3804       return BinaryOperator::createAnd(Or, 
3805                ConstantInt::get(RHS->getValue() | C1->getValue()));
3806     }
3807
3808     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3809     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3810       Instruction *Or = BinaryOperator::createOr(X, RHS);
3811       InsertNewInstBefore(Or, I);
3812       Or->takeName(Op0);
3813       return BinaryOperator::createXor(Or,
3814                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3815     }
3816
3817     // Try to fold constant and into select arguments.
3818     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3819       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3820         return R;
3821     if (isa<PHINode>(Op0))
3822       if (Instruction *NV = FoldOpIntoPhi(I))
3823         return NV;
3824   }
3825
3826   Value *A = 0, *B = 0;
3827   ConstantInt *C1 = 0, *C2 = 0;
3828
3829   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3830     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3831       return ReplaceInstUsesWith(I, Op1);
3832   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3833     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3834       return ReplaceInstUsesWith(I, Op0);
3835
3836   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3837   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3838   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3839       match(Op1, m_Or(m_Value(), m_Value())) ||
3840       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3841        match(Op1, m_Shift(m_Value(), m_Value())))) {
3842     if (Instruction *BSwap = MatchBSwap(I))
3843       return BSwap;
3844   }
3845   
3846   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3847   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3848       MaskedValueIsZero(Op1, C1->getValue())) {
3849     Instruction *NOr = BinaryOperator::createOr(A, Op1);
3850     InsertNewInstBefore(NOr, I);
3851     NOr->takeName(Op0);
3852     return BinaryOperator::createXor(NOr, C1);
3853   }
3854
3855   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3856   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3857       MaskedValueIsZero(Op0, C1->getValue())) {
3858     Instruction *NOr = BinaryOperator::createOr(A, Op0);
3859     InsertNewInstBefore(NOr, I);
3860     NOr->takeName(Op0);
3861     return BinaryOperator::createXor(NOr, C1);
3862   }
3863
3864   // (A & C)|(B & D)
3865   Value *C = 0, *D = 0;
3866   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3867       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3868     Value *V1 = 0, *V2 = 0, *V3 = 0;
3869     C1 = dyn_cast<ConstantInt>(C);
3870     C2 = dyn_cast<ConstantInt>(D);
3871     if (C1 && C2) {  // (A & C1)|(B & C2)
3872       // If we have: ((V + N) & C1) | (V & C2)
3873       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3874       // replace with V+N.
3875       if (C1->getValue() == ~C2->getValue()) {
3876         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3877             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3878           // Add commutes, try both ways.
3879           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3880             return ReplaceInstUsesWith(I, A);
3881           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3882             return ReplaceInstUsesWith(I, A);
3883         }
3884         // Or commutes, try both ways.
3885         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3886             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3887           // Add commutes, try both ways.
3888           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3889             return ReplaceInstUsesWith(I, B);
3890           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3891             return ReplaceInstUsesWith(I, B);
3892         }
3893       }
3894       V1 = 0; V2 = 0; V3 = 0;
3895     }
3896     
3897     // Check to see if we have any common things being and'ed.  If so, find the
3898     // terms for V1 & (V2|V3).
3899     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3900       if (A == B)      // (A & C)|(A & D) == A & (C|D)
3901         V1 = A, V2 = C, V3 = D;
3902       else if (A == D) // (A & C)|(B & A) == A & (B|C)
3903         V1 = A, V2 = B, V3 = C;
3904       else if (C == B) // (A & C)|(C & D) == C & (A|D)
3905         V1 = C, V2 = A, V3 = D;
3906       else if (C == D) // (A & C)|(B & C) == C & (A|B)
3907         V1 = C, V2 = A, V3 = B;
3908       
3909       if (V1) {
3910         Value *Or =
3911           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3912         return BinaryOperator::createAnd(V1, Or);
3913       }
3914     }
3915   }
3916   
3917   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
3918   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3919     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3920       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3921           SI0->getOperand(1) == SI1->getOperand(1) &&
3922           (SI0->hasOneUse() || SI1->hasOneUse())) {
3923         Instruction *NewOp =
3924         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3925                                                      SI1->getOperand(0),
3926                                                      SI0->getName()), I);
3927         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3928                                       SI1->getOperand(1));
3929       }
3930   }
3931
3932   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3933     if (A == Op1)   // ~A | A == -1
3934       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3935   } else {
3936     A = 0;
3937   }
3938   // Note, A is still live here!
3939   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3940     if (Op0 == B)
3941       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3942
3943     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3944     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3945       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3946                                               I.getName()+".demorgan"), I);
3947       return BinaryOperator::createNot(And);
3948     }
3949   }
3950
3951   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3952   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3953     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3954       return R;
3955
3956     Value *LHSVal, *RHSVal;
3957     ConstantInt *LHSCst, *RHSCst;
3958     ICmpInst::Predicate LHSCC, RHSCC;
3959     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3960       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3961         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
3962             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3963             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3964             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3965             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3966             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3967             // We can't fold (ugt x, C) | (sgt x, C2).
3968             PredicatesFoldable(LHSCC, RHSCC)) {
3969           // Ensure that the larger constant is on the RHS.
3970           ICmpInst *LHS = cast<ICmpInst>(Op0);
3971           bool NeedsSwap;
3972           if (ICmpInst::isSignedPredicate(LHSCC))
3973             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3974           else
3975             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3976             
3977           if (NeedsSwap) {
3978             std::swap(LHS, RHS);
3979             std::swap(LHSCst, RHSCst);
3980             std::swap(LHSCC, RHSCC);
3981           }
3982
3983           // At this point, we know we have have two icmp instructions
3984           // comparing a value against two constants and or'ing the result
3985           // together.  Because of the above check, we know that we only have
3986           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3987           // FoldICmpLogical check above), that the two constants are not
3988           // equal.
3989           assert(LHSCst != RHSCst && "Compares not folded above?");
3990
3991           switch (LHSCC) {
3992           default: assert(0 && "Unknown integer condition code!");
3993           case ICmpInst::ICMP_EQ:
3994             switch (RHSCC) {
3995             default: assert(0 && "Unknown integer condition code!");
3996             case ICmpInst::ICMP_EQ:
3997               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3998                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3999                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4000                                                       LHSVal->getName()+".off");
4001                 InsertNewInstBefore(Add, I);
4002                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4003                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4004               }
4005               break;                         // (X == 13 | X == 15) -> no change
4006             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4007             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4008               break;
4009             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4010             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4011             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4012               return ReplaceInstUsesWith(I, RHS);
4013             }
4014             break;
4015           case ICmpInst::ICMP_NE:
4016             switch (RHSCC) {
4017             default: assert(0 && "Unknown integer condition code!");
4018             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4019             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4020             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4021               return ReplaceInstUsesWith(I, LHS);
4022             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4023             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4024             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4025               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4026             }
4027             break;
4028           case ICmpInst::ICMP_ULT:
4029             switch (RHSCC) {
4030             default: assert(0 && "Unknown integer condition code!");
4031             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4032               break;
4033             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4034               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4035               // this can cause overflow.
4036               if (RHSCst->isMaxValue(false))
4037                 return ReplaceInstUsesWith(I, LHS);
4038               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4039                                      false, I);
4040             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4041               break;
4042             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4043             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4044               return ReplaceInstUsesWith(I, RHS);
4045             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4046               break;
4047             }
4048             break;
4049           case ICmpInst::ICMP_SLT:
4050             switch (RHSCC) {
4051             default: assert(0 && "Unknown integer condition code!");
4052             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4053               break;
4054             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4055               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4056               // this can cause overflow.
4057               if (RHSCst->isMaxValue(true))
4058                 return ReplaceInstUsesWith(I, LHS);
4059               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4060                                      false, I);
4061             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4062               break;
4063             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4064             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4065               return ReplaceInstUsesWith(I, RHS);
4066             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4067               break;
4068             }
4069             break;
4070           case ICmpInst::ICMP_UGT:
4071             switch (RHSCC) {
4072             default: assert(0 && "Unknown integer condition code!");
4073             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4074             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4075               return ReplaceInstUsesWith(I, LHS);
4076             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4077               break;
4078             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4079             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4080               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4081             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4082               break;
4083             }
4084             break;
4085           case ICmpInst::ICMP_SGT:
4086             switch (RHSCC) {
4087             default: assert(0 && "Unknown integer condition code!");
4088             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4089             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4090               return ReplaceInstUsesWith(I, LHS);
4091             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4092               break;
4093             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4094             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4095               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4096             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4097               break;
4098             }
4099             break;
4100           }
4101         }
4102   }
4103     
4104   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4105   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4106     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4107       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4108         const Type *SrcTy = Op0C->getOperand(0)->getType();
4109         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4110             // Only do this if the casts both really cause code to be generated.
4111             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4112                               I.getType(), TD) &&
4113             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4114                               I.getType(), TD)) {
4115           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4116                                                         Op1C->getOperand(0),
4117                                                         I.getName());
4118           InsertNewInstBefore(NewOp, I);
4119           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4120         }
4121       }
4122   }
4123   
4124     
4125   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4126   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4127     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4128       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4129           RHS->getPredicate() == FCmpInst::FCMP_UNO)
4130         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4131           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4132             // If either of the constants are nans, then the whole thing returns
4133             // true.
4134             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4135               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4136             
4137             // Otherwise, no need to compare the two constants, compare the
4138             // rest.
4139             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4140                                 RHS->getOperand(0));
4141           }
4142     }
4143   }
4144
4145   return Changed ? &I : 0;
4146 }
4147
4148 // XorSelf - Implements: X ^ X --> 0
4149 struct XorSelf {
4150   Value *RHS;
4151   XorSelf(Value *rhs) : RHS(rhs) {}
4152   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4153   Instruction *apply(BinaryOperator &Xor) const {
4154     return &Xor;
4155   }
4156 };
4157
4158
4159 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4160   bool Changed = SimplifyCommutative(I);
4161   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4162
4163   if (isa<UndefValue>(Op1))
4164     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4165
4166   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4167   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4168     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4169     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4170   }
4171   
4172   // See if we can simplify any instructions used by the instruction whose sole 
4173   // purpose is to compute bits we don't care about.
4174   if (!isa<VectorType>(I.getType())) {
4175     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4176     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4177     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4178                              KnownZero, KnownOne))
4179       return &I;
4180   } else if (isa<ConstantAggregateZero>(Op1)) {
4181     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4182   }
4183
4184   // Is this a ~ operation?
4185   if (Value *NotOp = dyn_castNotVal(&I)) {
4186     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4187     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4188     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4189       if (Op0I->getOpcode() == Instruction::And || 
4190           Op0I->getOpcode() == Instruction::Or) {
4191         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4192         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4193           Instruction *NotY =
4194             BinaryOperator::createNot(Op0I->getOperand(1),
4195                                       Op0I->getOperand(1)->getName()+".not");
4196           InsertNewInstBefore(NotY, I);
4197           if (Op0I->getOpcode() == Instruction::And)
4198             return BinaryOperator::createOr(Op0NotVal, NotY);
4199           else
4200             return BinaryOperator::createAnd(Op0NotVal, NotY);
4201         }
4202       }
4203     }
4204   }
4205   
4206   
4207   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4208     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4209     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4210       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4211         return new ICmpInst(ICI->getInversePredicate(),
4212                             ICI->getOperand(0), ICI->getOperand(1));
4213
4214       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4215         return new FCmpInst(FCI->getInversePredicate(),
4216                             FCI->getOperand(0), FCI->getOperand(1));
4217     }
4218
4219     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4220       // ~(c-X) == X-c-1 == X+(-c-1)
4221       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4222         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4223           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4224           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4225                                               ConstantInt::get(I.getType(), 1));
4226           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4227         }
4228           
4229       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4230         if (Op0I->getOpcode() == Instruction::Add) {
4231           // ~(X-c) --> (-c-1)-X
4232           if (RHS->isAllOnesValue()) {
4233             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4234             return BinaryOperator::createSub(
4235                            ConstantExpr::getSub(NegOp0CI,
4236                                              ConstantInt::get(I.getType(), 1)),
4237                                           Op0I->getOperand(0));
4238           } else if (RHS->getValue().isSignBit()) {
4239             // (X + C) ^ signbit -> (X + C + signbit)
4240             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4241             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4242
4243           }
4244         } else if (Op0I->getOpcode() == Instruction::Or) {
4245           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4246           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4247             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4248             // Anything in both C1 and C2 is known to be zero, remove it from
4249             // NewRHS.
4250             Constant *CommonBits = And(Op0CI, RHS);
4251             NewRHS = ConstantExpr::getAnd(NewRHS, 
4252                                           ConstantExpr::getNot(CommonBits));
4253             AddToWorkList(Op0I);
4254             I.setOperand(0, Op0I->getOperand(0));
4255             I.setOperand(1, NewRHS);
4256             return &I;
4257           }
4258         }
4259     }
4260
4261     // Try to fold constant and into select arguments.
4262     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4263       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4264         return R;
4265     if (isa<PHINode>(Op0))
4266       if (Instruction *NV = FoldOpIntoPhi(I))
4267         return NV;
4268   }
4269
4270   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4271     if (X == Op1)
4272       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4273
4274   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4275     if (X == Op0)
4276       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4277
4278   
4279   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4280   if (Op1I) {
4281     Value *A, *B;
4282     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4283       if (A == Op0) {              // B^(B|A) == (A|B)^B
4284         Op1I->swapOperands();
4285         I.swapOperands();
4286         std::swap(Op0, Op1);
4287       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4288         I.swapOperands();     // Simplified below.
4289         std::swap(Op0, Op1);
4290       }
4291     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4292       if (Op0 == A)                                          // A^(A^B) == B
4293         return ReplaceInstUsesWith(I, B);
4294       else if (Op0 == B)                                     // A^(B^A) == B
4295         return ReplaceInstUsesWith(I, A);
4296     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4297       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4298         Op1I->swapOperands();
4299         std::swap(A, B);
4300       }
4301       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4302         I.swapOperands();     // Simplified below.
4303         std::swap(Op0, Op1);
4304       }
4305     }
4306   }
4307   
4308   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4309   if (Op0I) {
4310     Value *A, *B;
4311     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4312       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4313         std::swap(A, B);
4314       if (B == Op1) {                                // (A|B)^B == A & ~B
4315         Instruction *NotB =
4316           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4317         return BinaryOperator::createAnd(A, NotB);
4318       }
4319     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4320       if (Op1 == A)                                          // (A^B)^A == B
4321         return ReplaceInstUsesWith(I, B);
4322       else if (Op1 == B)                                     // (B^A)^A == B
4323         return ReplaceInstUsesWith(I, A);
4324     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4325       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4326         std::swap(A, B);
4327       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4328           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4329         Instruction *N =
4330           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4331         return BinaryOperator::createAnd(N, Op1);
4332       }
4333     }
4334   }
4335   
4336   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4337   if (Op0I && Op1I && Op0I->isShift() && 
4338       Op0I->getOpcode() == Op1I->getOpcode() && 
4339       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4340       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4341     Instruction *NewOp =
4342       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4343                                                     Op1I->getOperand(0),
4344                                                     Op0I->getName()), I);
4345     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4346                                   Op1I->getOperand(1));
4347   }
4348     
4349   if (Op0I && Op1I) {
4350     Value *A, *B, *C, *D;
4351     // (A & B)^(A | B) -> A ^ B
4352     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4353         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4354       if ((A == C && B == D) || (A == D && B == C)) 
4355         return BinaryOperator::createXor(A, B);
4356     }
4357     // (A | B)^(A & B) -> A ^ B
4358     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4359         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4360       if ((A == C && B == D) || (A == D && B == C)) 
4361         return BinaryOperator::createXor(A, B);
4362     }
4363     
4364     // (A & B)^(C & D)
4365     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4366         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4367         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4368       // (X & Y)^(X & Y) -> (Y^Z) & X
4369       Value *X = 0, *Y = 0, *Z = 0;
4370       if (A == C)
4371         X = A, Y = B, Z = D;
4372       else if (A == D)
4373         X = A, Y = B, Z = C;
4374       else if (B == C)
4375         X = B, Y = A, Z = D;
4376       else if (B == D)
4377         X = B, Y = A, Z = C;
4378       
4379       if (X) {
4380         Instruction *NewOp =
4381         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4382         return BinaryOperator::createAnd(NewOp, X);
4383       }
4384     }
4385   }
4386     
4387   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4388   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4389     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4390       return R;
4391
4392   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4393   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4394     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4395       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4396         const Type *SrcTy = Op0C->getOperand(0)->getType();
4397         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4398             // Only do this if the casts both really cause code to be generated.
4399             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4400                               I.getType(), TD) &&
4401             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4402                               I.getType(), TD)) {
4403           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4404                                                          Op1C->getOperand(0),
4405                                                          I.getName());
4406           InsertNewInstBefore(NewOp, I);
4407           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4408         }
4409       }
4410   }
4411   return Changed ? &I : 0;
4412 }
4413
4414 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4415 /// overflowed for this type.
4416 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4417                             ConstantInt *In2, bool IsSigned = false) {
4418   Result = cast<ConstantInt>(Add(In1, In2));
4419
4420   if (IsSigned)
4421     if (In2->getValue().isNegative())
4422       return Result->getValue().sgt(In1->getValue());
4423     else
4424       return Result->getValue().slt(In1->getValue());
4425   else
4426     return Result->getValue().ult(In1->getValue());
4427 }
4428
4429 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4430 /// code necessary to compute the offset from the base pointer (without adding
4431 /// in the base pointer).  Return the result as a signed integer of intptr size.
4432 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4433   TargetData &TD = IC.getTargetData();
4434   gep_type_iterator GTI = gep_type_begin(GEP);
4435   const Type *IntPtrTy = TD.getIntPtrType();
4436   Value *Result = Constant::getNullValue(IntPtrTy);
4437
4438   // Build a mask for high order bits.
4439   unsigned IntPtrWidth = TD.getPointerSize()*8;
4440   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4441
4442   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4443     Value *Op = GEP->getOperand(i);
4444     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4445     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4446       if (OpC->isZero()) continue;
4447       
4448       // Handle a struct index, which adds its field offset to the pointer.
4449       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4450         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4451         
4452         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4453           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4454         else
4455           Result = IC.InsertNewInstBefore(
4456                    BinaryOperator::createAdd(Result,
4457                                              ConstantInt::get(IntPtrTy, Size),
4458                                              GEP->getName()+".offs"), I);
4459         continue;
4460       }
4461       
4462       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4463       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4464       Scale = ConstantExpr::getMul(OC, Scale);
4465       if (Constant *RC = dyn_cast<Constant>(Result))
4466         Result = ConstantExpr::getAdd(RC, Scale);
4467       else {
4468         // Emit an add instruction.
4469         Result = IC.InsertNewInstBefore(
4470            BinaryOperator::createAdd(Result, Scale,
4471                                      GEP->getName()+".offs"), I);
4472       }
4473       continue;
4474     }
4475     // Convert to correct type.
4476     if (Op->getType() != IntPtrTy) {
4477       if (Constant *OpC = dyn_cast<Constant>(Op))
4478         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4479       else
4480         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4481                                                  Op->getName()+".c"), I);
4482     }
4483     if (Size != 1) {
4484       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4485       if (Constant *OpC = dyn_cast<Constant>(Op))
4486         Op = ConstantExpr::getMul(OpC, Scale);
4487       else    // We'll let instcombine(mul) convert this to a shl if possible.
4488         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4489                                                   GEP->getName()+".idx"), I);
4490     }
4491
4492     // Emit an add instruction.
4493     if (isa<Constant>(Op) && isa<Constant>(Result))
4494       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4495                                     cast<Constant>(Result));
4496     else
4497       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4498                                                   GEP->getName()+".offs"), I);
4499   }
4500   return Result;
4501 }
4502
4503 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4504 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4505 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4506                                        ICmpInst::Predicate Cond,
4507                                        Instruction &I) {
4508   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4509
4510   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4511     if (isa<PointerType>(CI->getOperand(0)->getType()))
4512       RHS = CI->getOperand(0);
4513
4514   Value *PtrBase = GEPLHS->getOperand(0);
4515   if (PtrBase == RHS) {
4516     // As an optimization, we don't actually have to compute the actual value of
4517     // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether 
4518     // each index is zero or not.
4519     if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4520       Instruction *InVal = 0;
4521       gep_type_iterator GTI = gep_type_begin(GEPLHS);
4522       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4523         bool EmitIt = true;
4524         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4525           if (isa<UndefValue>(C))  // undef index -> undef.
4526             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4527           if (C->isNullValue())
4528             EmitIt = false;
4529           else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
4530             EmitIt = false;  // This is indexing into a zero sized array?
4531           } else if (isa<ConstantInt>(C))
4532             return ReplaceInstUsesWith(I, // No comparison is needed here.
4533                                  ConstantInt::get(Type::Int1Ty, 
4534                                                   Cond == ICmpInst::ICMP_NE));
4535         }
4536
4537         if (EmitIt) {
4538           Instruction *Comp =
4539             new ICmpInst(Cond, GEPLHS->getOperand(i),
4540                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4541           if (InVal == 0)
4542             InVal = Comp;
4543           else {
4544             InVal = InsertNewInstBefore(InVal, I);
4545             InsertNewInstBefore(Comp, I);
4546             if (Cond == ICmpInst::ICMP_NE)   // True if any are unequal
4547               InVal = BinaryOperator::createOr(InVal, Comp);
4548             else                              // True if all are equal
4549               InVal = BinaryOperator::createAnd(InVal, Comp);
4550           }
4551         }
4552       }
4553
4554       if (InVal)
4555         return InVal;
4556       else
4557         // No comparison is needed here, all indexes = 0
4558         ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4559                                                 Cond == ICmpInst::ICMP_EQ));
4560     }
4561
4562     // Only lower this if the icmp is the only user of the GEP or if we expect
4563     // the result to fold to a constant!
4564     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4565       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4566       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4567       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4568                           Constant::getNullValue(Offset->getType()));
4569     }
4570   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4571     // If the base pointers are different, but the indices are the same, just
4572     // compare the base pointer.
4573     if (PtrBase != GEPRHS->getOperand(0)) {
4574       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4575       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4576                         GEPRHS->getOperand(0)->getType();
4577       if (IndicesTheSame)
4578         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4579           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4580             IndicesTheSame = false;
4581             break;
4582           }
4583
4584       // If all indices are the same, just compare the base pointers.
4585       if (IndicesTheSame)
4586         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4587                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4588
4589       // Otherwise, the base pointers are different and the indices are
4590       // different, bail out.
4591       return 0;
4592     }
4593
4594     // If one of the GEPs has all zero indices, recurse.
4595     bool AllZeros = true;
4596     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4597       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4598           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4599         AllZeros = false;
4600         break;
4601       }
4602     if (AllZeros)
4603       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4604                           ICmpInst::getSwappedPredicate(Cond), I);
4605
4606     // If the other GEP has all zero indices, recurse.
4607     AllZeros = true;
4608     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4609       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4610           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4611         AllZeros = false;
4612         break;
4613       }
4614     if (AllZeros)
4615       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4616
4617     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4618       // If the GEPs only differ by one index, compare it.
4619       unsigned NumDifferences = 0;  // Keep track of # differences.
4620       unsigned DiffOperand = 0;     // The operand that differs.
4621       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4622         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4623           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4624                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4625             // Irreconcilable differences.
4626             NumDifferences = 2;
4627             break;
4628           } else {
4629             if (NumDifferences++) break;
4630             DiffOperand = i;
4631           }
4632         }
4633
4634       if (NumDifferences == 0)   // SAME GEP?
4635         return ReplaceInstUsesWith(I, // No comparison is needed here.
4636                                    ConstantInt::get(Type::Int1Ty,
4637                                                     isTrueWhenEqual(Cond)));
4638
4639       else if (NumDifferences == 1) {
4640         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4641         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4642         // Make sure we do a signed comparison here.
4643         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4644       }
4645     }
4646
4647     // Only lower this if the icmp is the only user of the GEP or if we expect
4648     // the result to fold to a constant!
4649     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4650         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4651       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4652       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4653       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4654       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4655     }
4656   }
4657   return 0;
4658 }
4659
4660 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4661   bool Changed = SimplifyCompare(I);
4662   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4663
4664   // Fold trivial predicates.
4665   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4666     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4667   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4668     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4669   
4670   // Simplify 'fcmp pred X, X'
4671   if (Op0 == Op1) {
4672     switch (I.getPredicate()) {
4673     default: assert(0 && "Unknown predicate!");
4674     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4675     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4676     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4677       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4678     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4679     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4680     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4681       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4682       
4683     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4684     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4685     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4686     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4687       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4688       I.setPredicate(FCmpInst::FCMP_UNO);
4689       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4690       return &I;
4691       
4692     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4693     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4694     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4695     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4696       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4697       I.setPredicate(FCmpInst::FCMP_ORD);
4698       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4699       return &I;
4700     }
4701   }
4702     
4703   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4704     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4705
4706   // Handle fcmp with constant RHS
4707   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4708     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4709       switch (LHSI->getOpcode()) {
4710       case Instruction::PHI:
4711         if (Instruction *NV = FoldOpIntoPhi(I))
4712           return NV;
4713         break;
4714       case Instruction::Select:
4715         // If either operand of the select is a constant, we can fold the
4716         // comparison into the select arms, which will cause one to be
4717         // constant folded and the select turned into a bitwise or.
4718         Value *Op1 = 0, *Op2 = 0;
4719         if (LHSI->hasOneUse()) {
4720           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4721             // Fold the known value into the constant operand.
4722             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4723             // Insert a new FCmp of the other select operand.
4724             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4725                                                       LHSI->getOperand(2), RHSC,
4726                                                       I.getName()), I);
4727           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4728             // Fold the known value into the constant operand.
4729             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4730             // Insert a new FCmp of the other select operand.
4731             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4732                                                       LHSI->getOperand(1), RHSC,
4733                                                       I.getName()), I);
4734           }
4735         }
4736
4737         if (Op1)
4738           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4739         break;
4740       }
4741   }
4742
4743   return Changed ? &I : 0;
4744 }
4745
4746 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4747   bool Changed = SimplifyCompare(I);
4748   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4749   const Type *Ty = Op0->getType();
4750
4751   // icmp X, X
4752   if (Op0 == Op1)
4753     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4754                                                    isTrueWhenEqual(I)));
4755
4756   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4757     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4758
4759   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4760   // addresses never equal each other!  We already know that Op0 != Op1.
4761   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4762        isa<ConstantPointerNull>(Op0)) &&
4763       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4764        isa<ConstantPointerNull>(Op1)))
4765     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4766                                                    !isTrueWhenEqual(I)));
4767
4768   // icmp's with boolean values can always be turned into bitwise operations
4769   if (Ty == Type::Int1Ty) {
4770     switch (I.getPredicate()) {
4771     default: assert(0 && "Invalid icmp instruction!");
4772     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4773       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4774       InsertNewInstBefore(Xor, I);
4775       return BinaryOperator::createNot(Xor);
4776     }
4777     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4778       return BinaryOperator::createXor(Op0, Op1);
4779
4780     case ICmpInst::ICMP_UGT:
4781     case ICmpInst::ICMP_SGT:
4782       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4783       // FALL THROUGH
4784     case ICmpInst::ICMP_ULT:
4785     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4786       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4787       InsertNewInstBefore(Not, I);
4788       return BinaryOperator::createAnd(Not, Op1);
4789     }
4790     case ICmpInst::ICMP_UGE:
4791     case ICmpInst::ICMP_SGE:
4792       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4793       // FALL THROUGH
4794     case ICmpInst::ICMP_ULE:
4795     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4796       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4797       InsertNewInstBefore(Not, I);
4798       return BinaryOperator::createOr(Not, Op1);
4799     }
4800     }
4801   }
4802
4803   // See if we are doing a comparison between a constant and an instruction that
4804   // can be folded into the comparison.
4805   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4806     switch (I.getPredicate()) {
4807     default: break;
4808     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4809       if (CI->isMinValue(false))
4810         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4811       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4812         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4813       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4814         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4815       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4816       if (CI->isMinValue(true))
4817         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4818                             ConstantInt::getAllOnesValue(Op0->getType()));
4819           
4820       break;
4821
4822     case ICmpInst::ICMP_SLT:
4823       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4824         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4825       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4826         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4827       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4828         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4829       break;
4830
4831     case ICmpInst::ICMP_UGT:
4832       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4833         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4834       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4835         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4836       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4837         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4838         
4839       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4840       if (CI->isMaxValue(true))
4841         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4842                             ConstantInt::getNullValue(Op0->getType()));
4843       break;
4844
4845     case ICmpInst::ICMP_SGT:
4846       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4847         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4848       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4849         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4850       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4851         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4852       break;
4853
4854     case ICmpInst::ICMP_ULE:
4855       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4856         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4857       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4858         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4859       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4860         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4861       break;
4862
4863     case ICmpInst::ICMP_SLE:
4864       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4865         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4866       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4867         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4868       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4869         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4870       break;
4871
4872     case ICmpInst::ICMP_UGE:
4873       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4874         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4875       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4876         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4877       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4878         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4879       break;
4880
4881     case ICmpInst::ICMP_SGE:
4882       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
4883         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4884       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
4885         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4886       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
4887         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4888       break;
4889     }
4890
4891     // If we still have a icmp le or icmp ge instruction, turn it into the
4892     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
4893     // already been handled above, this requires little checking.
4894     //
4895     switch (I.getPredicate()) {
4896     default: break;
4897     case ICmpInst::ICMP_ULE: 
4898       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4899     case ICmpInst::ICMP_SLE:
4900       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4901     case ICmpInst::ICMP_UGE:
4902       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4903     case ICmpInst::ICMP_SGE:
4904       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4905     }
4906     
4907     // See if we can fold the comparison based on bits known to be zero or one
4908     // in the input.  If this comparison is a normal comparison, it demands all
4909     // bits, if it is a sign bit comparison, it only demands the sign bit.
4910     
4911     bool UnusedBit;
4912     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4913     
4914     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4915     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4916     if (SimplifyDemandedBits(Op0, 
4917                              isSignBit ? APInt::getSignBit(BitWidth)
4918                                        : APInt::getAllOnesValue(BitWidth),
4919                              KnownZero, KnownOne, 0))
4920       return &I;
4921         
4922     // Given the known and unknown bits, compute a range that the LHS could be
4923     // in.
4924     if ((KnownOne | KnownZero) != 0) {
4925       // Compute the Min, Max and RHS values based on the known bits. For the
4926       // EQ and NE we use unsigned values.
4927       APInt Min(BitWidth, 0), Max(BitWidth, 0);
4928       const APInt& RHSVal = CI->getValue();
4929       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4930         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4931                                                Max);
4932       } else {
4933         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
4934                                                  Max);
4935       }
4936       switch (I.getPredicate()) {  // LE/GE have been folded already.
4937       default: assert(0 && "Unknown icmp opcode!");
4938       case ICmpInst::ICMP_EQ:
4939         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4940           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4941         break;
4942       case ICmpInst::ICMP_NE:
4943         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4944           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4945         break;
4946       case ICmpInst::ICMP_ULT:
4947         if (Max.ult(RHSVal))
4948           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4949         if (Min.uge(RHSVal))
4950           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4951         break;
4952       case ICmpInst::ICMP_UGT:
4953         if (Min.ugt(RHSVal))
4954           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4955         if (Max.ule(RHSVal))
4956           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4957         break;
4958       case ICmpInst::ICMP_SLT:
4959         if (Max.slt(RHSVal))
4960           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4961         if (Min.sgt(RHSVal))
4962           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4963         break;
4964       case ICmpInst::ICMP_SGT: 
4965         if (Min.sgt(RHSVal))
4966           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4967         if (Max.sle(RHSVal))
4968           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4969         break;
4970       }
4971     }
4972           
4973     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
4974     // instruction, see if that instruction also has constants so that the 
4975     // instruction can be folded into the icmp 
4976     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4977       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4978         return Res;
4979   }
4980
4981   // Handle icmp with constant (but not simple integer constant) RHS
4982   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4983     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4984       switch (LHSI->getOpcode()) {
4985       case Instruction::GetElementPtr:
4986         if (RHSC->isNullValue()) {
4987           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
4988           bool isAllZeros = true;
4989           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4990             if (!isa<Constant>(LHSI->getOperand(i)) ||
4991                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4992               isAllZeros = false;
4993               break;
4994             }
4995           if (isAllZeros)
4996             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4997                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
4998         }
4999         break;
5000
5001       case Instruction::PHI:
5002         if (Instruction *NV = FoldOpIntoPhi(I))
5003           return NV;
5004         break;
5005       case Instruction::Select: {
5006         // If either operand of the select is a constant, we can fold the
5007         // comparison into the select arms, which will cause one to be
5008         // constant folded and the select turned into a bitwise or.
5009         Value *Op1 = 0, *Op2 = 0;
5010         if (LHSI->hasOneUse()) {
5011           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5012             // Fold the known value into the constant operand.
5013             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5014             // Insert a new ICmp of the other select operand.
5015             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5016                                                    LHSI->getOperand(2), RHSC,
5017                                                    I.getName()), I);
5018           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5019             // Fold the known value into the constant operand.
5020             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5021             // Insert a new ICmp of the other select operand.
5022             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5023                                                    LHSI->getOperand(1), RHSC,
5024                                                    I.getName()), I);
5025           }
5026         }
5027
5028         if (Op1)
5029           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5030         break;
5031       }
5032       case Instruction::Malloc:
5033         // If we have (malloc != null), and if the malloc has a single use, we
5034         // can assume it is successful and remove the malloc.
5035         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5036           AddToWorkList(LHSI);
5037           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5038                                                          !isTrueWhenEqual(I)));
5039         }
5040         break;
5041       }
5042   }
5043
5044   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5045   if (User *GEP = dyn_castGetElementPtr(Op0))
5046     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5047       return NI;
5048   if (User *GEP = dyn_castGetElementPtr(Op1))
5049     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5050                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5051       return NI;
5052
5053   // Test to see if the operands of the icmp are casted versions of other
5054   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5055   // now.
5056   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5057     if (isa<PointerType>(Op0->getType()) && 
5058         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5059       // We keep moving the cast from the left operand over to the right
5060       // operand, where it can often be eliminated completely.
5061       Op0 = CI->getOperand(0);
5062
5063       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5064       // so eliminate it as well.
5065       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5066         Op1 = CI2->getOperand(0);
5067
5068       // If Op1 is a constant, we can fold the cast into the constant.
5069       if (Op0->getType() != Op1->getType())
5070         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5071           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5072         } else {
5073           // Otherwise, cast the RHS right before the icmp
5074           Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5075         }
5076       return new ICmpInst(I.getPredicate(), Op0, Op1);
5077     }
5078   }
5079   
5080   if (isa<CastInst>(Op0)) {
5081     // Handle the special case of: icmp (cast bool to X), <cst>
5082     // This comes up when you have code like
5083     //   int X = A < B;
5084     //   if (X) ...
5085     // For generality, we handle any zero-extension of any operand comparison
5086     // with a constant or another cast from the same type.
5087     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5088       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5089         return R;
5090   }
5091   
5092   if (I.isEquality()) {
5093     Value *A, *B, *C, *D;
5094     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5095       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5096         Value *OtherVal = A == Op1 ? B : A;
5097         return new ICmpInst(I.getPredicate(), OtherVal,
5098                             Constant::getNullValue(A->getType()));
5099       }
5100
5101       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5102         // A^c1 == C^c2 --> A == C^(c1^c2)
5103         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5104           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5105             if (Op1->hasOneUse()) {
5106               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5107               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5108               return new ICmpInst(I.getPredicate(), A,
5109                                   InsertNewInstBefore(Xor, I));
5110             }
5111         
5112         // A^B == A^D -> B == D
5113         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5114         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5115         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5116         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5117       }
5118     }
5119     
5120     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5121         (A == Op0 || B == Op0)) {
5122       // A == (A^B)  ->  B == 0
5123       Value *OtherVal = A == Op0 ? B : A;
5124       return new ICmpInst(I.getPredicate(), OtherVal,
5125                           Constant::getNullValue(A->getType()));
5126     }
5127     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5128       // (A-B) == A  ->  B == 0
5129       return new ICmpInst(I.getPredicate(), B,
5130                           Constant::getNullValue(B->getType()));
5131     }
5132     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5133       // A == (A-B)  ->  B == 0
5134       return new ICmpInst(I.getPredicate(), B,
5135                           Constant::getNullValue(B->getType()));
5136     }
5137     
5138     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5139     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5140         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5141         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5142       Value *X = 0, *Y = 0, *Z = 0;
5143       
5144       if (A == C) {
5145         X = B; Y = D; Z = A;
5146       } else if (A == D) {
5147         X = B; Y = C; Z = A;
5148       } else if (B == C) {
5149         X = A; Y = D; Z = B;
5150       } else if (B == D) {
5151         X = A; Y = C; Z = B;
5152       }
5153       
5154       if (X) {   // Build (X^Y) & Z
5155         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5156         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5157         I.setOperand(0, Op1);
5158         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5159         return &I;
5160       }
5161     }
5162   }
5163   return Changed ? &I : 0;
5164 }
5165
5166
5167 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5168 /// and CmpRHS are both known to be integer constants.
5169 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5170                                           ConstantInt *DivRHS) {
5171   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5172   const APInt &CmpRHSV = CmpRHS->getValue();
5173   
5174   // FIXME: If the operand types don't match the type of the divide 
5175   // then don't attempt this transform. The code below doesn't have the
5176   // logic to deal with a signed divide and an unsigned compare (and
5177   // vice versa). This is because (x /s C1) <s C2  produces different 
5178   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5179   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5180   // work. :(  The if statement below tests that condition and bails 
5181   // if it finds it. 
5182   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5183   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5184     return 0;
5185   if (DivRHS->isZero())
5186     return 0; // The ProdOV computation fails on divide by zero.
5187
5188   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5189   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5190   // C2 (CI). By solving for X we can turn this into a range check 
5191   // instead of computing a divide. 
5192   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5193
5194   // Determine if the product overflows by seeing if the product is
5195   // not equal to the divide. Make sure we do the same kind of divide
5196   // as in the LHS instruction that we're folding. 
5197   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5198                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5199
5200   // Get the ICmp opcode
5201   ICmpInst::Predicate Pred = ICI.getPredicate();
5202
5203   // Figure out the interval that is being checked.  For example, a comparison
5204   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5205   // Compute this interval based on the constants involved and the signedness of
5206   // the compare/divide.  This computes a half-open interval, keeping track of
5207   // whether either value in the interval overflows.  After analysis each
5208   // overflow variable is set to 0 if it's corresponding bound variable is valid
5209   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5210   int LoOverflow = 0, HiOverflow = 0;
5211   ConstantInt *LoBound = 0, *HiBound = 0;
5212   
5213   
5214   if (!DivIsSigned) {  // udiv
5215     // e.g. X/5 op 3  --> [15, 20)
5216     LoBound = Prod;
5217     HiOverflow = LoOverflow = ProdOV;
5218     if (!HiOverflow)
5219       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5220   } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5221     if (CmpRHSV == 0) {       // (X / pos) op 0
5222       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5223       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5224       HiBound = DivRHS;
5225     } else if (CmpRHSV.isPositive()) {   // (X / pos) op pos
5226       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5227       HiOverflow = LoOverflow = ProdOV;
5228       if (!HiOverflow)
5229         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5230     } else {                       // (X / pos) op neg
5231       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5232       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5233       LoOverflow = AddWithOverflow(LoBound, Prod,
5234                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5235       HiBound = AddOne(Prod);
5236       HiOverflow = ProdOV ? -1 : 0;
5237     }
5238   } else {                         // Divisor is < 0.
5239     if (CmpRHSV == 0) {       // (X / neg) op 0
5240       // e.g. X/-5 op 0  --> [-4, 5)
5241       LoBound = AddOne(DivRHS);
5242       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5243       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5244         HiOverflow = 1;            // [INTMIN+1, overflow)
5245         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5246       }
5247     } else if (CmpRHSV.isPositive()) {   // (X / neg) op pos
5248       // e.g. X/-5 op 3  --> [-19, -14)
5249       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5250       if (!LoOverflow)
5251         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5252       HiBound = AddOne(Prod);
5253     } else {                       // (X / neg) op neg
5254       // e.g. X/-5 op -3  --> [15, 20)
5255       LoBound = Prod;
5256       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5257       HiBound = Subtract(Prod, DivRHS);
5258     }
5259     
5260     // Dividing by a negative swaps the condition.  LT <-> GT
5261     Pred = ICmpInst::getSwappedPredicate(Pred);
5262   }
5263
5264   Value *X = DivI->getOperand(0);
5265   switch (Pred) {
5266   default: assert(0 && "Unhandled icmp opcode!");
5267   case ICmpInst::ICMP_EQ:
5268     if (LoOverflow && HiOverflow)
5269       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5270     else if (HiOverflow)
5271       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5272                           ICmpInst::ICMP_UGE, X, LoBound);
5273     else if (LoOverflow)
5274       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5275                           ICmpInst::ICMP_ULT, X, HiBound);
5276     else
5277       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5278   case ICmpInst::ICMP_NE:
5279     if (LoOverflow && HiOverflow)
5280       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5281     else if (HiOverflow)
5282       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5283                           ICmpInst::ICMP_ULT, X, LoBound);
5284     else if (LoOverflow)
5285       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5286                           ICmpInst::ICMP_UGE, X, HiBound);
5287     else
5288       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5289   case ICmpInst::ICMP_ULT:
5290   case ICmpInst::ICMP_SLT:
5291     if (LoOverflow == +1)   // Low bound is greater than input range.
5292       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5293     if (LoOverflow == -1)   // Low bound is less than input range.
5294       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5295     return new ICmpInst(Pred, X, LoBound);
5296   case ICmpInst::ICMP_UGT:
5297   case ICmpInst::ICMP_SGT:
5298     if (HiOverflow == +1)       // High bound greater than input range.
5299       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5300     else if (HiOverflow == -1)  // High bound less than input range.
5301       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5302     if (Pred == ICmpInst::ICMP_UGT)
5303       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5304     else
5305       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5306   }
5307 }
5308
5309
5310 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5311 ///
5312 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5313                                                           Instruction *LHSI,
5314                                                           ConstantInt *RHS) {
5315   const APInt &RHSV = RHS->getValue();
5316   
5317   switch (LHSI->getOpcode()) {
5318   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5319     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5320       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5321       // fold the xor.
5322       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5323           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5324         Value *CompareVal = LHSI->getOperand(0);
5325         
5326         // If the sign bit of the XorCST is not set, there is no change to
5327         // the operation, just stop using the Xor.
5328         if (!XorCST->getValue().isNegative()) {
5329           ICI.setOperand(0, CompareVal);
5330           AddToWorkList(LHSI);
5331           return &ICI;
5332         }
5333         
5334         // Was the old condition true if the operand is positive?
5335         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5336         
5337         // If so, the new one isn't.
5338         isTrueIfPositive ^= true;
5339         
5340         if (isTrueIfPositive)
5341           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5342         else
5343           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5344       }
5345     }
5346     break;
5347   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5348     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5349         LHSI->getOperand(0)->hasOneUse()) {
5350       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5351       
5352       // If the LHS is an AND of a truncating cast, we can widen the
5353       // and/compare to be the input width without changing the value
5354       // produced, eliminating a cast.
5355       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5356         // We can do this transformation if either the AND constant does not
5357         // have its sign bit set or if it is an equality comparison. 
5358         // Extending a relational comparison when we're checking the sign
5359         // bit would not work.
5360         if (Cast->hasOneUse() &&
5361             (ICI.isEquality() || AndCST->getValue().isPositive() && 
5362              RHSV.isPositive())) {
5363           uint32_t BitWidth = 
5364             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5365           APInt NewCST = AndCST->getValue();
5366           NewCST.zext(BitWidth);
5367           APInt NewCI = RHSV;
5368           NewCI.zext(BitWidth);
5369           Instruction *NewAnd = 
5370             BinaryOperator::createAnd(Cast->getOperand(0),
5371                                       ConstantInt::get(NewCST),LHSI->getName());
5372           InsertNewInstBefore(NewAnd, ICI);
5373           return new ICmpInst(ICI.getPredicate(), NewAnd,
5374                               ConstantInt::get(NewCI));
5375         }
5376       }
5377       
5378       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5379       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5380       // happens a LOT in code produced by the C front-end, for bitfield
5381       // access.
5382       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5383       if (Shift && !Shift->isShift())
5384         Shift = 0;
5385       
5386       ConstantInt *ShAmt;
5387       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5388       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5389       const Type *AndTy = AndCST->getType();          // Type of the and.
5390       
5391       // We can fold this as long as we can't shift unknown bits
5392       // into the mask.  This can only happen with signed shift
5393       // rights, as they sign-extend.
5394       if (ShAmt) {
5395         bool CanFold = Shift->isLogicalShift();
5396         if (!CanFold) {
5397           // To test for the bad case of the signed shr, see if any
5398           // of the bits shifted in could be tested after the mask.
5399           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5400           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5401           
5402           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5403           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5404                AndCST->getValue()) == 0)
5405             CanFold = true;
5406         }
5407         
5408         if (CanFold) {
5409           Constant *NewCst;
5410           if (Shift->getOpcode() == Instruction::Shl)
5411             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5412           else
5413             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5414           
5415           // Check to see if we are shifting out any of the bits being
5416           // compared.
5417           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5418             // If we shifted bits out, the fold is not going to work out.
5419             // As a special case, check to see if this means that the
5420             // result is always true or false now.
5421             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5422               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5423             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5424               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5425           } else {
5426             ICI.setOperand(1, NewCst);
5427             Constant *NewAndCST;
5428             if (Shift->getOpcode() == Instruction::Shl)
5429               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5430             else
5431               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5432             LHSI->setOperand(1, NewAndCST);
5433             LHSI->setOperand(0, Shift->getOperand(0));
5434             AddToWorkList(Shift); // Shift is dead.
5435             AddUsesToWorkList(ICI);
5436             return &ICI;
5437           }
5438         }
5439       }
5440       
5441       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5442       // preferable because it allows the C<<Y expression to be hoisted out
5443       // of a loop if Y is invariant and X is not.
5444       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5445           ICI.isEquality() && !Shift->isArithmeticShift() &&
5446           isa<Instruction>(Shift->getOperand(0))) {
5447         // Compute C << Y.
5448         Value *NS;
5449         if (Shift->getOpcode() == Instruction::LShr) {
5450           NS = BinaryOperator::createShl(AndCST, 
5451                                          Shift->getOperand(1), "tmp");
5452         } else {
5453           // Insert a logical shift.
5454           NS = BinaryOperator::createLShr(AndCST,
5455                                           Shift->getOperand(1), "tmp");
5456         }
5457         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5458         
5459         // Compute X & (C << Y).
5460         Instruction *NewAnd = 
5461           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5462         InsertNewInstBefore(NewAnd, ICI);
5463         
5464         ICI.setOperand(0, NewAnd);
5465         return &ICI;
5466       }
5467     }
5468     break;
5469     
5470   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5471     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5472     if (!ShAmt) break;
5473     
5474     uint32_t TypeBits = RHSV.getBitWidth();
5475     
5476     // Check that the shift amount is in range.  If not, don't perform
5477     // undefined shifts.  When the shift is visited it will be
5478     // simplified.
5479     if (ShAmt->uge(TypeBits))
5480       break;
5481     
5482     if (ICI.isEquality()) {
5483       // If we are comparing against bits always shifted out, the
5484       // comparison cannot succeed.
5485       Constant *Comp =
5486         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5487       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5488         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5489         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5490         return ReplaceInstUsesWith(ICI, Cst);
5491       }
5492       
5493       if (LHSI->hasOneUse()) {
5494         // Otherwise strength reduce the shift into an and.
5495         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5496         Constant *Mask =
5497           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5498         
5499         Instruction *AndI =
5500           BinaryOperator::createAnd(LHSI->getOperand(0),
5501                                     Mask, LHSI->getName()+".mask");
5502         Value *And = InsertNewInstBefore(AndI, ICI);
5503         return new ICmpInst(ICI.getPredicate(), And,
5504                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5505       }
5506     }
5507     
5508     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5509     bool TrueIfSigned = false;
5510     if (LHSI->hasOneUse() &&
5511         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5512       // (X << 31) <s 0  --> (X&1) != 0
5513       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5514                                            (TypeBits-ShAmt->getZExtValue()-1));
5515       Instruction *AndI =
5516         BinaryOperator::createAnd(LHSI->getOperand(0),
5517                                   Mask, LHSI->getName()+".mask");
5518       Value *And = InsertNewInstBefore(AndI, ICI);
5519       
5520       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5521                           And, Constant::getNullValue(And->getType()));
5522     }
5523     break;
5524   }
5525     
5526   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5527   case Instruction::AShr: {
5528     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5529     if (!ShAmt) break;
5530
5531     if (ICI.isEquality()) {
5532       // Check that the shift amount is in range.  If not, don't perform
5533       // undefined shifts.  When the shift is visited it will be
5534       // simplified.
5535       uint32_t TypeBits = RHSV.getBitWidth();
5536       if (ShAmt->uge(TypeBits))
5537         break;
5538       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5539       
5540       // If we are comparing against bits always shifted out, the
5541       // comparison cannot succeed.
5542       APInt Comp = RHSV << ShAmtVal;
5543       if (LHSI->getOpcode() == Instruction::LShr)
5544         Comp = Comp.lshr(ShAmtVal);
5545       else
5546         Comp = Comp.ashr(ShAmtVal);
5547       
5548       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5549         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5550         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5551         return ReplaceInstUsesWith(ICI, Cst);
5552       }
5553       
5554       if (LHSI->hasOneUse() || RHSV == 0) {
5555         // Otherwise strength reduce the shift into an and.
5556         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5557         Constant *Mask = ConstantInt::get(Val);
5558         
5559         Instruction *AndI =
5560           BinaryOperator::createAnd(LHSI->getOperand(0),
5561                                     Mask, LHSI->getName()+".mask");
5562         Value *And = InsertNewInstBefore(AndI, ICI);
5563         return new ICmpInst(ICI.getPredicate(), And,
5564                             ConstantExpr::getShl(RHS, ShAmt));
5565       }
5566     }
5567     break;
5568   }
5569     
5570   case Instruction::SDiv:
5571   case Instruction::UDiv:
5572     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5573     // Fold this div into the comparison, producing a range check. 
5574     // Determine, based on the divide type, what the range is being 
5575     // checked.  If there is an overflow on the low or high side, remember 
5576     // it, otherwise compute the range [low, hi) bounding the new value.
5577     // See: InsertRangeTest above for the kinds of replacements possible.
5578     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5579       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5580                                           DivRHS))
5581         return R;
5582     break;
5583   }
5584   
5585   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5586   if (ICI.isEquality()) {
5587     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5588     
5589     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5590     // the second operand is a constant, simplify a bit.
5591     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5592       switch (BO->getOpcode()) {
5593       case Instruction::SRem:
5594         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5595         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5596           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5597           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5598             Instruction *NewRem =
5599               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5600                                          BO->getName());
5601             InsertNewInstBefore(NewRem, ICI);
5602             return new ICmpInst(ICI.getPredicate(), NewRem, 
5603                                 Constant::getNullValue(BO->getType()));
5604           }
5605         }
5606         break;
5607       case Instruction::Add:
5608         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5609         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5610           if (BO->hasOneUse())
5611             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5612                                 Subtract(RHS, BOp1C));
5613         } else if (RHSV == 0) {
5614           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5615           // efficiently invertible, or if the add has just this one use.
5616           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5617           
5618           if (Value *NegVal = dyn_castNegVal(BOp1))
5619             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5620           else if (Value *NegVal = dyn_castNegVal(BOp0))
5621             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5622           else if (BO->hasOneUse()) {
5623             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5624             InsertNewInstBefore(Neg, ICI);
5625             Neg->takeName(BO);
5626             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5627           }
5628         }
5629         break;
5630       case Instruction::Xor:
5631         // For the xor case, we can xor two constants together, eliminating
5632         // the explicit xor.
5633         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5634           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5635                               ConstantExpr::getXor(RHS, BOC));
5636         
5637         // FALLTHROUGH
5638       case Instruction::Sub:
5639         // Replace (([sub|xor] A, B) != 0) with (A != B)
5640         if (RHSV == 0)
5641           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5642                               BO->getOperand(1));
5643         break;
5644         
5645       case Instruction::Or:
5646         // If bits are being or'd in that are not present in the constant we
5647         // are comparing against, then the comparison could never succeed!
5648         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5649           Constant *NotCI = ConstantExpr::getNot(RHS);
5650           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5651             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5652                                                              isICMP_NE));
5653         }
5654         break;
5655         
5656       case Instruction::And:
5657         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5658           // If bits are being compared against that are and'd out, then the
5659           // comparison can never succeed!
5660           if ((RHSV & ~BOC->getValue()) != 0)
5661             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5662                                                              isICMP_NE));
5663           
5664           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5665           if (RHS == BOC && RHSV.isPowerOf2())
5666             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5667                                 ICmpInst::ICMP_NE, LHSI,
5668                                 Constant::getNullValue(RHS->getType()));
5669           
5670           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5671           if (isSignBit(BOC)) {
5672             Value *X = BO->getOperand(0);
5673             Constant *Zero = Constant::getNullValue(X->getType());
5674             ICmpInst::Predicate pred = isICMP_NE ? 
5675               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5676             return new ICmpInst(pred, X, Zero);
5677           }
5678           
5679           // ((X & ~7) == 0) --> X < 8
5680           if (RHSV == 0 && isHighOnes(BOC)) {
5681             Value *X = BO->getOperand(0);
5682             Constant *NegX = ConstantExpr::getNeg(BOC);
5683             ICmpInst::Predicate pred = isICMP_NE ? 
5684               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5685             return new ICmpInst(pred, X, NegX);
5686           }
5687         }
5688       default: break;
5689       }
5690     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5691       // Handle icmp {eq|ne} <intrinsic>, intcst.
5692       if (II->getIntrinsicID() == Intrinsic::bswap) {
5693         AddToWorkList(II);
5694         ICI.setOperand(0, II->getOperand(1));
5695         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5696         return &ICI;
5697       }
5698     }
5699   } else {  // Not a ICMP_EQ/ICMP_NE
5700             // If the LHS is a cast from an integral value of the same size, 
5701             // then since we know the RHS is a constant, try to simlify.
5702     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5703       Value *CastOp = Cast->getOperand(0);
5704       const Type *SrcTy = CastOp->getType();
5705       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5706       if (SrcTy->isInteger() && 
5707           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5708         // If this is an unsigned comparison, try to make the comparison use
5709         // smaller constant values.
5710         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5711           // X u< 128 => X s> -1
5712           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5713                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5714         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5715                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5716           // X u> 127 => X s< 0
5717           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5718                               Constant::getNullValue(SrcTy));
5719         }
5720       }
5721     }
5722   }
5723   return 0;
5724 }
5725
5726 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5727 /// We only handle extending casts so far.
5728 ///
5729 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5730   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5731   Value *LHSCIOp        = LHSCI->getOperand(0);
5732   const Type *SrcTy     = LHSCIOp->getType();
5733   const Type *DestTy    = LHSCI->getType();
5734   Value *RHSCIOp;
5735
5736   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5737   // integer type is the same size as the pointer type.
5738   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5739       getTargetData().getPointerSizeInBits() == 
5740          cast<IntegerType>(DestTy)->getBitWidth()) {
5741     Value *RHSOp = 0;
5742     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5743       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5744     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5745       RHSOp = RHSC->getOperand(0);
5746       // If the pointer types don't match, insert a bitcast.
5747       if (LHSCIOp->getType() != RHSOp->getType())
5748         RHSOp = InsertCastBefore(Instruction::BitCast, RHSOp,
5749                                  LHSCIOp->getType(), ICI);
5750     }
5751
5752     if (RHSOp)
5753       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5754   }
5755   
5756   // The code below only handles extension cast instructions, so far.
5757   // Enforce this.
5758   if (LHSCI->getOpcode() != Instruction::ZExt &&
5759       LHSCI->getOpcode() != Instruction::SExt)
5760     return 0;
5761
5762   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5763   bool isSignedCmp = ICI.isSignedPredicate();
5764
5765   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5766     // Not an extension from the same type?
5767     RHSCIOp = CI->getOperand(0);
5768     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5769       return 0;
5770     
5771     // If the signedness of the two compares doesn't agree (i.e. one is a sext
5772     // and the other is a zext), then we can't handle this.
5773     if (CI->getOpcode() != LHSCI->getOpcode())
5774       return 0;
5775
5776     // Likewise, if the signedness of the [sz]exts and the compare don't match, 
5777     // then we can't handle this.
5778     if (isSignedExt != isSignedCmp && !ICI.isEquality())
5779       return 0;
5780     
5781     // Okay, just insert a compare of the reduced operands now!
5782     return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5783   }
5784
5785   // If we aren't dealing with a constant on the RHS, exit early
5786   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5787   if (!CI)
5788     return 0;
5789
5790   // Compute the constant that would happen if we truncated to SrcTy then
5791   // reextended to DestTy.
5792   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5793   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5794
5795   // If the re-extended constant didn't change...
5796   if (Res2 == CI) {
5797     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5798     // For example, we might have:
5799     //    %A = sext short %X to uint
5800     //    %B = icmp ugt uint %A, 1330
5801     // It is incorrect to transform this into 
5802     //    %B = icmp ugt short %X, 1330 
5803     // because %A may have negative value. 
5804     //
5805     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5806     // OR operation is EQ/NE.
5807     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5808       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5809     else
5810       return 0;
5811   }
5812
5813   // The re-extended constant changed so the constant cannot be represented 
5814   // in the shorter type. Consequently, we cannot emit a simple comparison.
5815
5816   // First, handle some easy cases. We know the result cannot be equal at this
5817   // point so handle the ICI.isEquality() cases
5818   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5819     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5820   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5821     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5822
5823   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5824   // should have been folded away previously and not enter in here.
5825   Value *Result;
5826   if (isSignedCmp) {
5827     // We're performing a signed comparison.
5828     if (cast<ConstantInt>(CI)->getValue().isNegative())
5829       Result = ConstantInt::getFalse();          // X < (small) --> false
5830     else
5831       Result = ConstantInt::getTrue();           // X < (large) --> true
5832   } else {
5833     // We're performing an unsigned comparison.
5834     if (isSignedExt) {
5835       // We're performing an unsigned comp with a sign extended value.
5836       // This is true if the input is >= 0. [aka >s -1]
5837       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5838       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5839                                    NegOne, ICI.getName()), ICI);
5840     } else {
5841       // Unsigned extend & unsigned compare -> always true.
5842       Result = ConstantInt::getTrue();
5843     }
5844   }
5845
5846   // Finally, return the value computed.
5847   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5848       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5849     return ReplaceInstUsesWith(ICI, Result);
5850   } else {
5851     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
5852             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5853            "ICmp should be folded!");
5854     if (Constant *CI = dyn_cast<Constant>(Result))
5855       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5856     else
5857       return BinaryOperator::createNot(Result);
5858   }
5859 }
5860
5861 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5862   return commonShiftTransforms(I);
5863 }
5864
5865 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5866   return commonShiftTransforms(I);
5867 }
5868
5869 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5870   return commonShiftTransforms(I);
5871 }
5872
5873 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5874   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5875   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5876
5877   // shl X, 0 == X and shr X, 0 == X
5878   // shl 0, X == 0 and shr 0, X == 0
5879   if (Op1 == Constant::getNullValue(Op1->getType()) ||
5880       Op0 == Constant::getNullValue(Op0->getType()))
5881     return ReplaceInstUsesWith(I, Op0);
5882   
5883   if (isa<UndefValue>(Op0)) {            
5884     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5885       return ReplaceInstUsesWith(I, Op0);
5886     else                                    // undef << X -> 0, undef >>u X -> 0
5887       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5888   }
5889   if (isa<UndefValue>(Op1)) {
5890     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
5891       return ReplaceInstUsesWith(I, Op0);          
5892     else                                     // X << undef, X >>u undef -> 0
5893       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5894   }
5895
5896   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
5897   if (I.getOpcode() == Instruction::AShr)
5898     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5899       if (CSI->isAllOnesValue())
5900         return ReplaceInstUsesWith(I, CSI);
5901
5902   // Try to fold constant and into select arguments.
5903   if (isa<Constant>(Op0))
5904     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5905       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5906         return R;
5907
5908   // See if we can turn a signed shr into an unsigned shr.
5909   if (I.isArithmeticShift()) {
5910     if (MaskedValueIsZero(Op0, 
5911           APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
5912       return BinaryOperator::createLShr(Op0, Op1, I.getName());
5913     }
5914   }
5915
5916   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5917     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5918       return Res;
5919   return 0;
5920 }
5921
5922 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5923                                                BinaryOperator &I) {
5924   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
5925
5926   // See if we can simplify any instructions used by the instruction whose sole 
5927   // purpose is to compute bits we don't care about.
5928   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5929   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5930   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5931                            KnownZero, KnownOne))
5932     return &I;
5933   
5934   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5935   // of a signed value.
5936   //
5937   if (Op1->uge(TypeBits)) {
5938     if (I.getOpcode() != Instruction::AShr)
5939       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5940     else {
5941       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5942       return &I;
5943     }
5944   }
5945   
5946   // ((X*C1) << C2) == (X * (C1 << C2))
5947   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5948     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5949       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5950         return BinaryOperator::createMul(BO->getOperand(0),
5951                                          ConstantExpr::getShl(BOOp, Op1));
5952   
5953   // Try to fold constant and into select arguments.
5954   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5955     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5956       return R;
5957   if (isa<PHINode>(Op0))
5958     if (Instruction *NV = FoldOpIntoPhi(I))
5959       return NV;
5960   
5961   if (Op0->hasOneUse()) {
5962     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5963       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5964       Value *V1, *V2;
5965       ConstantInt *CC;
5966       switch (Op0BO->getOpcode()) {
5967         default: break;
5968         case Instruction::Add:
5969         case Instruction::And:
5970         case Instruction::Or:
5971         case Instruction::Xor: {
5972           // These operators commute.
5973           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5974           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5975               match(Op0BO->getOperand(1),
5976                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5977             Instruction *YS = BinaryOperator::createShl(
5978                                             Op0BO->getOperand(0), Op1,
5979                                             Op0BO->getName());
5980             InsertNewInstBefore(YS, I); // (Y << C)
5981             Instruction *X = 
5982               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5983                                      Op0BO->getOperand(1)->getName());
5984             InsertNewInstBefore(X, I);  // (X + (Y << C))
5985             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5986             return BinaryOperator::createAnd(X, ConstantInt::get(
5987                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5988           }
5989           
5990           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5991           Value *Op0BOOp1 = Op0BO->getOperand(1);
5992           if (isLeftShift && Op0BOOp1->hasOneUse() &&
5993               match(Op0BOOp1, 
5994                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5995               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5996               V2 == Op1) {
5997             Instruction *YS = BinaryOperator::createShl(
5998                                                      Op0BO->getOperand(0), Op1,
5999                                                      Op0BO->getName());
6000             InsertNewInstBefore(YS, I); // (Y << C)
6001             Instruction *XM =
6002               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6003                                         V1->getName()+".mask");
6004             InsertNewInstBefore(XM, I); // X & (CC << C)
6005             
6006             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6007           }
6008         }
6009           
6010         // FALL THROUGH.
6011         case Instruction::Sub: {
6012           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6013           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6014               match(Op0BO->getOperand(0),
6015                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6016             Instruction *YS = BinaryOperator::createShl(
6017                                                      Op0BO->getOperand(1), Op1,
6018                                                      Op0BO->getName());
6019             InsertNewInstBefore(YS, I); // (Y << C)
6020             Instruction *X =
6021               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6022                                      Op0BO->getOperand(0)->getName());
6023             InsertNewInstBefore(X, I);  // (X + (Y << C))
6024             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6025             return BinaryOperator::createAnd(X, ConstantInt::get(
6026                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6027           }
6028           
6029           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6030           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6031               match(Op0BO->getOperand(0),
6032                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6033                           m_ConstantInt(CC))) && V2 == Op1 &&
6034               cast<BinaryOperator>(Op0BO->getOperand(0))
6035                   ->getOperand(0)->hasOneUse()) {
6036             Instruction *YS = BinaryOperator::createShl(
6037                                                      Op0BO->getOperand(1), Op1,
6038                                                      Op0BO->getName());
6039             InsertNewInstBefore(YS, I); // (Y << C)
6040             Instruction *XM =
6041               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6042                                         V1->getName()+".mask");
6043             InsertNewInstBefore(XM, I); // X & (CC << C)
6044             
6045             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6046           }
6047           
6048           break;
6049         }
6050       }
6051       
6052       
6053       // If the operand is an bitwise operator with a constant RHS, and the
6054       // shift is the only use, we can pull it out of the shift.
6055       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6056         bool isValid = true;     // Valid only for And, Or, Xor
6057         bool highBitSet = false; // Transform if high bit of constant set?
6058         
6059         switch (Op0BO->getOpcode()) {
6060           default: isValid = false; break;   // Do not perform transform!
6061           case Instruction::Add:
6062             isValid = isLeftShift;
6063             break;
6064           case Instruction::Or:
6065           case Instruction::Xor:
6066             highBitSet = false;
6067             break;
6068           case Instruction::And:
6069             highBitSet = true;
6070             break;
6071         }
6072         
6073         // If this is a signed shift right, and the high bit is modified
6074         // by the logical operation, do not perform the transformation.
6075         // The highBitSet boolean indicates the value of the high bit of
6076         // the constant which would cause it to be modified for this
6077         // operation.
6078         //
6079         if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
6080           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6081         }
6082         
6083         if (isValid) {
6084           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6085           
6086           Instruction *NewShift =
6087             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6088           InsertNewInstBefore(NewShift, I);
6089           NewShift->takeName(Op0BO);
6090           
6091           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6092                                         NewRHS);
6093         }
6094       }
6095     }
6096   }
6097   
6098   // Find out if this is a shift of a shift by a constant.
6099   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6100   if (ShiftOp && !ShiftOp->isShift())
6101     ShiftOp = 0;
6102   
6103   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6104     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6105     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6106     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6107     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6108     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6109     Value *X = ShiftOp->getOperand(0);
6110     
6111     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6112     if (AmtSum > TypeBits)
6113       AmtSum = TypeBits;
6114     
6115     const IntegerType *Ty = cast<IntegerType>(I.getType());
6116     
6117     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6118     if (I.getOpcode() == ShiftOp->getOpcode()) {
6119       return BinaryOperator::create(I.getOpcode(), X,
6120                                     ConstantInt::get(Ty, AmtSum));
6121     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6122                I.getOpcode() == Instruction::AShr) {
6123       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6124       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6125     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6126                I.getOpcode() == Instruction::LShr) {
6127       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6128       Instruction *Shift =
6129         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6130       InsertNewInstBefore(Shift, I);
6131
6132       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6133       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6134     }
6135     
6136     // Okay, if we get here, one shift must be left, and the other shift must be
6137     // right.  See if the amounts are equal.
6138     if (ShiftAmt1 == ShiftAmt2) {
6139       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6140       if (I.getOpcode() == Instruction::Shl) {
6141         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6142         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6143       }
6144       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6145       if (I.getOpcode() == Instruction::LShr) {
6146         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6147         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6148       }
6149       // We can simplify ((X << C) >>s C) into a trunc + sext.
6150       // NOTE: we could do this for any C, but that would make 'unusual' integer
6151       // types.  For now, just stick to ones well-supported by the code
6152       // generators.
6153       const Type *SExtType = 0;
6154       switch (Ty->getBitWidth() - ShiftAmt1) {
6155       case 1  :
6156       case 8  :
6157       case 16 :
6158       case 32 :
6159       case 64 :
6160       case 128:
6161         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6162         break;
6163       default: break;
6164       }
6165       if (SExtType) {
6166         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6167         InsertNewInstBefore(NewTrunc, I);
6168         return new SExtInst(NewTrunc, Ty);
6169       }
6170       // Otherwise, we can't handle it yet.
6171     } else if (ShiftAmt1 < ShiftAmt2) {
6172       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6173       
6174       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6175       if (I.getOpcode() == Instruction::Shl) {
6176         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6177                ShiftOp->getOpcode() == Instruction::AShr);
6178         Instruction *Shift =
6179           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6180         InsertNewInstBefore(Shift, I);
6181         
6182         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6183         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6184       }
6185       
6186       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6187       if (I.getOpcode() == Instruction::LShr) {
6188         assert(ShiftOp->getOpcode() == Instruction::Shl);
6189         Instruction *Shift =
6190           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6191         InsertNewInstBefore(Shift, I);
6192         
6193         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6194         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6195       }
6196       
6197       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6198     } else {
6199       assert(ShiftAmt2 < ShiftAmt1);
6200       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6201
6202       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6203       if (I.getOpcode() == Instruction::Shl) {
6204         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6205                ShiftOp->getOpcode() == Instruction::AShr);
6206         Instruction *Shift =
6207           BinaryOperator::create(ShiftOp->getOpcode(), X,
6208                                  ConstantInt::get(Ty, ShiftDiff));
6209         InsertNewInstBefore(Shift, I);
6210         
6211         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6212         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6213       }
6214       
6215       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6216       if (I.getOpcode() == Instruction::LShr) {
6217         assert(ShiftOp->getOpcode() == Instruction::Shl);
6218         Instruction *Shift =
6219           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6220         InsertNewInstBefore(Shift, I);
6221         
6222         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6223         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6224       }
6225       
6226       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6227     }
6228   }
6229   return 0;
6230 }
6231
6232
6233 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6234 /// expression.  If so, decompose it, returning some value X, such that Val is
6235 /// X*Scale+Offset.
6236 ///
6237 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6238                                         int &Offset) {
6239   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6240   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6241     Offset = CI->getZExtValue();
6242     Scale  = 0;
6243     return ConstantInt::get(Type::Int32Ty, 0);
6244   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6245     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6246       if (I->getOpcode() == Instruction::Shl) {
6247         // This is a value scaled by '1 << the shift amt'.
6248         Scale = 1U << RHS->getZExtValue();
6249         Offset = 0;
6250         return I->getOperand(0);
6251       } else if (I->getOpcode() == Instruction::Mul) {
6252         // This value is scaled by 'RHS'.
6253         Scale = RHS->getZExtValue();
6254         Offset = 0;
6255         return I->getOperand(0);
6256       } else if (I->getOpcode() == Instruction::Add) {
6257         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6258         // where C1 is divisible by C2.
6259         unsigned SubScale;
6260         Value *SubVal = 
6261           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6262         Offset += RHS->getZExtValue();
6263         Scale = SubScale;
6264         return SubVal;
6265       }
6266     }
6267   }
6268
6269   // Otherwise, we can't look past this.
6270   Scale = 1;
6271   Offset = 0;
6272   return Val;
6273 }
6274
6275
6276 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6277 /// try to eliminate the cast by moving the type information into the alloc.
6278 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6279                                                    AllocationInst &AI) {
6280   const PointerType *PTy = cast<PointerType>(CI.getType());
6281   
6282   // Remove any uses of AI that are dead.
6283   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6284   
6285   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6286     Instruction *User = cast<Instruction>(*UI++);
6287     if (isInstructionTriviallyDead(User)) {
6288       while (UI != E && *UI == User)
6289         ++UI; // If this instruction uses AI more than once, don't break UI.
6290       
6291       ++NumDeadInst;
6292       DOUT << "IC: DCE: " << *User;
6293       EraseInstFromFunction(*User);
6294     }
6295   }
6296   
6297   // Get the type really allocated and the type casted to.
6298   const Type *AllocElTy = AI.getAllocatedType();
6299   const Type *CastElTy = PTy->getElementType();
6300   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6301
6302   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6303   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6304   if (CastElTyAlign < AllocElTyAlign) return 0;
6305
6306   // If the allocation has multiple uses, only promote it if we are strictly
6307   // increasing the alignment of the resultant allocation.  If we keep it the
6308   // same, we open the door to infinite loops of various kinds.
6309   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6310
6311   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6312   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6313   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6314
6315   // See if we can satisfy the modulus by pulling a scale out of the array
6316   // size argument.
6317   unsigned ArraySizeScale;
6318   int ArrayOffset;
6319   Value *NumElements = // See if the array size is a decomposable linear expr.
6320     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6321  
6322   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6323   // do the xform.
6324   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6325       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6326
6327   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6328   Value *Amt = 0;
6329   if (Scale == 1) {
6330     Amt = NumElements;
6331   } else {
6332     // If the allocation size is constant, form a constant mul expression
6333     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6334     if (isa<ConstantInt>(NumElements))
6335       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6336     // otherwise multiply the amount and the number of elements
6337     else if (Scale != 1) {
6338       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6339       Amt = InsertNewInstBefore(Tmp, AI);
6340     }
6341   }
6342   
6343   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6344     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6345     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6346     Amt = InsertNewInstBefore(Tmp, AI);
6347   }
6348   
6349   AllocationInst *New;
6350   if (isa<MallocInst>(AI))
6351     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6352   else
6353     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6354   InsertNewInstBefore(New, AI);
6355   New->takeName(&AI);
6356   
6357   // If the allocation has multiple uses, insert a cast and change all things
6358   // that used it to use the new cast.  This will also hack on CI, but it will
6359   // die soon.
6360   if (!AI.hasOneUse()) {
6361     AddUsesToWorkList(AI);
6362     // New is the allocation instruction, pointer typed. AI is the original
6363     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6364     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6365     InsertNewInstBefore(NewCast, AI);
6366     AI.replaceAllUsesWith(NewCast);
6367   }
6368   return ReplaceInstUsesWith(CI, New);
6369 }
6370
6371 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6372 /// and return it as type Ty without inserting any new casts and without
6373 /// changing the computed value.  This is used by code that tries to decide
6374 /// whether promoting or shrinking integer operations to wider or smaller types
6375 /// will allow us to eliminate a truncate or extend.
6376 ///
6377 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6378 /// extension operation if Ty is larger.
6379 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6380                                        unsigned CastOpc, int &NumCastsRemoved) {
6381   // We can always evaluate constants in another type.
6382   if (isa<ConstantInt>(V))
6383     return true;
6384   
6385   Instruction *I = dyn_cast<Instruction>(V);
6386   if (!I) return false;
6387   
6388   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6389   
6390   // If this is an extension or truncate, we can often eliminate it.
6391   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6392     // If this is a cast from the destination type, we can trivially eliminate
6393     // it, and this will remove a cast overall.
6394     if (I->getOperand(0)->getType() == Ty) {
6395       // If the first operand is itself a cast, and is eliminable, do not count
6396       // this as an eliminable cast.  We would prefer to eliminate those two
6397       // casts first.
6398       if (!isa<CastInst>(I->getOperand(0)))
6399         ++NumCastsRemoved;
6400       return true;
6401     }
6402   }
6403
6404   // We can't extend or shrink something that has multiple uses: doing so would
6405   // require duplicating the instruction in general, which isn't profitable.
6406   if (!I->hasOneUse()) return false;
6407
6408   switch (I->getOpcode()) {
6409   case Instruction::Add:
6410   case Instruction::Sub:
6411   case Instruction::And:
6412   case Instruction::Or:
6413   case Instruction::Xor:
6414     // These operators can all arbitrarily be extended or truncated.
6415     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6416                                       NumCastsRemoved) &&
6417            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6418                                       NumCastsRemoved);
6419
6420   case Instruction::Shl:
6421     // If we are truncating the result of this SHL, and if it's a shift of a
6422     // constant amount, we can always perform a SHL in a smaller type.
6423     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6424       uint32_t BitWidth = Ty->getBitWidth();
6425       if (BitWidth < OrigTy->getBitWidth() && 
6426           CI->getLimitedValue(BitWidth) < BitWidth)
6427         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6428                                           NumCastsRemoved);
6429     }
6430     break;
6431   case Instruction::LShr:
6432     // If this is a truncate of a logical shr, we can truncate it to a smaller
6433     // lshr iff we know that the bits we would otherwise be shifting in are
6434     // already zeros.
6435     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6436       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6437       uint32_t BitWidth = Ty->getBitWidth();
6438       if (BitWidth < OrigBitWidth &&
6439           MaskedValueIsZero(I->getOperand(0),
6440             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6441           CI->getLimitedValue(BitWidth) < BitWidth) {
6442         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6443                                           NumCastsRemoved);
6444       }
6445     }
6446     break;
6447   case Instruction::ZExt:
6448   case Instruction::SExt:
6449   case Instruction::Trunc:
6450     // If this is the same kind of case as our original (e.g. zext+zext), we
6451     // can safely replace it.  Note that replacing it does not reduce the number
6452     // of casts in the input.
6453     if (I->getOpcode() == CastOpc)
6454       return true;
6455     
6456     break;
6457   default:
6458     // TODO: Can handle more cases here.
6459     break;
6460   }
6461   
6462   return false;
6463 }
6464
6465 /// EvaluateInDifferentType - Given an expression that 
6466 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6467 /// evaluate the expression.
6468 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6469                                              bool isSigned) {
6470   if (Constant *C = dyn_cast<Constant>(V))
6471     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6472
6473   // Otherwise, it must be an instruction.
6474   Instruction *I = cast<Instruction>(V);
6475   Instruction *Res = 0;
6476   switch (I->getOpcode()) {
6477   case Instruction::Add:
6478   case Instruction::Sub:
6479   case Instruction::And:
6480   case Instruction::Or:
6481   case Instruction::Xor:
6482   case Instruction::AShr:
6483   case Instruction::LShr:
6484   case Instruction::Shl: {
6485     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6486     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6487     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6488                                  LHS, RHS, I->getName());
6489     break;
6490   }    
6491   case Instruction::Trunc:
6492   case Instruction::ZExt:
6493   case Instruction::SExt:
6494     // If the source type of the cast is the type we're trying for then we can
6495     // just return the source.  There's no need to insert it because it is not
6496     // new.
6497     if (I->getOperand(0)->getType() == Ty)
6498       return I->getOperand(0);
6499     
6500     // Otherwise, must be the same type of case, so just reinsert a new one.
6501     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6502                            Ty, I->getName());
6503     break;
6504   default: 
6505     // TODO: Can handle more cases here.
6506     assert(0 && "Unreachable!");
6507     break;
6508   }
6509   
6510   return InsertNewInstBefore(Res, *I);
6511 }
6512
6513 /// @brief Implement the transforms common to all CastInst visitors.
6514 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6515   Value *Src = CI.getOperand(0);
6516
6517   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6518   // eliminate it now.
6519   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6520     if (Instruction::CastOps opc = 
6521         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6522       // The first cast (CSrc) is eliminable so we need to fix up or replace
6523       // the second cast (CI). CSrc will then have a good chance of being dead.
6524       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6525     }
6526   }
6527
6528   // If we are casting a select then fold the cast into the select
6529   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6530     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6531       return NV;
6532
6533   // If we are casting a PHI then fold the cast into the PHI
6534   if (isa<PHINode>(Src))
6535     if (Instruction *NV = FoldOpIntoPhi(CI))
6536       return NV;
6537   
6538   return 0;
6539 }
6540
6541 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6542 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6543   Value *Src = CI.getOperand(0);
6544   
6545   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6546     // If casting the result of a getelementptr instruction with no offset, turn
6547     // this into a cast of the original pointer!
6548     if (GEP->hasAllZeroIndices()) {
6549       // Changing the cast operand is usually not a good idea but it is safe
6550       // here because the pointer operand is being replaced with another 
6551       // pointer operand so the opcode doesn't need to change.
6552       AddToWorkList(GEP);
6553       CI.setOperand(0, GEP->getOperand(0));
6554       return &CI;
6555     }
6556     
6557     // If the GEP has a single use, and the base pointer is a bitcast, and the
6558     // GEP computes a constant offset, see if we can convert these three
6559     // instructions into fewer.  This typically happens with unions and other
6560     // non-type-safe code.
6561     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6562       if (GEP->hasAllConstantIndices()) {
6563         // We are guaranteed to get a constant from EmitGEPOffset.
6564         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6565         int64_t Offset = OffsetV->getSExtValue();
6566         
6567         // Get the base pointer input of the bitcast, and the type it points to.
6568         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6569         const Type *GEPIdxTy =
6570           cast<PointerType>(OrigBase->getType())->getElementType();
6571         if (GEPIdxTy->isSized()) {
6572           SmallVector<Value*, 8> NewIndices;
6573           
6574           // Start with the index over the outer type.  Note that the type size
6575           // might be zero (even if the offset isn't zero) if the indexed type
6576           // is something like [0 x {int, int}]
6577           const Type *IntPtrTy = TD->getIntPtrType();
6578           int64_t FirstIdx = 0;
6579           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6580             FirstIdx = Offset/TySize;
6581             Offset %= TySize;
6582           
6583             // Handle silly modulus not returning values values [0..TySize).
6584             if (Offset < 0) {
6585               --FirstIdx;
6586               Offset += TySize;
6587               assert(Offset >= 0);
6588             }
6589             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6590           }
6591           
6592           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6593
6594           // Index into the types.  If we fail, set OrigBase to null.
6595           while (Offset) {
6596             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6597               const StructLayout *SL = TD->getStructLayout(STy);
6598               if (Offset < (int64_t)SL->getSizeInBytes()) {
6599                 unsigned Elt = SL->getElementContainingOffset(Offset);
6600                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6601               
6602                 Offset -= SL->getElementOffset(Elt);
6603                 GEPIdxTy = STy->getElementType(Elt);
6604               } else {
6605                 // Otherwise, we can't index into this, bail out.
6606                 Offset = 0;
6607                 OrigBase = 0;
6608               }
6609             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6610               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6611               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6612                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6613                 Offset %= EltSize;
6614               } else {
6615                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6616               }
6617               GEPIdxTy = STy->getElementType();
6618             } else {
6619               // Otherwise, we can't index into this, bail out.
6620               Offset = 0;
6621               OrigBase = 0;
6622             }
6623           }
6624           if (OrigBase) {
6625             // If we were able to index down into an element, create the GEP
6626             // and bitcast the result.  This eliminates one bitcast, potentially
6627             // two.
6628             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6629                                                       NewIndices.begin(),
6630                                                       NewIndices.end(), "");
6631             InsertNewInstBefore(NGEP, CI);
6632             NGEP->takeName(GEP);
6633             
6634             if (isa<BitCastInst>(CI))
6635               return new BitCastInst(NGEP, CI.getType());
6636             assert(isa<PtrToIntInst>(CI));
6637             return new PtrToIntInst(NGEP, CI.getType());
6638           }
6639         }
6640       }      
6641     }
6642   }
6643     
6644   return commonCastTransforms(CI);
6645 }
6646
6647
6648
6649 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6650 /// integer types. This function implements the common transforms for all those
6651 /// cases.
6652 /// @brief Implement the transforms common to CastInst with integer operands
6653 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6654   if (Instruction *Result = commonCastTransforms(CI))
6655     return Result;
6656
6657   Value *Src = CI.getOperand(0);
6658   const Type *SrcTy = Src->getType();
6659   const Type *DestTy = CI.getType();
6660   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6661   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6662
6663   // See if we can simplify any instructions used by the LHS whose sole 
6664   // purpose is to compute bits we don't care about.
6665   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6666   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6667                            KnownZero, KnownOne))
6668     return &CI;
6669
6670   // If the source isn't an instruction or has more than one use then we
6671   // can't do anything more. 
6672   Instruction *SrcI = dyn_cast<Instruction>(Src);
6673   if (!SrcI || !Src->hasOneUse())
6674     return 0;
6675
6676   // Attempt to propagate the cast into the instruction for int->int casts.
6677   int NumCastsRemoved = 0;
6678   if (!isa<BitCastInst>(CI) &&
6679       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6680                                  CI.getOpcode(), NumCastsRemoved)) {
6681     // If this cast is a truncate, evaluting in a different type always
6682     // eliminates the cast, so it is always a win.  If this is a zero-extension,
6683     // we need to do an AND to maintain the clear top-part of the computation,
6684     // so we require that the input have eliminated at least one cast.  If this
6685     // is a sign extension, we insert two new casts (to do the extension) so we
6686     // require that two casts have been eliminated.
6687     bool DoXForm;
6688     switch (CI.getOpcode()) {
6689     default:
6690       // All the others use floating point so we shouldn't actually 
6691       // get here because of the check above.
6692       assert(0 && "Unknown cast type");
6693     case Instruction::Trunc:
6694       DoXForm = true;
6695       break;
6696     case Instruction::ZExt:
6697       DoXForm = NumCastsRemoved >= 1;
6698       break;
6699     case Instruction::SExt:
6700       DoXForm = NumCastsRemoved >= 2;
6701       break;
6702     }
6703     
6704     if (DoXForm) {
6705       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6706                                            CI.getOpcode() == Instruction::SExt);
6707       assert(Res->getType() == DestTy);
6708       switch (CI.getOpcode()) {
6709       default: assert(0 && "Unknown cast type!");
6710       case Instruction::Trunc:
6711       case Instruction::BitCast:
6712         // Just replace this cast with the result.
6713         return ReplaceInstUsesWith(CI, Res);
6714       case Instruction::ZExt: {
6715         // We need to emit an AND to clear the high bits.
6716         assert(SrcBitSize < DestBitSize && "Not a zext?");
6717         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6718                                                             SrcBitSize));
6719         return BinaryOperator::createAnd(Res, C);
6720       }
6721       case Instruction::SExt:
6722         // We need to emit a cast to truncate, then a cast to sext.
6723         return CastInst::create(Instruction::SExt,
6724             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6725                              CI), DestTy);
6726       }
6727     }
6728   }
6729   
6730   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6731   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6732
6733   switch (SrcI->getOpcode()) {
6734   case Instruction::Add:
6735   case Instruction::Mul:
6736   case Instruction::And:
6737   case Instruction::Or:
6738   case Instruction::Xor:
6739     // If we are discarding information, rewrite.
6740     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6741       // Don't insert two casts if they cannot be eliminated.  We allow 
6742       // two casts to be inserted if the sizes are the same.  This could 
6743       // only be converting signedness, which is a noop.
6744       if (DestBitSize == SrcBitSize || 
6745           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6746           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6747         Instruction::CastOps opcode = CI.getOpcode();
6748         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6749         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6750         return BinaryOperator::create(
6751             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6752       }
6753     }
6754
6755     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6756     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6757         SrcI->getOpcode() == Instruction::Xor &&
6758         Op1 == ConstantInt::getTrue() &&
6759         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6760       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6761       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6762     }
6763     break;
6764   case Instruction::SDiv:
6765   case Instruction::UDiv:
6766   case Instruction::SRem:
6767   case Instruction::URem:
6768     // If we are just changing the sign, rewrite.
6769     if (DestBitSize == SrcBitSize) {
6770       // Don't insert two casts if they cannot be eliminated.  We allow 
6771       // two casts to be inserted if the sizes are the same.  This could 
6772       // only be converting signedness, which is a noop.
6773       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6774           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6775         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6776                                               Op0, DestTy, SrcI);
6777         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6778                                               Op1, DestTy, SrcI);
6779         return BinaryOperator::create(
6780           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6781       }
6782     }
6783     break;
6784
6785   case Instruction::Shl:
6786     // Allow changing the sign of the source operand.  Do not allow 
6787     // changing the size of the shift, UNLESS the shift amount is a 
6788     // constant.  We must not change variable sized shifts to a smaller 
6789     // size, because it is undefined to shift more bits out than exist 
6790     // in the value.
6791     if (DestBitSize == SrcBitSize ||
6792         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6793       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6794           Instruction::BitCast : Instruction::Trunc);
6795       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6796       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6797       return BinaryOperator::createShl(Op0c, Op1c);
6798     }
6799     break;
6800   case Instruction::AShr:
6801     // If this is a signed shr, and if all bits shifted in are about to be
6802     // truncated off, turn it into an unsigned shr to allow greater
6803     // simplifications.
6804     if (DestBitSize < SrcBitSize &&
6805         isa<ConstantInt>(Op1)) {
6806       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6807       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6808         // Insert the new logical shift right.
6809         return BinaryOperator::createLShr(Op0, Op1);
6810       }
6811     }
6812     break;
6813   }
6814   return 0;
6815 }
6816
6817 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6818   if (Instruction *Result = commonIntCastTransforms(CI))
6819     return Result;
6820   
6821   Value *Src = CI.getOperand(0);
6822   const Type *Ty = CI.getType();
6823   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6824   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6825   
6826   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6827     switch (SrcI->getOpcode()) {
6828     default: break;
6829     case Instruction::LShr:
6830       // We can shrink lshr to something smaller if we know the bits shifted in
6831       // are already zeros.
6832       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6833         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6834         
6835         // Get a mask for the bits shifting in.
6836         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6837         Value* SrcIOp0 = SrcI->getOperand(0);
6838         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6839           if (ShAmt >= DestBitWidth)        // All zeros.
6840             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6841
6842           // Okay, we can shrink this.  Truncate the input, then return a new
6843           // shift.
6844           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6845           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6846                                        Ty, CI);
6847           return BinaryOperator::createLShr(V1, V2);
6848         }
6849       } else {     // This is a variable shr.
6850         
6851         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
6852         // more LLVM instructions, but allows '1 << Y' to be hoisted if
6853         // loop-invariant and CSE'd.
6854         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6855           Value *One = ConstantInt::get(SrcI->getType(), 1);
6856
6857           Value *V = InsertNewInstBefore(
6858               BinaryOperator::createShl(One, SrcI->getOperand(1),
6859                                      "tmp"), CI);
6860           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6861                                                             SrcI->getOperand(0),
6862                                                             "tmp"), CI);
6863           Value *Zero = Constant::getNullValue(V->getType());
6864           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6865         }
6866       }
6867       break;
6868     }
6869   }
6870   
6871   return 0;
6872 }
6873
6874 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6875   // If one of the common conversion will work ..
6876   if (Instruction *Result = commonIntCastTransforms(CI))
6877     return Result;
6878
6879   Value *Src = CI.getOperand(0);
6880
6881   // If this is a cast of a cast
6882   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6883     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6884     // types and if the sizes are just right we can convert this into a logical
6885     // 'and' which will be much cheaper than the pair of casts.
6886     if (isa<TruncInst>(CSrc)) {
6887       // Get the sizes of the types involved
6888       Value *A = CSrc->getOperand(0);
6889       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6890       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6891       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6892       // If we're actually extending zero bits and the trunc is a no-op
6893       if (MidSize < DstSize && SrcSize == DstSize) {
6894         // Replace both of the casts with an And of the type mask.
6895         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
6896         Constant *AndConst = ConstantInt::get(AndValue);
6897         Instruction *And = 
6898           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6899         // Unfortunately, if the type changed, we need to cast it back.
6900         if (And->getType() != CI.getType()) {
6901           And->setName(CSrc->getName()+".mask");
6902           InsertNewInstBefore(And, CI);
6903           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6904         }
6905         return And;
6906       }
6907     }
6908   }
6909
6910   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6911     // If we are just checking for a icmp eq of a single bit and zext'ing it
6912     // to an integer, then shift the bit to the appropriate place and then
6913     // cast to integer to avoid the comparison.
6914     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6915       const APInt &Op1CV = Op1C->getValue();
6916       
6917       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
6918       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
6919       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6920           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6921         Value *In = ICI->getOperand(0);
6922         Value *Sh = ConstantInt::get(In->getType(),
6923                                     In->getType()->getPrimitiveSizeInBits()-1);
6924         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
6925                                                         In->getName()+".lobit"),
6926                                  CI);
6927         if (In->getType() != CI.getType())
6928           In = CastInst::createIntegerCast(In, CI.getType(),
6929                                            false/*ZExt*/, "tmp", &CI);
6930
6931         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6932           Constant *One = ConstantInt::get(In->getType(), 1);
6933           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
6934                                                           In->getName()+".not"),
6935                                    CI);
6936         }
6937
6938         return ReplaceInstUsesWith(CI, In);
6939       }
6940       
6941       
6942       
6943       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
6944       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6945       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
6946       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
6947       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
6948       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
6949       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
6950       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6951       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
6952           // This only works for EQ and NE
6953           ICI->isEquality()) {
6954         // If Op1C some other power of two, convert:
6955         uint32_t BitWidth = Op1C->getType()->getBitWidth();
6956         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6957         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6958         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6959         
6960         APInt KnownZeroMask(~KnownZero);
6961         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6962           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6963           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6964             // (X&4) == 2 --> false
6965             // (X&4) != 2 --> true
6966             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6967             Res = ConstantExpr::getZExt(Res, CI.getType());
6968             return ReplaceInstUsesWith(CI, Res);
6969           }
6970           
6971           uint32_t ShiftAmt = KnownZeroMask.logBase2();
6972           Value *In = ICI->getOperand(0);
6973           if (ShiftAmt) {
6974             // Perform a logical shr by shiftamt.
6975             // Insert the shift to put the result in the low bit.
6976             In = InsertNewInstBefore(
6977                    BinaryOperator::createLShr(In,
6978                                      ConstantInt::get(In->getType(), ShiftAmt),
6979                                               In->getName()+".lobit"), CI);
6980           }
6981           
6982           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6983             Constant *One = ConstantInt::get(In->getType(), 1);
6984             In = BinaryOperator::createXor(In, One, "tmp");
6985             InsertNewInstBefore(cast<Instruction>(In), CI);
6986           }
6987           
6988           if (CI.getType() == In->getType())
6989             return ReplaceInstUsesWith(CI, In);
6990           else
6991             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6992         }
6993       }
6994     }
6995   }    
6996   return 0;
6997 }
6998
6999 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7000   if (Instruction *I = commonIntCastTransforms(CI))
7001     return I;
7002   
7003   Value *Src = CI.getOperand(0);
7004   
7005   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7006   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7007   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7008     // If we are just checking for a icmp eq of a single bit and zext'ing it
7009     // to an integer, then shift the bit to the appropriate place and then
7010     // cast to integer to avoid the comparison.
7011     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7012       const APInt &Op1CV = Op1C->getValue();
7013       
7014       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7015       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7016       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7017           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7018         Value *In = ICI->getOperand(0);
7019         Value *Sh = ConstantInt::get(In->getType(),
7020                                      In->getType()->getPrimitiveSizeInBits()-1);
7021         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7022                                                         In->getName()+".lobit"),
7023                                  CI);
7024         if (In->getType() != CI.getType())
7025           In = CastInst::createIntegerCast(In, CI.getType(),
7026                                            true/*SExt*/, "tmp", &CI);
7027         
7028         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7029           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7030                                      In->getName()+".not"), CI);
7031         
7032         return ReplaceInstUsesWith(CI, In);
7033       }
7034     }
7035   }
7036       
7037   return 0;
7038 }
7039
7040 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7041   return commonCastTransforms(CI);
7042 }
7043
7044 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7045   return commonCastTransforms(CI);
7046 }
7047
7048 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7049   return commonCastTransforms(CI);
7050 }
7051
7052 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7053   return commonCastTransforms(CI);
7054 }
7055
7056 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7057   return commonCastTransforms(CI);
7058 }
7059
7060 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7061   return commonCastTransforms(CI);
7062 }
7063
7064 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7065   return commonPointerCastTransforms(CI);
7066 }
7067
7068 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7069   return commonCastTransforms(CI);
7070 }
7071
7072 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7073   // If the operands are integer typed then apply the integer transforms,
7074   // otherwise just apply the common ones.
7075   Value *Src = CI.getOperand(0);
7076   const Type *SrcTy = Src->getType();
7077   const Type *DestTy = CI.getType();
7078
7079   if (SrcTy->isInteger() && DestTy->isInteger()) {
7080     if (Instruction *Result = commonIntCastTransforms(CI))
7081       return Result;
7082   } else if (isa<PointerType>(SrcTy)) {
7083     if (Instruction *I = commonPointerCastTransforms(CI))
7084       return I;
7085   } else {
7086     if (Instruction *Result = commonCastTransforms(CI))
7087       return Result;
7088   }
7089
7090
7091   // Get rid of casts from one type to the same type. These are useless and can
7092   // be replaced by the operand.
7093   if (DestTy == Src->getType())
7094     return ReplaceInstUsesWith(CI, Src);
7095
7096   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7097     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7098     const Type *DstElTy = DstPTy->getElementType();
7099     const Type *SrcElTy = SrcPTy->getElementType();
7100     
7101     // If we are casting a malloc or alloca to a pointer to a type of the same
7102     // size, rewrite the allocation instruction to allocate the "right" type.
7103     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7104       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7105         return V;
7106     
7107     // If the source and destination are pointers, and this cast is equivalent
7108     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7109     // This can enhance SROA and other transforms that want type-safe pointers.
7110     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7111     unsigned NumZeros = 0;
7112     while (SrcElTy != DstElTy && 
7113            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7114            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7115       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7116       ++NumZeros;
7117     }
7118
7119     // If we found a path from the src to dest, create the getelementptr now.
7120     if (SrcElTy == DstElTy) {
7121       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7122       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7123                                    ((Instruction*) NULL));
7124     }
7125   }
7126
7127   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7128     if (SVI->hasOneUse()) {
7129       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7130       // a bitconvert to a vector with the same # elts.
7131       if (isa<VectorType>(DestTy) && 
7132           cast<VectorType>(DestTy)->getNumElements() == 
7133                 SVI->getType()->getNumElements()) {
7134         CastInst *Tmp;
7135         // If either of the operands is a cast from CI.getType(), then
7136         // evaluating the shuffle in the casted destination's type will allow
7137         // us to eliminate at least one cast.
7138         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7139              Tmp->getOperand(0)->getType() == DestTy) ||
7140             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7141              Tmp->getOperand(0)->getType() == DestTy)) {
7142           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7143                                                SVI->getOperand(0), DestTy, &CI);
7144           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7145                                                SVI->getOperand(1), DestTy, &CI);
7146           // Return a new shuffle vector.  Use the same element ID's, as we
7147           // know the vector types match #elts.
7148           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7149         }
7150       }
7151     }
7152   }
7153   return 0;
7154 }
7155
7156 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7157 ///   %C = or %A, %B
7158 ///   %D = select %cond, %C, %A
7159 /// into:
7160 ///   %C = select %cond, %B, 0
7161 ///   %D = or %A, %C
7162 ///
7163 /// Assuming that the specified instruction is an operand to the select, return
7164 /// a bitmask indicating which operands of this instruction are foldable if they
7165 /// equal the other incoming value of the select.
7166 ///
7167 static unsigned GetSelectFoldableOperands(Instruction *I) {
7168   switch (I->getOpcode()) {
7169   case Instruction::Add:
7170   case Instruction::Mul:
7171   case Instruction::And:
7172   case Instruction::Or:
7173   case Instruction::Xor:
7174     return 3;              // Can fold through either operand.
7175   case Instruction::Sub:   // Can only fold on the amount subtracted.
7176   case Instruction::Shl:   // Can only fold on the shift amount.
7177   case Instruction::LShr:
7178   case Instruction::AShr:
7179     return 1;
7180   default:
7181     return 0;              // Cannot fold
7182   }
7183 }
7184
7185 /// GetSelectFoldableConstant - For the same transformation as the previous
7186 /// function, return the identity constant that goes into the select.
7187 static Constant *GetSelectFoldableConstant(Instruction *I) {
7188   switch (I->getOpcode()) {
7189   default: assert(0 && "This cannot happen!"); abort();
7190   case Instruction::Add:
7191   case Instruction::Sub:
7192   case Instruction::Or:
7193   case Instruction::Xor:
7194   case Instruction::Shl:
7195   case Instruction::LShr:
7196   case Instruction::AShr:
7197     return Constant::getNullValue(I->getType());
7198   case Instruction::And:
7199     return Constant::getAllOnesValue(I->getType());
7200   case Instruction::Mul:
7201     return ConstantInt::get(I->getType(), 1);
7202   }
7203 }
7204
7205 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7206 /// have the same opcode and only one use each.  Try to simplify this.
7207 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7208                                           Instruction *FI) {
7209   if (TI->getNumOperands() == 1) {
7210     // If this is a non-volatile load or a cast from the same type,
7211     // merge.
7212     if (TI->isCast()) {
7213       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7214         return 0;
7215     } else {
7216       return 0;  // unknown unary op.
7217     }
7218
7219     // Fold this by inserting a select from the input values.
7220     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7221                                        FI->getOperand(0), SI.getName()+".v");
7222     InsertNewInstBefore(NewSI, SI);
7223     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7224                             TI->getType());
7225   }
7226
7227   // Only handle binary operators here.
7228   if (!isa<BinaryOperator>(TI))
7229     return 0;
7230
7231   // Figure out if the operations have any operands in common.
7232   Value *MatchOp, *OtherOpT, *OtherOpF;
7233   bool MatchIsOpZero;
7234   if (TI->getOperand(0) == FI->getOperand(0)) {
7235     MatchOp  = TI->getOperand(0);
7236     OtherOpT = TI->getOperand(1);
7237     OtherOpF = FI->getOperand(1);
7238     MatchIsOpZero = true;
7239   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7240     MatchOp  = TI->getOperand(1);
7241     OtherOpT = TI->getOperand(0);
7242     OtherOpF = FI->getOperand(0);
7243     MatchIsOpZero = false;
7244   } else if (!TI->isCommutative()) {
7245     return 0;
7246   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7247     MatchOp  = TI->getOperand(0);
7248     OtherOpT = TI->getOperand(1);
7249     OtherOpF = FI->getOperand(0);
7250     MatchIsOpZero = true;
7251   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7252     MatchOp  = TI->getOperand(1);
7253     OtherOpT = TI->getOperand(0);
7254     OtherOpF = FI->getOperand(1);
7255     MatchIsOpZero = true;
7256   } else {
7257     return 0;
7258   }
7259
7260   // If we reach here, they do have operations in common.
7261   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7262                                      OtherOpF, SI.getName()+".v");
7263   InsertNewInstBefore(NewSI, SI);
7264
7265   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7266     if (MatchIsOpZero)
7267       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7268     else
7269       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7270   }
7271   assert(0 && "Shouldn't get here");
7272   return 0;
7273 }
7274
7275 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7276   Value *CondVal = SI.getCondition();
7277   Value *TrueVal = SI.getTrueValue();
7278   Value *FalseVal = SI.getFalseValue();
7279
7280   // select true, X, Y  -> X
7281   // select false, X, Y -> Y
7282   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7283     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7284
7285   // select C, X, X -> X
7286   if (TrueVal == FalseVal)
7287     return ReplaceInstUsesWith(SI, TrueVal);
7288
7289   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7290     return ReplaceInstUsesWith(SI, FalseVal);
7291   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7292     return ReplaceInstUsesWith(SI, TrueVal);
7293   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7294     if (isa<Constant>(TrueVal))
7295       return ReplaceInstUsesWith(SI, TrueVal);
7296     else
7297       return ReplaceInstUsesWith(SI, FalseVal);
7298   }
7299
7300   if (SI.getType() == Type::Int1Ty) {
7301     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7302       if (C->getZExtValue()) {
7303         // Change: A = select B, true, C --> A = or B, C
7304         return BinaryOperator::createOr(CondVal, FalseVal);
7305       } else {
7306         // Change: A = select B, false, C --> A = and !B, C
7307         Value *NotCond =
7308           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7309                                              "not."+CondVal->getName()), SI);
7310         return BinaryOperator::createAnd(NotCond, FalseVal);
7311       }
7312     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7313       if (C->getZExtValue() == false) {
7314         // Change: A = select B, C, false --> A = and B, C
7315         return BinaryOperator::createAnd(CondVal, TrueVal);
7316       } else {
7317         // Change: A = select B, C, true --> A = or !B, C
7318         Value *NotCond =
7319           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7320                                              "not."+CondVal->getName()), SI);
7321         return BinaryOperator::createOr(NotCond, TrueVal);
7322       }
7323     }
7324   }
7325
7326   // Selecting between two integer constants?
7327   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7328     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7329       // select C, 1, 0 -> zext C to int
7330       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7331         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7332       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7333         // select C, 0, 1 -> zext !C to int
7334         Value *NotCond =
7335           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7336                                                "not."+CondVal->getName()), SI);
7337         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7338       }
7339       
7340       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7341
7342       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7343
7344         // (x <s 0) ? -1 : 0 -> ashr x, 31
7345         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7346           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7347             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7348               // The comparison constant and the result are not neccessarily the
7349               // same width. Make an all-ones value by inserting a AShr.
7350               Value *X = IC->getOperand(0);
7351               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7352               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7353               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7354                                                         ShAmt, "ones");
7355               InsertNewInstBefore(SRA, SI);
7356               
7357               // Finally, convert to the type of the select RHS.  We figure out
7358               // if this requires a SExt, Trunc or BitCast based on the sizes.
7359               Instruction::CastOps opc = Instruction::BitCast;
7360               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7361               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7362               if (SRASize < SISize)
7363                 opc = Instruction::SExt;
7364               else if (SRASize > SISize)
7365                 opc = Instruction::Trunc;
7366               return CastInst::create(opc, SRA, SI.getType());
7367             }
7368           }
7369
7370
7371         // If one of the constants is zero (we know they can't both be) and we
7372         // have an icmp instruction with zero, and we have an 'and' with the
7373         // non-constant value, eliminate this whole mess.  This corresponds to
7374         // cases like this: ((X & 27) ? 27 : 0)
7375         if (TrueValC->isZero() || FalseValC->isZero())
7376           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7377               cast<Constant>(IC->getOperand(1))->isNullValue())
7378             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7379               if (ICA->getOpcode() == Instruction::And &&
7380                   isa<ConstantInt>(ICA->getOperand(1)) &&
7381                   (ICA->getOperand(1) == TrueValC ||
7382                    ICA->getOperand(1) == FalseValC) &&
7383                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7384                 // Okay, now we know that everything is set up, we just don't
7385                 // know whether we have a icmp_ne or icmp_eq and whether the 
7386                 // true or false val is the zero.
7387                 bool ShouldNotVal = !TrueValC->isZero();
7388                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7389                 Value *V = ICA;
7390                 if (ShouldNotVal)
7391                   V = InsertNewInstBefore(BinaryOperator::create(
7392                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7393                 return ReplaceInstUsesWith(SI, V);
7394               }
7395       }
7396     }
7397
7398   // See if we are selecting two values based on a comparison of the two values.
7399   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7400     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7401       // Transform (X == Y) ? X : Y  -> Y
7402       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7403         // This is not safe in general for floating point:  
7404         // consider X== -0, Y== +0.
7405         // It becomes safe if either operand is a nonzero constant.
7406         ConstantFP *CFPt, *CFPf;
7407         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7408               !CFPt->getValueAPF().isZero()) ||
7409             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7410              !CFPf->getValueAPF().isZero()))
7411         return ReplaceInstUsesWith(SI, FalseVal);
7412       }
7413       // Transform (X != Y) ? X : Y  -> X
7414       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7415         return ReplaceInstUsesWith(SI, TrueVal);
7416       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7417
7418     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7419       // Transform (X == Y) ? Y : X  -> X
7420       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7421         // This is not safe in general for floating point:  
7422         // consider X== -0, Y== +0.
7423         // It becomes safe if either operand is a nonzero constant.
7424         ConstantFP *CFPt, *CFPf;
7425         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7426               !CFPt->getValueAPF().isZero()) ||
7427             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7428              !CFPf->getValueAPF().isZero()))
7429           return ReplaceInstUsesWith(SI, FalseVal);
7430       }
7431       // Transform (X != Y) ? Y : X  -> Y
7432       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7433         return ReplaceInstUsesWith(SI, TrueVal);
7434       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7435     }
7436   }
7437
7438   // See if we are selecting two values based on a comparison of the two values.
7439   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7440     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7441       // Transform (X == Y) ? X : Y  -> Y
7442       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7443         return ReplaceInstUsesWith(SI, FalseVal);
7444       // Transform (X != Y) ? X : Y  -> X
7445       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7446         return ReplaceInstUsesWith(SI, TrueVal);
7447       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7448
7449     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7450       // Transform (X == Y) ? Y : X  -> X
7451       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7452         return ReplaceInstUsesWith(SI, FalseVal);
7453       // Transform (X != Y) ? Y : X  -> Y
7454       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7455         return ReplaceInstUsesWith(SI, TrueVal);
7456       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7457     }
7458   }
7459
7460   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7461     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7462       if (TI->hasOneUse() && FI->hasOneUse()) {
7463         Instruction *AddOp = 0, *SubOp = 0;
7464
7465         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7466         if (TI->getOpcode() == FI->getOpcode())
7467           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7468             return IV;
7469
7470         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7471         // even legal for FP.
7472         if (TI->getOpcode() == Instruction::Sub &&
7473             FI->getOpcode() == Instruction::Add) {
7474           AddOp = FI; SubOp = TI;
7475         } else if (FI->getOpcode() == Instruction::Sub &&
7476                    TI->getOpcode() == Instruction::Add) {
7477           AddOp = TI; SubOp = FI;
7478         }
7479
7480         if (AddOp) {
7481           Value *OtherAddOp = 0;
7482           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7483             OtherAddOp = AddOp->getOperand(1);
7484           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7485             OtherAddOp = AddOp->getOperand(0);
7486           }
7487
7488           if (OtherAddOp) {
7489             // So at this point we know we have (Y -> OtherAddOp):
7490             //        select C, (add X, Y), (sub X, Z)
7491             Value *NegVal;  // Compute -Z
7492             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7493               NegVal = ConstantExpr::getNeg(C);
7494             } else {
7495               NegVal = InsertNewInstBefore(
7496                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7497             }
7498
7499             Value *NewTrueOp = OtherAddOp;
7500             Value *NewFalseOp = NegVal;
7501             if (AddOp != TI)
7502               std::swap(NewTrueOp, NewFalseOp);
7503             Instruction *NewSel =
7504               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7505
7506             NewSel = InsertNewInstBefore(NewSel, SI);
7507             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7508           }
7509         }
7510       }
7511
7512   // See if we can fold the select into one of our operands.
7513   if (SI.getType()->isInteger()) {
7514     // See the comment above GetSelectFoldableOperands for a description of the
7515     // transformation we are doing here.
7516     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7517       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7518           !isa<Constant>(FalseVal))
7519         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7520           unsigned OpToFold = 0;
7521           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7522             OpToFold = 1;
7523           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7524             OpToFold = 2;
7525           }
7526
7527           if (OpToFold) {
7528             Constant *C = GetSelectFoldableConstant(TVI);
7529             Instruction *NewSel =
7530               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7531             InsertNewInstBefore(NewSel, SI);
7532             NewSel->takeName(TVI);
7533             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7534               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7535             else {
7536               assert(0 && "Unknown instruction!!");
7537             }
7538           }
7539         }
7540
7541     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7542       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7543           !isa<Constant>(TrueVal))
7544         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7545           unsigned OpToFold = 0;
7546           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7547             OpToFold = 1;
7548           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7549             OpToFold = 2;
7550           }
7551
7552           if (OpToFold) {
7553             Constant *C = GetSelectFoldableConstant(FVI);
7554             Instruction *NewSel =
7555               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7556             InsertNewInstBefore(NewSel, SI);
7557             NewSel->takeName(FVI);
7558             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7559               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7560             else
7561               assert(0 && "Unknown instruction!!");
7562           }
7563         }
7564   }
7565
7566   if (BinaryOperator::isNot(CondVal)) {
7567     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7568     SI.setOperand(1, FalseVal);
7569     SI.setOperand(2, TrueVal);
7570     return &SI;
7571   }
7572
7573   return 0;
7574 }
7575
7576 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7577 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
7578 /// and it is more than the alignment of the ultimate object, see if we can
7579 /// increase the alignment of the ultimate object, making this check succeed.
7580 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7581                                            unsigned PrefAlign = 0) {
7582   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7583     unsigned Align = GV->getAlignment();
7584     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
7585       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7586
7587     // If there is a large requested alignment and we can, bump up the alignment
7588     // of the global.
7589     if (PrefAlign > Align && GV->hasInitializer()) {
7590       GV->setAlignment(PrefAlign);
7591       Align = PrefAlign;
7592     }
7593     return Align;
7594   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7595     unsigned Align = AI->getAlignment();
7596     if (Align == 0 && TD) {
7597       if (isa<AllocaInst>(AI))
7598         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7599       else if (isa<MallocInst>(AI)) {
7600         // Malloc returns maximally aligned memory.
7601         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7602         Align =
7603           std::max(Align,
7604                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7605         Align =
7606           std::max(Align,
7607                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7608       }
7609     }
7610     
7611     // If there is a requested alignment and if this is an alloca, round up.  We
7612     // don't do this for malloc, because some systems can't respect the request.
7613     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7614       AI->setAlignment(PrefAlign);
7615       Align = PrefAlign;
7616     }
7617     return Align;
7618   } else if (isa<BitCastInst>(V) ||
7619              (isa<ConstantExpr>(V) && 
7620               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7621     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7622                                       TD, PrefAlign);
7623   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7624     // If all indexes are zero, it is just the alignment of the base pointer.
7625     bool AllZeroOperands = true;
7626     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7627       if (!isa<Constant>(GEPI->getOperand(i)) ||
7628           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7629         AllZeroOperands = false;
7630         break;
7631       }
7632
7633     if (AllZeroOperands) {
7634       // Treat this like a bitcast.
7635       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7636     }
7637
7638     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7639     if (BaseAlignment == 0) return 0;
7640
7641     // Otherwise, if the base alignment is >= the alignment we expect for the
7642     // base pointer type, then we know that the resultant pointer is aligned at
7643     // least as much as its type requires.
7644     if (!TD) return 0;
7645
7646     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7647     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7648     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7649     if (Align <= BaseAlignment) {
7650       const Type *GEPTy = GEPI->getType();
7651       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7652       Align = std::min(Align, (unsigned)
7653                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7654       return Align;
7655     }
7656     return 0;
7657   }
7658   return 0;
7659 }
7660
7661
7662 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
7663 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
7664 /// the heavy lifting.
7665 ///
7666 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7667   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7668   if (!II) return visitCallSite(&CI);
7669   
7670   // Intrinsics cannot occur in an invoke, so handle them here instead of in
7671   // visitCallSite.
7672   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7673     bool Changed = false;
7674
7675     // memmove/cpy/set of zero bytes is a noop.
7676     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7677       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7678
7679       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7680         if (CI->getZExtValue() == 1) {
7681           // Replace the instruction with just byte operations.  We would
7682           // transform other cases to loads/stores, but we don't know if
7683           // alignment is sufficient.
7684         }
7685     }
7686
7687     // If we have a memmove and the source operation is a constant global,
7688     // then the source and dest pointers can't alias, so we can change this
7689     // into a call to memcpy.
7690     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7691       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7692         if (GVSrc->isConstant()) {
7693           Module *M = CI.getParent()->getParent()->getParent();
7694           const char *Name;
7695           if (CI.getCalledFunction()->getFunctionType()->getParamType(2) == 
7696               Type::Int32Ty)
7697             Name = "llvm.memcpy.i32";
7698           else
7699             Name = "llvm.memcpy.i64";
7700           Constant *MemCpy = M->getOrInsertFunction(Name,
7701                                      CI.getCalledFunction()->getFunctionType());
7702           CI.setOperand(0, MemCpy);
7703           Changed = true;
7704         }
7705     }
7706
7707     // If we can determine a pointer alignment that is bigger than currently
7708     // set, update the alignment.
7709     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7710       unsigned Alignment1 = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7711       unsigned Alignment2 = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7712       unsigned Align = std::min(Alignment1, Alignment2);
7713       if (MI->getAlignment()->getZExtValue() < Align) {
7714         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7715         Changed = true;
7716       }
7717
7718       // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7719       // load/store.
7720       ConstantInt *MemOpLength = dyn_cast<ConstantInt>(CI.getOperand(3));
7721       if (MemOpLength) {
7722         unsigned Size = MemOpLength->getZExtValue();
7723         unsigned Align = cast<ConstantInt>(CI.getOperand(4))->getZExtValue();
7724         PointerType *NewPtrTy = NULL;
7725         // Destination pointer type is always i8 *
7726         // If Size is 8 then use Int64Ty
7727         // If Size is 4 then use Int32Ty
7728         // If Size is 2 then use Int16Ty
7729         // If Size is 1 then use Int8Ty
7730         if (Size && Size <=8 && !(Size&(Size-1)))
7731           NewPtrTy = PointerType::get(IntegerType::get(Size<<3));
7732
7733         if (NewPtrTy) {
7734           Value *Src = InsertCastBefore(Instruction::BitCast, CI.getOperand(2),
7735                                         NewPtrTy, CI);
7736           Value *Dest = InsertCastBefore(Instruction::BitCast, CI.getOperand(1),
7737                                          NewPtrTy, CI);
7738           Value *L = new LoadInst(Src, "tmp", false, Align, &CI);
7739           Value *NS = new StoreInst(L, Dest, false, Align, &CI);
7740           CI.replaceAllUsesWith(NS);
7741           Changed = true;
7742           return EraseInstFromFunction(CI);
7743         }
7744       }
7745     } else if (isa<MemSetInst>(MI)) {
7746       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
7747       if (MI->getAlignment()->getZExtValue() < Alignment) {
7748         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7749         Changed = true;
7750       }
7751     }
7752           
7753     if (Changed) return II;
7754   } else {
7755     switch (II->getIntrinsicID()) {
7756     default: break;
7757     case Intrinsic::ppc_altivec_lvx:
7758     case Intrinsic::ppc_altivec_lvxl:
7759     case Intrinsic::x86_sse_loadu_ps:
7760     case Intrinsic::x86_sse2_loadu_pd:
7761     case Intrinsic::x86_sse2_loadu_dq:
7762       // Turn PPC lvx     -> load if the pointer is known aligned.
7763       // Turn X86 loadups -> load if the pointer is known aligned.
7764       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
7765         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7766                                       PointerType::get(II->getType()), CI);
7767         return new LoadInst(Ptr);
7768       }
7769       break;
7770     case Intrinsic::ppc_altivec_stvx:
7771     case Intrinsic::ppc_altivec_stvxl:
7772       // Turn stvx -> store if the pointer is known aligned.
7773       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
7774         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7775         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7776                                       OpPtrTy, CI);
7777         return new StoreInst(II->getOperand(1), Ptr);
7778       }
7779       break;
7780     case Intrinsic::x86_sse_storeu_ps:
7781     case Intrinsic::x86_sse2_storeu_pd:
7782     case Intrinsic::x86_sse2_storeu_dq:
7783     case Intrinsic::x86_sse2_storel_dq:
7784       // Turn X86 storeu -> store if the pointer is known aligned.
7785       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
7786         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7787         Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7788                                       OpPtrTy, CI);
7789         return new StoreInst(II->getOperand(2), Ptr);
7790       }
7791       break;
7792       
7793     case Intrinsic::x86_sse_cvttss2si: {
7794       // These intrinsics only demands the 0th element of its input vector.  If
7795       // we can simplify the input based on that, do so now.
7796       uint64_t UndefElts;
7797       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
7798                                                 UndefElts)) {
7799         II->setOperand(1, V);
7800         return II;
7801       }
7802       break;
7803     }
7804       
7805     case Intrinsic::ppc_altivec_vperm:
7806       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7807       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7808         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7809         
7810         // Check that all of the elements are integer constants or undefs.
7811         bool AllEltsOk = true;
7812         for (unsigned i = 0; i != 16; ++i) {
7813           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
7814               !isa<UndefValue>(Mask->getOperand(i))) {
7815             AllEltsOk = false;
7816             break;
7817           }
7818         }
7819         
7820         if (AllEltsOk) {
7821           // Cast the input vectors to byte vectors.
7822           Value *Op0 = InsertCastBefore(Instruction::BitCast, 
7823                                         II->getOperand(1), Mask->getType(), CI);
7824           Value *Op1 = InsertCastBefore(Instruction::BitCast,
7825                                         II->getOperand(2), Mask->getType(), CI);
7826           Value *Result = UndefValue::get(Op0->getType());
7827           
7828           // Only extract each element once.
7829           Value *ExtractedElts[32];
7830           memset(ExtractedElts, 0, sizeof(ExtractedElts));
7831           
7832           for (unsigned i = 0; i != 16; ++i) {
7833             if (isa<UndefValue>(Mask->getOperand(i)))
7834               continue;
7835             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7836             Idx &= 31;  // Match the hardware behavior.
7837             
7838             if (ExtractedElts[Idx] == 0) {
7839               Instruction *Elt = 
7840                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7841               InsertNewInstBefore(Elt, CI);
7842               ExtractedElts[Idx] = Elt;
7843             }
7844           
7845             // Insert this value into the result vector.
7846             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7847             InsertNewInstBefore(cast<Instruction>(Result), CI);
7848           }
7849           return CastInst::create(Instruction::BitCast, Result, CI.getType());
7850         }
7851       }
7852       break;
7853
7854     case Intrinsic::stackrestore: {
7855       // If the save is right next to the restore, remove the restore.  This can
7856       // happen when variable allocas are DCE'd.
7857       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7858         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7859           BasicBlock::iterator BI = SS;
7860           if (&*++BI == II)
7861             return EraseInstFromFunction(CI);
7862         }
7863       }
7864       
7865       // If the stack restore is in a return/unwind block and if there are no
7866       // allocas or calls between the restore and the return, nuke the restore.
7867       TerminatorInst *TI = II->getParent()->getTerminator();
7868       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7869         BasicBlock::iterator BI = II;
7870         bool CannotRemove = false;
7871         for (++BI; &*BI != TI; ++BI) {
7872           if (isa<AllocaInst>(BI) ||
7873               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7874             CannotRemove = true;
7875             break;
7876           }
7877         }
7878         if (!CannotRemove)
7879           return EraseInstFromFunction(CI);
7880       }
7881       break;
7882     }
7883     }
7884   }
7885
7886   return visitCallSite(II);
7887 }
7888
7889 // InvokeInst simplification
7890 //
7891 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7892   return visitCallSite(&II);
7893 }
7894
7895 // visitCallSite - Improvements for call and invoke instructions.
7896 //
7897 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7898   bool Changed = false;
7899
7900   // If the callee is a constexpr cast of a function, attempt to move the cast
7901   // to the arguments of the call/invoke.
7902   if (transformConstExprCastCall(CS)) return 0;
7903
7904   Value *Callee = CS.getCalledValue();
7905
7906   if (Function *CalleeF = dyn_cast<Function>(Callee))
7907     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7908       Instruction *OldCall = CS.getInstruction();
7909       // If the call and callee calling conventions don't match, this call must
7910       // be unreachable, as the call is undefined.
7911       new StoreInst(ConstantInt::getTrue(),
7912                     UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7913       if (!OldCall->use_empty())
7914         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7915       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
7916         return EraseInstFromFunction(*OldCall);
7917       return 0;
7918     }
7919
7920   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7921     // This instruction is not reachable, just remove it.  We insert a store to
7922     // undef so that we know that this code is not reachable, despite the fact
7923     // that we can't modify the CFG here.
7924     new StoreInst(ConstantInt::getTrue(),
7925                   UndefValue::get(PointerType::get(Type::Int1Ty)),
7926                   CS.getInstruction());
7927
7928     if (!CS.getInstruction()->use_empty())
7929       CS.getInstruction()->
7930         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7931
7932     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7933       // Don't break the CFG, insert a dummy cond branch.
7934       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7935                      ConstantInt::getTrue(), II);
7936     }
7937     return EraseInstFromFunction(*CS.getInstruction());
7938   }
7939
7940   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
7941     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
7942       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
7943         return transformCallThroughTrampoline(CS);
7944
7945   const PointerType *PTy = cast<PointerType>(Callee->getType());
7946   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7947   if (FTy->isVarArg()) {
7948     // See if we can optimize any arguments passed through the varargs area of
7949     // the call.
7950     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7951            E = CS.arg_end(); I != E; ++I)
7952       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7953         // If this cast does not effect the value passed through the varargs
7954         // area, we can eliminate the use of the cast.
7955         Value *Op = CI->getOperand(0);
7956         if (CI->isLosslessCast()) {
7957           *I = Op;
7958           Changed = true;
7959         }
7960       }
7961   }
7962
7963   return Changed ? CS.getInstruction() : 0;
7964 }
7965
7966 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7967 // attempt to move the cast to the arguments of the call/invoke.
7968 //
7969 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7970   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7971   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7972   if (CE->getOpcode() != Instruction::BitCast || 
7973       !isa<Function>(CE->getOperand(0)))
7974     return false;
7975   Function *Callee = cast<Function>(CE->getOperand(0));
7976   Instruction *Caller = CS.getInstruction();
7977
7978   // Okay, this is a cast from a function to a different type.  Unless doing so
7979   // would cause a type conversion of one of our arguments, change this call to
7980   // be a direct call with arguments casted to the appropriate types.
7981   //
7982   const FunctionType *FT = Callee->getFunctionType();
7983   const Type *OldRetTy = Caller->getType();
7984
7985   const FunctionType *ActualFT =
7986     cast<FunctionType>(cast<PointerType>(CE->getType())->getElementType());
7987   
7988   // If the parameter attributes don't match up, don't do the xform.  We don't
7989   // want to lose an sret attribute or something.
7990   if (FT->getParamAttrs() != ActualFT->getParamAttrs())
7991     return false;
7992   
7993   // Check to see if we are changing the return type...
7994   if (OldRetTy != FT->getReturnType()) {
7995     if (Callee->isDeclaration() && !Caller->use_empty() && 
7996         // Conversion is ok if changing from pointer to int of same size.
7997         !(isa<PointerType>(FT->getReturnType()) &&
7998           TD->getIntPtrType() == OldRetTy))
7999       return false;   // Cannot transform this return value.
8000
8001     // If the callsite is an invoke instruction, and the return value is used by
8002     // a PHI node in a successor, we cannot change the return type of the call
8003     // because there is no place to put the cast instruction (without breaking
8004     // the critical edge).  Bail out in this case.
8005     if (!Caller->use_empty())
8006       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8007         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8008              UI != E; ++UI)
8009           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8010             if (PN->getParent() == II->getNormalDest() ||
8011                 PN->getParent() == II->getUnwindDest())
8012               return false;
8013   }
8014
8015   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8016   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8017
8018   CallSite::arg_iterator AI = CS.arg_begin();
8019   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8020     const Type *ParamTy = FT->getParamType(i);
8021     const Type *ActTy = (*AI)->getType();
8022     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8023     //Some conversions are safe even if we do not have a body.
8024     //Either we can cast directly, or we can upconvert the argument
8025     bool isConvertible = ActTy == ParamTy ||
8026       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8027       (ParamTy->isInteger() && ActTy->isInteger() &&
8028        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8029       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8030        && c->getValue().isStrictlyPositive());
8031     if (Callee->isDeclaration() && !isConvertible) return false;
8032
8033     // Most other conversions can be done if we have a body, even if these
8034     // lose information, e.g. int->short.
8035     // Some conversions cannot be done at all, e.g. float to pointer.
8036     // Logic here parallels CastInst::getCastOpcode (the design there
8037     // requires legality checks like this be done before calling it).
8038     if (ParamTy->isInteger()) {
8039       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8040         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
8041           return false;
8042       }
8043       if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
8044           !isa<PointerType>(ActTy))
8045         return false;
8046     } else if (ParamTy->isFloatingPoint()) {
8047       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8048         if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
8049           return false;
8050       }
8051       if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
8052         return false;
8053     } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
8054       if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8055         if (VActTy->getBitWidth() != VParamTy->getBitWidth())
8056           return false;
8057       }
8058       if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())      
8059         return false;
8060     } else if (isa<PointerType>(ParamTy)) {
8061       if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
8062         return false;
8063     } else {
8064       return false;
8065     }
8066   }
8067
8068   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8069       Callee->isDeclaration())
8070     return false;   // Do not delete arguments unless we have a function body...
8071
8072   // Okay, we decided that this is a safe thing to do: go ahead and start
8073   // inserting cast instructions as necessary...
8074   std::vector<Value*> Args;
8075   Args.reserve(NumActualArgs);
8076
8077   AI = CS.arg_begin();
8078   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8079     const Type *ParamTy = FT->getParamType(i);
8080     if ((*AI)->getType() == ParamTy) {
8081       Args.push_back(*AI);
8082     } else {
8083       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8084           false, ParamTy, false);
8085       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8086       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8087     }
8088   }
8089
8090   // If the function takes more arguments than the call was taking, add them
8091   // now...
8092   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8093     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8094
8095   // If we are removing arguments to the function, emit an obnoxious warning...
8096   if (FT->getNumParams() < NumActualArgs)
8097     if (!FT->isVarArg()) {
8098       cerr << "WARNING: While resolving call to function '"
8099            << Callee->getName() << "' arguments were dropped!\n";
8100     } else {
8101       // Add all of the arguments in their promoted form to the arg list...
8102       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8103         const Type *PTy = getPromotedType((*AI)->getType());
8104         if (PTy != (*AI)->getType()) {
8105           // Must promote to pass through va_arg area!
8106           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8107                                                                 PTy, false);
8108           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8109           InsertNewInstBefore(Cast, *Caller);
8110           Args.push_back(Cast);
8111         } else {
8112           Args.push_back(*AI);
8113         }
8114       }
8115     }
8116
8117   if (FT->getReturnType() == Type::VoidTy)
8118     Caller->setName("");   // Void type should not have a name.
8119
8120   Instruction *NC;
8121   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8122     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8123                         Args.begin(), Args.end(), Caller->getName(), Caller);
8124     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8125   } else {
8126     NC = new CallInst(Callee, Args.begin(), Args.end(),
8127                       Caller->getName(), Caller);
8128     if (cast<CallInst>(Caller)->isTailCall())
8129       cast<CallInst>(NC)->setTailCall();
8130    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8131   }
8132
8133   // Insert a cast of the return type as necessary.
8134   Value *NV = NC;
8135   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8136     if (NV->getType() != Type::VoidTy) {
8137       const Type *CallerTy = Caller->getType();
8138       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8139                                                             CallerTy, false);
8140       NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
8141
8142       // If this is an invoke instruction, we should insert it after the first
8143       // non-phi, instruction in the normal successor block.
8144       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8145         BasicBlock::iterator I = II->getNormalDest()->begin();
8146         while (isa<PHINode>(I)) ++I;
8147         InsertNewInstBefore(NC, *I);
8148       } else {
8149         // Otherwise, it's a call, just insert cast right after the call instr
8150         InsertNewInstBefore(NC, *Caller);
8151       }
8152       AddUsersToWorkList(*Caller);
8153     } else {
8154       NV = UndefValue::get(Caller->getType());
8155     }
8156   }
8157
8158   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8159     Caller->replaceAllUsesWith(NV);
8160   Caller->eraseFromParent();
8161   RemoveFromWorkList(Caller);
8162   return true;
8163 }
8164
8165 // transformCallThroughTrampoline - Turn a call to a function created by the
8166 // init_trampoline intrinsic into a direct call to the underlying function.
8167 //
8168 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8169   Value *Callee = CS.getCalledValue();
8170   const PointerType *PTy = cast<PointerType>(Callee->getType());
8171   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8172
8173   IntrinsicInst *Tramp =
8174     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8175
8176   Function *NestF =
8177     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8178   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8179   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8180
8181   if (const ParamAttrsList *NestAttrs = NestFTy->getParamAttrs()) {
8182     unsigned NestIdx = 1;
8183     const Type *NestTy = 0;
8184     uint16_t NestAttr = 0;
8185
8186     // Look for a parameter marked with the 'nest' attribute.
8187     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8188          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8189       if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8190         // Record the parameter type and any other attributes.
8191         NestTy = *I;
8192         NestAttr = NestAttrs->getParamAttrs(NestIdx);
8193         break;
8194       }
8195
8196     if (NestTy) {
8197       Instruction *Caller = CS.getInstruction();
8198       std::vector<Value*> NewArgs;
8199       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8200
8201       // Insert the nest argument into the call argument list, which may
8202       // mean appending it.
8203       {
8204         unsigned Idx = 1;
8205         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8206         do {
8207           if (Idx == NestIdx) {
8208             // Add the chain argument.
8209             Value *NestVal = Tramp->getOperand(3);
8210             if (NestVal->getType() != NestTy)
8211               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8212             NewArgs.push_back(NestVal);
8213           }
8214
8215           if (I == E)
8216             break;
8217
8218           // Add the original argument.
8219           NewArgs.push_back(*I);
8220
8221           ++Idx, ++I;
8222         } while (1);
8223       }
8224
8225       // The trampoline may have been bitcast to a bogus type (FTy).
8226       // Handle this by synthesizing a new function type, equal to FTy
8227       // with the chain parameter inserted.  Likewise for attributes.
8228
8229       const ParamAttrsList *Attrs = FTy->getParamAttrs();
8230       std::vector<const Type*> NewTypes;
8231       ParamAttrsVector NewAttrs;
8232       NewTypes.reserve(FTy->getNumParams()+1);
8233
8234       // Add any function result attributes.
8235       uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8236       if (Attr)
8237         NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8238
8239       // Insert the chain's type into the list of parameter types, which may
8240       // mean appending it.  Likewise for the chain's attributes.
8241       {
8242         unsigned Idx = 1;
8243         FunctionType::param_iterator I = FTy->param_begin(),
8244           E = FTy->param_end();
8245
8246         do {
8247           if (Idx == NestIdx) {
8248             // Add the chain's type and attributes.
8249             NewTypes.push_back(NestTy);
8250             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8251           }
8252
8253           if (I == E)
8254             break;
8255
8256           // Add the original type and attributes.
8257           NewTypes.push_back(*I);
8258           Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8259           if (Attr)
8260             NewAttrs.push_back
8261               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8262
8263           ++Idx, ++I;
8264         } while (1);
8265       }
8266
8267       // Replace the trampoline call with a direct call.  Let the generic
8268       // code sort out any function type mismatches.
8269       FunctionType *NewFTy =
8270         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg(),
8271                           ParamAttrsList::get(NewAttrs));
8272       Constant *NewCallee = NestF->getType() == PointerType::get(NewFTy) ?
8273         NestF : ConstantExpr::getBitCast(NestF, PointerType::get(NewFTy));
8274
8275       Instruction *NewCaller;
8276       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8277         NewCaller = new InvokeInst(NewCallee,
8278                                    II->getNormalDest(), II->getUnwindDest(),
8279                                    NewArgs.begin(), NewArgs.end(),
8280                                    Caller->getName(), Caller);
8281         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8282       } else {
8283         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8284                                  Caller->getName(), Caller);
8285         if (cast<CallInst>(Caller)->isTailCall())
8286           cast<CallInst>(NewCaller)->setTailCall();
8287         cast<CallInst>(NewCaller)->
8288           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8289       }
8290       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8291         Caller->replaceAllUsesWith(NewCaller);
8292       Caller->eraseFromParent();
8293       RemoveFromWorkList(Caller);
8294       return 0;
8295     }
8296   }
8297
8298   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8299   // parameter, there is no need to adjust the argument list.  Let the generic
8300   // code sort out any function type mismatches.
8301   Constant *NewCallee =
8302     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8303   CS.setCalledFunction(NewCallee);
8304   return CS.getInstruction();
8305 }
8306
8307 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8308 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8309 /// and a single binop.
8310 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8311   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8312   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8313          isa<CmpInst>(FirstInst));
8314   unsigned Opc = FirstInst->getOpcode();
8315   Value *LHSVal = FirstInst->getOperand(0);
8316   Value *RHSVal = FirstInst->getOperand(1);
8317     
8318   const Type *LHSType = LHSVal->getType();
8319   const Type *RHSType = RHSVal->getType();
8320   
8321   // Scan to see if all operands are the same opcode, all have one use, and all
8322   // kill their operands (i.e. the operands have one use).
8323   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8324     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8325     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8326         // Verify type of the LHS matches so we don't fold cmp's of different
8327         // types or GEP's with different index types.
8328         I->getOperand(0)->getType() != LHSType ||
8329         I->getOperand(1)->getType() != RHSType)
8330       return 0;
8331
8332     // If they are CmpInst instructions, check their predicates
8333     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8334       if (cast<CmpInst>(I)->getPredicate() !=
8335           cast<CmpInst>(FirstInst)->getPredicate())
8336         return 0;
8337     
8338     // Keep track of which operand needs a phi node.
8339     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8340     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8341   }
8342   
8343   // Otherwise, this is safe to transform, determine if it is profitable.
8344
8345   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8346   // Indexes are often folded into load/store instructions, so we don't want to
8347   // hide them behind a phi.
8348   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8349     return 0;
8350   
8351   Value *InLHS = FirstInst->getOperand(0);
8352   Value *InRHS = FirstInst->getOperand(1);
8353   PHINode *NewLHS = 0, *NewRHS = 0;
8354   if (LHSVal == 0) {
8355     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8356     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8357     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8358     InsertNewInstBefore(NewLHS, PN);
8359     LHSVal = NewLHS;
8360   }
8361   
8362   if (RHSVal == 0) {
8363     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8364     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8365     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8366     InsertNewInstBefore(NewRHS, PN);
8367     RHSVal = NewRHS;
8368   }
8369   
8370   // Add all operands to the new PHIs.
8371   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8372     if (NewLHS) {
8373       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8374       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8375     }
8376     if (NewRHS) {
8377       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8378       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8379     }
8380   }
8381     
8382   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8383     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8384   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8385     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8386                            RHSVal);
8387   else {
8388     assert(isa<GetElementPtrInst>(FirstInst));
8389     return new GetElementPtrInst(LHSVal, RHSVal);
8390   }
8391 }
8392
8393 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8394 /// of the block that defines it.  This means that it must be obvious the value
8395 /// of the load is not changed from the point of the load to the end of the
8396 /// block it is in.
8397 ///
8398 /// Finally, it is safe, but not profitable, to sink a load targetting a
8399 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8400 /// to a register.
8401 static bool isSafeToSinkLoad(LoadInst *L) {
8402   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8403   
8404   for (++BBI; BBI != E; ++BBI)
8405     if (BBI->mayWriteToMemory())
8406       return false;
8407   
8408   // Check for non-address taken alloca.  If not address-taken already, it isn't
8409   // profitable to do this xform.
8410   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8411     bool isAddressTaken = false;
8412     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8413          UI != E; ++UI) {
8414       if (isa<LoadInst>(UI)) continue;
8415       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8416         // If storing TO the alloca, then the address isn't taken.
8417         if (SI->getOperand(1) == AI) continue;
8418       }
8419       isAddressTaken = true;
8420       break;
8421     }
8422     
8423     if (!isAddressTaken)
8424       return false;
8425   }
8426   
8427   return true;
8428 }
8429
8430
8431 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8432 // operator and they all are only used by the PHI, PHI together their
8433 // inputs, and do the operation once, to the result of the PHI.
8434 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8435   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8436
8437   // Scan the instruction, looking for input operations that can be folded away.
8438   // If all input operands to the phi are the same instruction (e.g. a cast from
8439   // the same type or "+42") we can pull the operation through the PHI, reducing
8440   // code size and simplifying code.
8441   Constant *ConstantOp = 0;
8442   const Type *CastSrcTy = 0;
8443   bool isVolatile = false;
8444   if (isa<CastInst>(FirstInst)) {
8445     CastSrcTy = FirstInst->getOperand(0)->getType();
8446   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8447     // Can fold binop, compare or shift here if the RHS is a constant, 
8448     // otherwise call FoldPHIArgBinOpIntoPHI.
8449     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8450     if (ConstantOp == 0)
8451       return FoldPHIArgBinOpIntoPHI(PN);
8452   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8453     isVolatile = LI->isVolatile();
8454     // We can't sink the load if the loaded value could be modified between the
8455     // load and the PHI.
8456     if (LI->getParent() != PN.getIncomingBlock(0) ||
8457         !isSafeToSinkLoad(LI))
8458       return 0;
8459   } else if (isa<GetElementPtrInst>(FirstInst)) {
8460     if (FirstInst->getNumOperands() == 2)
8461       return FoldPHIArgBinOpIntoPHI(PN);
8462     // Can't handle general GEPs yet.
8463     return 0;
8464   } else {
8465     return 0;  // Cannot fold this operation.
8466   }
8467
8468   // Check to see if all arguments are the same operation.
8469   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8470     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8471     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8472     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8473       return 0;
8474     if (CastSrcTy) {
8475       if (I->getOperand(0)->getType() != CastSrcTy)
8476         return 0;  // Cast operation must match.
8477     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8478       // We can't sink the load if the loaded value could be modified between 
8479       // the load and the PHI.
8480       if (LI->isVolatile() != isVolatile ||
8481           LI->getParent() != PN.getIncomingBlock(i) ||
8482           !isSafeToSinkLoad(LI))
8483         return 0;
8484     } else if (I->getOperand(1) != ConstantOp) {
8485       return 0;
8486     }
8487   }
8488
8489   // Okay, they are all the same operation.  Create a new PHI node of the
8490   // correct type, and PHI together all of the LHS's of the instructions.
8491   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8492                                PN.getName()+".in");
8493   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8494
8495   Value *InVal = FirstInst->getOperand(0);
8496   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8497
8498   // Add all operands to the new PHI.
8499   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8500     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8501     if (NewInVal != InVal)
8502       InVal = 0;
8503     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8504   }
8505
8506   Value *PhiVal;
8507   if (InVal) {
8508     // The new PHI unions all of the same values together.  This is really
8509     // common, so we handle it intelligently here for compile-time speed.
8510     PhiVal = InVal;
8511     delete NewPN;
8512   } else {
8513     InsertNewInstBefore(NewPN, PN);
8514     PhiVal = NewPN;
8515   }
8516
8517   // Insert and return the new operation.
8518   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8519     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8520   else if (isa<LoadInst>(FirstInst))
8521     return new LoadInst(PhiVal, "", isVolatile);
8522   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8523     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8524   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8525     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8526                            PhiVal, ConstantOp);
8527   else
8528     assert(0 && "Unknown operation");
8529   return 0;
8530 }
8531
8532 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8533 /// that is dead.
8534 static bool DeadPHICycle(PHINode *PN,
8535                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8536   if (PN->use_empty()) return true;
8537   if (!PN->hasOneUse()) return false;
8538
8539   // Remember this node, and if we find the cycle, return.
8540   if (!PotentiallyDeadPHIs.insert(PN))
8541     return true;
8542   
8543   // Don't scan crazily complex things.
8544   if (PotentiallyDeadPHIs.size() == 16)
8545     return false;
8546
8547   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8548     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8549
8550   return false;
8551 }
8552
8553 /// PHIsEqualValue - Return true if this phi node is always equal to
8554 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
8555 ///   z = some value; x = phi (y, z); y = phi (x, z)
8556 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
8557                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8558   // See if we already saw this PHI node.
8559   if (!ValueEqualPHIs.insert(PN))
8560     return true;
8561   
8562   // Don't scan crazily complex things.
8563   if (ValueEqualPHIs.size() == 16)
8564     return false;
8565  
8566   // Scan the operands to see if they are either phi nodes or are equal to
8567   // the value.
8568   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8569     Value *Op = PN->getIncomingValue(i);
8570     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8571       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8572         return false;
8573     } else if (Op != NonPhiInVal)
8574       return false;
8575   }
8576   
8577   return true;
8578 }
8579
8580
8581 // PHINode simplification
8582 //
8583 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8584   // If LCSSA is around, don't mess with Phi nodes
8585   if (MustPreserveLCSSA) return 0;
8586   
8587   if (Value *V = PN.hasConstantValue())
8588     return ReplaceInstUsesWith(PN, V);
8589
8590   // If all PHI operands are the same operation, pull them through the PHI,
8591   // reducing code size.
8592   if (isa<Instruction>(PN.getIncomingValue(0)) &&
8593       PN.getIncomingValue(0)->hasOneUse())
8594     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8595       return Result;
8596
8597   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
8598   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8599   // PHI)... break the cycle.
8600   if (PN.hasOneUse()) {
8601     Instruction *PHIUser = cast<Instruction>(PN.use_back());
8602     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8603       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8604       PotentiallyDeadPHIs.insert(&PN);
8605       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8606         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8607     }
8608    
8609     // If this phi has a single use, and if that use just computes a value for
8610     // the next iteration of a loop, delete the phi.  This occurs with unused
8611     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
8612     // common case here is good because the only other things that catch this
8613     // are induction variable analysis (sometimes) and ADCE, which is only run
8614     // late.
8615     if (PHIUser->hasOneUse() &&
8616         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8617         PHIUser->use_back() == &PN) {
8618       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8619     }
8620   }
8621
8622   // We sometimes end up with phi cycles that non-obviously end up being the
8623   // same value, for example:
8624   //   z = some value; x = phi (y, z); y = phi (x, z)
8625   // where the phi nodes don't necessarily need to be in the same block.  Do a
8626   // quick check to see if the PHI node only contains a single non-phi value, if
8627   // so, scan to see if the phi cycle is actually equal to that value.
8628   {
8629     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8630     // Scan for the first non-phi operand.
8631     while (InValNo != NumOperandVals && 
8632            isa<PHINode>(PN.getIncomingValue(InValNo)))
8633       ++InValNo;
8634
8635     if (InValNo != NumOperandVals) {
8636       Value *NonPhiInVal = PN.getOperand(InValNo);
8637       
8638       // Scan the rest of the operands to see if there are any conflicts, if so
8639       // there is no need to recursively scan other phis.
8640       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8641         Value *OpVal = PN.getIncomingValue(InValNo);
8642         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8643           break;
8644       }
8645       
8646       // If we scanned over all operands, then we have one unique value plus
8647       // phi values.  Scan PHI nodes to see if they all merge in each other or
8648       // the value.
8649       if (InValNo == NumOperandVals) {
8650         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8651         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8652           return ReplaceInstUsesWith(PN, NonPhiInVal);
8653       }
8654     }
8655   }
8656   return 0;
8657 }
8658
8659 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8660                                    Instruction *InsertPoint,
8661                                    InstCombiner *IC) {
8662   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8663   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8664   // We must cast correctly to the pointer type. Ensure that we
8665   // sign extend the integer value if it is smaller as this is
8666   // used for address computation.
8667   Instruction::CastOps opcode = 
8668      (VTySize < PtrSize ? Instruction::SExt :
8669       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8670   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8671 }
8672
8673
8674 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8675   Value *PtrOp = GEP.getOperand(0);
8676   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
8677   // If so, eliminate the noop.
8678   if (GEP.getNumOperands() == 1)
8679     return ReplaceInstUsesWith(GEP, PtrOp);
8680
8681   if (isa<UndefValue>(GEP.getOperand(0)))
8682     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8683
8684   bool HasZeroPointerIndex = false;
8685   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8686     HasZeroPointerIndex = C->isNullValue();
8687
8688   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8689     return ReplaceInstUsesWith(GEP, PtrOp);
8690
8691   // Eliminate unneeded casts for indices.
8692   bool MadeChange = false;
8693   
8694   gep_type_iterator GTI = gep_type_begin(GEP);
8695   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8696     if (isa<SequentialType>(*GTI)) {
8697       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8698         if (CI->getOpcode() == Instruction::ZExt ||
8699             CI->getOpcode() == Instruction::SExt) {
8700           const Type *SrcTy = CI->getOperand(0)->getType();
8701           // We can eliminate a cast from i32 to i64 iff the target 
8702           // is a 32-bit pointer target.
8703           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8704             MadeChange = true;
8705             GEP.setOperand(i, CI->getOperand(0));
8706           }
8707         }
8708       }
8709       // If we are using a wider index than needed for this platform, shrink it
8710       // to what we need.  If the incoming value needs a cast instruction,
8711       // insert it.  This explicit cast can make subsequent optimizations more
8712       // obvious.
8713       Value *Op = GEP.getOperand(i);
8714       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
8715         if (Constant *C = dyn_cast<Constant>(Op)) {
8716           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8717           MadeChange = true;
8718         } else {
8719           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8720                                 GEP);
8721           GEP.setOperand(i, Op);
8722           MadeChange = true;
8723         }
8724     }
8725   }
8726   if (MadeChange) return &GEP;
8727
8728   // If this GEP instruction doesn't move the pointer, and if the input operand
8729   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8730   // real input to the dest type.
8731   if (GEP.hasAllZeroIndices()) {
8732     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
8733       // If the bitcast is of an allocation, and the allocation will be
8734       // converted to match the type of the cast, don't touch this.
8735       if (isa<AllocationInst>(BCI->getOperand(0))) {
8736         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
8737         if (Instruction *I = visitBitCast(*BCI)) {
8738           if (I != BCI) {
8739             I->takeName(BCI);
8740             BCI->getParent()->getInstList().insert(BCI, I);
8741             ReplaceInstUsesWith(*BCI, I);
8742           }
8743           return &GEP;
8744         }
8745       }
8746       return new BitCastInst(BCI->getOperand(0), GEP.getType());
8747     }
8748   }
8749   
8750   // Combine Indices - If the source pointer to this getelementptr instruction
8751   // is a getelementptr instruction, combine the indices of the two
8752   // getelementptr instructions into a single instruction.
8753   //
8754   SmallVector<Value*, 8> SrcGEPOperands;
8755   if (User *Src = dyn_castGetElementPtr(PtrOp))
8756     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8757
8758   if (!SrcGEPOperands.empty()) {
8759     // Note that if our source is a gep chain itself that we wait for that
8760     // chain to be resolved before we perform this transformation.  This
8761     // avoids us creating a TON of code in some cases.
8762     //
8763     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8764         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8765       return 0;   // Wait until our source is folded to completion.
8766
8767     SmallVector<Value*, 8> Indices;
8768
8769     // Find out whether the last index in the source GEP is a sequential idx.
8770     bool EndsWithSequential = false;
8771     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8772            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8773       EndsWithSequential = !isa<StructType>(*I);
8774
8775     // Can we combine the two pointer arithmetics offsets?
8776     if (EndsWithSequential) {
8777       // Replace: gep (gep %P, long B), long A, ...
8778       // With:    T = long A+B; gep %P, T, ...
8779       //
8780       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8781       if (SO1 == Constant::getNullValue(SO1->getType())) {
8782         Sum = GO1;
8783       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8784         Sum = SO1;
8785       } else {
8786         // If they aren't the same type, convert both to an integer of the
8787         // target's pointer size.
8788         if (SO1->getType() != GO1->getType()) {
8789           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8790             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8791           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8792             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8793           } else {
8794             unsigned PS = TD->getPointerSizeInBits();
8795             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
8796               // Convert GO1 to SO1's type.
8797               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8798
8799             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
8800               // Convert SO1 to GO1's type.
8801               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8802             } else {
8803               const Type *PT = TD->getIntPtrType();
8804               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8805               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8806             }
8807           }
8808         }
8809         if (isa<Constant>(SO1) && isa<Constant>(GO1))
8810           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8811         else {
8812           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8813           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8814         }
8815       }
8816
8817       // Recycle the GEP we already have if possible.
8818       if (SrcGEPOperands.size() == 2) {
8819         GEP.setOperand(0, SrcGEPOperands[0]);
8820         GEP.setOperand(1, Sum);
8821         return &GEP;
8822       } else {
8823         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8824                        SrcGEPOperands.end()-1);
8825         Indices.push_back(Sum);
8826         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8827       }
8828     } else if (isa<Constant>(*GEP.idx_begin()) &&
8829                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8830                SrcGEPOperands.size() != 1) {
8831       // Otherwise we can do the fold if the first index of the GEP is a zero
8832       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8833                      SrcGEPOperands.end());
8834       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8835     }
8836
8837     if (!Indices.empty())
8838       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
8839                                    Indices.end(), GEP.getName());
8840
8841   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8842     // GEP of global variable.  If all of the indices for this GEP are
8843     // constants, we can promote this to a constexpr instead of an instruction.
8844
8845     // Scan for nonconstants...
8846     SmallVector<Constant*, 8> Indices;
8847     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8848     for (; I != E && isa<Constant>(*I); ++I)
8849       Indices.push_back(cast<Constant>(*I));
8850
8851     if (I == E) {  // If they are all constants...
8852       Constant *CE = ConstantExpr::getGetElementPtr(GV,
8853                                                     &Indices[0],Indices.size());
8854
8855       // Replace all uses of the GEP with the new constexpr...
8856       return ReplaceInstUsesWith(GEP, CE);
8857     }
8858   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
8859     if (!isa<PointerType>(X->getType())) {
8860       // Not interesting.  Source pointer must be a cast from pointer.
8861     } else if (HasZeroPointerIndex) {
8862       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8863       // into     : GEP [10 x ubyte]* X, long 0, ...
8864       //
8865       // This occurs when the program declares an array extern like "int X[];"
8866       //
8867       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8868       const PointerType *XTy = cast<PointerType>(X->getType());
8869       if (const ArrayType *XATy =
8870           dyn_cast<ArrayType>(XTy->getElementType()))
8871         if (const ArrayType *CATy =
8872             dyn_cast<ArrayType>(CPTy->getElementType()))
8873           if (CATy->getElementType() == XATy->getElementType()) {
8874             // At this point, we know that the cast source type is a pointer
8875             // to an array of the same type as the destination pointer
8876             // array.  Because the array type is never stepped over (there
8877             // is a leading zero) we can fold the cast into this GEP.
8878             GEP.setOperand(0, X);
8879             return &GEP;
8880           }
8881     } else if (GEP.getNumOperands() == 2) {
8882       // Transform things like:
8883       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8884       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8885       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8886       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8887       if (isa<ArrayType>(SrcElTy) &&
8888           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8889           TD->getABITypeSize(ResElTy)) {
8890         Value *Idx[2];
8891         Idx[0] = Constant::getNullValue(Type::Int32Ty);
8892         Idx[1] = GEP.getOperand(1);
8893         Value *V = InsertNewInstBefore(
8894                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
8895         // V and GEP are both pointer types --> BitCast
8896         return new BitCastInst(V, GEP.getType());
8897       }
8898       
8899       // Transform things like:
8900       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8901       //   (where tmp = 8*tmp2) into:
8902       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8903       
8904       if (isa<ArrayType>(SrcElTy) &&
8905           (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8906         uint64_t ArrayEltSize =
8907             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8908         
8909         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
8910         // allow either a mul, shift, or constant here.
8911         Value *NewIdx = 0;
8912         ConstantInt *Scale = 0;
8913         if (ArrayEltSize == 1) {
8914           NewIdx = GEP.getOperand(1);
8915           Scale = ConstantInt::get(NewIdx->getType(), 1);
8916         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8917           NewIdx = ConstantInt::get(CI->getType(), 1);
8918           Scale = CI;
8919         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8920           if (Inst->getOpcode() == Instruction::Shl &&
8921               isa<ConstantInt>(Inst->getOperand(1))) {
8922             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8923             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8924             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
8925             NewIdx = Inst->getOperand(0);
8926           } else if (Inst->getOpcode() == Instruction::Mul &&
8927                      isa<ConstantInt>(Inst->getOperand(1))) {
8928             Scale = cast<ConstantInt>(Inst->getOperand(1));
8929             NewIdx = Inst->getOperand(0);
8930           }
8931         }
8932
8933         // If the index will be to exactly the right offset with the scale taken
8934         // out, perform the transformation.
8935         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8936           if (isa<ConstantInt>(Scale))
8937             Scale = ConstantInt::get(Scale->getType(),
8938                                       Scale->getZExtValue() / ArrayEltSize);
8939           if (Scale->getZExtValue() != 1) {
8940             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8941                                                        true /*SExt*/);
8942             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8943             NewIdx = InsertNewInstBefore(Sc, GEP);
8944           }
8945
8946           // Insert the new GEP instruction.
8947           Value *Idx[2];
8948           Idx[0] = Constant::getNullValue(Type::Int32Ty);
8949           Idx[1] = NewIdx;
8950           Instruction *NewGEP =
8951             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
8952           NewGEP = InsertNewInstBefore(NewGEP, GEP);
8953           // The NewGEP must be pointer typed, so must the old one -> BitCast
8954           return new BitCastInst(NewGEP, GEP.getType());
8955         }
8956       }
8957     }
8958   }
8959
8960   return 0;
8961 }
8962
8963 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8964   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8965   if (AI.isArrayAllocation())    // Check C != 1
8966     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8967       const Type *NewTy = 
8968         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8969       AllocationInst *New = 0;
8970
8971       // Create and insert the replacement instruction...
8972       if (isa<MallocInst>(AI))
8973         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8974       else {
8975         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8976         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8977       }
8978
8979       InsertNewInstBefore(New, AI);
8980
8981       // Scan to the end of the allocation instructions, to skip over a block of
8982       // allocas if possible...
8983       //
8984       BasicBlock::iterator It = New;
8985       while (isa<AllocationInst>(*It)) ++It;
8986
8987       // Now that I is pointing to the first non-allocation-inst in the block,
8988       // insert our getelementptr instruction...
8989       //
8990       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8991       Value *Idx[2];
8992       Idx[0] = NullIdx;
8993       Idx[1] = NullIdx;
8994       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
8995                                        New->getName()+".sub", It);
8996
8997       // Now make everything use the getelementptr instead of the original
8998       // allocation.
8999       return ReplaceInstUsesWith(AI, V);
9000     } else if (isa<UndefValue>(AI.getArraySize())) {
9001       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9002     }
9003
9004   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9005   // Note that we only do this for alloca's, because malloc should allocate and
9006   // return a unique pointer, even for a zero byte allocation.
9007   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9008       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9009     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9010
9011   return 0;
9012 }
9013
9014 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9015   Value *Op = FI.getOperand(0);
9016
9017   // free undef -> unreachable.
9018   if (isa<UndefValue>(Op)) {
9019     // Insert a new store to null because we cannot modify the CFG here.
9020     new StoreInst(ConstantInt::getTrue(),
9021                   UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
9022     return EraseInstFromFunction(FI);
9023   }
9024   
9025   // If we have 'free null' delete the instruction.  This can happen in stl code
9026   // when lots of inlining happens.
9027   if (isa<ConstantPointerNull>(Op))
9028     return EraseInstFromFunction(FI);
9029   
9030   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9031   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9032     FI.setOperand(0, CI->getOperand(0));
9033     return &FI;
9034   }
9035   
9036   // Change free (gep X, 0,0,0,0) into free(X)
9037   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9038     if (GEPI->hasAllZeroIndices()) {
9039       AddToWorkList(GEPI);
9040       FI.setOperand(0, GEPI->getOperand(0));
9041       return &FI;
9042     }
9043   }
9044   
9045   // Change free(malloc) into nothing, if the malloc has a single use.
9046   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9047     if (MI->hasOneUse()) {
9048       EraseInstFromFunction(FI);
9049       return EraseInstFromFunction(*MI);
9050     }
9051
9052   return 0;
9053 }
9054
9055
9056 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9057 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9058                                         const TargetData *TD) {
9059   User *CI = cast<User>(LI.getOperand(0));
9060   Value *CastOp = CI->getOperand(0);
9061
9062   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9063     // Instead of loading constant c string, use corresponding integer value
9064     // directly if string length is small enough.
9065     const std::string &Str = CE->getOperand(0)->getStringValue();
9066     if (!Str.empty()) {
9067       unsigned len = Str.length();
9068       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9069       unsigned numBits = Ty->getPrimitiveSizeInBits();
9070       // Replace LI with immediate integer store.
9071       if ((numBits >> 3) == len + 1) {
9072         APInt StrVal(numBits, 0);
9073         APInt SingleChar(numBits, 0);
9074         if (TD->isLittleEndian()) {
9075           for (signed i = len-1; i >= 0; i--) {
9076             SingleChar = (uint64_t) Str[i];
9077             StrVal = (StrVal << 8) | SingleChar;
9078           }
9079         } else {
9080           for (unsigned i = 0; i < len; i++) {
9081             SingleChar = (uint64_t) Str[i];
9082                 StrVal = (StrVal << 8) | SingleChar;
9083           }
9084           // Append NULL at the end.
9085           SingleChar = 0;
9086           StrVal = (StrVal << 8) | SingleChar;
9087         }
9088         Value *NL = ConstantInt::get(StrVal);
9089         return IC.ReplaceInstUsesWith(LI, NL);
9090       }
9091     }
9092   }
9093
9094   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9095   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9096     const Type *SrcPTy = SrcTy->getElementType();
9097
9098     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9099          isa<VectorType>(DestPTy)) {
9100       // If the source is an array, the code below will not succeed.  Check to
9101       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9102       // constants.
9103       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9104         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9105           if (ASrcTy->getNumElements() != 0) {
9106             Value *Idxs[2];
9107             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9108             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9109             SrcTy = cast<PointerType>(CastOp->getType());
9110             SrcPTy = SrcTy->getElementType();
9111           }
9112
9113       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9114             isa<VectorType>(SrcPTy)) &&
9115           // Do not allow turning this into a load of an integer, which is then
9116           // casted to a pointer, this pessimizes pointer analysis a lot.
9117           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9118           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9119                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9120
9121         // Okay, we are casting from one integer or pointer type to another of
9122         // the same size.  Instead of casting the pointer before the load, cast
9123         // the result of the loaded value.
9124         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9125                                                              CI->getName(),
9126                                                          LI.isVolatile()),LI);
9127         // Now cast the result of the load.
9128         return new BitCastInst(NewLoad, LI.getType());
9129       }
9130     }
9131   }
9132   return 0;
9133 }
9134
9135 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9136 /// from this value cannot trap.  If it is not obviously safe to load from the
9137 /// specified pointer, we do a quick local scan of the basic block containing
9138 /// ScanFrom, to determine if the address is already accessed.
9139 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9140   // If it is an alloca it is always safe to load from.
9141   if (isa<AllocaInst>(V)) return true;
9142
9143   // If it is a global variable it is mostly safe to load from.
9144   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9145     // Don't try to evaluate aliases.  External weak GV can be null.
9146     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9147
9148   // Otherwise, be a little bit agressive by scanning the local block where we
9149   // want to check to see if the pointer is already being loaded or stored
9150   // from/to.  If so, the previous load or store would have already trapped,
9151   // so there is no harm doing an extra load (also, CSE will later eliminate
9152   // the load entirely).
9153   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9154
9155   while (BBI != E) {
9156     --BBI;
9157
9158     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9159       if (LI->getOperand(0) == V) return true;
9160     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9161       if (SI->getOperand(1) == V) return true;
9162
9163   }
9164   return false;
9165 }
9166
9167 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9168 /// until we find the underlying object a pointer is referring to or something
9169 /// we don't understand.  Note that the returned pointer may be offset from the
9170 /// input, because we ignore GEP indices.
9171 static Value *GetUnderlyingObject(Value *Ptr) {
9172   while (1) {
9173     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9174       if (CE->getOpcode() == Instruction::BitCast ||
9175           CE->getOpcode() == Instruction::GetElementPtr)
9176         Ptr = CE->getOperand(0);
9177       else
9178         return Ptr;
9179     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9180       Ptr = BCI->getOperand(0);
9181     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9182       Ptr = GEP->getOperand(0);
9183     } else {
9184       return Ptr;
9185     }
9186   }
9187 }
9188
9189 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9190   Value *Op = LI.getOperand(0);
9191
9192   // Attempt to improve the alignment.
9193   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9194   if (KnownAlign > LI.getAlignment())
9195     LI.setAlignment(KnownAlign);
9196
9197   // load (cast X) --> cast (load X) iff safe
9198   if (isa<CastInst>(Op))
9199     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9200       return Res;
9201
9202   // None of the following transforms are legal for volatile loads.
9203   if (LI.isVolatile()) return 0;
9204   
9205   if (&LI.getParent()->front() != &LI) {
9206     BasicBlock::iterator BBI = &LI; --BBI;
9207     // If the instruction immediately before this is a store to the same
9208     // address, do a simple form of store->load forwarding.
9209     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9210       if (SI->getOperand(1) == LI.getOperand(0))
9211         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9212     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9213       if (LIB->getOperand(0) == LI.getOperand(0))
9214         return ReplaceInstUsesWith(LI, LIB);
9215   }
9216
9217   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
9218     if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
9219       // Insert a new store to null instruction before the load to indicate
9220       // that this code is not reachable.  We do this instead of inserting
9221       // an unreachable instruction directly because we cannot modify the
9222       // CFG.
9223       new StoreInst(UndefValue::get(LI.getType()),
9224                     Constant::getNullValue(Op->getType()), &LI);
9225       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9226     }
9227
9228   if (Constant *C = dyn_cast<Constant>(Op)) {
9229     // load null/undef -> undef
9230     if ((C->isNullValue() || isa<UndefValue>(C))) {
9231       // Insert a new store to null instruction before the load to indicate that
9232       // this code is not reachable.  We do this instead of inserting an
9233       // unreachable instruction directly because we cannot modify the CFG.
9234       new StoreInst(UndefValue::get(LI.getType()),
9235                     Constant::getNullValue(Op->getType()), &LI);
9236       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9237     }
9238
9239     // Instcombine load (constant global) into the value loaded.
9240     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9241       if (GV->isConstant() && !GV->isDeclaration())
9242         return ReplaceInstUsesWith(LI, GV->getInitializer());
9243
9244     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9245     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9246       if (CE->getOpcode() == Instruction::GetElementPtr) {
9247         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9248           if (GV->isConstant() && !GV->isDeclaration())
9249             if (Constant *V = 
9250                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9251               return ReplaceInstUsesWith(LI, V);
9252         if (CE->getOperand(0)->isNullValue()) {
9253           // Insert a new store to null instruction before the load to indicate
9254           // that this code is not reachable.  We do this instead of inserting
9255           // an unreachable instruction directly because we cannot modify the
9256           // CFG.
9257           new StoreInst(UndefValue::get(LI.getType()),
9258                         Constant::getNullValue(Op->getType()), &LI);
9259           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9260         }
9261
9262       } else if (CE->isCast()) {
9263         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9264           return Res;
9265       }
9266   }
9267     
9268   // If this load comes from anywhere in a constant global, and if the global
9269   // is all undef or zero, we know what it loads.
9270   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9271     if (GV->isConstant() && GV->hasInitializer()) {
9272       if (GV->getInitializer()->isNullValue())
9273         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9274       else if (isa<UndefValue>(GV->getInitializer()))
9275         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9276     }
9277   }
9278
9279   if (Op->hasOneUse()) {
9280     // Change select and PHI nodes to select values instead of addresses: this
9281     // helps alias analysis out a lot, allows many others simplifications, and
9282     // exposes redundancy in the code.
9283     //
9284     // Note that we cannot do the transformation unless we know that the
9285     // introduced loads cannot trap!  Something like this is valid as long as
9286     // the condition is always false: load (select bool %C, int* null, int* %G),
9287     // but it would not be valid if we transformed it to load from null
9288     // unconditionally.
9289     //
9290     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9291       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9292       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9293           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9294         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9295                                      SI->getOperand(1)->getName()+".val"), LI);
9296         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9297                                      SI->getOperand(2)->getName()+".val"), LI);
9298         return new SelectInst(SI->getCondition(), V1, V2);
9299       }
9300
9301       // load (select (cond, null, P)) -> load P
9302       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9303         if (C->isNullValue()) {
9304           LI.setOperand(0, SI->getOperand(2));
9305           return &LI;
9306         }
9307
9308       // load (select (cond, P, null)) -> load P
9309       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9310         if (C->isNullValue()) {
9311           LI.setOperand(0, SI->getOperand(1));
9312           return &LI;
9313         }
9314     }
9315   }
9316   return 0;
9317 }
9318
9319 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9320 /// when possible.
9321 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9322   User *CI = cast<User>(SI.getOperand(1));
9323   Value *CastOp = CI->getOperand(0);
9324
9325   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9326   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9327     const Type *SrcPTy = SrcTy->getElementType();
9328
9329     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9330       // If the source is an array, the code below will not succeed.  Check to
9331       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9332       // constants.
9333       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9334         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9335           if (ASrcTy->getNumElements() != 0) {
9336             Value* Idxs[2];
9337             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9338             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9339             SrcTy = cast<PointerType>(CastOp->getType());
9340             SrcPTy = SrcTy->getElementType();
9341           }
9342
9343       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9344           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9345                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9346
9347         // Okay, we are casting from one integer or pointer type to another of
9348         // the same size.  Instead of casting the pointer before 
9349         // the store, cast the value to be stored.
9350         Value *NewCast;
9351         Value *SIOp0 = SI.getOperand(0);
9352         Instruction::CastOps opcode = Instruction::BitCast;
9353         const Type* CastSrcTy = SIOp0->getType();
9354         const Type* CastDstTy = SrcPTy;
9355         if (isa<PointerType>(CastDstTy)) {
9356           if (CastSrcTy->isInteger())
9357             opcode = Instruction::IntToPtr;
9358         } else if (isa<IntegerType>(CastDstTy)) {
9359           if (isa<PointerType>(SIOp0->getType()))
9360             opcode = Instruction::PtrToInt;
9361         }
9362         if (Constant *C = dyn_cast<Constant>(SIOp0))
9363           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9364         else
9365           NewCast = IC.InsertNewInstBefore(
9366             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9367             SI);
9368         return new StoreInst(NewCast, CastOp);
9369       }
9370     }
9371   }
9372   return 0;
9373 }
9374
9375 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9376   Value *Val = SI.getOperand(0);
9377   Value *Ptr = SI.getOperand(1);
9378
9379   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9380     EraseInstFromFunction(SI);
9381     ++NumCombined;
9382     return 0;
9383   }
9384   
9385   // If the RHS is an alloca with a single use, zapify the store, making the
9386   // alloca dead.
9387   if (Ptr->hasOneUse()) {
9388     if (isa<AllocaInst>(Ptr)) {
9389       EraseInstFromFunction(SI);
9390       ++NumCombined;
9391       return 0;
9392     }
9393     
9394     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9395       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9396           GEP->getOperand(0)->hasOneUse()) {
9397         EraseInstFromFunction(SI);
9398         ++NumCombined;
9399         return 0;
9400       }
9401   }
9402
9403   // Attempt to improve the alignment.
9404   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9405   if (KnownAlign > SI.getAlignment())
9406     SI.setAlignment(KnownAlign);
9407
9408   // Do really simple DSE, to catch cases where there are several consequtive
9409   // stores to the same location, separated by a few arithmetic operations. This
9410   // situation often occurs with bitfield accesses.
9411   BasicBlock::iterator BBI = &SI;
9412   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9413        --ScanInsts) {
9414     --BBI;
9415     
9416     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9417       // Prev store isn't volatile, and stores to the same location?
9418       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9419         ++NumDeadStore;
9420         ++BBI;
9421         EraseInstFromFunction(*PrevSI);
9422         continue;
9423       }
9424       break;
9425     }
9426     
9427     // If this is a load, we have to stop.  However, if the loaded value is from
9428     // the pointer we're loading and is producing the pointer we're storing,
9429     // then *this* store is dead (X = load P; store X -> P).
9430     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9431       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
9432         EraseInstFromFunction(SI);
9433         ++NumCombined;
9434         return 0;
9435       }
9436       // Otherwise, this is a load from some other location.  Stores before it
9437       // may not be dead.
9438       break;
9439     }
9440     
9441     // Don't skip over loads or things that can modify memory.
9442     if (BBI->mayWriteToMemory())
9443       break;
9444   }
9445   
9446   
9447   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9448
9449   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9450   if (isa<ConstantPointerNull>(Ptr)) {
9451     if (!isa<UndefValue>(Val)) {
9452       SI.setOperand(0, UndefValue::get(Val->getType()));
9453       if (Instruction *U = dyn_cast<Instruction>(Val))
9454         AddToWorkList(U);  // Dropped a use.
9455       ++NumCombined;
9456     }
9457     return 0;  // Do not modify these!
9458   }
9459
9460   // store undef, Ptr -> noop
9461   if (isa<UndefValue>(Val)) {
9462     EraseInstFromFunction(SI);
9463     ++NumCombined;
9464     return 0;
9465   }
9466
9467   // If the pointer destination is a cast, see if we can fold the cast into the
9468   // source instead.
9469   if (isa<CastInst>(Ptr))
9470     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9471       return Res;
9472   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9473     if (CE->isCast())
9474       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9475         return Res;
9476
9477   
9478   // If this store is the last instruction in the basic block, and if the block
9479   // ends with an unconditional branch, try to move it to the successor block.
9480   BBI = &SI; ++BBI;
9481   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9482     if (BI->isUnconditional())
9483       if (SimplifyStoreAtEndOfBlock(SI))
9484         return 0;  // xform done!
9485   
9486   return 0;
9487 }
9488
9489 /// SimplifyStoreAtEndOfBlock - Turn things like:
9490 ///   if () { *P = v1; } else { *P = v2 }
9491 /// into a phi node with a store in the successor.
9492 ///
9493 /// Simplify things like:
9494 ///   *P = v1; if () { *P = v2; }
9495 /// into a phi node with a store in the successor.
9496 ///
9497 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9498   BasicBlock *StoreBB = SI.getParent();
9499   
9500   // Check to see if the successor block has exactly two incoming edges.  If
9501   // so, see if the other predecessor contains a store to the same location.
9502   // if so, insert a PHI node (if needed) and move the stores down.
9503   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9504   
9505   // Determine whether Dest has exactly two predecessors and, if so, compute
9506   // the other predecessor.
9507   pred_iterator PI = pred_begin(DestBB);
9508   BasicBlock *OtherBB = 0;
9509   if (*PI != StoreBB)
9510     OtherBB = *PI;
9511   ++PI;
9512   if (PI == pred_end(DestBB))
9513     return false;
9514   
9515   if (*PI != StoreBB) {
9516     if (OtherBB)
9517       return false;
9518     OtherBB = *PI;
9519   }
9520   if (++PI != pred_end(DestBB))
9521     return false;
9522   
9523   
9524   // Verify that the other block ends in a branch and is not otherwise empty.
9525   BasicBlock::iterator BBI = OtherBB->getTerminator();
9526   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9527   if (!OtherBr || BBI == OtherBB->begin())
9528     return false;
9529   
9530   // If the other block ends in an unconditional branch, check for the 'if then
9531   // else' case.  there is an instruction before the branch.
9532   StoreInst *OtherStore = 0;
9533   if (OtherBr->isUnconditional()) {
9534     // If this isn't a store, or isn't a store to the same location, bail out.
9535     --BBI;
9536     OtherStore = dyn_cast<StoreInst>(BBI);
9537     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9538       return false;
9539   } else {
9540     // Otherwise, the other block ended with a conditional branch. If one of the
9541     // destinations is StoreBB, then we have the if/then case.
9542     if (OtherBr->getSuccessor(0) != StoreBB && 
9543         OtherBr->getSuccessor(1) != StoreBB)
9544       return false;
9545     
9546     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9547     // if/then triangle.  See if there is a store to the same ptr as SI that
9548     // lives in OtherBB.
9549     for (;; --BBI) {
9550       // Check to see if we find the matching store.
9551       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9552         if (OtherStore->getOperand(1) != SI.getOperand(1))
9553           return false;
9554         break;
9555       }
9556       // If we find something that may be using the stored value, or if we run
9557       // out of instructions, we can't do the xform.
9558       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9559           BBI == OtherBB->begin())
9560         return false;
9561     }
9562     
9563     // In order to eliminate the store in OtherBr, we have to
9564     // make sure nothing reads the stored value in StoreBB.
9565     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9566       // FIXME: This should really be AA driven.
9567       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9568         return false;
9569     }
9570   }
9571   
9572   // Insert a PHI node now if we need it.
9573   Value *MergedVal = OtherStore->getOperand(0);
9574   if (MergedVal != SI.getOperand(0)) {
9575     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9576     PN->reserveOperandSpace(2);
9577     PN->addIncoming(SI.getOperand(0), SI.getParent());
9578     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9579     MergedVal = InsertNewInstBefore(PN, DestBB->front());
9580   }
9581   
9582   // Advance to a place where it is safe to insert the new store and
9583   // insert it.
9584   BBI = DestBB->begin();
9585   while (isa<PHINode>(BBI)) ++BBI;
9586   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9587                                     OtherStore->isVolatile()), *BBI);
9588   
9589   // Nuke the old stores.
9590   EraseInstFromFunction(SI);
9591   EraseInstFromFunction(*OtherStore);
9592   ++NumCombined;
9593   return true;
9594 }
9595
9596
9597 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9598   // Change br (not X), label True, label False to: br X, label False, True
9599   Value *X = 0;
9600   BasicBlock *TrueDest;
9601   BasicBlock *FalseDest;
9602   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9603       !isa<Constant>(X)) {
9604     // Swap Destinations and condition...
9605     BI.setCondition(X);
9606     BI.setSuccessor(0, FalseDest);
9607     BI.setSuccessor(1, TrueDest);
9608     return &BI;
9609   }
9610
9611   // Cannonicalize fcmp_one -> fcmp_oeq
9612   FCmpInst::Predicate FPred; Value *Y;
9613   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
9614                              TrueDest, FalseDest)))
9615     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9616          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9617       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9618       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9619       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9620       NewSCC->takeName(I);
9621       // Swap Destinations and condition...
9622       BI.setCondition(NewSCC);
9623       BI.setSuccessor(0, FalseDest);
9624       BI.setSuccessor(1, TrueDest);
9625       RemoveFromWorkList(I);
9626       I->eraseFromParent();
9627       AddToWorkList(NewSCC);
9628       return &BI;
9629     }
9630
9631   // Cannonicalize icmp_ne -> icmp_eq
9632   ICmpInst::Predicate IPred;
9633   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9634                       TrueDest, FalseDest)))
9635     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
9636          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9637          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9638       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9639       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9640       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9641       NewSCC->takeName(I);
9642       // Swap Destinations and condition...
9643       BI.setCondition(NewSCC);
9644       BI.setSuccessor(0, FalseDest);
9645       BI.setSuccessor(1, TrueDest);
9646       RemoveFromWorkList(I);
9647       I->eraseFromParent();;
9648       AddToWorkList(NewSCC);
9649       return &BI;
9650     }
9651
9652   return 0;
9653 }
9654
9655 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9656   Value *Cond = SI.getCondition();
9657   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9658     if (I->getOpcode() == Instruction::Add)
9659       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9660         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9661         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9662           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9663                                                 AddRHS));
9664         SI.setOperand(0, I->getOperand(0));
9665         AddToWorkList(I);
9666         return &SI;
9667       }
9668   }
9669   return 0;
9670 }
9671
9672 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9673 /// is to leave as a vector operation.
9674 static bool CheapToScalarize(Value *V, bool isConstant) {
9675   if (isa<ConstantAggregateZero>(V)) 
9676     return true;
9677   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9678     if (isConstant) return true;
9679     // If all elts are the same, we can extract.
9680     Constant *Op0 = C->getOperand(0);
9681     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9682       if (C->getOperand(i) != Op0)
9683         return false;
9684     return true;
9685   }
9686   Instruction *I = dyn_cast<Instruction>(V);
9687   if (!I) return false;
9688   
9689   // Insert element gets simplified to the inserted element or is deleted if
9690   // this is constant idx extract element and its a constant idx insertelt.
9691   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9692       isa<ConstantInt>(I->getOperand(2)))
9693     return true;
9694   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9695     return true;
9696   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9697     if (BO->hasOneUse() &&
9698         (CheapToScalarize(BO->getOperand(0), isConstant) ||
9699          CheapToScalarize(BO->getOperand(1), isConstant)))
9700       return true;
9701   if (CmpInst *CI = dyn_cast<CmpInst>(I))
9702     if (CI->hasOneUse() &&
9703         (CheapToScalarize(CI->getOperand(0), isConstant) ||
9704          CheapToScalarize(CI->getOperand(1), isConstant)))
9705       return true;
9706   
9707   return false;
9708 }
9709
9710 /// Read and decode a shufflevector mask.
9711 ///
9712 /// It turns undef elements into values that are larger than the number of
9713 /// elements in the input.
9714 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9715   unsigned NElts = SVI->getType()->getNumElements();
9716   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9717     return std::vector<unsigned>(NElts, 0);
9718   if (isa<UndefValue>(SVI->getOperand(2)))
9719     return std::vector<unsigned>(NElts, 2*NElts);
9720
9721   std::vector<unsigned> Result;
9722   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9723   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9724     if (isa<UndefValue>(CP->getOperand(i)))
9725       Result.push_back(NElts*2);  // undef -> 8
9726     else
9727       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9728   return Result;
9729 }
9730
9731 /// FindScalarElement - Given a vector and an element number, see if the scalar
9732 /// value is already around as a register, for example if it were inserted then
9733 /// extracted from the vector.
9734 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9735   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9736   const VectorType *PTy = cast<VectorType>(V->getType());
9737   unsigned Width = PTy->getNumElements();
9738   if (EltNo >= Width)  // Out of range access.
9739     return UndefValue::get(PTy->getElementType());
9740   
9741   if (isa<UndefValue>(V))
9742     return UndefValue::get(PTy->getElementType());
9743   else if (isa<ConstantAggregateZero>(V))
9744     return Constant::getNullValue(PTy->getElementType());
9745   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9746     return CP->getOperand(EltNo);
9747   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9748     // If this is an insert to a variable element, we don't know what it is.
9749     if (!isa<ConstantInt>(III->getOperand(2))) 
9750       return 0;
9751     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9752     
9753     // If this is an insert to the element we are looking for, return the
9754     // inserted value.
9755     if (EltNo == IIElt) 
9756       return III->getOperand(1);
9757     
9758     // Otherwise, the insertelement doesn't modify the value, recurse on its
9759     // vector input.
9760     return FindScalarElement(III->getOperand(0), EltNo);
9761   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9762     unsigned InEl = getShuffleMask(SVI)[EltNo];
9763     if (InEl < Width)
9764       return FindScalarElement(SVI->getOperand(0), InEl);
9765     else if (InEl < Width*2)
9766       return FindScalarElement(SVI->getOperand(1), InEl - Width);
9767     else
9768       return UndefValue::get(PTy->getElementType());
9769   }
9770   
9771   // Otherwise, we don't know.
9772   return 0;
9773 }
9774
9775 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9776
9777   // If vector val is undef, replace extract with scalar undef.
9778   if (isa<UndefValue>(EI.getOperand(0)))
9779     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9780
9781   // If vector val is constant 0, replace extract with scalar 0.
9782   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9783     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9784   
9785   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9786     // If vector val is constant with uniform operands, replace EI
9787     // with that operand
9788     Constant *op0 = C->getOperand(0);
9789     for (unsigned i = 1; i < C->getNumOperands(); ++i)
9790       if (C->getOperand(i) != op0) {
9791         op0 = 0; 
9792         break;
9793       }
9794     if (op0)
9795       return ReplaceInstUsesWith(EI, op0);
9796   }
9797   
9798   // If extracting a specified index from the vector, see if we can recursively
9799   // find a previously computed scalar that was inserted into the vector.
9800   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9801     unsigned IndexVal = IdxC->getZExtValue();
9802     unsigned VectorWidth = 
9803       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9804       
9805     // If this is extracting an invalid index, turn this into undef, to avoid
9806     // crashing the code below.
9807     if (IndexVal >= VectorWidth)
9808       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9809     
9810     // This instruction only demands the single element from the input vector.
9811     // If the input vector has a single use, simplify it based on this use
9812     // property.
9813     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
9814       uint64_t UndefElts;
9815       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9816                                                 1 << IndexVal,
9817                                                 UndefElts)) {
9818         EI.setOperand(0, V);
9819         return &EI;
9820       }
9821     }
9822     
9823     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9824       return ReplaceInstUsesWith(EI, Elt);
9825     
9826     // If the this extractelement is directly using a bitcast from a vector of
9827     // the same number of elements, see if we can find the source element from
9828     // it.  In this case, we will end up needing to bitcast the scalars.
9829     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9830       if (const VectorType *VT = 
9831               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9832         if (VT->getNumElements() == VectorWidth)
9833           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9834             return new BitCastInst(Elt, EI.getType());
9835     }
9836   }
9837   
9838   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9839     if (I->hasOneUse()) {
9840       // Push extractelement into predecessor operation if legal and
9841       // profitable to do so
9842       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9843         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9844         if (CheapToScalarize(BO, isConstantElt)) {
9845           ExtractElementInst *newEI0 = 
9846             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9847                                    EI.getName()+".lhs");
9848           ExtractElementInst *newEI1 =
9849             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9850                                    EI.getName()+".rhs");
9851           InsertNewInstBefore(newEI0, EI);
9852           InsertNewInstBefore(newEI1, EI);
9853           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9854         }
9855       } else if (isa<LoadInst>(I)) {
9856         Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9857                                       PointerType::get(EI.getType()), EI);
9858         GetElementPtrInst *GEP = 
9859           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9860         InsertNewInstBefore(GEP, EI);
9861         return new LoadInst(GEP);
9862       }
9863     }
9864     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9865       // Extracting the inserted element?
9866       if (IE->getOperand(2) == EI.getOperand(1))
9867         return ReplaceInstUsesWith(EI, IE->getOperand(1));
9868       // If the inserted and extracted elements are constants, they must not
9869       // be the same value, extract from the pre-inserted value instead.
9870       if (isa<Constant>(IE->getOperand(2)) &&
9871           isa<Constant>(EI.getOperand(1))) {
9872         AddUsesToWorkList(EI);
9873         EI.setOperand(0, IE->getOperand(0));
9874         return &EI;
9875       }
9876     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9877       // If this is extracting an element from a shufflevector, figure out where
9878       // it came from and extract from the appropriate input element instead.
9879       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9880         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9881         Value *Src;
9882         if (SrcIdx < SVI->getType()->getNumElements())
9883           Src = SVI->getOperand(0);
9884         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9885           SrcIdx -= SVI->getType()->getNumElements();
9886           Src = SVI->getOperand(1);
9887         } else {
9888           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9889         }
9890         return new ExtractElementInst(Src, SrcIdx);
9891       }
9892     }
9893   }
9894   return 0;
9895 }
9896
9897 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9898 /// elements from either LHS or RHS, return the shuffle mask and true. 
9899 /// Otherwise, return false.
9900 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9901                                          std::vector<Constant*> &Mask) {
9902   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9903          "Invalid CollectSingleShuffleElements");
9904   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9905
9906   if (isa<UndefValue>(V)) {
9907     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9908     return true;
9909   } else if (V == LHS) {
9910     for (unsigned i = 0; i != NumElts; ++i)
9911       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9912     return true;
9913   } else if (V == RHS) {
9914     for (unsigned i = 0; i != NumElts; ++i)
9915       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9916     return true;
9917   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9918     // If this is an insert of an extract from some other vector, include it.
9919     Value *VecOp    = IEI->getOperand(0);
9920     Value *ScalarOp = IEI->getOperand(1);
9921     Value *IdxOp    = IEI->getOperand(2);
9922     
9923     if (!isa<ConstantInt>(IdxOp))
9924       return false;
9925     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9926     
9927     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
9928       // Okay, we can handle this if the vector we are insertinting into is
9929       // transitively ok.
9930       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9931         // If so, update the mask to reflect the inserted undef.
9932         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9933         return true;
9934       }      
9935     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9936       if (isa<ConstantInt>(EI->getOperand(1)) &&
9937           EI->getOperand(0)->getType() == V->getType()) {
9938         unsigned ExtractedIdx =
9939           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9940         
9941         // This must be extracting from either LHS or RHS.
9942         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9943           // Okay, we can handle this if the vector we are insertinting into is
9944           // transitively ok.
9945           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9946             // If so, update the mask to reflect the inserted value.
9947             if (EI->getOperand(0) == LHS) {
9948               Mask[InsertedIdx & (NumElts-1)] = 
9949                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9950             } else {
9951               assert(EI->getOperand(0) == RHS);
9952               Mask[InsertedIdx & (NumElts-1)] = 
9953                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9954               
9955             }
9956             return true;
9957           }
9958         }
9959       }
9960     }
9961   }
9962   // TODO: Handle shufflevector here!
9963   
9964   return false;
9965 }
9966
9967 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9968 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
9969 /// that computes V and the LHS value of the shuffle.
9970 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9971                                      Value *&RHS) {
9972   assert(isa<VectorType>(V->getType()) && 
9973          (RHS == 0 || V->getType() == RHS->getType()) &&
9974          "Invalid shuffle!");
9975   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9976
9977   if (isa<UndefValue>(V)) {
9978     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9979     return V;
9980   } else if (isa<ConstantAggregateZero>(V)) {
9981     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9982     return V;
9983   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9984     // If this is an insert of an extract from some other vector, include it.
9985     Value *VecOp    = IEI->getOperand(0);
9986     Value *ScalarOp = IEI->getOperand(1);
9987     Value *IdxOp    = IEI->getOperand(2);
9988     
9989     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9990       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9991           EI->getOperand(0)->getType() == V->getType()) {
9992         unsigned ExtractedIdx =
9993           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9994         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9995         
9996         // Either the extracted from or inserted into vector must be RHSVec,
9997         // otherwise we'd end up with a shuffle of three inputs.
9998         if (EI->getOperand(0) == RHS || RHS == 0) {
9999           RHS = EI->getOperand(0);
10000           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10001           Mask[InsertedIdx & (NumElts-1)] = 
10002             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10003           return V;
10004         }
10005         
10006         if (VecOp == RHS) {
10007           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10008           // Everything but the extracted element is replaced with the RHS.
10009           for (unsigned i = 0; i != NumElts; ++i) {
10010             if (i != InsertedIdx)
10011               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10012           }
10013           return V;
10014         }
10015         
10016         // If this insertelement is a chain that comes from exactly these two
10017         // vectors, return the vector and the effective shuffle.
10018         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10019           return EI->getOperand(0);
10020         
10021       }
10022     }
10023   }
10024   // TODO: Handle shufflevector here!
10025   
10026   // Otherwise, can't do anything fancy.  Return an identity vector.
10027   for (unsigned i = 0; i != NumElts; ++i)
10028     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10029   return V;
10030 }
10031
10032 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10033   Value *VecOp    = IE.getOperand(0);
10034   Value *ScalarOp = IE.getOperand(1);
10035   Value *IdxOp    = IE.getOperand(2);
10036   
10037   // Inserting an undef or into an undefined place, remove this.
10038   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10039     ReplaceInstUsesWith(IE, VecOp);
10040   
10041   // If the inserted element was extracted from some other vector, and if the 
10042   // indexes are constant, try to turn this into a shufflevector operation.
10043   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10044     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10045         EI->getOperand(0)->getType() == IE.getType()) {
10046       unsigned NumVectorElts = IE.getType()->getNumElements();
10047       unsigned ExtractedIdx =
10048         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10049       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10050       
10051       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10052         return ReplaceInstUsesWith(IE, VecOp);
10053       
10054       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10055         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10056       
10057       // If we are extracting a value from a vector, then inserting it right
10058       // back into the same place, just use the input vector.
10059       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10060         return ReplaceInstUsesWith(IE, VecOp);      
10061       
10062       // We could theoretically do this for ANY input.  However, doing so could
10063       // turn chains of insertelement instructions into a chain of shufflevector
10064       // instructions, and right now we do not merge shufflevectors.  As such,
10065       // only do this in a situation where it is clear that there is benefit.
10066       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10067         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10068         // the values of VecOp, except then one read from EIOp0.
10069         // Build a new shuffle mask.
10070         std::vector<Constant*> Mask;
10071         if (isa<UndefValue>(VecOp))
10072           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10073         else {
10074           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10075           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10076                                                        NumVectorElts));
10077         } 
10078         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10079         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10080                                      ConstantVector::get(Mask));
10081       }
10082       
10083       // If this insertelement isn't used by some other insertelement, turn it
10084       // (and any insertelements it points to), into one big shuffle.
10085       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10086         std::vector<Constant*> Mask;
10087         Value *RHS = 0;
10088         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10089         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10090         // We now have a shuffle of LHS, RHS, Mask.
10091         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10092       }
10093     }
10094   }
10095
10096   return 0;
10097 }
10098
10099
10100 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10101   Value *LHS = SVI.getOperand(0);
10102   Value *RHS = SVI.getOperand(1);
10103   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10104
10105   bool MadeChange = false;
10106   
10107   // Undefined shuffle mask -> undefined value.
10108   if (isa<UndefValue>(SVI.getOperand(2)))
10109     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10110   
10111   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10112   // the undef, change them to undefs.
10113   if (isa<UndefValue>(SVI.getOperand(1))) {
10114     // Scan to see if there are any references to the RHS.  If so, replace them
10115     // with undef element refs and set MadeChange to true.
10116     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10117       if (Mask[i] >= e && Mask[i] != 2*e) {
10118         Mask[i] = 2*e;
10119         MadeChange = true;
10120       }
10121     }
10122     
10123     if (MadeChange) {
10124       // Remap any references to RHS to use LHS.
10125       std::vector<Constant*> Elts;
10126       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10127         if (Mask[i] == 2*e)
10128           Elts.push_back(UndefValue::get(Type::Int32Ty));
10129         else
10130           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10131       }
10132       SVI.setOperand(2, ConstantVector::get(Elts));
10133     }
10134   }
10135   
10136   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10137   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10138   if (LHS == RHS || isa<UndefValue>(LHS)) {
10139     if (isa<UndefValue>(LHS) && LHS == RHS) {
10140       // shuffle(undef,undef,mask) -> undef.
10141       return ReplaceInstUsesWith(SVI, LHS);
10142     }
10143     
10144     // Remap any references to RHS to use LHS.
10145     std::vector<Constant*> Elts;
10146     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10147       if (Mask[i] >= 2*e)
10148         Elts.push_back(UndefValue::get(Type::Int32Ty));
10149       else {
10150         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10151             (Mask[i] <  e && isa<UndefValue>(LHS)))
10152           Mask[i] = 2*e;     // Turn into undef.
10153         else
10154           Mask[i] &= (e-1);  // Force to LHS.
10155         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10156       }
10157     }
10158     SVI.setOperand(0, SVI.getOperand(1));
10159     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10160     SVI.setOperand(2, ConstantVector::get(Elts));
10161     LHS = SVI.getOperand(0);
10162     RHS = SVI.getOperand(1);
10163     MadeChange = true;
10164   }
10165   
10166   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10167   bool isLHSID = true, isRHSID = true;
10168     
10169   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10170     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10171     // Is this an identity shuffle of the LHS value?
10172     isLHSID &= (Mask[i] == i);
10173       
10174     // Is this an identity shuffle of the RHS value?
10175     isRHSID &= (Mask[i]-e == i);
10176   }
10177
10178   // Eliminate identity shuffles.
10179   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10180   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10181   
10182   // If the LHS is a shufflevector itself, see if we can combine it with this
10183   // one without producing an unusual shuffle.  Here we are really conservative:
10184   // we are absolutely afraid of producing a shuffle mask not in the input
10185   // program, because the code gen may not be smart enough to turn a merged
10186   // shuffle into two specific shuffles: it may produce worse code.  As such,
10187   // we only merge two shuffles if the result is one of the two input shuffle
10188   // masks.  In this case, merging the shuffles just removes one instruction,
10189   // which we know is safe.  This is good for things like turning:
10190   // (splat(splat)) -> splat.
10191   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10192     if (isa<UndefValue>(RHS)) {
10193       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10194
10195       std::vector<unsigned> NewMask;
10196       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10197         if (Mask[i] >= 2*e)
10198           NewMask.push_back(2*e);
10199         else
10200           NewMask.push_back(LHSMask[Mask[i]]);
10201       
10202       // If the result mask is equal to the src shuffle or this shuffle mask, do
10203       // the replacement.
10204       if (NewMask == LHSMask || NewMask == Mask) {
10205         std::vector<Constant*> Elts;
10206         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10207           if (NewMask[i] >= e*2) {
10208             Elts.push_back(UndefValue::get(Type::Int32Ty));
10209           } else {
10210             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10211           }
10212         }
10213         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10214                                      LHSSVI->getOperand(1),
10215                                      ConstantVector::get(Elts));
10216       }
10217     }
10218   }
10219
10220   return MadeChange ? &SVI : 0;
10221 }
10222
10223
10224
10225
10226 /// TryToSinkInstruction - Try to move the specified instruction from its
10227 /// current block into the beginning of DestBlock, which can only happen if it's
10228 /// safe to move the instruction past all of the instructions between it and the
10229 /// end of its block.
10230 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10231   assert(I->hasOneUse() && "Invariants didn't hold!");
10232
10233   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10234   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10235
10236   // Do not sink alloca instructions out of the entry block.
10237   if (isa<AllocaInst>(I) && I->getParent() ==
10238         &DestBlock->getParent()->getEntryBlock())
10239     return false;
10240
10241   // We can only sink load instructions if there is nothing between the load and
10242   // the end of block that could change the value.
10243   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10244     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10245          Scan != E; ++Scan)
10246       if (Scan->mayWriteToMemory())
10247         return false;
10248   }
10249
10250   BasicBlock::iterator InsertPos = DestBlock->begin();
10251   while (isa<PHINode>(InsertPos)) ++InsertPos;
10252
10253   I->moveBefore(InsertPos);
10254   ++NumSunkInst;
10255   return true;
10256 }
10257
10258
10259 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10260 /// all reachable code to the worklist.
10261 ///
10262 /// This has a couple of tricks to make the code faster and more powerful.  In
10263 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10264 /// them to the worklist (this significantly speeds up instcombine on code where
10265 /// many instructions are dead or constant).  Additionally, if we find a branch
10266 /// whose condition is a known constant, we only visit the reachable successors.
10267 ///
10268 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10269                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10270                                        InstCombiner &IC,
10271                                        const TargetData *TD) {
10272   std::vector<BasicBlock*> Worklist;
10273   Worklist.push_back(BB);
10274
10275   while (!Worklist.empty()) {
10276     BB = Worklist.back();
10277     Worklist.pop_back();
10278     
10279     // We have now visited this block!  If we've already been here, ignore it.
10280     if (!Visited.insert(BB)) continue;
10281     
10282     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10283       Instruction *Inst = BBI++;
10284       
10285       // DCE instruction if trivially dead.
10286       if (isInstructionTriviallyDead(Inst)) {
10287         ++NumDeadInst;
10288         DOUT << "IC: DCE: " << *Inst;
10289         Inst->eraseFromParent();
10290         continue;
10291       }
10292       
10293       // ConstantProp instruction if trivially constant.
10294       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10295         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10296         Inst->replaceAllUsesWith(C);
10297         ++NumConstProp;
10298         Inst->eraseFromParent();
10299         continue;
10300       }
10301      
10302       IC.AddToWorkList(Inst);
10303     }
10304
10305     // Recursively visit successors.  If this is a branch or switch on a
10306     // constant, only visit the reachable successor.
10307     TerminatorInst *TI = BB->getTerminator();
10308     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10309       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10310         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10311         Worklist.push_back(BI->getSuccessor(!CondVal));
10312         continue;
10313       }
10314     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10315       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10316         // See if this is an explicit destination.
10317         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10318           if (SI->getCaseValue(i) == Cond) {
10319             Worklist.push_back(SI->getSuccessor(i));
10320             continue;
10321           }
10322         
10323         // Otherwise it is the default destination.
10324         Worklist.push_back(SI->getSuccessor(0));
10325         continue;
10326       }
10327     }
10328     
10329     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10330       Worklist.push_back(TI->getSuccessor(i));
10331   }
10332 }
10333
10334 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10335   bool Changed = false;
10336   TD = &getAnalysis<TargetData>();
10337   
10338   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10339              << F.getNameStr() << "\n");
10340
10341   {
10342     // Do a depth-first traversal of the function, populate the worklist with
10343     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10344     // track of which blocks we visit.
10345     SmallPtrSet<BasicBlock*, 64> Visited;
10346     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10347
10348     // Do a quick scan over the function.  If we find any blocks that are
10349     // unreachable, remove any instructions inside of them.  This prevents
10350     // the instcombine code from having to deal with some bad special cases.
10351     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10352       if (!Visited.count(BB)) {
10353         Instruction *Term = BB->getTerminator();
10354         while (Term != BB->begin()) {   // Remove instrs bottom-up
10355           BasicBlock::iterator I = Term; --I;
10356
10357           DOUT << "IC: DCE: " << *I;
10358           ++NumDeadInst;
10359
10360           if (!I->use_empty())
10361             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10362           I->eraseFromParent();
10363         }
10364       }
10365   }
10366
10367   while (!Worklist.empty()) {
10368     Instruction *I = RemoveOneFromWorkList();
10369     if (I == 0) continue;  // skip null values.
10370
10371     // Check to see if we can DCE the instruction.
10372     if (isInstructionTriviallyDead(I)) {
10373       // Add operands to the worklist.
10374       if (I->getNumOperands() < 4)
10375         AddUsesToWorkList(*I);
10376       ++NumDeadInst;
10377
10378       DOUT << "IC: DCE: " << *I;
10379
10380       I->eraseFromParent();
10381       RemoveFromWorkList(I);
10382       continue;
10383     }
10384
10385     // Instruction isn't dead, see if we can constant propagate it.
10386     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10387       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10388
10389       // Add operands to the worklist.
10390       AddUsesToWorkList(*I);
10391       ReplaceInstUsesWith(*I, C);
10392
10393       ++NumConstProp;
10394       I->eraseFromParent();
10395       RemoveFromWorkList(I);
10396       continue;
10397     }
10398
10399     // See if we can trivially sink this instruction to a successor basic block.
10400     if (I->hasOneUse()) {
10401       BasicBlock *BB = I->getParent();
10402       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10403       if (UserParent != BB) {
10404         bool UserIsSuccessor = false;
10405         // See if the user is one of our successors.
10406         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10407           if (*SI == UserParent) {
10408             UserIsSuccessor = true;
10409             break;
10410           }
10411
10412         // If the user is one of our immediate successors, and if that successor
10413         // only has us as a predecessors (we'd have to split the critical edge
10414         // otherwise), we can keep going.
10415         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10416             next(pred_begin(UserParent)) == pred_end(UserParent))
10417           // Okay, the CFG is simple enough, try to sink this instruction.
10418           Changed |= TryToSinkInstruction(I, UserParent);
10419       }
10420     }
10421
10422     // Now that we have an instruction, try combining it to simplify it...
10423 #ifndef NDEBUG
10424     std::string OrigI;
10425 #endif
10426     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10427     if (Instruction *Result = visit(*I)) {
10428       ++NumCombined;
10429       // Should we replace the old instruction with a new one?
10430       if (Result != I) {
10431         DOUT << "IC: Old = " << *I
10432              << "    New = " << *Result;
10433
10434         // Everything uses the new instruction now.
10435         I->replaceAllUsesWith(Result);
10436
10437         // Push the new instruction and any users onto the worklist.
10438         AddToWorkList(Result);
10439         AddUsersToWorkList(*Result);
10440
10441         // Move the name to the new instruction first.
10442         Result->takeName(I);
10443
10444         // Insert the new instruction into the basic block...
10445         BasicBlock *InstParent = I->getParent();
10446         BasicBlock::iterator InsertPos = I;
10447
10448         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10449           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10450             ++InsertPos;
10451
10452         InstParent->getInstList().insert(InsertPos, Result);
10453
10454         // Make sure that we reprocess all operands now that we reduced their
10455         // use counts.
10456         AddUsesToWorkList(*I);
10457
10458         // Instructions can end up on the worklist more than once.  Make sure
10459         // we do not process an instruction that has been deleted.
10460         RemoveFromWorkList(I);
10461
10462         // Erase the old instruction.
10463         InstParent->getInstList().erase(I);
10464       } else {
10465 #ifndef NDEBUG
10466         DOUT << "IC: Mod = " << OrigI
10467              << "    New = " << *I;
10468 #endif
10469
10470         // If the instruction was modified, it's possible that it is now dead.
10471         // if so, remove it.
10472         if (isInstructionTriviallyDead(I)) {
10473           // Make sure we process all operands now that we are reducing their
10474           // use counts.
10475           AddUsesToWorkList(*I);
10476
10477           // Instructions may end up in the worklist more than once.  Erase all
10478           // occurrences of this instruction.
10479           RemoveFromWorkList(I);
10480           I->eraseFromParent();
10481         } else {
10482           AddToWorkList(I);
10483           AddUsersToWorkList(*I);
10484         }
10485       }
10486       Changed = true;
10487     }
10488   }
10489
10490   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10491     
10492   // Do an explicit clear, this shrinks the map if needed.
10493   WorklistMap.clear();
10494   return Changed;
10495 }
10496
10497
10498 bool InstCombiner::runOnFunction(Function &F) {
10499   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10500   
10501   bool EverMadeChange = false;
10502
10503   // Iterate while there is work to do.
10504   unsigned Iteration = 0;
10505   while (DoOneIteration(F, Iteration++)) 
10506     EverMadeChange = true;
10507   return EverMadeChange;
10508 }
10509
10510 FunctionPass *llvm::createInstructionCombiningPass() {
10511   return new InstCombiner();
10512 }
10513