Expand ParameterAttributes to 32 bits (in preparation
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <sstream>
62 using namespace llvm;
63 using namespace llvm::PatternMatch;
64
65 STATISTIC(NumCombined , "Number of insts combined");
66 STATISTIC(NumConstProp, "Number of constant folds");
67 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69 STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71 namespace {
72   class VISIBILITY_HIDDEN InstCombiner
73     : public FunctionPass,
74       public InstVisitor<InstCombiner, Instruction*> {
75     // Worklist of all of the instructions that need to be simplified.
76     std::vector<Instruction*> Worklist;
77     DenseMap<Instruction*, unsigned> WorklistMap;
78     TargetData *TD;
79     bool MustPreserveLCSSA;
80   public:
81     static char ID; // Pass identification, replacement for typeid
82     InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84     /// AddToWorkList - Add the specified instruction to the worklist if it
85     /// isn't already in it.
86     void AddToWorkList(Instruction *I) {
87       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88         Worklist.push_back(I);
89     }
90     
91     // RemoveFromWorkList - remove I from the worklist if it exists.
92     void RemoveFromWorkList(Instruction *I) {
93       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94       if (It == WorklistMap.end()) return; // Not in worklist.
95       
96       // Don't bother moving everything down, just null out the slot.
97       Worklist[It->second] = 0;
98       
99       WorklistMap.erase(It);
100     }
101     
102     Instruction *RemoveOneFromWorkList() {
103       Instruction *I = Worklist.back();
104       Worklist.pop_back();
105       WorklistMap.erase(I);
106       return I;
107     }
108
109     
110     /// AddUsersToWorkList - When an instruction is simplified, add all users of
111     /// the instruction to the work lists because they might get more simplified
112     /// now.
113     ///
114     void AddUsersToWorkList(Value &I) {
115       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116            UI != UE; ++UI)
117         AddToWorkList(cast<Instruction>(*UI));
118     }
119
120     /// AddUsesToWorkList - When an instruction is simplified, add operands to
121     /// the work lists because they might get more simplified now.
122     ///
123     void AddUsesToWorkList(Instruction &I) {
124       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126           AddToWorkList(Op);
127     }
128     
129     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130     /// dead.  Add all of its operands to the worklist, turning them into
131     /// undef's to reduce the number of uses of those instructions.
132     ///
133     /// Return the specified operand before it is turned into an undef.
134     ///
135     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136       Value *R = I.getOperand(op);
137       
138       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140           AddToWorkList(Op);
141           // Set the operand to undef to drop the use.
142           I.setOperand(i, UndefValue::get(Op->getType()));
143         }
144       
145       return R;
146     }
147
148   public:
149     virtual bool runOnFunction(Function &F);
150     
151     bool DoOneIteration(Function &F, unsigned ItNum);
152
153     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154       AU.addRequired<TargetData>();
155       AU.addPreservedID(LCSSAID);
156       AU.setPreservesCFG();
157     }
158
159     TargetData &getTargetData() const { return *TD; }
160
161     // Visitation implementation - Implement instruction combining for different
162     // instruction types.  The semantics are as follows:
163     // Return Value:
164     //    null        - No change was made
165     //     I          - Change was made, I is still valid, I may be dead though
166     //   otherwise    - Change was made, replace I with returned instruction
167     //
168     Instruction *visitAdd(BinaryOperator &I);
169     Instruction *visitSub(BinaryOperator &I);
170     Instruction *visitMul(BinaryOperator &I);
171     Instruction *visitURem(BinaryOperator &I);
172     Instruction *visitSRem(BinaryOperator &I);
173     Instruction *visitFRem(BinaryOperator &I);
174     Instruction *commonRemTransforms(BinaryOperator &I);
175     Instruction *commonIRemTransforms(BinaryOperator &I);
176     Instruction *commonDivTransforms(BinaryOperator &I);
177     Instruction *commonIDivTransforms(BinaryOperator &I);
178     Instruction *visitUDiv(BinaryOperator &I);
179     Instruction *visitSDiv(BinaryOperator &I);
180     Instruction *visitFDiv(BinaryOperator &I);
181     Instruction *visitAnd(BinaryOperator &I);
182     Instruction *visitOr (BinaryOperator &I);
183     Instruction *visitXor(BinaryOperator &I);
184     Instruction *visitShl(BinaryOperator &I);
185     Instruction *visitAShr(BinaryOperator &I);
186     Instruction *visitLShr(BinaryOperator &I);
187     Instruction *commonShiftTransforms(BinaryOperator &I);
188     Instruction *visitFCmpInst(FCmpInst &I);
189     Instruction *visitICmpInst(ICmpInst &I);
190     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
191     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192                                                 Instruction *LHS,
193                                                 ConstantInt *RHS);
194     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195                                 ConstantInt *DivRHS);
196
197     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198                              ICmpInst::Predicate Cond, Instruction &I);
199     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
200                                      BinaryOperator &I);
201     Instruction *commonCastTransforms(CastInst &CI);
202     Instruction *commonIntCastTransforms(CastInst &CI);
203     Instruction *commonPointerCastTransforms(CastInst &CI);
204     Instruction *visitTrunc(TruncInst &CI);
205     Instruction *visitZExt(ZExtInst &CI);
206     Instruction *visitSExt(SExtInst &CI);
207     Instruction *visitFPTrunc(FPTruncInst &CI);
208     Instruction *visitFPExt(CastInst &CI);
209     Instruction *visitFPToUI(CastInst &CI);
210     Instruction *visitFPToSI(CastInst &CI);
211     Instruction *visitUIToFP(CastInst &CI);
212     Instruction *visitSIToFP(CastInst &CI);
213     Instruction *visitPtrToInt(CastInst &CI);
214     Instruction *visitIntToPtr(IntToPtrInst &CI);
215     Instruction *visitBitCast(BitCastInst &CI);
216     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217                                 Instruction *FI);
218     Instruction *visitSelectInst(SelectInst &CI);
219     Instruction *visitCallInst(CallInst &CI);
220     Instruction *visitInvokeInst(InvokeInst &II);
221     Instruction *visitPHINode(PHINode &PN);
222     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
223     Instruction *visitAllocationInst(AllocationInst &AI);
224     Instruction *visitFreeInst(FreeInst &FI);
225     Instruction *visitLoadInst(LoadInst &LI);
226     Instruction *visitStoreInst(StoreInst &SI);
227     Instruction *visitBranchInst(BranchInst &BI);
228     Instruction *visitSwitchInst(SwitchInst &SI);
229     Instruction *visitInsertElementInst(InsertElementInst &IE);
230     Instruction *visitExtractElementInst(ExtractElementInst &EI);
231     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
232
233     // visitInstruction - Specify what to return for unhandled instructions...
234     Instruction *visitInstruction(Instruction &I) { return 0; }
235
236   private:
237     Instruction *visitCallSite(CallSite CS);
238     bool transformConstExprCastCall(CallSite CS);
239     Instruction *transformCallThroughTrampoline(CallSite CS);
240
241   public:
242     // InsertNewInstBefore - insert an instruction New before instruction Old
243     // in the program.  Add the new instruction to the worklist.
244     //
245     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
246       assert(New && New->getParent() == 0 &&
247              "New instruction already inserted into a basic block!");
248       BasicBlock *BB = Old.getParent();
249       BB->getInstList().insert(&Old, New);  // Insert inst
250       AddToWorkList(New);
251       return New;
252     }
253
254     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
255     /// This also adds the cast to the worklist.  Finally, this returns the
256     /// cast.
257     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
258                             Instruction &Pos) {
259       if (V->getType() == Ty) return V;
260
261       if (Constant *CV = dyn_cast<Constant>(V))
262         return ConstantExpr::getCast(opc, CV, Ty);
263       
264       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
265       AddToWorkList(C);
266       return C;
267     }
268         
269     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
270       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
271     }
272
273
274     // ReplaceInstUsesWith - This method is to be used when an instruction is
275     // found to be dead, replacable with another preexisting expression.  Here
276     // we add all uses of I to the worklist, replace all uses of I with the new
277     // value, then return I, so that the inst combiner will know that I was
278     // modified.
279     //
280     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
281       AddUsersToWorkList(I);         // Add all modified instrs to worklist
282       if (&I != V) {
283         I.replaceAllUsesWith(V);
284         return &I;
285       } else {
286         // If we are replacing the instruction with itself, this must be in a
287         // segment of unreachable code, so just clobber the instruction.
288         I.replaceAllUsesWith(UndefValue::get(I.getType()));
289         return &I;
290       }
291     }
292
293     // UpdateValueUsesWith - This method is to be used when an value is
294     // found to be replacable with another preexisting expression or was
295     // updated.  Here we add all uses of I to the worklist, replace all uses of
296     // I with the new value (unless the instruction was just updated), then
297     // return true, so that the inst combiner will know that I was modified.
298     //
299     bool UpdateValueUsesWith(Value *Old, Value *New) {
300       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
301       if (Old != New)
302         Old->replaceAllUsesWith(New);
303       if (Instruction *I = dyn_cast<Instruction>(Old))
304         AddToWorkList(I);
305       if (Instruction *I = dyn_cast<Instruction>(New))
306         AddToWorkList(I);
307       return true;
308     }
309     
310     // EraseInstFromFunction - When dealing with an instruction that has side
311     // effects or produces a void value, we can't rely on DCE to delete the
312     // instruction.  Instead, visit methods should return the value returned by
313     // this function.
314     Instruction *EraseInstFromFunction(Instruction &I) {
315       assert(I.use_empty() && "Cannot erase instruction that is used!");
316       AddUsesToWorkList(I);
317       RemoveFromWorkList(&I);
318       I.eraseFromParent();
319       return 0;  // Don't do anything with FI
320     }
321
322   private:
323     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
324     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
325     /// casts that are known to not do anything...
326     ///
327     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
328                                    Value *V, const Type *DestTy,
329                                    Instruction *InsertBefore);
330
331     /// SimplifyCommutative - This performs a few simplifications for 
332     /// commutative operators.
333     bool SimplifyCommutative(BinaryOperator &I);
334
335     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
336     /// most-complex to least-complex order.
337     bool SimplifyCompare(CmpInst &I);
338
339     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
340     /// on the demanded bits.
341     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
342                               APInt& KnownZero, APInt& KnownOne,
343                               unsigned Depth = 0);
344
345     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
346                                       uint64_t &UndefElts, unsigned Depth = 0);
347       
348     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
349     // PHI node as operand #0, see if we can fold the instruction into the PHI
350     // (which is only possible if all operands to the PHI are constants).
351     Instruction *FoldOpIntoPhi(Instruction &I);
352
353     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
354     // operator and they all are only used by the PHI, PHI together their
355     // inputs, and do the operation once, to the result of the PHI.
356     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
357     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
358     
359     
360     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
361                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
362     
363     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
364                               bool isSub, Instruction &I);
365     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
366                                  bool isSigned, bool Inside, Instruction &IB);
367     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
368     Instruction *MatchBSwap(BinaryOperator &I);
369     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
370     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
371
372
373     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
374   };
375
376   char InstCombiner::ID = 0;
377   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
378 }
379
380 // getComplexity:  Assign a complexity or rank value to LLVM Values...
381 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
382 static unsigned getComplexity(Value *V) {
383   if (isa<Instruction>(V)) {
384     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
385       return 3;
386     return 4;
387   }
388   if (isa<Argument>(V)) return 3;
389   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
390 }
391
392 // isOnlyUse - Return true if this instruction will be deleted if we stop using
393 // it.
394 static bool isOnlyUse(Value *V) {
395   return V->hasOneUse() || isa<Constant>(V);
396 }
397
398 // getPromotedType - Return the specified type promoted as it would be to pass
399 // though a va_arg area...
400 static const Type *getPromotedType(const Type *Ty) {
401   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
402     if (ITy->getBitWidth() < 32)
403       return Type::Int32Ty;
404   }
405   return Ty;
406 }
407
408 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
409 /// expression bitcast,  return the operand value, otherwise return null.
410 static Value *getBitCastOperand(Value *V) {
411   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
412     return I->getOperand(0);
413   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
414     if (CE->getOpcode() == Instruction::BitCast)
415       return CE->getOperand(0);
416   return 0;
417 }
418
419 /// This function is a wrapper around CastInst::isEliminableCastPair. It
420 /// simply extracts arguments and returns what that function returns.
421 static Instruction::CastOps 
422 isEliminableCastPair(
423   const CastInst *CI, ///< The first cast instruction
424   unsigned opcode,       ///< The opcode of the second cast instruction
425   const Type *DstTy,     ///< The target type for the second cast instruction
426   TargetData *TD         ///< The target data for pointer size
427 ) {
428   
429   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
430   const Type *MidTy = CI->getType();                  // B from above
431
432   // Get the opcodes of the two Cast instructions
433   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
434   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
435
436   return Instruction::CastOps(
437       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
438                                      DstTy, TD->getIntPtrType()));
439 }
440
441 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442 /// in any code being generated.  It does not require codegen if V is simple
443 /// enough or if the cast can be folded into other casts.
444 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
445                               const Type *Ty, TargetData *TD) {
446   if (V->getType() == Ty || isa<Constant>(V)) return false;
447   
448   // If this is another cast that can be eliminated, it isn't codegen either.
449   if (const CastInst *CI = dyn_cast<CastInst>(V))
450     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
451       return false;
452   return true;
453 }
454
455 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
456 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
457 /// casts that are known to not do anything...
458 ///
459 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
460                                              Value *V, const Type *DestTy,
461                                              Instruction *InsertBefore) {
462   if (V->getType() == DestTy) return V;
463   if (Constant *C = dyn_cast<Constant>(V))
464     return ConstantExpr::getCast(opcode, C, DestTy);
465   
466   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
467 }
468
469 // SimplifyCommutative - This performs a few simplifications for commutative
470 // operators:
471 //
472 //  1. Order operands such that they are listed from right (least complex) to
473 //     left (most complex).  This puts constants before unary operators before
474 //     binary operators.
475 //
476 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
478 //
479 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
480   bool Changed = false;
481   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482     Changed = !I.swapOperands();
483
484   if (!I.isAssociative()) return Changed;
485   Instruction::BinaryOps Opcode = I.getOpcode();
486   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488       if (isa<Constant>(I.getOperand(1))) {
489         Constant *Folded = ConstantExpr::get(I.getOpcode(),
490                                              cast<Constant>(I.getOperand(1)),
491                                              cast<Constant>(Op->getOperand(1)));
492         I.setOperand(0, Op->getOperand(0));
493         I.setOperand(1, Folded);
494         return true;
495       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497             isOnlyUse(Op) && isOnlyUse(Op1)) {
498           Constant *C1 = cast<Constant>(Op->getOperand(1));
499           Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
502           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
503           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504                                                     Op1->getOperand(0),
505                                                     Op1->getName(), &I);
506           AddToWorkList(New);
507           I.setOperand(0, New);
508           I.setOperand(1, Folded);
509           return true;
510         }
511     }
512   return Changed;
513 }
514
515 /// SimplifyCompare - For a CmpInst this function just orders the operands
516 /// so that theyare listed from right (least complex) to left (most complex).
517 /// This puts constants before unary operators before binary operators.
518 bool InstCombiner::SimplifyCompare(CmpInst &I) {
519   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
520     return false;
521   I.swapOperands();
522   // Compare instructions are not associative so there's nothing else we can do.
523   return true;
524 }
525
526 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
527 // if the LHS is a constant zero (which is the 'negate' form).
528 //
529 static inline Value *dyn_castNegVal(Value *V) {
530   if (BinaryOperator::isNeg(V))
531     return BinaryOperator::getNegArgument(V);
532
533   // Constants can be considered to be negated values if they can be folded.
534   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535     return ConstantExpr::getNeg(C);
536   return 0;
537 }
538
539 static inline Value *dyn_castNotVal(Value *V) {
540   if (BinaryOperator::isNot(V))
541     return BinaryOperator::getNotArgument(V);
542
543   // Constants can be considered to be not'ed values...
544   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
545     return ConstantInt::get(~C->getValue());
546   return 0;
547 }
548
549 // dyn_castFoldableMul - If this value is a multiply that can be folded into
550 // other computations (because it has a constant operand), return the
551 // non-constant operand of the multiply, and set CST to point to the multiplier.
552 // Otherwise, return null.
553 //
554 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
555   if (V->hasOneUse() && V->getType()->isInteger())
556     if (Instruction *I = dyn_cast<Instruction>(V)) {
557       if (I->getOpcode() == Instruction::Mul)
558         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
559           return I->getOperand(0);
560       if (I->getOpcode() == Instruction::Shl)
561         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
562           // The multiplier is really 1 << CST.
563           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
564           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
565           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
566           return I->getOperand(0);
567         }
568     }
569   return 0;
570 }
571
572 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
573 /// expression, return it.
574 static User *dyn_castGetElementPtr(Value *V) {
575   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
576   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
577     if (CE->getOpcode() == Instruction::GetElementPtr)
578       return cast<User>(V);
579   return false;
580 }
581
582 /// AddOne - Add one to a ConstantInt
583 static ConstantInt *AddOne(ConstantInt *C) {
584   APInt Val(C->getValue());
585   return ConstantInt::get(++Val);
586 }
587 /// SubOne - Subtract one from a ConstantInt
588 static ConstantInt *SubOne(ConstantInt *C) {
589   APInt Val(C->getValue());
590   return ConstantInt::get(--Val);
591 }
592 /// Add - Add two ConstantInts together
593 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
594   return ConstantInt::get(C1->getValue() + C2->getValue());
595 }
596 /// And - Bitwise AND two ConstantInts together
597 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
598   return ConstantInt::get(C1->getValue() & C2->getValue());
599 }
600 /// Subtract - Subtract one ConstantInt from another
601 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
602   return ConstantInt::get(C1->getValue() - C2->getValue());
603 }
604 /// Multiply - Multiply two ConstantInts together
605 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
606   return ConstantInt::get(C1->getValue() * C2->getValue());
607 }
608 /// MultiplyOverflows - True if the multiply can not be expressed in an int
609 /// this size.
610 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
611   uint32_t W = C1->getBitWidth();
612   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
613   if (sign) {
614     LHSExt.sext(W * 2);
615     RHSExt.sext(W * 2);
616   } else {
617     LHSExt.zext(W * 2);
618     RHSExt.zext(W * 2);
619   }
620
621   APInt MulExt = LHSExt * RHSExt;
622
623   if (sign) {
624     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
625     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
626     return MulExt.slt(Min) || MulExt.sgt(Max);
627   } else 
628     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
629 }
630
631 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
632 /// known to be either zero or one and return them in the KnownZero/KnownOne
633 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
634 /// processing.
635 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
636 /// we cannot optimize based on the assumption that it is zero without changing
637 /// it to be an explicit zero.  If we don't change it to zero, other code could
638 /// optimized based on the contradictory assumption that it is non-zero.
639 /// Because instcombine aggressively folds operations with undef args anyway,
640 /// this won't lose us code quality.
641 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
642                               APInt& KnownOne, unsigned Depth = 0) {
643   assert(V && "No Value?");
644   assert(Depth <= 6 && "Limit Search Depth");
645   uint32_t BitWidth = Mask.getBitWidth();
646   assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
647          KnownZero.getBitWidth() == BitWidth && 
648          KnownOne.getBitWidth() == BitWidth &&
649          "V, Mask, KnownOne and KnownZero should have same BitWidth");
650   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
651     // We know all of the bits for a constant!
652     KnownOne = CI->getValue() & Mask;
653     KnownZero = ~KnownOne & Mask;
654     return;
655   }
656
657   if (Depth == 6 || Mask == 0)
658     return;  // Limit search depth.
659
660   Instruction *I = dyn_cast<Instruction>(V);
661   if (!I) return;
662
663   KnownZero.clear(); KnownOne.clear();   // Don't know anything.
664   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
665   
666   switch (I->getOpcode()) {
667   case Instruction::And: {
668     // If either the LHS or the RHS are Zero, the result is zero.
669     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
670     APInt Mask2(Mask & ~KnownZero);
671     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
672     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
673     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
674     
675     // Output known-1 bits are only known if set in both the LHS & RHS.
676     KnownOne &= KnownOne2;
677     // Output known-0 are known to be clear if zero in either the LHS | RHS.
678     KnownZero |= KnownZero2;
679     return;
680   }
681   case Instruction::Or: {
682     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
683     APInt Mask2(Mask & ~KnownOne);
684     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
685     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
686     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
687     
688     // Output known-0 bits are only known if clear in both the LHS & RHS.
689     KnownZero &= KnownZero2;
690     // Output known-1 are known to be set if set in either the LHS | RHS.
691     KnownOne |= KnownOne2;
692     return;
693   }
694   case Instruction::Xor: {
695     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
696     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
697     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
698     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
699     
700     // Output known-0 bits are known if clear or set in both the LHS & RHS.
701     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
702     // Output known-1 are known to be set if set in only one of the LHS, RHS.
703     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
704     KnownZero = KnownZeroOut;
705     return;
706   }
707   case Instruction::Select:
708     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
709     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
710     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
711     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
712
713     // Only known if known in both the LHS and RHS.
714     KnownOne &= KnownOne2;
715     KnownZero &= KnownZero2;
716     return;
717   case Instruction::FPTrunc:
718   case Instruction::FPExt:
719   case Instruction::FPToUI:
720   case Instruction::FPToSI:
721   case Instruction::SIToFP:
722   case Instruction::PtrToInt:
723   case Instruction::UIToFP:
724   case Instruction::IntToPtr:
725     return; // Can't work with floating point or pointers
726   case Instruction::Trunc: {
727     // All these have integer operands
728     uint32_t SrcBitWidth = 
729       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
730     APInt MaskIn(Mask);
731     MaskIn.zext(SrcBitWidth);
732     KnownZero.zext(SrcBitWidth);
733     KnownOne.zext(SrcBitWidth);
734     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
735     KnownZero.trunc(BitWidth);
736     KnownOne.trunc(BitWidth);
737     return;
738   }
739   case Instruction::BitCast: {
740     const Type *SrcTy = I->getOperand(0)->getType();
741     if (SrcTy->isInteger()) {
742       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
743       return;
744     }
745     break;
746   }
747   case Instruction::ZExt:  {
748     // Compute the bits in the result that are not present in the input.
749     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
750     uint32_t SrcBitWidth = SrcTy->getBitWidth();
751       
752     APInt MaskIn(Mask);
753     MaskIn.trunc(SrcBitWidth);
754     KnownZero.trunc(SrcBitWidth);
755     KnownOne.trunc(SrcBitWidth);
756     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
757     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
758     // The top bits are known to be zero.
759     KnownZero.zext(BitWidth);
760     KnownOne.zext(BitWidth);
761     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
762     return;
763   }
764   case Instruction::SExt: {
765     // Compute the bits in the result that are not present in the input.
766     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
767     uint32_t SrcBitWidth = SrcTy->getBitWidth();
768       
769     APInt MaskIn(Mask); 
770     MaskIn.trunc(SrcBitWidth);
771     KnownZero.trunc(SrcBitWidth);
772     KnownOne.trunc(SrcBitWidth);
773     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
774     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
775     KnownZero.zext(BitWidth);
776     KnownOne.zext(BitWidth);
777
778     // If the sign bit of the input is known set or clear, then we know the
779     // top bits of the result.
780     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
781       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
782     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
783       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
784     return;
785   }
786   case Instruction::Shl:
787     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
788     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
789       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
790       APInt Mask2(Mask.lshr(ShiftAmt));
791       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
792       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
793       KnownZero <<= ShiftAmt;
794       KnownOne  <<= ShiftAmt;
795       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
796       return;
797     }
798     break;
799   case Instruction::LShr:
800     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
801     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
802       // Compute the new bits that are at the top now.
803       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
804       
805       // Unsigned shift right.
806       APInt Mask2(Mask.shl(ShiftAmt));
807       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
808       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
809       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
810       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
811       // high bits known zero.
812       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
813       return;
814     }
815     break;
816   case Instruction::AShr:
817     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
818     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
819       // Compute the new bits that are at the top now.
820       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
821       
822       // Signed shift right.
823       APInt Mask2(Mask.shl(ShiftAmt));
824       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
825       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
826       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
827       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
828         
829       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
830       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
831         KnownZero |= HighBits;
832       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
833         KnownOne |= HighBits;
834       return;
835     }
836     break;
837   }
838 }
839
840 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
841 /// this predicate to simplify operations downstream.  Mask is known to be zero
842 /// for bits that V cannot have.
843 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
844   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
845   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
846   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
847   return (KnownZero & Mask) == Mask;
848 }
849
850 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
851 /// specified instruction is a constant integer.  If so, check to see if there
852 /// are any bits set in the constant that are not demanded.  If so, shrink the
853 /// constant and return true.
854 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
855                                    APInt Demanded) {
856   assert(I && "No instruction?");
857   assert(OpNo < I->getNumOperands() && "Operand index too large");
858
859   // If the operand is not a constant integer, nothing to do.
860   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
861   if (!OpC) return false;
862
863   // If there are no bits set that aren't demanded, nothing to do.
864   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
865   if ((~Demanded & OpC->getValue()) == 0)
866     return false;
867
868   // This instruction is producing bits that are not demanded. Shrink the RHS.
869   Demanded &= OpC->getValue();
870   I->setOperand(OpNo, ConstantInt::get(Demanded));
871   return true;
872 }
873
874 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
875 // set of known zero and one bits, compute the maximum and minimum values that
876 // could have the specified known zero and known one bits, returning them in
877 // min/max.
878 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
879                                                    const APInt& KnownZero,
880                                                    const APInt& KnownOne,
881                                                    APInt& Min, APInt& Max) {
882   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
883   assert(KnownZero.getBitWidth() == BitWidth && 
884          KnownOne.getBitWidth() == BitWidth &&
885          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
886          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
887   APInt UnknownBits = ~(KnownZero|KnownOne);
888
889   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
890   // bit if it is unknown.
891   Min = KnownOne;
892   Max = KnownOne|UnknownBits;
893   
894   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
895     Min.set(BitWidth-1);
896     Max.clear(BitWidth-1);
897   }
898 }
899
900 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
901 // a set of known zero and one bits, compute the maximum and minimum values that
902 // could have the specified known zero and known one bits, returning them in
903 // min/max.
904 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
905                                                      const APInt &KnownZero,
906                                                      const APInt &KnownOne,
907                                                      APInt &Min, APInt &Max) {
908   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
909   assert(KnownZero.getBitWidth() == BitWidth && 
910          KnownOne.getBitWidth() == BitWidth &&
911          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
912          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
913   APInt UnknownBits = ~(KnownZero|KnownOne);
914   
915   // The minimum value is when the unknown bits are all zeros.
916   Min = KnownOne;
917   // The maximum value is when the unknown bits are all ones.
918   Max = KnownOne|UnknownBits;
919 }
920
921 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
922 /// value based on the demanded bits. When this function is called, it is known
923 /// that only the bits set in DemandedMask of the result of V are ever used
924 /// downstream. Consequently, depending on the mask and V, it may be possible
925 /// to replace V with a constant or one of its operands. In such cases, this
926 /// function does the replacement and returns true. In all other cases, it
927 /// returns false after analyzing the expression and setting KnownOne and known
928 /// to be one in the expression. KnownZero contains all the bits that are known
929 /// to be zero in the expression. These are provided to potentially allow the
930 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
931 /// the expression. KnownOne and KnownZero always follow the invariant that 
932 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
933 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
934 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
935 /// and KnownOne must all be the same.
936 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
937                                         APInt& KnownZero, APInt& KnownOne,
938                                         unsigned Depth) {
939   assert(V != 0 && "Null pointer of Value???");
940   assert(Depth <= 6 && "Limit Search Depth");
941   uint32_t BitWidth = DemandedMask.getBitWidth();
942   const IntegerType *VTy = cast<IntegerType>(V->getType());
943   assert(VTy->getBitWidth() == BitWidth && 
944          KnownZero.getBitWidth() == BitWidth && 
945          KnownOne.getBitWidth() == BitWidth &&
946          "Value *V, DemandedMask, KnownZero and KnownOne \
947           must have same BitWidth");
948   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
949     // We know all of the bits for a constant!
950     KnownOne = CI->getValue() & DemandedMask;
951     KnownZero = ~KnownOne & DemandedMask;
952     return false;
953   }
954   
955   KnownZero.clear(); 
956   KnownOne.clear();
957   if (!V->hasOneUse()) {    // Other users may use these bits.
958     if (Depth != 0) {       // Not at the root.
959       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
960       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
961       return false;
962     }
963     // If this is the root being simplified, allow it to have multiple uses,
964     // just set the DemandedMask to all bits.
965     DemandedMask = APInt::getAllOnesValue(BitWidth);
966   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
967     if (V != UndefValue::get(VTy))
968       return UpdateValueUsesWith(V, UndefValue::get(VTy));
969     return false;
970   } else if (Depth == 6) {        // Limit search depth.
971     return false;
972   }
973   
974   Instruction *I = dyn_cast<Instruction>(V);
975   if (!I) return false;        // Only analyze instructions.
976
977   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
978   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
979   switch (I->getOpcode()) {
980   default: break;
981   case Instruction::And:
982     // If either the LHS or the RHS are Zero, the result is zero.
983     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
984                              RHSKnownZero, RHSKnownOne, Depth+1))
985       return true;
986     assert((RHSKnownZero & RHSKnownOne) == 0 && 
987            "Bits known to be one AND zero?"); 
988
989     // If something is known zero on the RHS, the bits aren't demanded on the
990     // LHS.
991     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
992                              LHSKnownZero, LHSKnownOne, Depth+1))
993       return true;
994     assert((LHSKnownZero & LHSKnownOne) == 0 && 
995            "Bits known to be one AND zero?"); 
996
997     // If all of the demanded bits are known 1 on one side, return the other.
998     // These bits cannot contribute to the result of the 'and'.
999     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1000         (DemandedMask & ~LHSKnownZero))
1001       return UpdateValueUsesWith(I, I->getOperand(0));
1002     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1003         (DemandedMask & ~RHSKnownZero))
1004       return UpdateValueUsesWith(I, I->getOperand(1));
1005     
1006     // If all of the demanded bits in the inputs are known zeros, return zero.
1007     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1008       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1009       
1010     // If the RHS is a constant, see if we can simplify it.
1011     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1012       return UpdateValueUsesWith(I, I);
1013       
1014     // Output known-1 bits are only known if set in both the LHS & RHS.
1015     RHSKnownOne &= LHSKnownOne;
1016     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1017     RHSKnownZero |= LHSKnownZero;
1018     break;
1019   case Instruction::Or:
1020     // If either the LHS or the RHS are One, the result is One.
1021     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1022                              RHSKnownZero, RHSKnownOne, Depth+1))
1023       return true;
1024     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1025            "Bits known to be one AND zero?"); 
1026     // If something is known one on the RHS, the bits aren't demanded on the
1027     // LHS.
1028     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1029                              LHSKnownZero, LHSKnownOne, Depth+1))
1030       return true;
1031     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1032            "Bits known to be one AND zero?"); 
1033     
1034     // If all of the demanded bits are known zero on one side, return the other.
1035     // These bits cannot contribute to the result of the 'or'.
1036     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1037         (DemandedMask & ~LHSKnownOne))
1038       return UpdateValueUsesWith(I, I->getOperand(0));
1039     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1040         (DemandedMask & ~RHSKnownOne))
1041       return UpdateValueUsesWith(I, I->getOperand(1));
1042
1043     // If all of the potentially set bits on one side are known to be set on
1044     // the other side, just use the 'other' side.
1045     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1046         (DemandedMask & (~RHSKnownZero)))
1047       return UpdateValueUsesWith(I, I->getOperand(0));
1048     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1049         (DemandedMask & (~LHSKnownZero)))
1050       return UpdateValueUsesWith(I, I->getOperand(1));
1051         
1052     // If the RHS is a constant, see if we can simplify it.
1053     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1054       return UpdateValueUsesWith(I, I);
1055           
1056     // Output known-0 bits are only known if clear in both the LHS & RHS.
1057     RHSKnownZero &= LHSKnownZero;
1058     // Output known-1 are known to be set if set in either the LHS | RHS.
1059     RHSKnownOne |= LHSKnownOne;
1060     break;
1061   case Instruction::Xor: {
1062     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1063                              RHSKnownZero, RHSKnownOne, Depth+1))
1064       return true;
1065     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1066            "Bits known to be one AND zero?"); 
1067     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1068                              LHSKnownZero, LHSKnownOne, Depth+1))
1069       return true;
1070     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1071            "Bits known to be one AND zero?"); 
1072     
1073     // If all of the demanded bits are known zero on one side, return the other.
1074     // These bits cannot contribute to the result of the 'xor'.
1075     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1076       return UpdateValueUsesWith(I, I->getOperand(0));
1077     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1078       return UpdateValueUsesWith(I, I->getOperand(1));
1079     
1080     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1081     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1082                          (RHSKnownOne & LHSKnownOne);
1083     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1084     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1085                         (RHSKnownOne & LHSKnownZero);
1086     
1087     // If all of the demanded bits are known to be zero on one side or the
1088     // other, turn this into an *inclusive* or.
1089     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1090     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1091       Instruction *Or =
1092         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1093                                  I->getName());
1094       InsertNewInstBefore(Or, *I);
1095       return UpdateValueUsesWith(I, Or);
1096     }
1097     
1098     // If all of the demanded bits on one side are known, and all of the set
1099     // bits on that side are also known to be set on the other side, turn this
1100     // into an AND, as we know the bits will be cleared.
1101     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1102     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1103       // all known
1104       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1105         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1106         Instruction *And = 
1107           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1108         InsertNewInstBefore(And, *I);
1109         return UpdateValueUsesWith(I, And);
1110       }
1111     }
1112     
1113     // If the RHS is a constant, see if we can simplify it.
1114     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1115     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1116       return UpdateValueUsesWith(I, I);
1117     
1118     RHSKnownZero = KnownZeroOut;
1119     RHSKnownOne  = KnownOneOut;
1120     break;
1121   }
1122   case Instruction::Select:
1123     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1124                              RHSKnownZero, RHSKnownOne, Depth+1))
1125       return true;
1126     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1127                              LHSKnownZero, LHSKnownOne, Depth+1))
1128       return true;
1129     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1130            "Bits known to be one AND zero?"); 
1131     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1132            "Bits known to be one AND zero?"); 
1133     
1134     // If the operands are constants, see if we can simplify them.
1135     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1136       return UpdateValueUsesWith(I, I);
1137     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1138       return UpdateValueUsesWith(I, I);
1139     
1140     // Only known if known in both the LHS and RHS.
1141     RHSKnownOne &= LHSKnownOne;
1142     RHSKnownZero &= LHSKnownZero;
1143     break;
1144   case Instruction::Trunc: {
1145     uint32_t truncBf = 
1146       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1147     DemandedMask.zext(truncBf);
1148     RHSKnownZero.zext(truncBf);
1149     RHSKnownOne.zext(truncBf);
1150     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1151                              RHSKnownZero, RHSKnownOne, Depth+1))
1152       return true;
1153     DemandedMask.trunc(BitWidth);
1154     RHSKnownZero.trunc(BitWidth);
1155     RHSKnownOne.trunc(BitWidth);
1156     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1157            "Bits known to be one AND zero?"); 
1158     break;
1159   }
1160   case Instruction::BitCast:
1161     if (!I->getOperand(0)->getType()->isInteger())
1162       return false;
1163       
1164     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1165                              RHSKnownZero, RHSKnownOne, Depth+1))
1166       return true;
1167     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1168            "Bits known to be one AND zero?"); 
1169     break;
1170   case Instruction::ZExt: {
1171     // Compute the bits in the result that are not present in the input.
1172     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1173     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1174     
1175     DemandedMask.trunc(SrcBitWidth);
1176     RHSKnownZero.trunc(SrcBitWidth);
1177     RHSKnownOne.trunc(SrcBitWidth);
1178     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1179                              RHSKnownZero, RHSKnownOne, Depth+1))
1180       return true;
1181     DemandedMask.zext(BitWidth);
1182     RHSKnownZero.zext(BitWidth);
1183     RHSKnownOne.zext(BitWidth);
1184     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1185            "Bits known to be one AND zero?"); 
1186     // The top bits are known to be zero.
1187     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1188     break;
1189   }
1190   case Instruction::SExt: {
1191     // Compute the bits in the result that are not present in the input.
1192     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1193     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1194     
1195     APInt InputDemandedBits = DemandedMask & 
1196                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1197
1198     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1199     // If any of the sign extended bits are demanded, we know that the sign
1200     // bit is demanded.
1201     if ((NewBits & DemandedMask) != 0)
1202       InputDemandedBits.set(SrcBitWidth-1);
1203       
1204     InputDemandedBits.trunc(SrcBitWidth);
1205     RHSKnownZero.trunc(SrcBitWidth);
1206     RHSKnownOne.trunc(SrcBitWidth);
1207     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1208                              RHSKnownZero, RHSKnownOne, Depth+1))
1209       return true;
1210     InputDemandedBits.zext(BitWidth);
1211     RHSKnownZero.zext(BitWidth);
1212     RHSKnownOne.zext(BitWidth);
1213     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1214            "Bits known to be one AND zero?"); 
1215       
1216     // If the sign bit of the input is known set or clear, then we know the
1217     // top bits of the result.
1218
1219     // If the input sign bit is known zero, or if the NewBits are not demanded
1220     // convert this into a zero extension.
1221     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1222     {
1223       // Convert to ZExt cast
1224       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1225       return UpdateValueUsesWith(I, NewCast);
1226     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1227       RHSKnownOne |= NewBits;
1228     }
1229     break;
1230   }
1231   case Instruction::Add: {
1232     // Figure out what the input bits are.  If the top bits of the and result
1233     // are not demanded, then the add doesn't demand them from its input
1234     // either.
1235     uint32_t NLZ = DemandedMask.countLeadingZeros();
1236       
1237     // If there is a constant on the RHS, there are a variety of xformations
1238     // we can do.
1239     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1240       // If null, this should be simplified elsewhere.  Some of the xforms here
1241       // won't work if the RHS is zero.
1242       if (RHS->isZero())
1243         break;
1244       
1245       // If the top bit of the output is demanded, demand everything from the
1246       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1247       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1248
1249       // Find information about known zero/one bits in the input.
1250       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1251                                LHSKnownZero, LHSKnownOne, Depth+1))
1252         return true;
1253
1254       // If the RHS of the add has bits set that can't affect the input, reduce
1255       // the constant.
1256       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1257         return UpdateValueUsesWith(I, I);
1258       
1259       // Avoid excess work.
1260       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1261         break;
1262       
1263       // Turn it into OR if input bits are zero.
1264       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1265         Instruction *Or =
1266           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1267                                    I->getName());
1268         InsertNewInstBefore(Or, *I);
1269         return UpdateValueUsesWith(I, Or);
1270       }
1271       
1272       // We can say something about the output known-zero and known-one bits,
1273       // depending on potential carries from the input constant and the
1274       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1275       // bits set and the RHS constant is 0x01001, then we know we have a known
1276       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1277       
1278       // To compute this, we first compute the potential carry bits.  These are
1279       // the bits which may be modified.  I'm not aware of a better way to do
1280       // this scan.
1281       const APInt& RHSVal = RHS->getValue();
1282       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1283       
1284       // Now that we know which bits have carries, compute the known-1/0 sets.
1285       
1286       // Bits are known one if they are known zero in one operand and one in the
1287       // other, and there is no input carry.
1288       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1289                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1290       
1291       // Bits are known zero if they are known zero in both operands and there
1292       // is no input carry.
1293       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1294     } else {
1295       // If the high-bits of this ADD are not demanded, then it does not demand
1296       // the high bits of its LHS or RHS.
1297       if (DemandedMask[BitWidth-1] == 0) {
1298         // Right fill the mask of bits for this ADD to demand the most
1299         // significant bit and all those below it.
1300         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1301         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1302                                  LHSKnownZero, LHSKnownOne, Depth+1))
1303           return true;
1304         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1305                                  LHSKnownZero, LHSKnownOne, Depth+1))
1306           return true;
1307       }
1308     }
1309     break;
1310   }
1311   case Instruction::Sub:
1312     // If the high-bits of this SUB are not demanded, then it does not demand
1313     // the high bits of its LHS or RHS.
1314     if (DemandedMask[BitWidth-1] == 0) {
1315       // Right fill the mask of bits for this SUB to demand the most
1316       // significant bit and all those below it.
1317       uint32_t NLZ = DemandedMask.countLeadingZeros();
1318       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1319       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1320                                LHSKnownZero, LHSKnownOne, Depth+1))
1321         return true;
1322       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1323                                LHSKnownZero, LHSKnownOne, Depth+1))
1324         return true;
1325     }
1326     break;
1327   case Instruction::Shl:
1328     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1330       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1331       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1332                                RHSKnownZero, RHSKnownOne, Depth+1))
1333         return true;
1334       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1335              "Bits known to be one AND zero?"); 
1336       RHSKnownZero <<= ShiftAmt;
1337       RHSKnownOne  <<= ShiftAmt;
1338       // low bits known zero.
1339       if (ShiftAmt)
1340         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1341     }
1342     break;
1343   case Instruction::LShr:
1344     // For a logical shift right
1345     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1346       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1347       
1348       // Unsigned shift right.
1349       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1350       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1351                                RHSKnownZero, RHSKnownOne, Depth+1))
1352         return true;
1353       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1354              "Bits known to be one AND zero?"); 
1355       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1356       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1357       if (ShiftAmt) {
1358         // Compute the new bits that are at the top now.
1359         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1360         RHSKnownZero |= HighBits;  // high bits known zero.
1361       }
1362     }
1363     break;
1364   case Instruction::AShr:
1365     // If this is an arithmetic shift right and only the low-bit is set, we can
1366     // always convert this into a logical shr, even if the shift amount is
1367     // variable.  The low bit of the shift cannot be an input sign bit unless
1368     // the shift amount is >= the size of the datatype, which is undefined.
1369     if (DemandedMask == 1) {
1370       // Perform the logical shift right.
1371       Value *NewVal = BinaryOperator::createLShr(
1372                         I->getOperand(0), I->getOperand(1), I->getName());
1373       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1374       return UpdateValueUsesWith(I, NewVal);
1375     }    
1376
1377     // If the sign bit is the only bit demanded by this ashr, then there is no
1378     // need to do it, the shift doesn't change the high bit.
1379     if (DemandedMask.isSignBit())
1380       return UpdateValueUsesWith(I, I->getOperand(0));
1381     
1382     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1383       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1384       
1385       // Signed shift right.
1386       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1387       // If any of the "high bits" are demanded, we should set the sign bit as
1388       // demanded.
1389       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1390         DemandedMaskIn.set(BitWidth-1);
1391       if (SimplifyDemandedBits(I->getOperand(0),
1392                                DemandedMaskIn,
1393                                RHSKnownZero, RHSKnownOne, Depth+1))
1394         return true;
1395       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1396              "Bits known to be one AND zero?"); 
1397       // Compute the new bits that are at the top now.
1398       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1399       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1400       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1401         
1402       // Handle the sign bits.
1403       APInt SignBit(APInt::getSignBit(BitWidth));
1404       // Adjust to where it is now in the mask.
1405       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1406         
1407       // If the input sign bit is known to be zero, or if none of the top bits
1408       // are demanded, turn this into an unsigned shift right.
1409       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1410           (HighBits & ~DemandedMask) == HighBits) {
1411         // Perform the logical shift right.
1412         Value *NewVal = BinaryOperator::createLShr(
1413                           I->getOperand(0), SA, I->getName());
1414         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1415         return UpdateValueUsesWith(I, NewVal);
1416       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1417         RHSKnownOne |= HighBits;
1418       }
1419     }
1420     break;
1421   }
1422   
1423   // If the client is only demanding bits that we know, return the known
1424   // constant.
1425   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1426     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1427   return false;
1428 }
1429
1430
1431 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1432 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1433 /// actually used by the caller.  This method analyzes which elements of the
1434 /// operand are undef and returns that information in UndefElts.
1435 ///
1436 /// If the information about demanded elements can be used to simplify the
1437 /// operation, the operation is simplified, then the resultant value is
1438 /// returned.  This returns null if no change was made.
1439 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1440                                                 uint64_t &UndefElts,
1441                                                 unsigned Depth) {
1442   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1443   assert(VWidth <= 64 && "Vector too wide to analyze!");
1444   uint64_t EltMask = ~0ULL >> (64-VWidth);
1445   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1446          "Invalid DemandedElts!");
1447
1448   if (isa<UndefValue>(V)) {
1449     // If the entire vector is undefined, just return this info.
1450     UndefElts = EltMask;
1451     return 0;
1452   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1453     UndefElts = EltMask;
1454     return UndefValue::get(V->getType());
1455   }
1456   
1457   UndefElts = 0;
1458   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1459     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1460     Constant *Undef = UndefValue::get(EltTy);
1461
1462     std::vector<Constant*> Elts;
1463     for (unsigned i = 0; i != VWidth; ++i)
1464       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1465         Elts.push_back(Undef);
1466         UndefElts |= (1ULL << i);
1467       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1468         Elts.push_back(Undef);
1469         UndefElts |= (1ULL << i);
1470       } else {                               // Otherwise, defined.
1471         Elts.push_back(CP->getOperand(i));
1472       }
1473         
1474     // If we changed the constant, return it.
1475     Constant *NewCP = ConstantVector::get(Elts);
1476     return NewCP != CP ? NewCP : 0;
1477   } else if (isa<ConstantAggregateZero>(V)) {
1478     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1479     // set to undef.
1480     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1481     Constant *Zero = Constant::getNullValue(EltTy);
1482     Constant *Undef = UndefValue::get(EltTy);
1483     std::vector<Constant*> Elts;
1484     for (unsigned i = 0; i != VWidth; ++i)
1485       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1486     UndefElts = DemandedElts ^ EltMask;
1487     return ConstantVector::get(Elts);
1488   }
1489   
1490   if (!V->hasOneUse()) {    // Other users may use these bits.
1491     if (Depth != 0) {       // Not at the root.
1492       // TODO: Just compute the UndefElts information recursively.
1493       return false;
1494     }
1495     return false;
1496   } else if (Depth == 10) {        // Limit search depth.
1497     return false;
1498   }
1499   
1500   Instruction *I = dyn_cast<Instruction>(V);
1501   if (!I) return false;        // Only analyze instructions.
1502   
1503   bool MadeChange = false;
1504   uint64_t UndefElts2;
1505   Value *TmpV;
1506   switch (I->getOpcode()) {
1507   default: break;
1508     
1509   case Instruction::InsertElement: {
1510     // If this is a variable index, we don't know which element it overwrites.
1511     // demand exactly the same input as we produce.
1512     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1513     if (Idx == 0) {
1514       // Note that we can't propagate undef elt info, because we don't know
1515       // which elt is getting updated.
1516       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1517                                         UndefElts2, Depth+1);
1518       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1519       break;
1520     }
1521     
1522     // If this is inserting an element that isn't demanded, remove this
1523     // insertelement.
1524     unsigned IdxNo = Idx->getZExtValue();
1525     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1526       return AddSoonDeadInstToWorklist(*I, 0);
1527     
1528     // Otherwise, the element inserted overwrites whatever was there, so the
1529     // input demanded set is simpler than the output set.
1530     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1531                                       DemandedElts & ~(1ULL << IdxNo),
1532                                       UndefElts, Depth+1);
1533     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1534
1535     // The inserted element is defined.
1536     UndefElts |= 1ULL << IdxNo;
1537     break;
1538   }
1539   case Instruction::BitCast: {
1540     // Vector->vector casts only.
1541     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1542     if (!VTy) break;
1543     unsigned InVWidth = VTy->getNumElements();
1544     uint64_t InputDemandedElts = 0;
1545     unsigned Ratio;
1546
1547     if (VWidth == InVWidth) {
1548       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1549       // elements as are demanded of us.
1550       Ratio = 1;
1551       InputDemandedElts = DemandedElts;
1552     } else if (VWidth > InVWidth) {
1553       // Untested so far.
1554       break;
1555       
1556       // If there are more elements in the result than there are in the source,
1557       // then an input element is live if any of the corresponding output
1558       // elements are live.
1559       Ratio = VWidth/InVWidth;
1560       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1561         if (DemandedElts & (1ULL << OutIdx))
1562           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1563       }
1564     } else {
1565       // Untested so far.
1566       break;
1567       
1568       // If there are more elements in the source than there are in the result,
1569       // then an input element is live if the corresponding output element is
1570       // live.
1571       Ratio = InVWidth/VWidth;
1572       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1573         if (DemandedElts & (1ULL << InIdx/Ratio))
1574           InputDemandedElts |= 1ULL << InIdx;
1575     }
1576     
1577     // div/rem demand all inputs, because they don't want divide by zero.
1578     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1579                                       UndefElts2, Depth+1);
1580     if (TmpV) {
1581       I->setOperand(0, TmpV);
1582       MadeChange = true;
1583     }
1584     
1585     UndefElts = UndefElts2;
1586     if (VWidth > InVWidth) {
1587       assert(0 && "Unimp");
1588       // If there are more elements in the result than there are in the source,
1589       // then an output element is undef if the corresponding input element is
1590       // undef.
1591       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1592         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1593           UndefElts |= 1ULL << OutIdx;
1594     } else if (VWidth < InVWidth) {
1595       assert(0 && "Unimp");
1596       // If there are more elements in the source than there are in the result,
1597       // then a result element is undef if all of the corresponding input
1598       // elements are undef.
1599       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1600       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1601         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1602           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1603     }
1604     break;
1605   }
1606   case Instruction::And:
1607   case Instruction::Or:
1608   case Instruction::Xor:
1609   case Instruction::Add:
1610   case Instruction::Sub:
1611   case Instruction::Mul:
1612     // div/rem demand all inputs, because they don't want divide by zero.
1613     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1614                                       UndefElts, Depth+1);
1615     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1616     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1617                                       UndefElts2, Depth+1);
1618     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1619       
1620     // Output elements are undefined if both are undefined.  Consider things
1621     // like undef&0.  The result is known zero, not undef.
1622     UndefElts &= UndefElts2;
1623     break;
1624     
1625   case Instruction::Call: {
1626     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1627     if (!II) break;
1628     switch (II->getIntrinsicID()) {
1629     default: break;
1630       
1631     // Binary vector operations that work column-wise.  A dest element is a
1632     // function of the corresponding input elements from the two inputs.
1633     case Intrinsic::x86_sse_sub_ss:
1634     case Intrinsic::x86_sse_mul_ss:
1635     case Intrinsic::x86_sse_min_ss:
1636     case Intrinsic::x86_sse_max_ss:
1637     case Intrinsic::x86_sse2_sub_sd:
1638     case Intrinsic::x86_sse2_mul_sd:
1639     case Intrinsic::x86_sse2_min_sd:
1640     case Intrinsic::x86_sse2_max_sd:
1641       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1642                                         UndefElts, Depth+1);
1643       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1644       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1645                                         UndefElts2, Depth+1);
1646       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1647
1648       // If only the low elt is demanded and this is a scalarizable intrinsic,
1649       // scalarize it now.
1650       if (DemandedElts == 1) {
1651         switch (II->getIntrinsicID()) {
1652         default: break;
1653         case Intrinsic::x86_sse_sub_ss:
1654         case Intrinsic::x86_sse_mul_ss:
1655         case Intrinsic::x86_sse2_sub_sd:
1656         case Intrinsic::x86_sse2_mul_sd:
1657           // TODO: Lower MIN/MAX/ABS/etc
1658           Value *LHS = II->getOperand(1);
1659           Value *RHS = II->getOperand(2);
1660           // Extract the element as scalars.
1661           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1662           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1663           
1664           switch (II->getIntrinsicID()) {
1665           default: assert(0 && "Case stmts out of sync!");
1666           case Intrinsic::x86_sse_sub_ss:
1667           case Intrinsic::x86_sse2_sub_sd:
1668             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1669                                                         II->getName()), *II);
1670             break;
1671           case Intrinsic::x86_sse_mul_ss:
1672           case Intrinsic::x86_sse2_mul_sd:
1673             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1674                                                          II->getName()), *II);
1675             break;
1676           }
1677           
1678           Instruction *New =
1679             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1680                                   II->getName());
1681           InsertNewInstBefore(New, *II);
1682           AddSoonDeadInstToWorklist(*II, 0);
1683           return New;
1684         }            
1685       }
1686         
1687       // Output elements are undefined if both are undefined.  Consider things
1688       // like undef&0.  The result is known zero, not undef.
1689       UndefElts &= UndefElts2;
1690       break;
1691     }
1692     break;
1693   }
1694   }
1695   return MadeChange ? I : 0;
1696 }
1697
1698 /// @returns true if the specified compare predicate is
1699 /// true when both operands are equal...
1700 /// @brief Determine if the icmp Predicate is true when both operands are equal
1701 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1702   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
1703          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1704          pred == ICmpInst::ICMP_SLE;
1705 }
1706
1707 /// @returns true if the specified compare instruction is
1708 /// true when both operands are equal...
1709 /// @brief Determine if the ICmpInst returns true when both operands are equal
1710 static bool isTrueWhenEqual(ICmpInst &ICI) {
1711   return isTrueWhenEqual(ICI.getPredicate());
1712 }
1713
1714 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1715 /// function is designed to check a chain of associative operators for a
1716 /// potential to apply a certain optimization.  Since the optimization may be
1717 /// applicable if the expression was reassociated, this checks the chain, then
1718 /// reassociates the expression as necessary to expose the optimization
1719 /// opportunity.  This makes use of a special Functor, which must define
1720 /// 'shouldApply' and 'apply' methods.
1721 ///
1722 template<typename Functor>
1723 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1724   unsigned Opcode = Root.getOpcode();
1725   Value *LHS = Root.getOperand(0);
1726
1727   // Quick check, see if the immediate LHS matches...
1728   if (F.shouldApply(LHS))
1729     return F.apply(Root);
1730
1731   // Otherwise, if the LHS is not of the same opcode as the root, return.
1732   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1733   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1734     // Should we apply this transform to the RHS?
1735     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1736
1737     // If not to the RHS, check to see if we should apply to the LHS...
1738     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1739       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1740       ShouldApply = true;
1741     }
1742
1743     // If the functor wants to apply the optimization to the RHS of LHSI,
1744     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1745     if (ShouldApply) {
1746       BasicBlock *BB = Root.getParent();
1747
1748       // Now all of the instructions are in the current basic block, go ahead
1749       // and perform the reassociation.
1750       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1751
1752       // First move the selected RHS to the LHS of the root...
1753       Root.setOperand(0, LHSI->getOperand(1));
1754
1755       // Make what used to be the LHS of the root be the user of the root...
1756       Value *ExtraOperand = TmpLHSI->getOperand(1);
1757       if (&Root == TmpLHSI) {
1758         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1759         return 0;
1760       }
1761       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1762       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1763       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1764       BasicBlock::iterator ARI = &Root; ++ARI;
1765       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1766       ARI = Root;
1767
1768       // Now propagate the ExtraOperand down the chain of instructions until we
1769       // get to LHSI.
1770       while (TmpLHSI != LHSI) {
1771         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1772         // Move the instruction to immediately before the chain we are
1773         // constructing to avoid breaking dominance properties.
1774         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1775         BB->getInstList().insert(ARI, NextLHSI);
1776         ARI = NextLHSI;
1777
1778         Value *NextOp = NextLHSI->getOperand(1);
1779         NextLHSI->setOperand(1, ExtraOperand);
1780         TmpLHSI = NextLHSI;
1781         ExtraOperand = NextOp;
1782       }
1783
1784       // Now that the instructions are reassociated, have the functor perform
1785       // the transformation...
1786       return F.apply(Root);
1787     }
1788
1789     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1790   }
1791   return 0;
1792 }
1793
1794
1795 // AddRHS - Implements: X + X --> X << 1
1796 struct AddRHS {
1797   Value *RHS;
1798   AddRHS(Value *rhs) : RHS(rhs) {}
1799   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1800   Instruction *apply(BinaryOperator &Add) const {
1801     return BinaryOperator::createShl(Add.getOperand(0),
1802                                   ConstantInt::get(Add.getType(), 1));
1803   }
1804 };
1805
1806 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1807 //                 iff C1&C2 == 0
1808 struct AddMaskingAnd {
1809   Constant *C2;
1810   AddMaskingAnd(Constant *c) : C2(c) {}
1811   bool shouldApply(Value *LHS) const {
1812     ConstantInt *C1;
1813     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1814            ConstantExpr::getAnd(C1, C2)->isNullValue();
1815   }
1816   Instruction *apply(BinaryOperator &Add) const {
1817     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1818   }
1819 };
1820
1821 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1822                                              InstCombiner *IC) {
1823   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1824     if (Constant *SOC = dyn_cast<Constant>(SO))
1825       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1826
1827     return IC->InsertNewInstBefore(CastInst::create(
1828           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1829   }
1830
1831   // Figure out if the constant is the left or the right argument.
1832   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1833   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1834
1835   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1836     if (ConstIsRHS)
1837       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1838     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1839   }
1840
1841   Value *Op0 = SO, *Op1 = ConstOperand;
1842   if (!ConstIsRHS)
1843     std::swap(Op0, Op1);
1844   Instruction *New;
1845   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1846     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1847   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1848     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1849                           SO->getName()+".cmp");
1850   else {
1851     assert(0 && "Unknown binary instruction type!");
1852     abort();
1853   }
1854   return IC->InsertNewInstBefore(New, I);
1855 }
1856
1857 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1858 // constant as the other operand, try to fold the binary operator into the
1859 // select arguments.  This also works for Cast instructions, which obviously do
1860 // not have a second operand.
1861 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1862                                      InstCombiner *IC) {
1863   // Don't modify shared select instructions
1864   if (!SI->hasOneUse()) return 0;
1865   Value *TV = SI->getOperand(1);
1866   Value *FV = SI->getOperand(2);
1867
1868   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1869     // Bool selects with constant operands can be folded to logical ops.
1870     if (SI->getType() == Type::Int1Ty) return 0;
1871
1872     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1873     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1874
1875     return new SelectInst(SI->getCondition(), SelectTrueVal,
1876                           SelectFalseVal);
1877   }
1878   return 0;
1879 }
1880
1881
1882 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1883 /// node as operand #0, see if we can fold the instruction into the PHI (which
1884 /// is only possible if all operands to the PHI are constants).
1885 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1886   PHINode *PN = cast<PHINode>(I.getOperand(0));
1887   unsigned NumPHIValues = PN->getNumIncomingValues();
1888   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1889
1890   // Check to see if all of the operands of the PHI are constants.  If there is
1891   // one non-constant value, remember the BB it is.  If there is more than one
1892   // or if *it* is a PHI, bail out.
1893   BasicBlock *NonConstBB = 0;
1894   for (unsigned i = 0; i != NumPHIValues; ++i)
1895     if (!isa<Constant>(PN->getIncomingValue(i))) {
1896       if (NonConstBB) return 0;  // More than one non-const value.
1897       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1898       NonConstBB = PN->getIncomingBlock(i);
1899       
1900       // If the incoming non-constant value is in I's block, we have an infinite
1901       // loop.
1902       if (NonConstBB == I.getParent())
1903         return 0;
1904     }
1905   
1906   // If there is exactly one non-constant value, we can insert a copy of the
1907   // operation in that block.  However, if this is a critical edge, we would be
1908   // inserting the computation one some other paths (e.g. inside a loop).  Only
1909   // do this if the pred block is unconditionally branching into the phi block.
1910   if (NonConstBB) {
1911     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1912     if (!BI || !BI->isUnconditional()) return 0;
1913   }
1914
1915   // Okay, we can do the transformation: create the new PHI node.
1916   PHINode *NewPN = new PHINode(I.getType(), "");
1917   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1918   InsertNewInstBefore(NewPN, *PN);
1919   NewPN->takeName(PN);
1920
1921   // Next, add all of the operands to the PHI.
1922   if (I.getNumOperands() == 2) {
1923     Constant *C = cast<Constant>(I.getOperand(1));
1924     for (unsigned i = 0; i != NumPHIValues; ++i) {
1925       Value *InV = 0;
1926       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1927         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1928           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1929         else
1930           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1931       } else {
1932         assert(PN->getIncomingBlock(i) == NonConstBB);
1933         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1934           InV = BinaryOperator::create(BO->getOpcode(),
1935                                        PN->getIncomingValue(i), C, "phitmp",
1936                                        NonConstBB->getTerminator());
1937         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1938           InV = CmpInst::create(CI->getOpcode(), 
1939                                 CI->getPredicate(),
1940                                 PN->getIncomingValue(i), C, "phitmp",
1941                                 NonConstBB->getTerminator());
1942         else
1943           assert(0 && "Unknown binop!");
1944         
1945         AddToWorkList(cast<Instruction>(InV));
1946       }
1947       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1948     }
1949   } else { 
1950     CastInst *CI = cast<CastInst>(&I);
1951     const Type *RetTy = CI->getType();
1952     for (unsigned i = 0; i != NumPHIValues; ++i) {
1953       Value *InV;
1954       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1955         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1956       } else {
1957         assert(PN->getIncomingBlock(i) == NonConstBB);
1958         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
1959                                I.getType(), "phitmp", 
1960                                NonConstBB->getTerminator());
1961         AddToWorkList(cast<Instruction>(InV));
1962       }
1963       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1964     }
1965   }
1966   return ReplaceInstUsesWith(I, NewPN);
1967 }
1968
1969
1970 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
1971 /// value is never equal to -0.0.
1972 ///
1973 /// Note that this function will need to be revisited when we support nondefault
1974 /// rounding modes!
1975 ///
1976 static bool CannotBeNegativeZero(const Value *V) {
1977   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1978     return !CFP->getValueAPF().isNegZero();
1979
1980   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1981   if (const Instruction *I = dyn_cast<Instruction>(V)) {
1982     if (I->getOpcode() == Instruction::Add &&
1983         isa<ConstantFP>(I->getOperand(1)) && 
1984         cast<ConstantFP>(I->getOperand(1))->isNullValue())
1985       return true;
1986     
1987     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1988       if (II->getIntrinsicID() == Intrinsic::sqrt)
1989         return CannotBeNegativeZero(II->getOperand(1));
1990     
1991     if (const CallInst *CI = dyn_cast<CallInst>(I))
1992       if (const Function *F = CI->getCalledFunction()) {
1993         if (F->isDeclaration()) {
1994           switch (F->getNameLen()) {
1995           case 3:  // abs(x) != -0.0
1996             if (!strcmp(F->getNameStart(), "abs")) return true;
1997             break;
1998           case 4:  // abs[lf](x) != -0.0
1999             if (!strcmp(F->getNameStart(), "absf")) return true;
2000             if (!strcmp(F->getNameStart(), "absl")) return true;
2001             break;
2002           }
2003         }
2004       }
2005   }
2006   
2007   return false;
2008 }
2009
2010
2011 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2012   bool Changed = SimplifyCommutative(I);
2013   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2014
2015   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2016     // X + undef -> undef
2017     if (isa<UndefValue>(RHS))
2018       return ReplaceInstUsesWith(I, RHS);
2019
2020     // X + 0 --> X
2021     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2022       if (RHSC->isNullValue())
2023         return ReplaceInstUsesWith(I, LHS);
2024     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2025       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2026                               (I.getType())->getValueAPF()))
2027         return ReplaceInstUsesWith(I, LHS);
2028     }
2029
2030     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2031       // X + (signbit) --> X ^ signbit
2032       const APInt& Val = CI->getValue();
2033       uint32_t BitWidth = Val.getBitWidth();
2034       if (Val == APInt::getSignBit(BitWidth))
2035         return BinaryOperator::createXor(LHS, RHS);
2036       
2037       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2038       // (X & 254)+1 -> (X&254)|1
2039       if (!isa<VectorType>(I.getType())) {
2040         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2041         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2042                                  KnownZero, KnownOne))
2043           return &I;
2044       }
2045     }
2046
2047     if (isa<PHINode>(LHS))
2048       if (Instruction *NV = FoldOpIntoPhi(I))
2049         return NV;
2050     
2051     ConstantInt *XorRHS = 0;
2052     Value *XorLHS = 0;
2053     if (isa<ConstantInt>(RHSC) &&
2054         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2055       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2056       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2057       
2058       uint32_t Size = TySizeBits / 2;
2059       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2060       APInt CFF80Val(-C0080Val);
2061       do {
2062         if (TySizeBits > Size) {
2063           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2064           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2065           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2066               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2067             // This is a sign extend if the top bits are known zero.
2068             if (!MaskedValueIsZero(XorLHS, 
2069                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2070               Size = 0;  // Not a sign ext, but can't be any others either.
2071             break;
2072           }
2073         }
2074         Size >>= 1;
2075         C0080Val = APIntOps::lshr(C0080Val, Size);
2076         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2077       } while (Size >= 1);
2078       
2079       // FIXME: This shouldn't be necessary. When the backends can handle types
2080       // with funny bit widths then this whole cascade of if statements should
2081       // be removed. It is just here to get the size of the "middle" type back
2082       // up to something that the back ends can handle.
2083       const Type *MiddleType = 0;
2084       switch (Size) {
2085         default: break;
2086         case 32: MiddleType = Type::Int32Ty; break;
2087         case 16: MiddleType = Type::Int16Ty; break;
2088         case  8: MiddleType = Type::Int8Ty; break;
2089       }
2090       if (MiddleType) {
2091         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2092         InsertNewInstBefore(NewTrunc, I);
2093         return new SExtInst(NewTrunc, I.getType(), I.getName());
2094       }
2095     }
2096   }
2097
2098   // X + X --> X << 1
2099   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2100     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2101
2102     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2103       if (RHSI->getOpcode() == Instruction::Sub)
2104         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2105           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2106     }
2107     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2108       if (LHSI->getOpcode() == Instruction::Sub)
2109         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2110           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2111     }
2112   }
2113
2114   // -A + B  -->  B - A
2115   // -A + -B  -->  -(A + B)
2116   if (Value *LHSV = dyn_castNegVal(LHS)) {
2117     if (LHS->getType()->isIntOrIntVector()) {
2118       if (Value *RHSV = dyn_castNegVal(RHS)) {
2119         Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2120         InsertNewInstBefore(NewAdd, I);
2121         return BinaryOperator::createNeg(NewAdd);
2122       }
2123     }
2124     
2125     return BinaryOperator::createSub(RHS, LHSV);
2126   }
2127
2128   // A + -B  -->  A - B
2129   if (!isa<Constant>(RHS))
2130     if (Value *V = dyn_castNegVal(RHS))
2131       return BinaryOperator::createSub(LHS, V);
2132
2133
2134   ConstantInt *C2;
2135   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2136     if (X == RHS)   // X*C + X --> X * (C+1)
2137       return BinaryOperator::createMul(RHS, AddOne(C2));
2138
2139     // X*C1 + X*C2 --> X * (C1+C2)
2140     ConstantInt *C1;
2141     if (X == dyn_castFoldableMul(RHS, C1))
2142       return BinaryOperator::createMul(X, Add(C1, C2));
2143   }
2144
2145   // X + X*C --> X * (C+1)
2146   if (dyn_castFoldableMul(RHS, C2) == LHS)
2147     return BinaryOperator::createMul(LHS, AddOne(C2));
2148
2149   // X + ~X --> -1   since   ~X = -X-1
2150   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2151     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2152   
2153
2154   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2155   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2156     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2157       return R;
2158
2159   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2160   if (I.getType()->isIntOrIntVector()) {
2161     Value *W, *X, *Y, *Z;
2162     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2163         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2164       if (W != Y) {
2165         if (W == Z) {
2166           std::swap(Y, Z);
2167         } else if (Y == X) {
2168           std::swap(W, X);
2169         } else if (X == Z) {
2170           std::swap(Y, Z);
2171           std::swap(W, X);
2172         }
2173       }
2174
2175       if (W == Y) {
2176         Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2177                                                             LHS->getName()), I);
2178         return BinaryOperator::createMul(W, NewAdd);
2179       }
2180     }
2181   }
2182
2183   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2184     Value *X = 0;
2185     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2186       return BinaryOperator::createSub(SubOne(CRHS), X);
2187
2188     // (X & FF00) + xx00  -> (X+xx00) & FF00
2189     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2190       Constant *Anded = And(CRHS, C2);
2191       if (Anded == CRHS) {
2192         // See if all bits from the first bit set in the Add RHS up are included
2193         // in the mask.  First, get the rightmost bit.
2194         const APInt& AddRHSV = CRHS->getValue();
2195
2196         // Form a mask of all bits from the lowest bit added through the top.
2197         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2198
2199         // See if the and mask includes all of these bits.
2200         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2201
2202         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2203           // Okay, the xform is safe.  Insert the new add pronto.
2204           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2205                                                             LHS->getName()), I);
2206           return BinaryOperator::createAnd(NewAdd, C2);
2207         }
2208       }
2209     }
2210
2211     // Try to fold constant add into select arguments.
2212     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2213       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2214         return R;
2215   }
2216
2217   // add (cast *A to intptrtype) B -> 
2218   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2219   {
2220     CastInst *CI = dyn_cast<CastInst>(LHS);
2221     Value *Other = RHS;
2222     if (!CI) {
2223       CI = dyn_cast<CastInst>(RHS);
2224       Other = LHS;
2225     }
2226     if (CI && CI->getType()->isSized() && 
2227         (CI->getType()->getPrimitiveSizeInBits() == 
2228          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2229         && isa<PointerType>(CI->getOperand(0)->getType())) {
2230       unsigned AS =
2231         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2232       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2233                                       PointerType::get(Type::Int8Ty, AS), I);
2234       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2235       return new PtrToIntInst(I2, CI->getType());
2236     }
2237   }
2238   
2239   // add (select X 0 (sub n A)) A  -->  select X A n
2240   {
2241     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2242     Value *Other = RHS;
2243     if (!SI) {
2244       SI = dyn_cast<SelectInst>(RHS);
2245       Other = LHS;
2246     }
2247     if (SI && SI->hasOneUse()) {
2248       Value *TV = SI->getTrueValue();
2249       Value *FV = SI->getFalseValue();
2250       Value *A, *N;
2251
2252       // Can we fold the add into the argument of the select?
2253       // We check both true and false select arguments for a matching subtract.
2254       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2255           A == Other)  // Fold the add into the true select value.
2256         return new SelectInst(SI->getCondition(), N, A);
2257       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2258           A == Other)  // Fold the add into the false select value.
2259         return new SelectInst(SI->getCondition(), A, N);
2260     }
2261   }
2262   
2263   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2264   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2265     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2266       return ReplaceInstUsesWith(I, LHS);
2267
2268   return Changed ? &I : 0;
2269 }
2270
2271 // isSignBit - Return true if the value represented by the constant only has the
2272 // highest order bit set.
2273 static bool isSignBit(ConstantInt *CI) {
2274   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2275   return CI->getValue() == APInt::getSignBit(NumBits);
2276 }
2277
2278 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2279   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2280
2281   if (Op0 == Op1)         // sub X, X  -> 0
2282     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2283
2284   // If this is a 'B = x-(-A)', change to B = x+A...
2285   if (Value *V = dyn_castNegVal(Op1))
2286     return BinaryOperator::createAdd(Op0, V);
2287
2288   if (isa<UndefValue>(Op0))
2289     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2290   if (isa<UndefValue>(Op1))
2291     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2292
2293   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2294     // Replace (-1 - A) with (~A)...
2295     if (C->isAllOnesValue())
2296       return BinaryOperator::createNot(Op1);
2297
2298     // C - ~X == X + (1+C)
2299     Value *X = 0;
2300     if (match(Op1, m_Not(m_Value(X))))
2301       return BinaryOperator::createAdd(X, AddOne(C));
2302
2303     // -(X >>u 31) -> (X >>s 31)
2304     // -(X >>s 31) -> (X >>u 31)
2305     if (C->isZero()) {
2306       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2307         if (SI->getOpcode() == Instruction::LShr) {
2308           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2309             // Check to see if we are shifting out everything but the sign bit.
2310             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2311                 SI->getType()->getPrimitiveSizeInBits()-1) {
2312               // Ok, the transformation is safe.  Insert AShr.
2313               return BinaryOperator::create(Instruction::AShr, 
2314                                           SI->getOperand(0), CU, SI->getName());
2315             }
2316           }
2317         }
2318         else if (SI->getOpcode() == Instruction::AShr) {
2319           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2320             // Check to see if we are shifting out everything but the sign bit.
2321             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2322                 SI->getType()->getPrimitiveSizeInBits()-1) {
2323               // Ok, the transformation is safe.  Insert LShr. 
2324               return BinaryOperator::createLShr(
2325                                           SI->getOperand(0), CU, SI->getName());
2326             }
2327           }
2328         } 
2329     }
2330
2331     // Try to fold constant sub into select arguments.
2332     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2333       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2334         return R;
2335
2336     if (isa<PHINode>(Op0))
2337       if (Instruction *NV = FoldOpIntoPhi(I))
2338         return NV;
2339   }
2340
2341   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2342     if (Op1I->getOpcode() == Instruction::Add &&
2343         !Op0->getType()->isFPOrFPVector()) {
2344       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2345         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2346       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2347         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2348       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2349         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2350           // C1-(X+C2) --> (C1-C2)-X
2351           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2352                                            Op1I->getOperand(0));
2353       }
2354     }
2355
2356     if (Op1I->hasOneUse()) {
2357       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2358       // is not used by anyone else...
2359       //
2360       if (Op1I->getOpcode() == Instruction::Sub &&
2361           !Op1I->getType()->isFPOrFPVector()) {
2362         // Swap the two operands of the subexpr...
2363         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2364         Op1I->setOperand(0, IIOp1);
2365         Op1I->setOperand(1, IIOp0);
2366
2367         // Create the new top level add instruction...
2368         return BinaryOperator::createAdd(Op0, Op1);
2369       }
2370
2371       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2372       //
2373       if (Op1I->getOpcode() == Instruction::And &&
2374           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2375         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2376
2377         Value *NewNot =
2378           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2379         return BinaryOperator::createAnd(Op0, NewNot);
2380       }
2381
2382       // 0 - (X sdiv C)  -> (X sdiv -C)
2383       if (Op1I->getOpcode() == Instruction::SDiv)
2384         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2385           if (CSI->isZero())
2386             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2387               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2388                                                ConstantExpr::getNeg(DivRHS));
2389
2390       // X - X*C --> X * (1-C)
2391       ConstantInt *C2 = 0;
2392       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2393         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2394         return BinaryOperator::createMul(Op0, CP1);
2395       }
2396
2397       // X - ((X / Y) * Y) --> X % Y
2398       if (Op1I->getOpcode() == Instruction::Mul)
2399         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2400           if (Op0 == I->getOperand(0) &&
2401               Op1I->getOperand(1) == I->getOperand(1)) {
2402             if (I->getOpcode() == Instruction::SDiv)
2403               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2404             if (I->getOpcode() == Instruction::UDiv)
2405               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2406           }
2407     }
2408   }
2409
2410   if (!Op0->getType()->isFPOrFPVector())
2411     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2412       if (Op0I->getOpcode() == Instruction::Add) {
2413         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2414           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2415         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2416           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2417       } else if (Op0I->getOpcode() == Instruction::Sub) {
2418         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2419           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2420       }
2421
2422   ConstantInt *C1;
2423   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2424     if (X == Op1)  // X*C - X --> X * (C-1)
2425       return BinaryOperator::createMul(Op1, SubOne(C1));
2426
2427     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2428     if (X == dyn_castFoldableMul(Op1, C2))
2429       return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2430   }
2431   return 0;
2432 }
2433
2434 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2435 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2436 /// TrueIfSigned if the result of the comparison is true when the input value is
2437 /// signed.
2438 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2439                            bool &TrueIfSigned) {
2440   switch (pred) {
2441   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2442     TrueIfSigned = true;
2443     return RHS->isZero();
2444   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2445     TrueIfSigned = true;
2446     return RHS->isAllOnesValue();
2447   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2448     TrueIfSigned = false;
2449     return RHS->isAllOnesValue();
2450   case ICmpInst::ICMP_UGT:
2451     // True if LHS u> RHS and RHS == high-bit-mask - 1
2452     TrueIfSigned = true;
2453     return RHS->getValue() ==
2454       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2455   case ICmpInst::ICMP_UGE: 
2456     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2457     TrueIfSigned = true;
2458     return RHS->getValue() == 
2459       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2460   default:
2461     return false;
2462   }
2463 }
2464
2465 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2466   bool Changed = SimplifyCommutative(I);
2467   Value *Op0 = I.getOperand(0);
2468
2469   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2470     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2471
2472   // Simplify mul instructions with a constant RHS...
2473   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2474     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2475
2476       // ((X << C1)*C2) == (X * (C2 << C1))
2477       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2478         if (SI->getOpcode() == Instruction::Shl)
2479           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2480             return BinaryOperator::createMul(SI->getOperand(0),
2481                                              ConstantExpr::getShl(CI, ShOp));
2482
2483       if (CI->isZero())
2484         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2485       if (CI->equalsInt(1))                  // X * 1  == X
2486         return ReplaceInstUsesWith(I, Op0);
2487       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2488         return BinaryOperator::createNeg(Op0, I.getName());
2489
2490       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2491       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2492         return BinaryOperator::createShl(Op0,
2493                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2494       }
2495     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2496       if (Op1F->isNullValue())
2497         return ReplaceInstUsesWith(I, Op1);
2498
2499       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2500       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2501       // We need a better interface for long double here.
2502       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2503         if (Op1F->isExactlyValue(1.0))
2504           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2505     }
2506     
2507     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2508       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2509           isa<ConstantInt>(Op0I->getOperand(1))) {
2510         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2511         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2512                                                      Op1, "tmp");
2513         InsertNewInstBefore(Add, I);
2514         Value *C1C2 = ConstantExpr::getMul(Op1, 
2515                                            cast<Constant>(Op0I->getOperand(1)));
2516         return BinaryOperator::createAdd(Add, C1C2);
2517         
2518       }
2519
2520     // Try to fold constant mul into select arguments.
2521     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2522       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2523         return R;
2524
2525     if (isa<PHINode>(Op0))
2526       if (Instruction *NV = FoldOpIntoPhi(I))
2527         return NV;
2528   }
2529
2530   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2531     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2532       return BinaryOperator::createMul(Op0v, Op1v);
2533
2534   // If one of the operands of the multiply is a cast from a boolean value, then
2535   // we know the bool is either zero or one, so this is a 'masking' multiply.
2536   // See if we can simplify things based on how the boolean was originally
2537   // formed.
2538   CastInst *BoolCast = 0;
2539   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2540     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2541       BoolCast = CI;
2542   if (!BoolCast)
2543     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2544       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2545         BoolCast = CI;
2546   if (BoolCast) {
2547     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2548       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2549       const Type *SCOpTy = SCIOp0->getType();
2550       bool TIS = false;
2551       
2552       // If the icmp is true iff the sign bit of X is set, then convert this
2553       // multiply into a shift/and combination.
2554       if (isa<ConstantInt>(SCIOp1) &&
2555           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2556           TIS) {
2557         // Shift the X value right to turn it into "all signbits".
2558         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2559                                           SCOpTy->getPrimitiveSizeInBits()-1);
2560         Value *V =
2561           InsertNewInstBefore(
2562             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2563                                             BoolCast->getOperand(0)->getName()+
2564                                             ".mask"), I);
2565
2566         // If the multiply type is not the same as the source type, sign extend
2567         // or truncate to the multiply type.
2568         if (I.getType() != V->getType()) {
2569           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2570           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2571           Instruction::CastOps opcode = 
2572             (SrcBits == DstBits ? Instruction::BitCast : 
2573              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2574           V = InsertCastBefore(opcode, V, I.getType(), I);
2575         }
2576
2577         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2578         return BinaryOperator::createAnd(V, OtherOp);
2579       }
2580     }
2581   }
2582
2583   return Changed ? &I : 0;
2584 }
2585
2586 /// This function implements the transforms on div instructions that work
2587 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2588 /// used by the visitors to those instructions.
2589 /// @brief Transforms common to all three div instructions
2590 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2591   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2592
2593   // undef / X -> 0        for integer.
2594   // undef / X -> undef    for FP (the undef could be a snan).
2595   if (isa<UndefValue>(Op0)) {
2596     if (Op0->getType()->isFPOrFPVector())
2597       return ReplaceInstUsesWith(I, Op0);
2598     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2599   }
2600
2601   // X / undef -> undef
2602   if (isa<UndefValue>(Op1))
2603     return ReplaceInstUsesWith(I, Op1);
2604
2605   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2606   // This does not apply for fdiv.
2607   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2608     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2609     // the same basic block, then we replace the select with Y, and the
2610     // condition of the select with false (if the cond value is in the same BB).
2611     // If the select has uses other than the div, this allows them to be
2612     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2613     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2614       if (ST->isNullValue()) {
2615         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2616         if (CondI && CondI->getParent() == I.getParent())
2617           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2618         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2619           I.setOperand(1, SI->getOperand(2));
2620         else
2621           UpdateValueUsesWith(SI, SI->getOperand(2));
2622         return &I;
2623       }
2624
2625     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2626     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2627       if (ST->isNullValue()) {
2628         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2629         if (CondI && CondI->getParent() == I.getParent())
2630           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2631         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2632           I.setOperand(1, SI->getOperand(1));
2633         else
2634           UpdateValueUsesWith(SI, SI->getOperand(1));
2635         return &I;
2636       }
2637   }
2638
2639   return 0;
2640 }
2641
2642 /// This function implements the transforms common to both integer division
2643 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2644 /// division instructions.
2645 /// @brief Common integer divide transforms
2646 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2647   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2648
2649   if (Instruction *Common = commonDivTransforms(I))
2650     return Common;
2651
2652   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2653     // div X, 1 == X
2654     if (RHS->equalsInt(1))
2655       return ReplaceInstUsesWith(I, Op0);
2656
2657     // (X / C1) / C2  -> X / (C1*C2)
2658     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2659       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2660         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2661           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2662             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2663           else 
2664             return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2665                                           Multiply(RHS, LHSRHS));
2666         }
2667
2668     if (!RHS->isZero()) { // avoid X udiv 0
2669       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2670         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2671           return R;
2672       if (isa<PHINode>(Op0))
2673         if (Instruction *NV = FoldOpIntoPhi(I))
2674           return NV;
2675     }
2676   }
2677
2678   // 0 / X == 0, we don't need to preserve faults!
2679   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2680     if (LHS->equalsInt(0))
2681       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2682
2683   return 0;
2684 }
2685
2686 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2687   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2688
2689   // Handle the integer div common cases
2690   if (Instruction *Common = commonIDivTransforms(I))
2691     return Common;
2692
2693   // X udiv C^2 -> X >> C
2694   // Check to see if this is an unsigned division with an exact power of 2,
2695   // if so, convert to a right shift.
2696   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2697     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2698       return BinaryOperator::createLShr(Op0, 
2699                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2700   }
2701
2702   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2703   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2704     if (RHSI->getOpcode() == Instruction::Shl &&
2705         isa<ConstantInt>(RHSI->getOperand(0))) {
2706       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2707       if (C1.isPowerOf2()) {
2708         Value *N = RHSI->getOperand(1);
2709         const Type *NTy = N->getType();
2710         if (uint32_t C2 = C1.logBase2()) {
2711           Constant *C2V = ConstantInt::get(NTy, C2);
2712           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2713         }
2714         return BinaryOperator::createLShr(Op0, N);
2715       }
2716     }
2717   }
2718   
2719   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2720   // where C1&C2 are powers of two.
2721   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2722     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2723       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2724         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2725         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2726           // Compute the shift amounts
2727           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2728           // Construct the "on true" case of the select
2729           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2730           Instruction *TSI = BinaryOperator::createLShr(
2731                                                  Op0, TC, SI->getName()+".t");
2732           TSI = InsertNewInstBefore(TSI, I);
2733   
2734           // Construct the "on false" case of the select
2735           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2736           Instruction *FSI = BinaryOperator::createLShr(
2737                                                  Op0, FC, SI->getName()+".f");
2738           FSI = InsertNewInstBefore(FSI, I);
2739
2740           // construct the select instruction and return it.
2741           return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2742         }
2743       }
2744   return 0;
2745 }
2746
2747 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2748   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2749
2750   // Handle the integer div common cases
2751   if (Instruction *Common = commonIDivTransforms(I))
2752     return Common;
2753
2754   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2755     // sdiv X, -1 == -X
2756     if (RHS->isAllOnesValue())
2757       return BinaryOperator::createNeg(Op0);
2758
2759     // -X/C -> X/-C
2760     if (Value *LHSNeg = dyn_castNegVal(Op0))
2761       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2762   }
2763
2764   // If the sign bits of both operands are zero (i.e. we can prove they are
2765   // unsigned inputs), turn this into a udiv.
2766   if (I.getType()->isInteger()) {
2767     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2768     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2769       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2770       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2771     }
2772   }      
2773   
2774   return 0;
2775 }
2776
2777 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2778   return commonDivTransforms(I);
2779 }
2780
2781 /// GetFactor - If we can prove that the specified value is at least a multiple
2782 /// of some factor, return that factor.
2783 static Constant *GetFactor(Value *V) {
2784   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2785     return CI;
2786   
2787   // Unless we can be tricky, we know this is a multiple of 1.
2788   Constant *Result = ConstantInt::get(V->getType(), 1);
2789   
2790   Instruction *I = dyn_cast<Instruction>(V);
2791   if (!I) return Result;
2792   
2793   if (I->getOpcode() == Instruction::Mul) {
2794     // Handle multiplies by a constant, etc.
2795     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2796                                 GetFactor(I->getOperand(1)));
2797   } else if (I->getOpcode() == Instruction::Shl) {
2798     // (X<<C) -> X * (1 << C)
2799     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2800       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2801       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2802     }
2803   } else if (I->getOpcode() == Instruction::And) {
2804     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2805       // X & 0xFFF0 is known to be a multiple of 16.
2806       uint32_t Zeros = RHS->getValue().countTrailingZeros();
2807       if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
2808         return ConstantExpr::getShl(Result, 
2809                                     ConstantInt::get(Result->getType(), Zeros));
2810     }
2811   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2812     // Only handle int->int casts.
2813     if (!CI->isIntegerCast())
2814       return Result;
2815     Value *Op = CI->getOperand(0);
2816     return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2817   }    
2818   return Result;
2819 }
2820
2821 /// This function implements the transforms on rem instructions that work
2822 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2823 /// is used by the visitors to those instructions.
2824 /// @brief Transforms common to all three rem instructions
2825 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2826   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2827
2828   // 0 % X == 0 for integer, we don't need to preserve faults!
2829   if (Constant *LHS = dyn_cast<Constant>(Op0))
2830     if (LHS->isNullValue())
2831       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2832
2833   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2834     if (I.getType()->isFPOrFPVector())
2835       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2836     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2837   }
2838   if (isa<UndefValue>(Op1))
2839     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2840
2841   // Handle cases involving: rem X, (select Cond, Y, Z)
2842   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2843     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2844     // the same basic block, then we replace the select with Y, and the
2845     // condition of the select with false (if the cond value is in the same
2846     // BB).  If the select has uses other than the div, this allows them to be
2847     // simplified also.
2848     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2849       if (ST->isNullValue()) {
2850         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2851         if (CondI && CondI->getParent() == I.getParent())
2852           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2853         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2854           I.setOperand(1, SI->getOperand(2));
2855         else
2856           UpdateValueUsesWith(SI, SI->getOperand(2));
2857         return &I;
2858       }
2859     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2860     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2861       if (ST->isNullValue()) {
2862         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2863         if (CondI && CondI->getParent() == I.getParent())
2864           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2865         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2866           I.setOperand(1, SI->getOperand(1));
2867         else
2868           UpdateValueUsesWith(SI, SI->getOperand(1));
2869         return &I;
2870       }
2871   }
2872
2873   return 0;
2874 }
2875
2876 /// This function implements the transforms common to both integer remainder
2877 /// instructions (urem and srem). It is called by the visitors to those integer
2878 /// remainder instructions.
2879 /// @brief Common integer remainder transforms
2880 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2881   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2882
2883   if (Instruction *common = commonRemTransforms(I))
2884     return common;
2885
2886   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2887     // X % 0 == undef, we don't need to preserve faults!
2888     if (RHS->equalsInt(0))
2889       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2890     
2891     if (RHS->equalsInt(1))  // X % 1 == 0
2892       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2893
2894     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2895       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2896         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2897           return R;
2898       } else if (isa<PHINode>(Op0I)) {
2899         if (Instruction *NV = FoldOpIntoPhi(I))
2900           return NV;
2901       }
2902       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2903       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2904         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2905     }
2906   }
2907
2908   return 0;
2909 }
2910
2911 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2912   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2913
2914   if (Instruction *common = commonIRemTransforms(I))
2915     return common;
2916   
2917   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2918     // X urem C^2 -> X and C
2919     // Check to see if this is an unsigned remainder with an exact power of 2,
2920     // if so, convert to a bitwise and.
2921     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2922       if (C->getValue().isPowerOf2())
2923         return BinaryOperator::createAnd(Op0, SubOne(C));
2924   }
2925
2926   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2927     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2928     if (RHSI->getOpcode() == Instruction::Shl &&
2929         isa<ConstantInt>(RHSI->getOperand(0))) {
2930       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2931         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2932         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2933                                                                    "tmp"), I);
2934         return BinaryOperator::createAnd(Op0, Add);
2935       }
2936     }
2937   }
2938
2939   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2940   // where C1&C2 are powers of two.
2941   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2942     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2943       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2944         // STO == 0 and SFO == 0 handled above.
2945         if ((STO->getValue().isPowerOf2()) && 
2946             (SFO->getValue().isPowerOf2())) {
2947           Value *TrueAnd = InsertNewInstBefore(
2948             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2949           Value *FalseAnd = InsertNewInstBefore(
2950             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2951           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2952         }
2953       }
2954   }
2955   
2956   return 0;
2957 }
2958
2959 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2960   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2961
2962   // Handle the integer rem common cases
2963   if (Instruction *common = commonIRemTransforms(I))
2964     return common;
2965   
2966   if (Value *RHSNeg = dyn_castNegVal(Op1))
2967     if (!isa<ConstantInt>(RHSNeg) || 
2968         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2969       // X % -Y -> X % Y
2970       AddUsesToWorkList(I);
2971       I.setOperand(1, RHSNeg);
2972       return &I;
2973     }
2974  
2975   // If the sign bits of both operands are zero (i.e. we can prove they are
2976   // unsigned inputs), turn this into a urem.
2977   if (I.getType()->isInteger()) {
2978     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2979     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2980       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2981       return BinaryOperator::createURem(Op0, Op1, I.getName());
2982     }
2983   }
2984
2985   return 0;
2986 }
2987
2988 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2989   return commonRemTransforms(I);
2990 }
2991
2992 // isMaxValueMinusOne - return true if this is Max-1
2993 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2994   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2995   if (!isSigned)
2996     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2997   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2998 }
2999
3000 // isMinValuePlusOne - return true if this is Min+1
3001 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3002   if (!isSigned)
3003     return C->getValue() == 1; // unsigned
3004     
3005   // Calculate 1111111111000000000000
3006   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3007   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3008 }
3009
3010 // isOneBitSet - Return true if there is exactly one bit set in the specified
3011 // constant.
3012 static bool isOneBitSet(const ConstantInt *CI) {
3013   return CI->getValue().isPowerOf2();
3014 }
3015
3016 // isHighOnes - Return true if the constant is of the form 1+0+.
3017 // This is the same as lowones(~X).
3018 static bool isHighOnes(const ConstantInt *CI) {
3019   return (~CI->getValue() + 1).isPowerOf2();
3020 }
3021
3022 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3023 /// are carefully arranged to allow folding of expressions such as:
3024 ///
3025 ///      (A < B) | (A > B) --> (A != B)
3026 ///
3027 /// Note that this is only valid if the first and second predicates have the
3028 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3029 ///
3030 /// Three bits are used to represent the condition, as follows:
3031 ///   0  A > B
3032 ///   1  A == B
3033 ///   2  A < B
3034 ///
3035 /// <=>  Value  Definition
3036 /// 000     0   Always false
3037 /// 001     1   A >  B
3038 /// 010     2   A == B
3039 /// 011     3   A >= B
3040 /// 100     4   A <  B
3041 /// 101     5   A != B
3042 /// 110     6   A <= B
3043 /// 111     7   Always true
3044 ///  
3045 static unsigned getICmpCode(const ICmpInst *ICI) {
3046   switch (ICI->getPredicate()) {
3047     // False -> 0
3048   case ICmpInst::ICMP_UGT: return 1;  // 001
3049   case ICmpInst::ICMP_SGT: return 1;  // 001
3050   case ICmpInst::ICMP_EQ:  return 2;  // 010
3051   case ICmpInst::ICMP_UGE: return 3;  // 011
3052   case ICmpInst::ICMP_SGE: return 3;  // 011
3053   case ICmpInst::ICMP_ULT: return 4;  // 100
3054   case ICmpInst::ICMP_SLT: return 4;  // 100
3055   case ICmpInst::ICMP_NE:  return 5;  // 101
3056   case ICmpInst::ICMP_ULE: return 6;  // 110
3057   case ICmpInst::ICMP_SLE: return 6;  // 110
3058     // True -> 7
3059   default:
3060     assert(0 && "Invalid ICmp predicate!");
3061     return 0;
3062   }
3063 }
3064
3065 /// getICmpValue - This is the complement of getICmpCode, which turns an
3066 /// opcode and two operands into either a constant true or false, or a brand 
3067 /// new ICmp instruction. The sign is passed in to determine which kind
3068 /// of predicate to use in new icmp instructions.
3069 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3070   switch (code) {
3071   default: assert(0 && "Illegal ICmp code!");
3072   case  0: return ConstantInt::getFalse();
3073   case  1: 
3074     if (sign)
3075       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3076     else
3077       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3078   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3079   case  3: 
3080     if (sign)
3081       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3082     else
3083       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3084   case  4: 
3085     if (sign)
3086       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3087     else
3088       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3089   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3090   case  6: 
3091     if (sign)
3092       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3093     else
3094       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3095   case  7: return ConstantInt::getTrue();
3096   }
3097 }
3098
3099 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3100   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3101     (ICmpInst::isSignedPredicate(p1) && 
3102      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3103     (ICmpInst::isSignedPredicate(p2) && 
3104      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3105 }
3106
3107 namespace { 
3108 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3109 struct FoldICmpLogical {
3110   InstCombiner &IC;
3111   Value *LHS, *RHS;
3112   ICmpInst::Predicate pred;
3113   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3114     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3115       pred(ICI->getPredicate()) {}
3116   bool shouldApply(Value *V) const {
3117     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3118       if (PredicatesFoldable(pred, ICI->getPredicate()))
3119         return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3120                 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3121     return false;
3122   }
3123   Instruction *apply(Instruction &Log) const {
3124     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3125     if (ICI->getOperand(0) != LHS) {
3126       assert(ICI->getOperand(1) == LHS);
3127       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3128     }
3129
3130     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3131     unsigned LHSCode = getICmpCode(ICI);
3132     unsigned RHSCode = getICmpCode(RHSICI);
3133     unsigned Code;
3134     switch (Log.getOpcode()) {
3135     case Instruction::And: Code = LHSCode & RHSCode; break;
3136     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3137     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3138     default: assert(0 && "Illegal logical opcode!"); return 0;
3139     }
3140
3141     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3142                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3143       
3144     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3145     if (Instruction *I = dyn_cast<Instruction>(RV))
3146       return I;
3147     // Otherwise, it's a constant boolean value...
3148     return IC.ReplaceInstUsesWith(Log, RV);
3149   }
3150 };
3151 } // end anonymous namespace
3152
3153 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3154 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3155 // guaranteed to be a binary operator.
3156 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3157                                     ConstantInt *OpRHS,
3158                                     ConstantInt *AndRHS,
3159                                     BinaryOperator &TheAnd) {
3160   Value *X = Op->getOperand(0);
3161   Constant *Together = 0;
3162   if (!Op->isShift())
3163     Together = And(AndRHS, OpRHS);
3164
3165   switch (Op->getOpcode()) {
3166   case Instruction::Xor:
3167     if (Op->hasOneUse()) {
3168       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3169       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3170       InsertNewInstBefore(And, TheAnd);
3171       And->takeName(Op);
3172       return BinaryOperator::createXor(And, Together);
3173     }
3174     break;
3175   case Instruction::Or:
3176     if (Together == AndRHS) // (X | C) & C --> C
3177       return ReplaceInstUsesWith(TheAnd, AndRHS);
3178
3179     if (Op->hasOneUse() && Together != OpRHS) {
3180       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3181       Instruction *Or = BinaryOperator::createOr(X, Together);
3182       InsertNewInstBefore(Or, TheAnd);
3183       Or->takeName(Op);
3184       return BinaryOperator::createAnd(Or, AndRHS);
3185     }
3186     break;
3187   case Instruction::Add:
3188     if (Op->hasOneUse()) {
3189       // Adding a one to a single bit bit-field should be turned into an XOR
3190       // of the bit.  First thing to check is to see if this AND is with a
3191       // single bit constant.
3192       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3193
3194       // If there is only one bit set...
3195       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3196         // Ok, at this point, we know that we are masking the result of the
3197         // ADD down to exactly one bit.  If the constant we are adding has
3198         // no bits set below this bit, then we can eliminate the ADD.
3199         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3200
3201         // Check to see if any bits below the one bit set in AndRHSV are set.
3202         if ((AddRHS & (AndRHSV-1)) == 0) {
3203           // If not, the only thing that can effect the output of the AND is
3204           // the bit specified by AndRHSV.  If that bit is set, the effect of
3205           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3206           // no effect.
3207           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3208             TheAnd.setOperand(0, X);
3209             return &TheAnd;
3210           } else {
3211             // Pull the XOR out of the AND.
3212             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3213             InsertNewInstBefore(NewAnd, TheAnd);
3214             NewAnd->takeName(Op);
3215             return BinaryOperator::createXor(NewAnd, AndRHS);
3216           }
3217         }
3218       }
3219     }
3220     break;
3221
3222   case Instruction::Shl: {
3223     // We know that the AND will not produce any of the bits shifted in, so if
3224     // the anded constant includes them, clear them now!
3225     //
3226     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3227     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3228     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3229     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3230
3231     if (CI->getValue() == ShlMask) { 
3232     // Masking out bits that the shift already masks
3233       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3234     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3235       TheAnd.setOperand(1, CI);
3236       return &TheAnd;
3237     }
3238     break;
3239   }
3240   case Instruction::LShr:
3241   {
3242     // We know that the AND will not produce any of the bits shifted in, so if
3243     // the anded constant includes them, clear them now!  This only applies to
3244     // unsigned shifts, because a signed shr may bring in set bits!
3245     //
3246     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3247     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3248     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3249     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3250
3251     if (CI->getValue() == ShrMask) {   
3252     // Masking out bits that the shift already masks.
3253       return ReplaceInstUsesWith(TheAnd, Op);
3254     } else if (CI != AndRHS) {
3255       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3256       return &TheAnd;
3257     }
3258     break;
3259   }
3260   case Instruction::AShr:
3261     // Signed shr.
3262     // See if this is shifting in some sign extension, then masking it out
3263     // with an and.
3264     if (Op->hasOneUse()) {
3265       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3266       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3267       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3268       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3269       if (C == AndRHS) {          // Masking out bits shifted in.
3270         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3271         // Make the argument unsigned.
3272         Value *ShVal = Op->getOperand(0);
3273         ShVal = InsertNewInstBefore(
3274             BinaryOperator::createLShr(ShVal, OpRHS, 
3275                                    Op->getName()), TheAnd);
3276         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3277       }
3278     }
3279     break;
3280   }
3281   return 0;
3282 }
3283
3284
3285 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3286 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3287 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3288 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3289 /// insert new instructions.
3290 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3291                                            bool isSigned, bool Inside, 
3292                                            Instruction &IB) {
3293   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3294             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3295          "Lo is not <= Hi in range emission code!");
3296     
3297   if (Inside) {
3298     if (Lo == Hi)  // Trivially false.
3299       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3300
3301     // V >= Min && V < Hi --> V < Hi
3302     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3303       ICmpInst::Predicate pred = (isSigned ? 
3304         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3305       return new ICmpInst(pred, V, Hi);
3306     }
3307
3308     // Emit V-Lo <u Hi-Lo
3309     Constant *NegLo = ConstantExpr::getNeg(Lo);
3310     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3311     InsertNewInstBefore(Add, IB);
3312     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3313     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3314   }
3315
3316   if (Lo == Hi)  // Trivially true.
3317     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3318
3319   // V < Min || V >= Hi -> V > Hi-1
3320   Hi = SubOne(cast<ConstantInt>(Hi));
3321   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3322     ICmpInst::Predicate pred = (isSigned ? 
3323         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3324     return new ICmpInst(pred, V, Hi);
3325   }
3326
3327   // Emit V-Lo >u Hi-1-Lo
3328   // Note that Hi has already had one subtracted from it, above.
3329   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3330   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3331   InsertNewInstBefore(Add, IB);
3332   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3333   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3334 }
3335
3336 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3337 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3338 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3339 // not, since all 1s are not contiguous.
3340 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3341   const APInt& V = Val->getValue();
3342   uint32_t BitWidth = Val->getType()->getBitWidth();
3343   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3344
3345   // look for the first zero bit after the run of ones
3346   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3347   // look for the first non-zero bit
3348   ME = V.getActiveBits(); 
3349   return true;
3350 }
3351
3352 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3353 /// where isSub determines whether the operator is a sub.  If we can fold one of
3354 /// the following xforms:
3355 /// 
3356 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3357 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3358 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3359 ///
3360 /// return (A +/- B).
3361 ///
3362 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3363                                         ConstantInt *Mask, bool isSub,
3364                                         Instruction &I) {
3365   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3366   if (!LHSI || LHSI->getNumOperands() != 2 ||
3367       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3368
3369   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3370
3371   switch (LHSI->getOpcode()) {
3372   default: return 0;
3373   case Instruction::And:
3374     if (And(N, Mask) == Mask) {
3375       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3376       if ((Mask->getValue().countLeadingZeros() + 
3377            Mask->getValue().countPopulation()) == 
3378           Mask->getValue().getBitWidth())
3379         break;
3380
3381       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3382       // part, we don't need any explicit masks to take them out of A.  If that
3383       // is all N is, ignore it.
3384       uint32_t MB = 0, ME = 0;
3385       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3386         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3387         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3388         if (MaskedValueIsZero(RHS, Mask))
3389           break;
3390       }
3391     }
3392     return 0;
3393   case Instruction::Or:
3394   case Instruction::Xor:
3395     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3396     if ((Mask->getValue().countLeadingZeros() + 
3397          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3398         && And(N, Mask)->isZero())
3399       break;
3400     return 0;
3401   }
3402   
3403   Instruction *New;
3404   if (isSub)
3405     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3406   else
3407     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3408   return InsertNewInstBefore(New, I);
3409 }
3410
3411 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3412   bool Changed = SimplifyCommutative(I);
3413   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3414
3415   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3416     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3417
3418   // and X, X = X
3419   if (Op0 == Op1)
3420     return ReplaceInstUsesWith(I, Op1);
3421
3422   // See if we can simplify any instructions used by the instruction whose sole 
3423   // purpose is to compute bits we don't care about.
3424   if (!isa<VectorType>(I.getType())) {
3425     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3426     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3427     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3428                              KnownZero, KnownOne))
3429       return &I;
3430   } else {
3431     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3432       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3433         return ReplaceInstUsesWith(I, I.getOperand(0));
3434     } else if (isa<ConstantAggregateZero>(Op1)) {
3435       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3436     }
3437   }
3438   
3439   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3440     const APInt& AndRHSMask = AndRHS->getValue();
3441     APInt NotAndRHS(~AndRHSMask);
3442
3443     // Optimize a variety of ((val OP C1) & C2) combinations...
3444     if (isa<BinaryOperator>(Op0)) {
3445       Instruction *Op0I = cast<Instruction>(Op0);
3446       Value *Op0LHS = Op0I->getOperand(0);
3447       Value *Op0RHS = Op0I->getOperand(1);
3448       switch (Op0I->getOpcode()) {
3449       case Instruction::Xor:
3450       case Instruction::Or:
3451         // If the mask is only needed on one incoming arm, push it up.
3452         if (Op0I->hasOneUse()) {
3453           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3454             // Not masking anything out for the LHS, move to RHS.
3455             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3456                                                    Op0RHS->getName()+".masked");
3457             InsertNewInstBefore(NewRHS, I);
3458             return BinaryOperator::create(
3459                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3460           }
3461           if (!isa<Constant>(Op0RHS) &&
3462               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3463             // Not masking anything out for the RHS, move to LHS.
3464             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3465                                                    Op0LHS->getName()+".masked");
3466             InsertNewInstBefore(NewLHS, I);
3467             return BinaryOperator::create(
3468                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3469           }
3470         }
3471
3472         break;
3473       case Instruction::Add:
3474         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3475         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3476         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3477         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3478           return BinaryOperator::createAnd(V, AndRHS);
3479         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3480           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3481         break;
3482
3483       case Instruction::Sub:
3484         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3485         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3486         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3487         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3488           return BinaryOperator::createAnd(V, AndRHS);
3489         break;
3490       }
3491
3492       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3493         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3494           return Res;
3495     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3496       // If this is an integer truncation or change from signed-to-unsigned, and
3497       // if the source is an and/or with immediate, transform it.  This
3498       // frequently occurs for bitfield accesses.
3499       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3500         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3501             CastOp->getNumOperands() == 2)
3502           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3503             if (CastOp->getOpcode() == Instruction::And) {
3504               // Change: and (cast (and X, C1) to T), C2
3505               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3506               // This will fold the two constants together, which may allow 
3507               // other simplifications.
3508               Instruction *NewCast = CastInst::createTruncOrBitCast(
3509                 CastOp->getOperand(0), I.getType(), 
3510                 CastOp->getName()+".shrunk");
3511               NewCast = InsertNewInstBefore(NewCast, I);
3512               // trunc_or_bitcast(C1)&C2
3513               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3514               C3 = ConstantExpr::getAnd(C3, AndRHS);
3515               return BinaryOperator::createAnd(NewCast, C3);
3516             } else if (CastOp->getOpcode() == Instruction::Or) {
3517               // Change: and (cast (or X, C1) to T), C2
3518               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3519               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3520               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3521                 return ReplaceInstUsesWith(I, AndRHS);
3522             }
3523       }
3524     }
3525
3526     // Try to fold constant and into select arguments.
3527     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3528       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3529         return R;
3530     if (isa<PHINode>(Op0))
3531       if (Instruction *NV = FoldOpIntoPhi(I))
3532         return NV;
3533   }
3534
3535   Value *Op0NotVal = dyn_castNotVal(Op0);
3536   Value *Op1NotVal = dyn_castNotVal(Op1);
3537
3538   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3539     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3540
3541   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3542   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3543     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3544                                                I.getName()+".demorgan");
3545     InsertNewInstBefore(Or, I);
3546     return BinaryOperator::createNot(Or);
3547   }
3548   
3549   {
3550     Value *A = 0, *B = 0, *C = 0, *D = 0;
3551     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3552       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3553         return ReplaceInstUsesWith(I, Op1);
3554     
3555       // (A|B) & ~(A&B) -> A^B
3556       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3557         if ((A == C && B == D) || (A == D && B == C))
3558           return BinaryOperator::createXor(A, B);
3559       }
3560     }
3561     
3562     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3563       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3564         return ReplaceInstUsesWith(I, Op0);
3565
3566       // ~(A&B) & (A|B) -> A^B
3567       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3568         if ((A == C && B == D) || (A == D && B == C))
3569           return BinaryOperator::createXor(A, B);
3570       }
3571     }
3572     
3573     if (Op0->hasOneUse() &&
3574         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3575       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3576         I.swapOperands();     // Simplify below
3577         std::swap(Op0, Op1);
3578       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3579         cast<BinaryOperator>(Op0)->swapOperands();
3580         I.swapOperands();     // Simplify below
3581         std::swap(Op0, Op1);
3582       }
3583     }
3584     if (Op1->hasOneUse() &&
3585         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3586       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3587         cast<BinaryOperator>(Op1)->swapOperands();
3588         std::swap(A, B);
3589       }
3590       if (A == Op0) {                                // A&(A^B) -> A & ~B
3591         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3592         InsertNewInstBefore(NotB, I);
3593         return BinaryOperator::createAnd(A, NotB);
3594       }
3595     }
3596   }
3597   
3598   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3599     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3600     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3601       return R;
3602
3603     Value *LHSVal, *RHSVal;
3604     ConstantInt *LHSCst, *RHSCst;
3605     ICmpInst::Predicate LHSCC, RHSCC;
3606     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3607       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3608         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3609             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3610             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3611             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3612             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3613             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3614             
3615             // Don't try to fold ICMP_SLT + ICMP_ULT.
3616             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3617              ICmpInst::isSignedPredicate(LHSCC) == 
3618                  ICmpInst::isSignedPredicate(RHSCC))) {
3619           // Ensure that the larger constant is on the RHS.
3620           ICmpInst::Predicate GT;
3621           if (ICmpInst::isSignedPredicate(LHSCC) ||
3622               (ICmpInst::isEquality(LHSCC) && 
3623                ICmpInst::isSignedPredicate(RHSCC)))
3624             GT = ICmpInst::ICMP_SGT;
3625           else
3626             GT = ICmpInst::ICMP_UGT;
3627           
3628           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3629           ICmpInst *LHS = cast<ICmpInst>(Op0);
3630           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3631             std::swap(LHS, RHS);
3632             std::swap(LHSCst, RHSCst);
3633             std::swap(LHSCC, RHSCC);
3634           }
3635
3636           // At this point, we know we have have two icmp instructions
3637           // comparing a value against two constants and and'ing the result
3638           // together.  Because of the above check, we know that we only have
3639           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3640           // (from the FoldICmpLogical check above), that the two constants 
3641           // are not equal and that the larger constant is on the RHS
3642           assert(LHSCst != RHSCst && "Compares not folded above?");
3643
3644           switch (LHSCC) {
3645           default: assert(0 && "Unknown integer condition code!");
3646           case ICmpInst::ICMP_EQ:
3647             switch (RHSCC) {
3648             default: assert(0 && "Unknown integer condition code!");
3649             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3650             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3651             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3652               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3653             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3654             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3655             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3656               return ReplaceInstUsesWith(I, LHS);
3657             }
3658           case ICmpInst::ICMP_NE:
3659             switch (RHSCC) {
3660             default: assert(0 && "Unknown integer condition code!");
3661             case ICmpInst::ICMP_ULT:
3662               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3663                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3664               break;                        // (X != 13 & X u< 15) -> no change
3665             case ICmpInst::ICMP_SLT:
3666               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3667                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3668               break;                        // (X != 13 & X s< 15) -> no change
3669             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3670             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3671             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3672               return ReplaceInstUsesWith(I, RHS);
3673             case ICmpInst::ICMP_NE:
3674               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3675                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3676                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3677                                                       LHSVal->getName()+".off");
3678                 InsertNewInstBefore(Add, I);
3679                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3680                                     ConstantInt::get(Add->getType(), 1));
3681               }
3682               break;                        // (X != 13 & X != 15) -> no change
3683             }
3684             break;
3685           case ICmpInst::ICMP_ULT:
3686             switch (RHSCC) {
3687             default: assert(0 && "Unknown integer condition code!");
3688             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3689             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3690               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3691             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3692               break;
3693             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3694             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3695               return ReplaceInstUsesWith(I, LHS);
3696             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3697               break;
3698             }
3699             break;
3700           case ICmpInst::ICMP_SLT:
3701             switch (RHSCC) {
3702             default: assert(0 && "Unknown integer condition code!");
3703             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3704             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3705               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3706             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3707               break;
3708             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3709             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3710               return ReplaceInstUsesWith(I, LHS);
3711             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3712               break;
3713             }
3714             break;
3715           case ICmpInst::ICMP_UGT:
3716             switch (RHSCC) {
3717             default: assert(0 && "Unknown integer condition code!");
3718             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3719               return ReplaceInstUsesWith(I, LHS);
3720             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3721               return ReplaceInstUsesWith(I, RHS);
3722             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3723               break;
3724             case ICmpInst::ICMP_NE:
3725               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3726                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3727               break;                        // (X u> 13 & X != 15) -> no change
3728             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3729               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3730                                      true, I);
3731             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3732               break;
3733             }
3734             break;
3735           case ICmpInst::ICMP_SGT:
3736             switch (RHSCC) {
3737             default: assert(0 && "Unknown integer condition code!");
3738             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3739             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3740               return ReplaceInstUsesWith(I, RHS);
3741             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3742               break;
3743             case ICmpInst::ICMP_NE:
3744               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3745                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3746               break;                        // (X s> 13 & X != 15) -> no change
3747             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3748               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3749                                      true, I);
3750             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3751               break;
3752             }
3753             break;
3754           }
3755         }
3756   }
3757
3758   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3759   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3760     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3761       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3762         const Type *SrcTy = Op0C->getOperand(0)->getType();
3763         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3764             // Only do this if the casts both really cause code to be generated.
3765             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3766                               I.getType(), TD) &&
3767             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3768                               I.getType(), TD)) {
3769           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3770                                                          Op1C->getOperand(0),
3771                                                          I.getName());
3772           InsertNewInstBefore(NewOp, I);
3773           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3774         }
3775       }
3776     
3777   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3778   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3779     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3780       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3781           SI0->getOperand(1) == SI1->getOperand(1) &&
3782           (SI0->hasOneUse() || SI1->hasOneUse())) {
3783         Instruction *NewOp =
3784           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3785                                                         SI1->getOperand(0),
3786                                                         SI0->getName()), I);
3787         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
3788                                       SI1->getOperand(1));
3789       }
3790   }
3791
3792   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3793   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3794     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3795       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3796           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3797         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3798           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3799             // If either of the constants are nans, then the whole thing returns
3800             // false.
3801             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3802               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3803             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3804                                 RHS->getOperand(0));
3805           }
3806     }
3807   }
3808       
3809   return Changed ? &I : 0;
3810 }
3811
3812 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3813 /// in the result.  If it does, and if the specified byte hasn't been filled in
3814 /// yet, fill it in and return false.
3815 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3816   Instruction *I = dyn_cast<Instruction>(V);
3817   if (I == 0) return true;
3818
3819   // If this is an or instruction, it is an inner node of the bswap.
3820   if (I->getOpcode() == Instruction::Or)
3821     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3822            CollectBSwapParts(I->getOperand(1), ByteValues);
3823   
3824   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3825   // If this is a shift by a constant int, and it is "24", then its operand
3826   // defines a byte.  We only handle unsigned types here.
3827   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3828     // Not shifting the entire input by N-1 bytes?
3829     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3830         8*(ByteValues.size()-1))
3831       return true;
3832     
3833     unsigned DestNo;
3834     if (I->getOpcode() == Instruction::Shl) {
3835       // X << 24 defines the top byte with the lowest of the input bytes.
3836       DestNo = ByteValues.size()-1;
3837     } else {
3838       // X >>u 24 defines the low byte with the highest of the input bytes.
3839       DestNo = 0;
3840     }
3841     
3842     // If the destination byte value is already defined, the values are or'd
3843     // together, which isn't a bswap (unless it's an or of the same bits).
3844     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3845       return true;
3846     ByteValues[DestNo] = I->getOperand(0);
3847     return false;
3848   }
3849   
3850   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3851   // don't have this.
3852   Value *Shift = 0, *ShiftLHS = 0;
3853   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3854   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3855       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3856     return true;
3857   Instruction *SI = cast<Instruction>(Shift);
3858
3859   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3860   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3861       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3862     return true;
3863   
3864   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3865   unsigned DestByte;
3866   if (AndAmt->getValue().getActiveBits() > 64)
3867     return true;
3868   uint64_t AndAmtVal = AndAmt->getZExtValue();
3869   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3870     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3871       break;
3872   // Unknown mask for bswap.
3873   if (DestByte == ByteValues.size()) return true;
3874   
3875   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3876   unsigned SrcByte;
3877   if (SI->getOpcode() == Instruction::Shl)
3878     SrcByte = DestByte - ShiftBytes;
3879   else
3880     SrcByte = DestByte + ShiftBytes;
3881   
3882   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3883   if (SrcByte != ByteValues.size()-DestByte-1)
3884     return true;
3885   
3886   // If the destination byte value is already defined, the values are or'd
3887   // together, which isn't a bswap (unless it's an or of the same bits).
3888   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3889     return true;
3890   ByteValues[DestByte] = SI->getOperand(0);
3891   return false;
3892 }
3893
3894 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3895 /// If so, insert the new bswap intrinsic and return it.
3896 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3897   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3898   if (!ITy || ITy->getBitWidth() % 16) 
3899     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3900   
3901   /// ByteValues - For each byte of the result, we keep track of which value
3902   /// defines each byte.
3903   SmallVector<Value*, 8> ByteValues;
3904   ByteValues.resize(ITy->getBitWidth()/8);
3905     
3906   // Try to find all the pieces corresponding to the bswap.
3907   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3908       CollectBSwapParts(I.getOperand(1), ByteValues))
3909     return 0;
3910   
3911   // Check to see if all of the bytes come from the same value.
3912   Value *V = ByteValues[0];
3913   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3914   
3915   // Check to make sure that all of the bytes come from the same value.
3916   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3917     if (ByteValues[i] != V)
3918       return 0;
3919   const Type *Tys[] = { ITy };
3920   Module *M = I.getParent()->getParent()->getParent();
3921   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3922   return new CallInst(F, V);
3923 }
3924
3925
3926 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3927   bool Changed = SimplifyCommutative(I);
3928   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3929
3930   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3931     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3932
3933   // or X, X = X
3934   if (Op0 == Op1)
3935     return ReplaceInstUsesWith(I, Op0);
3936
3937   // See if we can simplify any instructions used by the instruction whose sole 
3938   // purpose is to compute bits we don't care about.
3939   if (!isa<VectorType>(I.getType())) {
3940     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3941     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3942     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3943                              KnownZero, KnownOne))
3944       return &I;
3945   } else if (isa<ConstantAggregateZero>(Op1)) {
3946     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3947   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3948     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3949       return ReplaceInstUsesWith(I, I.getOperand(1));
3950   }
3951     
3952
3953   
3954   // or X, -1 == -1
3955   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3956     ConstantInt *C1 = 0; Value *X = 0;
3957     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3958     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3959       Instruction *Or = BinaryOperator::createOr(X, RHS);
3960       InsertNewInstBefore(Or, I);
3961       Or->takeName(Op0);
3962       return BinaryOperator::createAnd(Or, 
3963                ConstantInt::get(RHS->getValue() | C1->getValue()));
3964     }
3965
3966     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3967     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3968       Instruction *Or = BinaryOperator::createOr(X, RHS);
3969       InsertNewInstBefore(Or, I);
3970       Or->takeName(Op0);
3971       return BinaryOperator::createXor(Or,
3972                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3973     }
3974
3975     // Try to fold constant and into select arguments.
3976     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3977       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3978         return R;
3979     if (isa<PHINode>(Op0))
3980       if (Instruction *NV = FoldOpIntoPhi(I))
3981         return NV;
3982   }
3983
3984   Value *A = 0, *B = 0;
3985   ConstantInt *C1 = 0, *C2 = 0;
3986
3987   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3988     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3989       return ReplaceInstUsesWith(I, Op1);
3990   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3991     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3992       return ReplaceInstUsesWith(I, Op0);
3993
3994   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3995   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3996   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3997       match(Op1, m_Or(m_Value(), m_Value())) ||
3998       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3999        match(Op1, m_Shift(m_Value(), m_Value())))) {
4000     if (Instruction *BSwap = MatchBSwap(I))
4001       return BSwap;
4002   }
4003   
4004   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4005   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4006       MaskedValueIsZero(Op1, C1->getValue())) {
4007     Instruction *NOr = BinaryOperator::createOr(A, Op1);
4008     InsertNewInstBefore(NOr, I);
4009     NOr->takeName(Op0);
4010     return BinaryOperator::createXor(NOr, C1);
4011   }
4012
4013   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4014   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4015       MaskedValueIsZero(Op0, C1->getValue())) {
4016     Instruction *NOr = BinaryOperator::createOr(A, Op0);
4017     InsertNewInstBefore(NOr, I);
4018     NOr->takeName(Op0);
4019     return BinaryOperator::createXor(NOr, C1);
4020   }
4021
4022   // (A & C)|(B & D)
4023   Value *C = 0, *D = 0;
4024   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4025       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4026     Value *V1 = 0, *V2 = 0, *V3 = 0;
4027     C1 = dyn_cast<ConstantInt>(C);
4028     C2 = dyn_cast<ConstantInt>(D);
4029     if (C1 && C2) {  // (A & C1)|(B & C2)
4030       // If we have: ((V + N) & C1) | (V & C2)
4031       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4032       // replace with V+N.
4033       if (C1->getValue() == ~C2->getValue()) {
4034         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4035             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4036           // Add commutes, try both ways.
4037           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4038             return ReplaceInstUsesWith(I, A);
4039           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4040             return ReplaceInstUsesWith(I, A);
4041         }
4042         // Or commutes, try both ways.
4043         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4044             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4045           // Add commutes, try both ways.
4046           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4047             return ReplaceInstUsesWith(I, B);
4048           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4049             return ReplaceInstUsesWith(I, B);
4050         }
4051       }
4052       V1 = 0; V2 = 0; V3 = 0;
4053     }
4054     
4055     // Check to see if we have any common things being and'ed.  If so, find the
4056     // terms for V1 & (V2|V3).
4057     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4058       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4059         V1 = A, V2 = C, V3 = D;
4060       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4061         V1 = A, V2 = B, V3 = C;
4062       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4063         V1 = C, V2 = A, V3 = D;
4064       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4065         V1 = C, V2 = A, V3 = B;
4066       
4067       if (V1) {
4068         Value *Or =
4069           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4070         return BinaryOperator::createAnd(V1, Or);
4071       }
4072     }
4073   }
4074   
4075   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4076   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4077     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4078       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4079           SI0->getOperand(1) == SI1->getOperand(1) &&
4080           (SI0->hasOneUse() || SI1->hasOneUse())) {
4081         Instruction *NewOp =
4082         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4083                                                      SI1->getOperand(0),
4084                                                      SI0->getName()), I);
4085         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4086                                       SI1->getOperand(1));
4087       }
4088   }
4089
4090   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4091     if (A == Op1)   // ~A | A == -1
4092       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4093   } else {
4094     A = 0;
4095   }
4096   // Note, A is still live here!
4097   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4098     if (Op0 == B)
4099       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4100
4101     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4102     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4103       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4104                                               I.getName()+".demorgan"), I);
4105       return BinaryOperator::createNot(And);
4106     }
4107   }
4108
4109   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4110   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4111     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4112       return R;
4113
4114     Value *LHSVal, *RHSVal;
4115     ConstantInt *LHSCst, *RHSCst;
4116     ICmpInst::Predicate LHSCC, RHSCC;
4117     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4118       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4119         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4120             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4121             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4122             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4123             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4124             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4125             // We can't fold (ugt x, C) | (sgt x, C2).
4126             PredicatesFoldable(LHSCC, RHSCC)) {
4127           // Ensure that the larger constant is on the RHS.
4128           ICmpInst *LHS = cast<ICmpInst>(Op0);
4129           bool NeedsSwap;
4130           if (ICmpInst::isSignedPredicate(LHSCC))
4131             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4132           else
4133             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4134             
4135           if (NeedsSwap) {
4136             std::swap(LHS, RHS);
4137             std::swap(LHSCst, RHSCst);
4138             std::swap(LHSCC, RHSCC);
4139           }
4140
4141           // At this point, we know we have have two icmp instructions
4142           // comparing a value against two constants and or'ing the result
4143           // together.  Because of the above check, we know that we only have
4144           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4145           // FoldICmpLogical check above), that the two constants are not
4146           // equal.
4147           assert(LHSCst != RHSCst && "Compares not folded above?");
4148
4149           switch (LHSCC) {
4150           default: assert(0 && "Unknown integer condition code!");
4151           case ICmpInst::ICMP_EQ:
4152             switch (RHSCC) {
4153             default: assert(0 && "Unknown integer condition code!");
4154             case ICmpInst::ICMP_EQ:
4155               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4156                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4157                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4158                                                       LHSVal->getName()+".off");
4159                 InsertNewInstBefore(Add, I);
4160                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4161                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4162               }
4163               break;                         // (X == 13 | X == 15) -> no change
4164             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4165             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4166               break;
4167             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4168             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4169             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4170               return ReplaceInstUsesWith(I, RHS);
4171             }
4172             break;
4173           case ICmpInst::ICMP_NE:
4174             switch (RHSCC) {
4175             default: assert(0 && "Unknown integer condition code!");
4176             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4177             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4178             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4179               return ReplaceInstUsesWith(I, LHS);
4180             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4181             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4182             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4183               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4184             }
4185             break;
4186           case ICmpInst::ICMP_ULT:
4187             switch (RHSCC) {
4188             default: assert(0 && "Unknown integer condition code!");
4189             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4190               break;
4191             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4192               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4193               // this can cause overflow.
4194               if (RHSCst->isMaxValue(false))
4195                 return ReplaceInstUsesWith(I, LHS);
4196               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4197                                      false, I);
4198             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4199               break;
4200             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4201             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4202               return ReplaceInstUsesWith(I, RHS);
4203             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4204               break;
4205             }
4206             break;
4207           case ICmpInst::ICMP_SLT:
4208             switch (RHSCC) {
4209             default: assert(0 && "Unknown integer condition code!");
4210             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4211               break;
4212             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4213               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4214               // this can cause overflow.
4215               if (RHSCst->isMaxValue(true))
4216                 return ReplaceInstUsesWith(I, LHS);
4217               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4218                                      false, I);
4219             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4220               break;
4221             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4222             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4223               return ReplaceInstUsesWith(I, RHS);
4224             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4225               break;
4226             }
4227             break;
4228           case ICmpInst::ICMP_UGT:
4229             switch (RHSCC) {
4230             default: assert(0 && "Unknown integer condition code!");
4231             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4232             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4233               return ReplaceInstUsesWith(I, LHS);
4234             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4235               break;
4236             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4237             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4238               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4239             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4240               break;
4241             }
4242             break;
4243           case ICmpInst::ICMP_SGT:
4244             switch (RHSCC) {
4245             default: assert(0 && "Unknown integer condition code!");
4246             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4247             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4248               return ReplaceInstUsesWith(I, LHS);
4249             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4250               break;
4251             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4252             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4253               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4254             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4255               break;
4256             }
4257             break;
4258           }
4259         }
4260   }
4261     
4262   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4263   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4264     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4265       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4266         const Type *SrcTy = Op0C->getOperand(0)->getType();
4267         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4268             // Only do this if the casts both really cause code to be generated.
4269             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4270                               I.getType(), TD) &&
4271             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4272                               I.getType(), TD)) {
4273           Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4274                                                         Op1C->getOperand(0),
4275                                                         I.getName());
4276           InsertNewInstBefore(NewOp, I);
4277           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4278         }
4279       }
4280   }
4281   
4282     
4283   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4284   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4285     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4286       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4287           RHS->getPredicate() == FCmpInst::FCMP_UNO)
4288         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4289           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4290             // If either of the constants are nans, then the whole thing returns
4291             // true.
4292             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4293               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4294             
4295             // Otherwise, no need to compare the two constants, compare the
4296             // rest.
4297             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4298                                 RHS->getOperand(0));
4299           }
4300     }
4301   }
4302
4303   return Changed ? &I : 0;
4304 }
4305
4306 // XorSelf - Implements: X ^ X --> 0
4307 struct XorSelf {
4308   Value *RHS;
4309   XorSelf(Value *rhs) : RHS(rhs) {}
4310   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4311   Instruction *apply(BinaryOperator &Xor) const {
4312     return &Xor;
4313   }
4314 };
4315
4316
4317 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4318   bool Changed = SimplifyCommutative(I);
4319   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4320
4321   if (isa<UndefValue>(Op1))
4322     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4323
4324   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4325   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4326     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4327     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4328   }
4329   
4330   // See if we can simplify any instructions used by the instruction whose sole 
4331   // purpose is to compute bits we don't care about.
4332   if (!isa<VectorType>(I.getType())) {
4333     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4334     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4335     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4336                              KnownZero, KnownOne))
4337       return &I;
4338   } else if (isa<ConstantAggregateZero>(Op1)) {
4339     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4340   }
4341
4342   // Is this a ~ operation?
4343   if (Value *NotOp = dyn_castNotVal(&I)) {
4344     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4345     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4346     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4347       if (Op0I->getOpcode() == Instruction::And || 
4348           Op0I->getOpcode() == Instruction::Or) {
4349         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4350         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4351           Instruction *NotY =
4352             BinaryOperator::createNot(Op0I->getOperand(1),
4353                                       Op0I->getOperand(1)->getName()+".not");
4354           InsertNewInstBefore(NotY, I);
4355           if (Op0I->getOpcode() == Instruction::And)
4356             return BinaryOperator::createOr(Op0NotVal, NotY);
4357           else
4358             return BinaryOperator::createAnd(Op0NotVal, NotY);
4359         }
4360       }
4361     }
4362   }
4363   
4364   
4365   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4366     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4367     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4368       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4369         return new ICmpInst(ICI->getInversePredicate(),
4370                             ICI->getOperand(0), ICI->getOperand(1));
4371
4372       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4373         return new FCmpInst(FCI->getInversePredicate(),
4374                             FCI->getOperand(0), FCI->getOperand(1));
4375     }
4376
4377     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4378       // ~(c-X) == X-c-1 == X+(-c-1)
4379       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4380         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4381           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4382           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4383                                               ConstantInt::get(I.getType(), 1));
4384           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4385         }
4386           
4387       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4388         if (Op0I->getOpcode() == Instruction::Add) {
4389           // ~(X-c) --> (-c-1)-X
4390           if (RHS->isAllOnesValue()) {
4391             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4392             return BinaryOperator::createSub(
4393                            ConstantExpr::getSub(NegOp0CI,
4394                                              ConstantInt::get(I.getType(), 1)),
4395                                           Op0I->getOperand(0));
4396           } else if (RHS->getValue().isSignBit()) {
4397             // (X + C) ^ signbit -> (X + C + signbit)
4398             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4399             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4400
4401           }
4402         } else if (Op0I->getOpcode() == Instruction::Or) {
4403           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4404           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4405             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4406             // Anything in both C1 and C2 is known to be zero, remove it from
4407             // NewRHS.
4408             Constant *CommonBits = And(Op0CI, RHS);
4409             NewRHS = ConstantExpr::getAnd(NewRHS, 
4410                                           ConstantExpr::getNot(CommonBits));
4411             AddToWorkList(Op0I);
4412             I.setOperand(0, Op0I->getOperand(0));
4413             I.setOperand(1, NewRHS);
4414             return &I;
4415           }
4416         }
4417     }
4418
4419     // Try to fold constant and into select arguments.
4420     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4421       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4422         return R;
4423     if (isa<PHINode>(Op0))
4424       if (Instruction *NV = FoldOpIntoPhi(I))
4425         return NV;
4426   }
4427
4428   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4429     if (X == Op1)
4430       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4431
4432   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4433     if (X == Op0)
4434       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4435
4436   
4437   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4438   if (Op1I) {
4439     Value *A, *B;
4440     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4441       if (A == Op0) {              // B^(B|A) == (A|B)^B
4442         Op1I->swapOperands();
4443         I.swapOperands();
4444         std::swap(Op0, Op1);
4445       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4446         I.swapOperands();     // Simplified below.
4447         std::swap(Op0, Op1);
4448       }
4449     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4450       if (Op0 == A)                                          // A^(A^B) == B
4451         return ReplaceInstUsesWith(I, B);
4452       else if (Op0 == B)                                     // A^(B^A) == B
4453         return ReplaceInstUsesWith(I, A);
4454     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4455       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4456         Op1I->swapOperands();
4457         std::swap(A, B);
4458       }
4459       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4460         I.swapOperands();     // Simplified below.
4461         std::swap(Op0, Op1);
4462       }
4463     }
4464   }
4465   
4466   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4467   if (Op0I) {
4468     Value *A, *B;
4469     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4470       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4471         std::swap(A, B);
4472       if (B == Op1) {                                // (A|B)^B == A & ~B
4473         Instruction *NotB =
4474           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4475         return BinaryOperator::createAnd(A, NotB);
4476       }
4477     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4478       if (Op1 == A)                                          // (A^B)^A == B
4479         return ReplaceInstUsesWith(I, B);
4480       else if (Op1 == B)                                     // (B^A)^A == B
4481         return ReplaceInstUsesWith(I, A);
4482     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4483       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4484         std::swap(A, B);
4485       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4486           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4487         Instruction *N =
4488           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4489         return BinaryOperator::createAnd(N, Op1);
4490       }
4491     }
4492   }
4493   
4494   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4495   if (Op0I && Op1I && Op0I->isShift() && 
4496       Op0I->getOpcode() == Op1I->getOpcode() && 
4497       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4498       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4499     Instruction *NewOp =
4500       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4501                                                     Op1I->getOperand(0),
4502                                                     Op0I->getName()), I);
4503     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4504                                   Op1I->getOperand(1));
4505   }
4506     
4507   if (Op0I && Op1I) {
4508     Value *A, *B, *C, *D;
4509     // (A & B)^(A | B) -> A ^ B
4510     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4511         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4512       if ((A == C && B == D) || (A == D && B == C)) 
4513         return BinaryOperator::createXor(A, B);
4514     }
4515     // (A | B)^(A & B) -> A ^ B
4516     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4517         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4518       if ((A == C && B == D) || (A == D && B == C)) 
4519         return BinaryOperator::createXor(A, B);
4520     }
4521     
4522     // (A & B)^(C & D)
4523     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4524         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4525         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4526       // (X & Y)^(X & Y) -> (Y^Z) & X
4527       Value *X = 0, *Y = 0, *Z = 0;
4528       if (A == C)
4529         X = A, Y = B, Z = D;
4530       else if (A == D)
4531         X = A, Y = B, Z = C;
4532       else if (B == C)
4533         X = B, Y = A, Z = D;
4534       else if (B == D)
4535         X = B, Y = A, Z = C;
4536       
4537       if (X) {
4538         Instruction *NewOp =
4539         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4540         return BinaryOperator::createAnd(NewOp, X);
4541       }
4542     }
4543   }
4544     
4545   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4546   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4547     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4548       return R;
4549
4550   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4551   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4552     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4553       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4554         const Type *SrcTy = Op0C->getOperand(0)->getType();
4555         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4556             // Only do this if the casts both really cause code to be generated.
4557             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4558                               I.getType(), TD) &&
4559             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4560                               I.getType(), TD)) {
4561           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4562                                                          Op1C->getOperand(0),
4563                                                          I.getName());
4564           InsertNewInstBefore(NewOp, I);
4565           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4566         }
4567       }
4568   }
4569   return Changed ? &I : 0;
4570 }
4571
4572 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4573 /// overflowed for this type.
4574 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4575                             ConstantInt *In2, bool IsSigned = false) {
4576   Result = cast<ConstantInt>(Add(In1, In2));
4577
4578   if (IsSigned)
4579     if (In2->getValue().isNegative())
4580       return Result->getValue().sgt(In1->getValue());
4581     else
4582       return Result->getValue().slt(In1->getValue());
4583   else
4584     return Result->getValue().ult(In1->getValue());
4585 }
4586
4587 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4588 /// code necessary to compute the offset from the base pointer (without adding
4589 /// in the base pointer).  Return the result as a signed integer of intptr size.
4590 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4591   TargetData &TD = IC.getTargetData();
4592   gep_type_iterator GTI = gep_type_begin(GEP);
4593   const Type *IntPtrTy = TD.getIntPtrType();
4594   Value *Result = Constant::getNullValue(IntPtrTy);
4595
4596   // Build a mask for high order bits.
4597   unsigned IntPtrWidth = TD.getPointerSize()*8;
4598   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4599
4600   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4601     Value *Op = GEP->getOperand(i);
4602     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4603     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4604       if (OpC->isZero()) continue;
4605       
4606       // Handle a struct index, which adds its field offset to the pointer.
4607       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4608         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4609         
4610         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4611           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4612         else
4613           Result = IC.InsertNewInstBefore(
4614                    BinaryOperator::createAdd(Result,
4615                                              ConstantInt::get(IntPtrTy, Size),
4616                                              GEP->getName()+".offs"), I);
4617         continue;
4618       }
4619       
4620       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4621       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4622       Scale = ConstantExpr::getMul(OC, Scale);
4623       if (Constant *RC = dyn_cast<Constant>(Result))
4624         Result = ConstantExpr::getAdd(RC, Scale);
4625       else {
4626         // Emit an add instruction.
4627         Result = IC.InsertNewInstBefore(
4628            BinaryOperator::createAdd(Result, Scale,
4629                                      GEP->getName()+".offs"), I);
4630       }
4631       continue;
4632     }
4633     // Convert to correct type.
4634     if (Op->getType() != IntPtrTy) {
4635       if (Constant *OpC = dyn_cast<Constant>(Op))
4636         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4637       else
4638         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4639                                                  Op->getName()+".c"), I);
4640     }
4641     if (Size != 1) {
4642       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4643       if (Constant *OpC = dyn_cast<Constant>(Op))
4644         Op = ConstantExpr::getMul(OpC, Scale);
4645       else    // We'll let instcombine(mul) convert this to a shl if possible.
4646         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4647                                                   GEP->getName()+".idx"), I);
4648     }
4649
4650     // Emit an add instruction.
4651     if (isa<Constant>(Op) && isa<Constant>(Result))
4652       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4653                                     cast<Constant>(Result));
4654     else
4655       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4656                                                   GEP->getName()+".offs"), I);
4657   }
4658   return Result;
4659 }
4660
4661 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4662 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4663 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4664                                        ICmpInst::Predicate Cond,
4665                                        Instruction &I) {
4666   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4667
4668   if (CastInst *CI = dyn_cast<CastInst>(RHS))
4669     if (isa<PointerType>(CI->getOperand(0)->getType()))
4670       RHS = CI->getOperand(0);
4671
4672   Value *PtrBase = GEPLHS->getOperand(0);
4673   if (PtrBase == RHS) {
4674     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4675     // This transformation is valid because we know pointers can't overflow.
4676     Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4677     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4678                         Constant::getNullValue(Offset->getType()));
4679   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4680     // If the base pointers are different, but the indices are the same, just
4681     // compare the base pointer.
4682     if (PtrBase != GEPRHS->getOperand(0)) {
4683       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4684       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4685                         GEPRHS->getOperand(0)->getType();
4686       if (IndicesTheSame)
4687         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4688           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4689             IndicesTheSame = false;
4690             break;
4691           }
4692
4693       // If all indices are the same, just compare the base pointers.
4694       if (IndicesTheSame)
4695         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4696                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4697
4698       // Otherwise, the base pointers are different and the indices are
4699       // different, bail out.
4700       return 0;
4701     }
4702
4703     // If one of the GEPs has all zero indices, recurse.
4704     bool AllZeros = true;
4705     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4706       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4707           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4708         AllZeros = false;
4709         break;
4710       }
4711     if (AllZeros)
4712       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4713                           ICmpInst::getSwappedPredicate(Cond), I);
4714
4715     // If the other GEP has all zero indices, recurse.
4716     AllZeros = true;
4717     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4718       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4719           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4720         AllZeros = false;
4721         break;
4722       }
4723     if (AllZeros)
4724       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4725
4726     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4727       // If the GEPs only differ by one index, compare it.
4728       unsigned NumDifferences = 0;  // Keep track of # differences.
4729       unsigned DiffOperand = 0;     // The operand that differs.
4730       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4731         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4732           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4733                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4734             // Irreconcilable differences.
4735             NumDifferences = 2;
4736             break;
4737           } else {
4738             if (NumDifferences++) break;
4739             DiffOperand = i;
4740           }
4741         }
4742
4743       if (NumDifferences == 0)   // SAME GEP?
4744         return ReplaceInstUsesWith(I, // No comparison is needed here.
4745                                    ConstantInt::get(Type::Int1Ty,
4746                                                     isTrueWhenEqual(Cond)));
4747
4748       else if (NumDifferences == 1) {
4749         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4750         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4751         // Make sure we do a signed comparison here.
4752         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4753       }
4754     }
4755
4756     // Only lower this if the icmp is the only user of the GEP or if we expect
4757     // the result to fold to a constant!
4758     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4759         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4760       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4761       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4762       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4763       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4764     }
4765   }
4766   return 0;
4767 }
4768
4769 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4770   bool Changed = SimplifyCompare(I);
4771   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4772
4773   // Fold trivial predicates.
4774   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4775     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4776   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4777     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4778   
4779   // Simplify 'fcmp pred X, X'
4780   if (Op0 == Op1) {
4781     switch (I.getPredicate()) {
4782     default: assert(0 && "Unknown predicate!");
4783     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
4784     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
4785     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
4786       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4787     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
4788     case FCmpInst::FCMP_OLT:    // True if ordered and less than
4789     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
4790       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4791       
4792     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
4793     case FCmpInst::FCMP_ULT:    // True if unordered or less than
4794     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
4795     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
4796       // Canonicalize these to be 'fcmp uno %X, 0.0'.
4797       I.setPredicate(FCmpInst::FCMP_UNO);
4798       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4799       return &I;
4800       
4801     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
4802     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
4803     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
4804     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
4805       // Canonicalize these to be 'fcmp ord %X, 0.0'.
4806       I.setPredicate(FCmpInst::FCMP_ORD);
4807       I.setOperand(1, Constant::getNullValue(Op0->getType()));
4808       return &I;
4809     }
4810   }
4811     
4812   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
4813     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4814
4815   // Handle fcmp with constant RHS
4816   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4817     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4818       switch (LHSI->getOpcode()) {
4819       case Instruction::PHI:
4820         if (Instruction *NV = FoldOpIntoPhi(I))
4821           return NV;
4822         break;
4823       case Instruction::Select:
4824         // If either operand of the select is a constant, we can fold the
4825         // comparison into the select arms, which will cause one to be
4826         // constant folded and the select turned into a bitwise or.
4827         Value *Op1 = 0, *Op2 = 0;
4828         if (LHSI->hasOneUse()) {
4829           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4830             // Fold the known value into the constant operand.
4831             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4832             // Insert a new FCmp of the other select operand.
4833             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4834                                                       LHSI->getOperand(2), RHSC,
4835                                                       I.getName()), I);
4836           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4837             // Fold the known value into the constant operand.
4838             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4839             // Insert a new FCmp of the other select operand.
4840             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4841                                                       LHSI->getOperand(1), RHSC,
4842                                                       I.getName()), I);
4843           }
4844         }
4845
4846         if (Op1)
4847           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4848         break;
4849       }
4850   }
4851
4852   return Changed ? &I : 0;
4853 }
4854
4855 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4856   bool Changed = SimplifyCompare(I);
4857   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4858   const Type *Ty = Op0->getType();
4859
4860   // icmp X, X
4861   if (Op0 == Op1)
4862     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4863                                                    isTrueWhenEqual(I)));
4864
4865   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
4866     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4867   
4868   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4869   // addresses never equal each other!  We already know that Op0 != Op1.
4870   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4871        isa<ConstantPointerNull>(Op0)) &&
4872       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4873        isa<ConstantPointerNull>(Op1)))
4874     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
4875                                                    !isTrueWhenEqual(I)));
4876
4877   // icmp's with boolean values can always be turned into bitwise operations
4878   if (Ty == Type::Int1Ty) {
4879     switch (I.getPredicate()) {
4880     default: assert(0 && "Invalid icmp instruction!");
4881     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
4882       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4883       InsertNewInstBefore(Xor, I);
4884       return BinaryOperator::createNot(Xor);
4885     }
4886     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
4887       return BinaryOperator::createXor(Op0, Op1);
4888
4889     case ICmpInst::ICMP_UGT:
4890     case ICmpInst::ICMP_SGT:
4891       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
4892       // FALL THROUGH
4893     case ICmpInst::ICMP_ULT:
4894     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
4895       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4896       InsertNewInstBefore(Not, I);
4897       return BinaryOperator::createAnd(Not, Op1);
4898     }
4899     case ICmpInst::ICMP_UGE:
4900     case ICmpInst::ICMP_SGE:
4901       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
4902       // FALL THROUGH
4903     case ICmpInst::ICMP_ULE:
4904     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
4905       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4906       InsertNewInstBefore(Not, I);
4907       return BinaryOperator::createOr(Not, Op1);
4908     }
4909     }
4910   }
4911
4912   // See if we are doing a comparison between a constant and an instruction that
4913   // can be folded into the comparison.
4914   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4915       Value *A, *B;
4916     
4917     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4918     if (I.isEquality() && CI->isNullValue() &&
4919         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4920       // (icmp cond A B) if cond is equality
4921       return new ICmpInst(I.getPredicate(), A, B);
4922     }
4923     
4924     switch (I.getPredicate()) {
4925     default: break;
4926     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
4927       if (CI->isMinValue(false))
4928         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4929       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
4930         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4931       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
4932         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4933       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
4934       if (CI->isMinValue(true))
4935         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4936                             ConstantInt::getAllOnesValue(Op0->getType()));
4937           
4938       break;
4939
4940     case ICmpInst::ICMP_SLT:
4941       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
4942         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4943       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
4944         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4945       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
4946         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4947       break;
4948
4949     case ICmpInst::ICMP_UGT:
4950       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
4951         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4952       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
4953         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4954       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
4955         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4956         
4957       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
4958       if (CI->isMaxValue(true))
4959         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4960                             ConstantInt::getNullValue(Op0->getType()));
4961       break;
4962
4963     case ICmpInst::ICMP_SGT:
4964       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
4965         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4966       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
4967         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4968       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
4969         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4970       break;
4971
4972     case ICmpInst::ICMP_ULE:
4973       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
4974         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4975       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
4976         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4977       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
4978         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4979       break;
4980
4981     case ICmpInst::ICMP_SLE:
4982       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
4983         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4984       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
4985         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4986       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
4987         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4988       break;
4989
4990     case ICmpInst::ICMP_UGE:
4991       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
4992         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4993       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
4994         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4995       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
4996         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4997       break;
4998
4999     case ICmpInst::ICMP_SGE:
5000       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5001         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5002       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5003         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5004       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5005         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5006       break;
5007     }
5008
5009     // If we still have a icmp le or icmp ge instruction, turn it into the
5010     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5011     // already been handled above, this requires little checking.
5012     //
5013     switch (I.getPredicate()) {
5014     default: break;
5015     case ICmpInst::ICMP_ULE: 
5016       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5017     case ICmpInst::ICMP_SLE:
5018       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5019     case ICmpInst::ICMP_UGE:
5020       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5021     case ICmpInst::ICMP_SGE:
5022       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5023     }
5024     
5025     // See if we can fold the comparison based on bits known to be zero or one
5026     // in the input.  If this comparison is a normal comparison, it demands all
5027     // bits, if it is a sign bit comparison, it only demands the sign bit.
5028     
5029     bool UnusedBit;
5030     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5031     
5032     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5033     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5034     if (SimplifyDemandedBits(Op0, 
5035                              isSignBit ? APInt::getSignBit(BitWidth)
5036                                        : APInt::getAllOnesValue(BitWidth),
5037                              KnownZero, KnownOne, 0))
5038       return &I;
5039         
5040     // Given the known and unknown bits, compute a range that the LHS could be
5041     // in.
5042     if ((KnownOne | KnownZero) != 0) {
5043       // Compute the Min, Max and RHS values based on the known bits. For the
5044       // EQ and NE we use unsigned values.
5045       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5046       const APInt& RHSVal = CI->getValue();
5047       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5048         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5049                                                Max);
5050       } else {
5051         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5052                                                  Max);
5053       }
5054       switch (I.getPredicate()) {  // LE/GE have been folded already.
5055       default: assert(0 && "Unknown icmp opcode!");
5056       case ICmpInst::ICMP_EQ:
5057         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5058           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5059         break;
5060       case ICmpInst::ICMP_NE:
5061         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5062           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5063         break;
5064       case ICmpInst::ICMP_ULT:
5065         if (Max.ult(RHSVal))
5066           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5067         if (Min.uge(RHSVal))
5068           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5069         break;
5070       case ICmpInst::ICMP_UGT:
5071         if (Min.ugt(RHSVal))
5072           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5073         if (Max.ule(RHSVal))
5074           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5075         break;
5076       case ICmpInst::ICMP_SLT:
5077         if (Max.slt(RHSVal))
5078           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5079         if (Min.sgt(RHSVal))
5080           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5081         break;
5082       case ICmpInst::ICMP_SGT: 
5083         if (Min.sgt(RHSVal))
5084           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5085         if (Max.sle(RHSVal))
5086           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5087         break;
5088       }
5089     }
5090           
5091     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5092     // instruction, see if that instruction also has constants so that the 
5093     // instruction can be folded into the icmp 
5094     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5095       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5096         return Res;
5097   }
5098
5099   // Handle icmp with constant (but not simple integer constant) RHS
5100   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5101     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5102       switch (LHSI->getOpcode()) {
5103       case Instruction::GetElementPtr:
5104         if (RHSC->isNullValue()) {
5105           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5106           bool isAllZeros = true;
5107           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5108             if (!isa<Constant>(LHSI->getOperand(i)) ||
5109                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5110               isAllZeros = false;
5111               break;
5112             }
5113           if (isAllZeros)
5114             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5115                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5116         }
5117         break;
5118
5119       case Instruction::PHI:
5120         if (Instruction *NV = FoldOpIntoPhi(I))
5121           return NV;
5122         break;
5123       case Instruction::Select: {
5124         // If either operand of the select is a constant, we can fold the
5125         // comparison into the select arms, which will cause one to be
5126         // constant folded and the select turned into a bitwise or.
5127         Value *Op1 = 0, *Op2 = 0;
5128         if (LHSI->hasOneUse()) {
5129           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5130             // Fold the known value into the constant operand.
5131             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5132             // Insert a new ICmp of the other select operand.
5133             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5134                                                    LHSI->getOperand(2), RHSC,
5135                                                    I.getName()), I);
5136           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5137             // Fold the known value into the constant operand.
5138             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5139             // Insert a new ICmp of the other select operand.
5140             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5141                                                    LHSI->getOperand(1), RHSC,
5142                                                    I.getName()), I);
5143           }
5144         }
5145
5146         if (Op1)
5147           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5148         break;
5149       }
5150       case Instruction::Malloc:
5151         // If we have (malloc != null), and if the malloc has a single use, we
5152         // can assume it is successful and remove the malloc.
5153         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5154           AddToWorkList(LHSI);
5155           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5156                                                          !isTrueWhenEqual(I)));
5157         }
5158         break;
5159       }
5160   }
5161
5162   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5163   if (User *GEP = dyn_castGetElementPtr(Op0))
5164     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5165       return NI;
5166   if (User *GEP = dyn_castGetElementPtr(Op1))
5167     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5168                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5169       return NI;
5170
5171   // Test to see if the operands of the icmp are casted versions of other
5172   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5173   // now.
5174   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5175     if (isa<PointerType>(Op0->getType()) && 
5176         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5177       // We keep moving the cast from the left operand over to the right
5178       // operand, where it can often be eliminated completely.
5179       Op0 = CI->getOperand(0);
5180
5181       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5182       // so eliminate it as well.
5183       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5184         Op1 = CI2->getOperand(0);
5185
5186       // If Op1 is a constant, we can fold the cast into the constant.
5187       if (Op0->getType() != Op1->getType())
5188         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5189           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5190         } else {
5191           // Otherwise, cast the RHS right before the icmp
5192           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5193         }
5194       return new ICmpInst(I.getPredicate(), Op0, Op1);
5195     }
5196   }
5197   
5198   if (isa<CastInst>(Op0)) {
5199     // Handle the special case of: icmp (cast bool to X), <cst>
5200     // This comes up when you have code like
5201     //   int X = A < B;
5202     //   if (X) ...
5203     // For generality, we handle any zero-extension of any operand comparison
5204     // with a constant or another cast from the same type.
5205     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5206       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5207         return R;
5208   }
5209   
5210   if (I.isEquality()) {
5211     Value *A, *B, *C, *D;
5212     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5213       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5214         Value *OtherVal = A == Op1 ? B : A;
5215         return new ICmpInst(I.getPredicate(), OtherVal,
5216                             Constant::getNullValue(A->getType()));
5217       }
5218
5219       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5220         // A^c1 == C^c2 --> A == C^(c1^c2)
5221         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5222           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5223             if (Op1->hasOneUse()) {
5224               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5225               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5226               return new ICmpInst(I.getPredicate(), A,
5227                                   InsertNewInstBefore(Xor, I));
5228             }
5229         
5230         // A^B == A^D -> B == D
5231         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5232         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5233         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5234         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5235       }
5236     }
5237     
5238     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5239         (A == Op0 || B == Op0)) {
5240       // A == (A^B)  ->  B == 0
5241       Value *OtherVal = A == Op0 ? B : A;
5242       return new ICmpInst(I.getPredicate(), OtherVal,
5243                           Constant::getNullValue(A->getType()));
5244     }
5245     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5246       // (A-B) == A  ->  B == 0
5247       return new ICmpInst(I.getPredicate(), B,
5248                           Constant::getNullValue(B->getType()));
5249     }
5250     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5251       // A == (A-B)  ->  B == 0
5252       return new ICmpInst(I.getPredicate(), B,
5253                           Constant::getNullValue(B->getType()));
5254     }
5255     
5256     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5257     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5258         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5259         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5260       Value *X = 0, *Y = 0, *Z = 0;
5261       
5262       if (A == C) {
5263         X = B; Y = D; Z = A;
5264       } else if (A == D) {
5265         X = B; Y = C; Z = A;
5266       } else if (B == C) {
5267         X = A; Y = D; Z = B;
5268       } else if (B == D) {
5269         X = A; Y = C; Z = B;
5270       }
5271       
5272       if (X) {   // Build (X^Y) & Z
5273         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5274         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5275         I.setOperand(0, Op1);
5276         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5277         return &I;
5278       }
5279     }
5280   }
5281   return Changed ? &I : 0;
5282 }
5283
5284
5285 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5286 /// and CmpRHS are both known to be integer constants.
5287 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5288                                           ConstantInt *DivRHS) {
5289   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5290   const APInt &CmpRHSV = CmpRHS->getValue();
5291   
5292   // FIXME: If the operand types don't match the type of the divide 
5293   // then don't attempt this transform. The code below doesn't have the
5294   // logic to deal with a signed divide and an unsigned compare (and
5295   // vice versa). This is because (x /s C1) <s C2  produces different 
5296   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5297   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5298   // work. :(  The if statement below tests that condition and bails 
5299   // if it finds it. 
5300   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5301   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5302     return 0;
5303   if (DivRHS->isZero())
5304     return 0; // The ProdOV computation fails on divide by zero.
5305
5306   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5307   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5308   // C2 (CI). By solving for X we can turn this into a range check 
5309   // instead of computing a divide. 
5310   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5311
5312   // Determine if the product overflows by seeing if the product is
5313   // not equal to the divide. Make sure we do the same kind of divide
5314   // as in the LHS instruction that we're folding. 
5315   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5316                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5317
5318   // Get the ICmp opcode
5319   ICmpInst::Predicate Pred = ICI.getPredicate();
5320
5321   // Figure out the interval that is being checked.  For example, a comparison
5322   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5323   // Compute this interval based on the constants involved and the signedness of
5324   // the compare/divide.  This computes a half-open interval, keeping track of
5325   // whether either value in the interval overflows.  After analysis each
5326   // overflow variable is set to 0 if it's corresponding bound variable is valid
5327   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5328   int LoOverflow = 0, HiOverflow = 0;
5329   ConstantInt *LoBound = 0, *HiBound = 0;
5330   
5331   
5332   if (!DivIsSigned) {  // udiv
5333     // e.g. X/5 op 3  --> [15, 20)
5334     LoBound = Prod;
5335     HiOverflow = LoOverflow = ProdOV;
5336     if (!HiOverflow)
5337       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5338   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5339     if (CmpRHSV == 0) {       // (X / pos) op 0
5340       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5341       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5342       HiBound = DivRHS;
5343     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5344       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5345       HiOverflow = LoOverflow = ProdOV;
5346       if (!HiOverflow)
5347         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5348     } else {                       // (X / pos) op neg
5349       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5350       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5351       LoOverflow = AddWithOverflow(LoBound, Prod,
5352                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5353       HiBound = AddOne(Prod);
5354       HiOverflow = ProdOV ? -1 : 0;
5355     }
5356   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5357     if (CmpRHSV == 0) {       // (X / neg) op 0
5358       // e.g. X/-5 op 0  --> [-4, 5)
5359       LoBound = AddOne(DivRHS);
5360       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5361       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5362         HiOverflow = 1;            // [INTMIN+1, overflow)
5363         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5364       }
5365     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5366       // e.g. X/-5 op 3  --> [-19, -14)
5367       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5368       if (!LoOverflow)
5369         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5370       HiBound = AddOne(Prod);
5371     } else {                       // (X / neg) op neg
5372       // e.g. X/-5 op -3  --> [15, 20)
5373       LoBound = Prod;
5374       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5375       HiBound = Subtract(Prod, DivRHS);
5376     }
5377     
5378     // Dividing by a negative swaps the condition.  LT <-> GT
5379     Pred = ICmpInst::getSwappedPredicate(Pred);
5380   }
5381
5382   Value *X = DivI->getOperand(0);
5383   switch (Pred) {
5384   default: assert(0 && "Unhandled icmp opcode!");
5385   case ICmpInst::ICMP_EQ:
5386     if (LoOverflow && HiOverflow)
5387       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5388     else if (HiOverflow)
5389       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5390                           ICmpInst::ICMP_UGE, X, LoBound);
5391     else if (LoOverflow)
5392       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5393                           ICmpInst::ICMP_ULT, X, HiBound);
5394     else
5395       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5396   case ICmpInst::ICMP_NE:
5397     if (LoOverflow && HiOverflow)
5398       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5399     else if (HiOverflow)
5400       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5401                           ICmpInst::ICMP_ULT, X, LoBound);
5402     else if (LoOverflow)
5403       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5404                           ICmpInst::ICMP_UGE, X, HiBound);
5405     else
5406       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5407   case ICmpInst::ICMP_ULT:
5408   case ICmpInst::ICMP_SLT:
5409     if (LoOverflow == +1)   // Low bound is greater than input range.
5410       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5411     if (LoOverflow == -1)   // Low bound is less than input range.
5412       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5413     return new ICmpInst(Pred, X, LoBound);
5414   case ICmpInst::ICMP_UGT:
5415   case ICmpInst::ICMP_SGT:
5416     if (HiOverflow == +1)       // High bound greater than input range.
5417       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5418     else if (HiOverflow == -1)  // High bound less than input range.
5419       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5420     if (Pred == ICmpInst::ICMP_UGT)
5421       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5422     else
5423       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5424   }
5425 }
5426
5427
5428 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5429 ///
5430 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5431                                                           Instruction *LHSI,
5432                                                           ConstantInt *RHS) {
5433   const APInt &RHSV = RHS->getValue();
5434   
5435   switch (LHSI->getOpcode()) {
5436   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5437     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5438       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5439       // fold the xor.
5440       if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5441           ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5442         Value *CompareVal = LHSI->getOperand(0);
5443         
5444         // If the sign bit of the XorCST is not set, there is no change to
5445         // the operation, just stop using the Xor.
5446         if (!XorCST->getValue().isNegative()) {
5447           ICI.setOperand(0, CompareVal);
5448           AddToWorkList(LHSI);
5449           return &ICI;
5450         }
5451         
5452         // Was the old condition true if the operand is positive?
5453         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5454         
5455         // If so, the new one isn't.
5456         isTrueIfPositive ^= true;
5457         
5458         if (isTrueIfPositive)
5459           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5460         else
5461           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5462       }
5463     }
5464     break;
5465   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5466     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5467         LHSI->getOperand(0)->hasOneUse()) {
5468       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5469       
5470       // If the LHS is an AND of a truncating cast, we can widen the
5471       // and/compare to be the input width without changing the value
5472       // produced, eliminating a cast.
5473       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5474         // We can do this transformation if either the AND constant does not
5475         // have its sign bit set or if it is an equality comparison. 
5476         // Extending a relational comparison when we're checking the sign
5477         // bit would not work.
5478         if (Cast->hasOneUse() &&
5479             (ICI.isEquality() || AndCST->getValue().isNonNegative() && 
5480              RHSV.isNonNegative())) {
5481           uint32_t BitWidth = 
5482             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5483           APInt NewCST = AndCST->getValue();
5484           NewCST.zext(BitWidth);
5485           APInt NewCI = RHSV;
5486           NewCI.zext(BitWidth);
5487           Instruction *NewAnd = 
5488             BinaryOperator::createAnd(Cast->getOperand(0),
5489                                       ConstantInt::get(NewCST),LHSI->getName());
5490           InsertNewInstBefore(NewAnd, ICI);
5491           return new ICmpInst(ICI.getPredicate(), NewAnd,
5492                               ConstantInt::get(NewCI));
5493         }
5494       }
5495       
5496       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5497       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5498       // happens a LOT in code produced by the C front-end, for bitfield
5499       // access.
5500       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5501       if (Shift && !Shift->isShift())
5502         Shift = 0;
5503       
5504       ConstantInt *ShAmt;
5505       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5506       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5507       const Type *AndTy = AndCST->getType();          // Type of the and.
5508       
5509       // We can fold this as long as we can't shift unknown bits
5510       // into the mask.  This can only happen with signed shift
5511       // rights, as they sign-extend.
5512       if (ShAmt) {
5513         bool CanFold = Shift->isLogicalShift();
5514         if (!CanFold) {
5515           // To test for the bad case of the signed shr, see if any
5516           // of the bits shifted in could be tested after the mask.
5517           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5518           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5519           
5520           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5521           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5522                AndCST->getValue()) == 0)
5523             CanFold = true;
5524         }
5525         
5526         if (CanFold) {
5527           Constant *NewCst;
5528           if (Shift->getOpcode() == Instruction::Shl)
5529             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5530           else
5531             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5532           
5533           // Check to see if we are shifting out any of the bits being
5534           // compared.
5535           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5536             // If we shifted bits out, the fold is not going to work out.
5537             // As a special case, check to see if this means that the
5538             // result is always true or false now.
5539             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5540               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5541             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5542               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5543           } else {
5544             ICI.setOperand(1, NewCst);
5545             Constant *NewAndCST;
5546             if (Shift->getOpcode() == Instruction::Shl)
5547               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5548             else
5549               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5550             LHSI->setOperand(1, NewAndCST);
5551             LHSI->setOperand(0, Shift->getOperand(0));
5552             AddToWorkList(Shift); // Shift is dead.
5553             AddUsesToWorkList(ICI);
5554             return &ICI;
5555           }
5556         }
5557       }
5558       
5559       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5560       // preferable because it allows the C<<Y expression to be hoisted out
5561       // of a loop if Y is invariant and X is not.
5562       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5563           ICI.isEquality() && !Shift->isArithmeticShift() &&
5564           isa<Instruction>(Shift->getOperand(0))) {
5565         // Compute C << Y.
5566         Value *NS;
5567         if (Shift->getOpcode() == Instruction::LShr) {
5568           NS = BinaryOperator::createShl(AndCST, 
5569                                          Shift->getOperand(1), "tmp");
5570         } else {
5571           // Insert a logical shift.
5572           NS = BinaryOperator::createLShr(AndCST,
5573                                           Shift->getOperand(1), "tmp");
5574         }
5575         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5576         
5577         // Compute X & (C << Y).
5578         Instruction *NewAnd = 
5579           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5580         InsertNewInstBefore(NewAnd, ICI);
5581         
5582         ICI.setOperand(0, NewAnd);
5583         return &ICI;
5584       }
5585     }
5586     break;
5587     
5588   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5589     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5590     if (!ShAmt) break;
5591     
5592     uint32_t TypeBits = RHSV.getBitWidth();
5593     
5594     // Check that the shift amount is in range.  If not, don't perform
5595     // undefined shifts.  When the shift is visited it will be
5596     // simplified.
5597     if (ShAmt->uge(TypeBits))
5598       break;
5599     
5600     if (ICI.isEquality()) {
5601       // If we are comparing against bits always shifted out, the
5602       // comparison cannot succeed.
5603       Constant *Comp =
5604         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5605       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5606         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5607         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5608         return ReplaceInstUsesWith(ICI, Cst);
5609       }
5610       
5611       if (LHSI->hasOneUse()) {
5612         // Otherwise strength reduce the shift into an and.
5613         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5614         Constant *Mask =
5615           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5616         
5617         Instruction *AndI =
5618           BinaryOperator::createAnd(LHSI->getOperand(0),
5619                                     Mask, LHSI->getName()+".mask");
5620         Value *And = InsertNewInstBefore(AndI, ICI);
5621         return new ICmpInst(ICI.getPredicate(), And,
5622                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5623       }
5624     }
5625     
5626     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5627     bool TrueIfSigned = false;
5628     if (LHSI->hasOneUse() &&
5629         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5630       // (X << 31) <s 0  --> (X&1) != 0
5631       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5632                                            (TypeBits-ShAmt->getZExtValue()-1));
5633       Instruction *AndI =
5634         BinaryOperator::createAnd(LHSI->getOperand(0),
5635                                   Mask, LHSI->getName()+".mask");
5636       Value *And = InsertNewInstBefore(AndI, ICI);
5637       
5638       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5639                           And, Constant::getNullValue(And->getType()));
5640     }
5641     break;
5642   }
5643     
5644   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5645   case Instruction::AShr: {
5646     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5647     if (!ShAmt) break;
5648
5649     if (ICI.isEquality()) {
5650       // Check that the shift amount is in range.  If not, don't perform
5651       // undefined shifts.  When the shift is visited it will be
5652       // simplified.
5653       uint32_t TypeBits = RHSV.getBitWidth();
5654       if (ShAmt->uge(TypeBits))
5655         break;
5656       uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5657       
5658       // If we are comparing against bits always shifted out, the
5659       // comparison cannot succeed.
5660       APInt Comp = RHSV << ShAmtVal;
5661       if (LHSI->getOpcode() == Instruction::LShr)
5662         Comp = Comp.lshr(ShAmtVal);
5663       else
5664         Comp = Comp.ashr(ShAmtVal);
5665       
5666       if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5667         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5668         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5669         return ReplaceInstUsesWith(ICI, Cst);
5670       }
5671       
5672       if (LHSI->hasOneUse() || RHSV == 0) {
5673         // Otherwise strength reduce the shift into an and.
5674         APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5675         Constant *Mask = ConstantInt::get(Val);
5676         
5677         Instruction *AndI =
5678           BinaryOperator::createAnd(LHSI->getOperand(0),
5679                                     Mask, LHSI->getName()+".mask");
5680         Value *And = InsertNewInstBefore(AndI, ICI);
5681         return new ICmpInst(ICI.getPredicate(), And,
5682                             ConstantExpr::getShl(RHS, ShAmt));
5683       }
5684     }
5685     break;
5686   }
5687     
5688   case Instruction::SDiv:
5689   case Instruction::UDiv:
5690     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5691     // Fold this div into the comparison, producing a range check. 
5692     // Determine, based on the divide type, what the range is being 
5693     // checked.  If there is an overflow on the low or high side, remember 
5694     // it, otherwise compute the range [low, hi) bounding the new value.
5695     // See: InsertRangeTest above for the kinds of replacements possible.
5696     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5697       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5698                                           DivRHS))
5699         return R;
5700     break;
5701
5702   case Instruction::Add:
5703     // Fold: icmp pred (add, X, C1), C2
5704
5705     if (!ICI.isEquality()) {
5706       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5707       if (!LHSC) break;
5708       const APInt &LHSV = LHSC->getValue();
5709
5710       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5711                             .subtract(LHSV);
5712
5713       if (ICI.isSignedPredicate()) {
5714         if (CR.getLower().isSignBit()) {
5715           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5716                               ConstantInt::get(CR.getUpper()));
5717         } else if (CR.getUpper().isSignBit()) {
5718           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5719                               ConstantInt::get(CR.getLower()));
5720         }
5721       } else {
5722         if (CR.getLower().isMinValue()) {
5723           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5724                               ConstantInt::get(CR.getUpper()));
5725         } else if (CR.getUpper().isMinValue()) {
5726           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5727                               ConstantInt::get(CR.getLower()));
5728         }
5729       }
5730     }
5731     break;
5732   }
5733   
5734   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5735   if (ICI.isEquality()) {
5736     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5737     
5738     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
5739     // the second operand is a constant, simplify a bit.
5740     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5741       switch (BO->getOpcode()) {
5742       case Instruction::SRem:
5743         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5744         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5745           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5746           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5747             Instruction *NewRem =
5748               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5749                                          BO->getName());
5750             InsertNewInstBefore(NewRem, ICI);
5751             return new ICmpInst(ICI.getPredicate(), NewRem, 
5752                                 Constant::getNullValue(BO->getType()));
5753           }
5754         }
5755         break;
5756       case Instruction::Add:
5757         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5758         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5759           if (BO->hasOneUse())
5760             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5761                                 Subtract(RHS, BOp1C));
5762         } else if (RHSV == 0) {
5763           // Replace ((add A, B) != 0) with (A != -B) if A or B is
5764           // efficiently invertible, or if the add has just this one use.
5765           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5766           
5767           if (Value *NegVal = dyn_castNegVal(BOp1))
5768             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5769           else if (Value *NegVal = dyn_castNegVal(BOp0))
5770             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5771           else if (BO->hasOneUse()) {
5772             Instruction *Neg = BinaryOperator::createNeg(BOp1);
5773             InsertNewInstBefore(Neg, ICI);
5774             Neg->takeName(BO);
5775             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5776           }
5777         }
5778         break;
5779       case Instruction::Xor:
5780         // For the xor case, we can xor two constants together, eliminating
5781         // the explicit xor.
5782         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5783           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
5784                               ConstantExpr::getXor(RHS, BOC));
5785         
5786         // FALLTHROUGH
5787       case Instruction::Sub:
5788         // Replace (([sub|xor] A, B) != 0) with (A != B)
5789         if (RHSV == 0)
5790           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5791                               BO->getOperand(1));
5792         break;
5793         
5794       case Instruction::Or:
5795         // If bits are being or'd in that are not present in the constant we
5796         // are comparing against, then the comparison could never succeed!
5797         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5798           Constant *NotCI = ConstantExpr::getNot(RHS);
5799           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5800             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
5801                                                              isICMP_NE));
5802         }
5803         break;
5804         
5805       case Instruction::And:
5806         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5807           // If bits are being compared against that are and'd out, then the
5808           // comparison can never succeed!
5809           if ((RHSV & ~BOC->getValue()) != 0)
5810             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5811                                                              isICMP_NE));
5812           
5813           // If we have ((X & C) == C), turn it into ((X & C) != 0).
5814           if (RHS == BOC && RHSV.isPowerOf2())
5815             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5816                                 ICmpInst::ICMP_NE, LHSI,
5817                                 Constant::getNullValue(RHS->getType()));
5818           
5819           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5820           if (isSignBit(BOC)) {
5821             Value *X = BO->getOperand(0);
5822             Constant *Zero = Constant::getNullValue(X->getType());
5823             ICmpInst::Predicate pred = isICMP_NE ? 
5824               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5825             return new ICmpInst(pred, X, Zero);
5826           }
5827           
5828           // ((X & ~7) == 0) --> X < 8
5829           if (RHSV == 0 && isHighOnes(BOC)) {
5830             Value *X = BO->getOperand(0);
5831             Constant *NegX = ConstantExpr::getNeg(BOC);
5832             ICmpInst::Predicate pred = isICMP_NE ? 
5833               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5834             return new ICmpInst(pred, X, NegX);
5835           }
5836         }
5837       default: break;
5838       }
5839     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5840       // Handle icmp {eq|ne} <intrinsic>, intcst.
5841       if (II->getIntrinsicID() == Intrinsic::bswap) {
5842         AddToWorkList(II);
5843         ICI.setOperand(0, II->getOperand(1));
5844         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5845         return &ICI;
5846       }
5847     }
5848   } else {  // Not a ICMP_EQ/ICMP_NE
5849             // If the LHS is a cast from an integral value of the same size, 
5850             // then since we know the RHS is a constant, try to simlify.
5851     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5852       Value *CastOp = Cast->getOperand(0);
5853       const Type *SrcTy = CastOp->getType();
5854       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5855       if (SrcTy->isInteger() && 
5856           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5857         // If this is an unsigned comparison, try to make the comparison use
5858         // smaller constant values.
5859         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5860           // X u< 128 => X s> -1
5861           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
5862                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5863         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5864                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5865           // X u> 127 => X s< 0
5866           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
5867                               Constant::getNullValue(SrcTy));
5868         }
5869       }
5870     }
5871   }
5872   return 0;
5873 }
5874
5875 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5876 /// We only handle extending casts so far.
5877 ///
5878 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5879   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5880   Value *LHSCIOp        = LHSCI->getOperand(0);
5881   const Type *SrcTy     = LHSCIOp->getType();
5882   const Type *DestTy    = LHSCI->getType();
5883   Value *RHSCIOp;
5884
5885   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
5886   // integer type is the same size as the pointer type.
5887   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5888       getTargetData().getPointerSizeInBits() == 
5889          cast<IntegerType>(DestTy)->getBitWidth()) {
5890     Value *RHSOp = 0;
5891     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5892       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5893     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5894       RHSOp = RHSC->getOperand(0);
5895       // If the pointer types don't match, insert a bitcast.
5896       if (LHSCIOp->getType() != RHSOp->getType())
5897         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
5898     }
5899
5900     if (RHSOp)
5901       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5902   }
5903   
5904   // The code below only handles extension cast instructions, so far.
5905   // Enforce this.
5906   if (LHSCI->getOpcode() != Instruction::ZExt &&
5907       LHSCI->getOpcode() != Instruction::SExt)
5908     return 0;
5909
5910   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5911   bool isSignedCmp = ICI.isSignedPredicate();
5912
5913   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5914     // Not an extension from the same type?
5915     RHSCIOp = CI->getOperand(0);
5916     if (RHSCIOp->getType() != LHSCIOp->getType()) 
5917       return 0;
5918     
5919     // If the signedness of the two casts doesn't agree (i.e. one is a sext
5920     // and the other is a zext), then we can't handle this.
5921     if (CI->getOpcode() != LHSCI->getOpcode())
5922       return 0;
5923
5924     // Deal with equality cases early.
5925     if (ICI.isEquality())
5926       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5927
5928     // A signed comparison of sign extended values simplifies into a
5929     // signed comparison.
5930     if (isSignedCmp && isSignedExt)
5931       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5932
5933     // The other three cases all fold into an unsigned comparison.
5934     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
5935   }
5936
5937   // If we aren't dealing with a constant on the RHS, exit early
5938   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5939   if (!CI)
5940     return 0;
5941
5942   // Compute the constant that would happen if we truncated to SrcTy then
5943   // reextended to DestTy.
5944   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5945   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5946
5947   // If the re-extended constant didn't change...
5948   if (Res2 == CI) {
5949     // Make sure that sign of the Cmp and the sign of the Cast are the same.
5950     // For example, we might have:
5951     //    %A = sext short %X to uint
5952     //    %B = icmp ugt uint %A, 1330
5953     // It is incorrect to transform this into 
5954     //    %B = icmp ugt short %X, 1330 
5955     // because %A may have negative value. 
5956     //
5957     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5958     // OR operation is EQ/NE.
5959     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5960       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5961     else
5962       return 0;
5963   }
5964
5965   // The re-extended constant changed so the constant cannot be represented 
5966   // in the shorter type. Consequently, we cannot emit a simple comparison.
5967
5968   // First, handle some easy cases. We know the result cannot be equal at this
5969   // point so handle the ICI.isEquality() cases
5970   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5971     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5972   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5973     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5974
5975   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5976   // should have been folded away previously and not enter in here.
5977   Value *Result;
5978   if (isSignedCmp) {
5979     // We're performing a signed comparison.
5980     if (cast<ConstantInt>(CI)->getValue().isNegative())
5981       Result = ConstantInt::getFalse();          // X < (small) --> false
5982     else
5983       Result = ConstantInt::getTrue();           // X < (large) --> true
5984   } else {
5985     // We're performing an unsigned comparison.
5986     if (isSignedExt) {
5987       // We're performing an unsigned comp with a sign extended value.
5988       // This is true if the input is >= 0. [aka >s -1]
5989       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5990       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5991                                    NegOne, ICI.getName()), ICI);
5992     } else {
5993       // Unsigned extend & unsigned compare -> always true.
5994       Result = ConstantInt::getTrue();
5995     }
5996   }
5997
5998   // Finally, return the value computed.
5999   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6000       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6001     return ReplaceInstUsesWith(ICI, Result);
6002   } else {
6003     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6004             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6005            "ICmp should be folded!");
6006     if (Constant *CI = dyn_cast<Constant>(Result))
6007       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6008     else
6009       return BinaryOperator::createNot(Result);
6010   }
6011 }
6012
6013 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6014   return commonShiftTransforms(I);
6015 }
6016
6017 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6018   return commonShiftTransforms(I);
6019 }
6020
6021 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6022   if (Instruction *R = commonShiftTransforms(I))
6023     return R;
6024   
6025   Value *Op0 = I.getOperand(0);
6026   
6027   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6028   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6029     if (CSI->isAllOnesValue())
6030       return ReplaceInstUsesWith(I, CSI);
6031   
6032   // See if we can turn a signed shr into an unsigned shr.
6033   if (MaskedValueIsZero(Op0, 
6034                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6035     return BinaryOperator::createLShr(Op0, I.getOperand(1));
6036   
6037   return 0;
6038 }
6039
6040 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6041   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6042   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6043
6044   // shl X, 0 == X and shr X, 0 == X
6045   // shl 0, X == 0 and shr 0, X == 0
6046   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6047       Op0 == Constant::getNullValue(Op0->getType()))
6048     return ReplaceInstUsesWith(I, Op0);
6049   
6050   if (isa<UndefValue>(Op0)) {            
6051     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6052       return ReplaceInstUsesWith(I, Op0);
6053     else                                    // undef << X -> 0, undef >>u X -> 0
6054       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6055   }
6056   if (isa<UndefValue>(Op1)) {
6057     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6058       return ReplaceInstUsesWith(I, Op0);          
6059     else                                     // X << undef, X >>u undef -> 0
6060       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6061   }
6062
6063   // Try to fold constant and into select arguments.
6064   if (isa<Constant>(Op0))
6065     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6066       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6067         return R;
6068
6069   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6070     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6071       return Res;
6072   return 0;
6073 }
6074
6075 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6076                                                BinaryOperator &I) {
6077   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6078
6079   // See if we can simplify any instructions used by the instruction whose sole 
6080   // purpose is to compute bits we don't care about.
6081   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6082   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6083   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6084                            KnownZero, KnownOne))
6085     return &I;
6086   
6087   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6088   // of a signed value.
6089   //
6090   if (Op1->uge(TypeBits)) {
6091     if (I.getOpcode() != Instruction::AShr)
6092       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6093     else {
6094       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6095       return &I;
6096     }
6097   }
6098   
6099   // ((X*C1) << C2) == (X * (C1 << C2))
6100   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6101     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6102       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6103         return BinaryOperator::createMul(BO->getOperand(0),
6104                                          ConstantExpr::getShl(BOOp, Op1));
6105   
6106   // Try to fold constant and into select arguments.
6107   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6108     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6109       return R;
6110   if (isa<PHINode>(Op0))
6111     if (Instruction *NV = FoldOpIntoPhi(I))
6112       return NV;
6113   
6114   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6115   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6116     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6117     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6118     // place.  Don't try to do this transformation in this case.  Also, we
6119     // require that the input operand is a shift-by-constant so that we have
6120     // confidence that the shifts will get folded together.  We could do this
6121     // xform in more cases, but it is unlikely to be profitable.
6122     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6123         isa<ConstantInt>(TrOp->getOperand(1))) {
6124       // Okay, we'll do this xform.  Make the shift of shift.
6125       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6126       Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6127                                                 I.getName());
6128       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6129
6130       // For logical shifts, the truncation has the effect of making the high
6131       // part of the register be zeros.  Emulate this by inserting an AND to
6132       // clear the top bits as needed.  This 'and' will usually be zapped by
6133       // other xforms later if dead.
6134       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6135       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6136       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6137       
6138       // The mask we constructed says what the trunc would do if occurring
6139       // between the shifts.  We want to know the effect *after* the second
6140       // shift.  We know that it is a logical shift by a constant, so adjust the
6141       // mask as appropriate.
6142       if (I.getOpcode() == Instruction::Shl)
6143         MaskV <<= Op1->getZExtValue();
6144       else {
6145         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6146         MaskV = MaskV.lshr(Op1->getZExtValue());
6147       }
6148
6149       Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6150                                                    TI->getName());
6151       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6152
6153       // Return the value truncated to the interesting size.
6154       return new TruncInst(And, I.getType());
6155     }
6156   }
6157   
6158   if (Op0->hasOneUse()) {
6159     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6160       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6161       Value *V1, *V2;
6162       ConstantInt *CC;
6163       switch (Op0BO->getOpcode()) {
6164         default: break;
6165         case Instruction::Add:
6166         case Instruction::And:
6167         case Instruction::Or:
6168         case Instruction::Xor: {
6169           // These operators commute.
6170           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6171           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6172               match(Op0BO->getOperand(1),
6173                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6174             Instruction *YS = BinaryOperator::createShl(
6175                                             Op0BO->getOperand(0), Op1,
6176                                             Op0BO->getName());
6177             InsertNewInstBefore(YS, I); // (Y << C)
6178             Instruction *X = 
6179               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6180                                      Op0BO->getOperand(1)->getName());
6181             InsertNewInstBefore(X, I);  // (X + (Y << C))
6182             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6183             return BinaryOperator::createAnd(X, ConstantInt::get(
6184                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6185           }
6186           
6187           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6188           Value *Op0BOOp1 = Op0BO->getOperand(1);
6189           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6190               match(Op0BOOp1, 
6191                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6192               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6193               V2 == Op1) {
6194             Instruction *YS = BinaryOperator::createShl(
6195                                                      Op0BO->getOperand(0), Op1,
6196                                                      Op0BO->getName());
6197             InsertNewInstBefore(YS, I); // (Y << C)
6198             Instruction *XM =
6199               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6200                                         V1->getName()+".mask");
6201             InsertNewInstBefore(XM, I); // X & (CC << C)
6202             
6203             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6204           }
6205         }
6206           
6207         // FALL THROUGH.
6208         case Instruction::Sub: {
6209           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6210           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6211               match(Op0BO->getOperand(0),
6212                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6213             Instruction *YS = BinaryOperator::createShl(
6214                                                      Op0BO->getOperand(1), Op1,
6215                                                      Op0BO->getName());
6216             InsertNewInstBefore(YS, I); // (Y << C)
6217             Instruction *X =
6218               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6219                                      Op0BO->getOperand(0)->getName());
6220             InsertNewInstBefore(X, I);  // (X + (Y << C))
6221             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6222             return BinaryOperator::createAnd(X, ConstantInt::get(
6223                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6224           }
6225           
6226           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6227           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6228               match(Op0BO->getOperand(0),
6229                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6230                           m_ConstantInt(CC))) && V2 == Op1 &&
6231               cast<BinaryOperator>(Op0BO->getOperand(0))
6232                   ->getOperand(0)->hasOneUse()) {
6233             Instruction *YS = BinaryOperator::createShl(
6234                                                      Op0BO->getOperand(1), Op1,
6235                                                      Op0BO->getName());
6236             InsertNewInstBefore(YS, I); // (Y << C)
6237             Instruction *XM =
6238               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6239                                         V1->getName()+".mask");
6240             InsertNewInstBefore(XM, I); // X & (CC << C)
6241             
6242             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6243           }
6244           
6245           break;
6246         }
6247       }
6248       
6249       
6250       // If the operand is an bitwise operator with a constant RHS, and the
6251       // shift is the only use, we can pull it out of the shift.
6252       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6253         bool isValid = true;     // Valid only for And, Or, Xor
6254         bool highBitSet = false; // Transform if high bit of constant set?
6255         
6256         switch (Op0BO->getOpcode()) {
6257           default: isValid = false; break;   // Do not perform transform!
6258           case Instruction::Add:
6259             isValid = isLeftShift;
6260             break;
6261           case Instruction::Or:
6262           case Instruction::Xor:
6263             highBitSet = false;
6264             break;
6265           case Instruction::And:
6266             highBitSet = true;
6267             break;
6268         }
6269         
6270         // If this is a signed shift right, and the high bit is modified
6271         // by the logical operation, do not perform the transformation.
6272         // The highBitSet boolean indicates the value of the high bit of
6273         // the constant which would cause it to be modified for this
6274         // operation.
6275         //
6276         if (isValid && I.getOpcode() == Instruction::AShr)
6277           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6278         
6279         if (isValid) {
6280           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6281           
6282           Instruction *NewShift =
6283             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6284           InsertNewInstBefore(NewShift, I);
6285           NewShift->takeName(Op0BO);
6286           
6287           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6288                                         NewRHS);
6289         }
6290       }
6291     }
6292   }
6293   
6294   // Find out if this is a shift of a shift by a constant.
6295   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6296   if (ShiftOp && !ShiftOp->isShift())
6297     ShiftOp = 0;
6298   
6299   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6300     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6301     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6302     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6303     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6304     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6305     Value *X = ShiftOp->getOperand(0);
6306     
6307     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6308     if (AmtSum > TypeBits)
6309       AmtSum = TypeBits;
6310     
6311     const IntegerType *Ty = cast<IntegerType>(I.getType());
6312     
6313     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6314     if (I.getOpcode() == ShiftOp->getOpcode()) {
6315       return BinaryOperator::create(I.getOpcode(), X,
6316                                     ConstantInt::get(Ty, AmtSum));
6317     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6318                I.getOpcode() == Instruction::AShr) {
6319       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6320       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6321     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6322                I.getOpcode() == Instruction::LShr) {
6323       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6324       Instruction *Shift =
6325         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6326       InsertNewInstBefore(Shift, I);
6327
6328       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6329       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6330     }
6331     
6332     // Okay, if we get here, one shift must be left, and the other shift must be
6333     // right.  See if the amounts are equal.
6334     if (ShiftAmt1 == ShiftAmt2) {
6335       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6336       if (I.getOpcode() == Instruction::Shl) {
6337         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6338         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6339       }
6340       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6341       if (I.getOpcode() == Instruction::LShr) {
6342         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6343         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6344       }
6345       // We can simplify ((X << C) >>s C) into a trunc + sext.
6346       // NOTE: we could do this for any C, but that would make 'unusual' integer
6347       // types.  For now, just stick to ones well-supported by the code
6348       // generators.
6349       const Type *SExtType = 0;
6350       switch (Ty->getBitWidth() - ShiftAmt1) {
6351       case 1  :
6352       case 8  :
6353       case 16 :
6354       case 32 :
6355       case 64 :
6356       case 128:
6357         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6358         break;
6359       default: break;
6360       }
6361       if (SExtType) {
6362         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6363         InsertNewInstBefore(NewTrunc, I);
6364         return new SExtInst(NewTrunc, Ty);
6365       }
6366       // Otherwise, we can't handle it yet.
6367     } else if (ShiftAmt1 < ShiftAmt2) {
6368       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6369       
6370       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6371       if (I.getOpcode() == Instruction::Shl) {
6372         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6373                ShiftOp->getOpcode() == Instruction::AShr);
6374         Instruction *Shift =
6375           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6376         InsertNewInstBefore(Shift, I);
6377         
6378         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6379         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6380       }
6381       
6382       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6383       if (I.getOpcode() == Instruction::LShr) {
6384         assert(ShiftOp->getOpcode() == Instruction::Shl);
6385         Instruction *Shift =
6386           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6387         InsertNewInstBefore(Shift, I);
6388         
6389         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6390         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6391       }
6392       
6393       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6394     } else {
6395       assert(ShiftAmt2 < ShiftAmt1);
6396       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6397
6398       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6399       if (I.getOpcode() == Instruction::Shl) {
6400         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6401                ShiftOp->getOpcode() == Instruction::AShr);
6402         Instruction *Shift =
6403           BinaryOperator::create(ShiftOp->getOpcode(), X,
6404                                  ConstantInt::get(Ty, ShiftDiff));
6405         InsertNewInstBefore(Shift, I);
6406         
6407         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6408         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6409       }
6410       
6411       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6412       if (I.getOpcode() == Instruction::LShr) {
6413         assert(ShiftOp->getOpcode() == Instruction::Shl);
6414         Instruction *Shift =
6415           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6416         InsertNewInstBefore(Shift, I);
6417         
6418         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6419         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6420       }
6421       
6422       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6423     }
6424   }
6425   return 0;
6426 }
6427
6428
6429 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6430 /// expression.  If so, decompose it, returning some value X, such that Val is
6431 /// X*Scale+Offset.
6432 ///
6433 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6434                                         int &Offset) {
6435   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6436   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6437     Offset = CI->getZExtValue();
6438     Scale  = 0;
6439     return ConstantInt::get(Type::Int32Ty, 0);
6440   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6441     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6442       if (I->getOpcode() == Instruction::Shl) {
6443         // This is a value scaled by '1 << the shift amt'.
6444         Scale = 1U << RHS->getZExtValue();
6445         Offset = 0;
6446         return I->getOperand(0);
6447       } else if (I->getOpcode() == Instruction::Mul) {
6448         // This value is scaled by 'RHS'.
6449         Scale = RHS->getZExtValue();
6450         Offset = 0;
6451         return I->getOperand(0);
6452       } else if (I->getOpcode() == Instruction::Add) {
6453         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6454         // where C1 is divisible by C2.
6455         unsigned SubScale;
6456         Value *SubVal = 
6457           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6458         Offset += RHS->getZExtValue();
6459         Scale = SubScale;
6460         return SubVal;
6461       }
6462     }
6463   }
6464
6465   // Otherwise, we can't look past this.
6466   Scale = 1;
6467   Offset = 0;
6468   return Val;
6469 }
6470
6471
6472 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6473 /// try to eliminate the cast by moving the type information into the alloc.
6474 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6475                                                    AllocationInst &AI) {
6476   const PointerType *PTy = cast<PointerType>(CI.getType());
6477   
6478   // Remove any uses of AI that are dead.
6479   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6480   
6481   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6482     Instruction *User = cast<Instruction>(*UI++);
6483     if (isInstructionTriviallyDead(User)) {
6484       while (UI != E && *UI == User)
6485         ++UI; // If this instruction uses AI more than once, don't break UI.
6486       
6487       ++NumDeadInst;
6488       DOUT << "IC: DCE: " << *User;
6489       EraseInstFromFunction(*User);
6490     }
6491   }
6492   
6493   // Get the type really allocated and the type casted to.
6494   const Type *AllocElTy = AI.getAllocatedType();
6495   const Type *CastElTy = PTy->getElementType();
6496   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6497
6498   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6499   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6500   if (CastElTyAlign < AllocElTyAlign) return 0;
6501
6502   // If the allocation has multiple uses, only promote it if we are strictly
6503   // increasing the alignment of the resultant allocation.  If we keep it the
6504   // same, we open the door to infinite loops of various kinds.
6505   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6506
6507   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6508   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6509   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6510
6511   // See if we can satisfy the modulus by pulling a scale out of the array
6512   // size argument.
6513   unsigned ArraySizeScale;
6514   int ArrayOffset;
6515   Value *NumElements = // See if the array size is a decomposable linear expr.
6516     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6517  
6518   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6519   // do the xform.
6520   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6521       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6522
6523   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6524   Value *Amt = 0;
6525   if (Scale == 1) {
6526     Amt = NumElements;
6527   } else {
6528     // If the allocation size is constant, form a constant mul expression
6529     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6530     if (isa<ConstantInt>(NumElements))
6531       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6532     // otherwise multiply the amount and the number of elements
6533     else if (Scale != 1) {
6534       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6535       Amt = InsertNewInstBefore(Tmp, AI);
6536     }
6537   }
6538   
6539   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6540     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6541     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6542     Amt = InsertNewInstBefore(Tmp, AI);
6543   }
6544   
6545   AllocationInst *New;
6546   if (isa<MallocInst>(AI))
6547     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6548   else
6549     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6550   InsertNewInstBefore(New, AI);
6551   New->takeName(&AI);
6552   
6553   // If the allocation has multiple uses, insert a cast and change all things
6554   // that used it to use the new cast.  This will also hack on CI, but it will
6555   // die soon.
6556   if (!AI.hasOneUse()) {
6557     AddUsesToWorkList(AI);
6558     // New is the allocation instruction, pointer typed. AI is the original
6559     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6560     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6561     InsertNewInstBefore(NewCast, AI);
6562     AI.replaceAllUsesWith(NewCast);
6563   }
6564   return ReplaceInstUsesWith(CI, New);
6565 }
6566
6567 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6568 /// and return it as type Ty without inserting any new casts and without
6569 /// changing the computed value.  This is used by code that tries to decide
6570 /// whether promoting or shrinking integer operations to wider or smaller types
6571 /// will allow us to eliminate a truncate or extend.
6572 ///
6573 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6574 /// extension operation if Ty is larger.
6575 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6576                                        unsigned CastOpc, int &NumCastsRemoved) {
6577   // We can always evaluate constants in another type.
6578   if (isa<ConstantInt>(V))
6579     return true;
6580   
6581   Instruction *I = dyn_cast<Instruction>(V);
6582   if (!I) return false;
6583   
6584   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6585   
6586   // If this is an extension or truncate, we can often eliminate it.
6587   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6588     // If this is a cast from the destination type, we can trivially eliminate
6589     // it, and this will remove a cast overall.
6590     if (I->getOperand(0)->getType() == Ty) {
6591       // If the first operand is itself a cast, and is eliminable, do not count
6592       // this as an eliminable cast.  We would prefer to eliminate those two
6593       // casts first.
6594       if (!isa<CastInst>(I->getOperand(0)))
6595         ++NumCastsRemoved;
6596       return true;
6597     }
6598   }
6599
6600   // We can't extend or shrink something that has multiple uses: doing so would
6601   // require duplicating the instruction in general, which isn't profitable.
6602   if (!I->hasOneUse()) return false;
6603
6604   switch (I->getOpcode()) {
6605   case Instruction::Add:
6606   case Instruction::Sub:
6607   case Instruction::And:
6608   case Instruction::Or:
6609   case Instruction::Xor:
6610     // These operators can all arbitrarily be extended or truncated.
6611     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6612                                       NumCastsRemoved) &&
6613            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6614                                       NumCastsRemoved);
6615
6616   case Instruction::Mul:
6617     // A multiply can be truncated by truncating its operands.
6618     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6619            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6620                                       NumCastsRemoved) &&
6621            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6622                                       NumCastsRemoved);
6623
6624   case Instruction::Shl:
6625     // If we are truncating the result of this SHL, and if it's a shift of a
6626     // constant amount, we can always perform a SHL in a smaller type.
6627     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6628       uint32_t BitWidth = Ty->getBitWidth();
6629       if (BitWidth < OrigTy->getBitWidth() && 
6630           CI->getLimitedValue(BitWidth) < BitWidth)
6631         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6632                                           NumCastsRemoved);
6633     }
6634     break;
6635   case Instruction::LShr:
6636     // If this is a truncate of a logical shr, we can truncate it to a smaller
6637     // lshr iff we know that the bits we would otherwise be shifting in are
6638     // already zeros.
6639     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6640       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6641       uint32_t BitWidth = Ty->getBitWidth();
6642       if (BitWidth < OrigBitWidth &&
6643           MaskedValueIsZero(I->getOperand(0),
6644             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6645           CI->getLimitedValue(BitWidth) < BitWidth) {
6646         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6647                                           NumCastsRemoved);
6648       }
6649     }
6650     break;
6651   case Instruction::ZExt:
6652   case Instruction::SExt:
6653   case Instruction::Trunc:
6654     // If this is the same kind of case as our original (e.g. zext+zext), we
6655     // can safely replace it.  Note that replacing it does not reduce the number
6656     // of casts in the input.
6657     if (I->getOpcode() == CastOpc)
6658       return true;
6659     
6660     break;
6661   default:
6662     // TODO: Can handle more cases here.
6663     break;
6664   }
6665   
6666   return false;
6667 }
6668
6669 /// EvaluateInDifferentType - Given an expression that 
6670 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6671 /// evaluate the expression.
6672 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6673                                              bool isSigned) {
6674   if (Constant *C = dyn_cast<Constant>(V))
6675     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6676
6677   // Otherwise, it must be an instruction.
6678   Instruction *I = cast<Instruction>(V);
6679   Instruction *Res = 0;
6680   switch (I->getOpcode()) {
6681   case Instruction::Add:
6682   case Instruction::Sub:
6683   case Instruction::Mul:
6684   case Instruction::And:
6685   case Instruction::Or:
6686   case Instruction::Xor:
6687   case Instruction::AShr:
6688   case Instruction::LShr:
6689   case Instruction::Shl: {
6690     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6691     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6692     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6693                                  LHS, RHS, I->getName());
6694     break;
6695   }    
6696   case Instruction::Trunc:
6697   case Instruction::ZExt:
6698   case Instruction::SExt:
6699     // If the source type of the cast is the type we're trying for then we can
6700     // just return the source.  There's no need to insert it because it is not
6701     // new.
6702     if (I->getOperand(0)->getType() == Ty)
6703       return I->getOperand(0);
6704     
6705     // Otherwise, must be the same type of case, so just reinsert a new one.
6706     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6707                            Ty, I->getName());
6708     break;
6709   default: 
6710     // TODO: Can handle more cases here.
6711     assert(0 && "Unreachable!");
6712     break;
6713   }
6714   
6715   return InsertNewInstBefore(Res, *I);
6716 }
6717
6718 /// @brief Implement the transforms common to all CastInst visitors.
6719 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6720   Value *Src = CI.getOperand(0);
6721
6722   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6723   // eliminate it now.
6724   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
6725     if (Instruction::CastOps opc = 
6726         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6727       // The first cast (CSrc) is eliminable so we need to fix up or replace
6728       // the second cast (CI). CSrc will then have a good chance of being dead.
6729       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6730     }
6731   }
6732
6733   // If we are casting a select then fold the cast into the select
6734   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6735     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6736       return NV;
6737
6738   // If we are casting a PHI then fold the cast into the PHI
6739   if (isa<PHINode>(Src))
6740     if (Instruction *NV = FoldOpIntoPhi(CI))
6741       return NV;
6742   
6743   return 0;
6744 }
6745
6746 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6747 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6748   Value *Src = CI.getOperand(0);
6749   
6750   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6751     // If casting the result of a getelementptr instruction with no offset, turn
6752     // this into a cast of the original pointer!
6753     if (GEP->hasAllZeroIndices()) {
6754       // Changing the cast operand is usually not a good idea but it is safe
6755       // here because the pointer operand is being replaced with another 
6756       // pointer operand so the opcode doesn't need to change.
6757       AddToWorkList(GEP);
6758       CI.setOperand(0, GEP->getOperand(0));
6759       return &CI;
6760     }
6761     
6762     // If the GEP has a single use, and the base pointer is a bitcast, and the
6763     // GEP computes a constant offset, see if we can convert these three
6764     // instructions into fewer.  This typically happens with unions and other
6765     // non-type-safe code.
6766     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6767       if (GEP->hasAllConstantIndices()) {
6768         // We are guaranteed to get a constant from EmitGEPOffset.
6769         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6770         int64_t Offset = OffsetV->getSExtValue();
6771         
6772         // Get the base pointer input of the bitcast, and the type it points to.
6773         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6774         const Type *GEPIdxTy =
6775           cast<PointerType>(OrigBase->getType())->getElementType();
6776         if (GEPIdxTy->isSized()) {
6777           SmallVector<Value*, 8> NewIndices;
6778           
6779           // Start with the index over the outer type.  Note that the type size
6780           // might be zero (even if the offset isn't zero) if the indexed type
6781           // is something like [0 x {int, int}]
6782           const Type *IntPtrTy = TD->getIntPtrType();
6783           int64_t FirstIdx = 0;
6784           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6785             FirstIdx = Offset/TySize;
6786             Offset %= TySize;
6787           
6788             // Handle silly modulus not returning values values [0..TySize).
6789             if (Offset < 0) {
6790               --FirstIdx;
6791               Offset += TySize;
6792               assert(Offset >= 0);
6793             }
6794             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6795           }
6796           
6797           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6798
6799           // Index into the types.  If we fail, set OrigBase to null.
6800           while (Offset) {
6801             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6802               const StructLayout *SL = TD->getStructLayout(STy);
6803               if (Offset < (int64_t)SL->getSizeInBytes()) {
6804                 unsigned Elt = SL->getElementContainingOffset(Offset);
6805                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6806               
6807                 Offset -= SL->getElementOffset(Elt);
6808                 GEPIdxTy = STy->getElementType(Elt);
6809               } else {
6810                 // Otherwise, we can't index into this, bail out.
6811                 Offset = 0;
6812                 OrigBase = 0;
6813               }
6814             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6815               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6816               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6817                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6818                 Offset %= EltSize;
6819               } else {
6820                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6821               }
6822               GEPIdxTy = STy->getElementType();
6823             } else {
6824               // Otherwise, we can't index into this, bail out.
6825               Offset = 0;
6826               OrigBase = 0;
6827             }
6828           }
6829           if (OrigBase) {
6830             // If we were able to index down into an element, create the GEP
6831             // and bitcast the result.  This eliminates one bitcast, potentially
6832             // two.
6833             Instruction *NGEP = new GetElementPtrInst(OrigBase, 
6834                                                       NewIndices.begin(),
6835                                                       NewIndices.end(), "");
6836             InsertNewInstBefore(NGEP, CI);
6837             NGEP->takeName(GEP);
6838             
6839             if (isa<BitCastInst>(CI))
6840               return new BitCastInst(NGEP, CI.getType());
6841             assert(isa<PtrToIntInst>(CI));
6842             return new PtrToIntInst(NGEP, CI.getType());
6843           }
6844         }
6845       }      
6846     }
6847   }
6848     
6849   return commonCastTransforms(CI);
6850 }
6851
6852
6853
6854 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6855 /// integer types. This function implements the common transforms for all those
6856 /// cases.
6857 /// @brief Implement the transforms common to CastInst with integer operands
6858 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6859   if (Instruction *Result = commonCastTransforms(CI))
6860     return Result;
6861
6862   Value *Src = CI.getOperand(0);
6863   const Type *SrcTy = Src->getType();
6864   const Type *DestTy = CI.getType();
6865   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6866   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6867
6868   // See if we can simplify any instructions used by the LHS whose sole 
6869   // purpose is to compute bits we don't care about.
6870   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6871   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6872                            KnownZero, KnownOne))
6873     return &CI;
6874
6875   // If the source isn't an instruction or has more than one use then we
6876   // can't do anything more. 
6877   Instruction *SrcI = dyn_cast<Instruction>(Src);
6878   if (!SrcI || !Src->hasOneUse())
6879     return 0;
6880
6881   // Attempt to propagate the cast into the instruction for int->int casts.
6882   int NumCastsRemoved = 0;
6883   if (!isa<BitCastInst>(CI) &&
6884       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6885                                  CI.getOpcode(), NumCastsRemoved)) {
6886     // If this cast is a truncate, evaluting in a different type always
6887     // eliminates the cast, so it is always a win.  If this is a zero-extension,
6888     // we need to do an AND to maintain the clear top-part of the computation,
6889     // so we require that the input have eliminated at least one cast.  If this
6890     // is a sign extension, we insert two new casts (to do the extension) so we
6891     // require that two casts have been eliminated.
6892     bool DoXForm;
6893     switch (CI.getOpcode()) {
6894     default:
6895       // All the others use floating point so we shouldn't actually 
6896       // get here because of the check above.
6897       assert(0 && "Unknown cast type");
6898     case Instruction::Trunc:
6899       DoXForm = true;
6900       break;
6901     case Instruction::ZExt:
6902       DoXForm = NumCastsRemoved >= 1;
6903       break;
6904     case Instruction::SExt:
6905       DoXForm = NumCastsRemoved >= 2;
6906       break;
6907     }
6908     
6909     if (DoXForm) {
6910       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
6911                                            CI.getOpcode() == Instruction::SExt);
6912       assert(Res->getType() == DestTy);
6913       switch (CI.getOpcode()) {
6914       default: assert(0 && "Unknown cast type!");
6915       case Instruction::Trunc:
6916       case Instruction::BitCast:
6917         // Just replace this cast with the result.
6918         return ReplaceInstUsesWith(CI, Res);
6919       case Instruction::ZExt: {
6920         // We need to emit an AND to clear the high bits.
6921         assert(SrcBitSize < DestBitSize && "Not a zext?");
6922         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6923                                                             SrcBitSize));
6924         return BinaryOperator::createAnd(Res, C);
6925       }
6926       case Instruction::SExt:
6927         // We need to emit a cast to truncate, then a cast to sext.
6928         return CastInst::create(Instruction::SExt,
6929             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
6930                              CI), DestTy);
6931       }
6932     }
6933   }
6934   
6935   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6936   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6937
6938   switch (SrcI->getOpcode()) {
6939   case Instruction::Add:
6940   case Instruction::Mul:
6941   case Instruction::And:
6942   case Instruction::Or:
6943   case Instruction::Xor:
6944     // If we are discarding information, rewrite.
6945     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6946       // Don't insert two casts if they cannot be eliminated.  We allow 
6947       // two casts to be inserted if the sizes are the same.  This could 
6948       // only be converting signedness, which is a noop.
6949       if (DestBitSize == SrcBitSize || 
6950           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6951           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6952         Instruction::CastOps opcode = CI.getOpcode();
6953         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6954         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6955         return BinaryOperator::create(
6956             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6957       }
6958     }
6959
6960     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
6961     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
6962         SrcI->getOpcode() == Instruction::Xor &&
6963         Op1 == ConstantInt::getTrue() &&
6964         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6965       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6966       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6967     }
6968     break;
6969   case Instruction::SDiv:
6970   case Instruction::UDiv:
6971   case Instruction::SRem:
6972   case Instruction::URem:
6973     // If we are just changing the sign, rewrite.
6974     if (DestBitSize == SrcBitSize) {
6975       // Don't insert two casts if they cannot be eliminated.  We allow 
6976       // two casts to be inserted if the sizes are the same.  This could 
6977       // only be converting signedness, which is a noop.
6978       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
6979           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6980         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
6981                                               Op0, DestTy, SrcI);
6982         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
6983                                               Op1, DestTy, SrcI);
6984         return BinaryOperator::create(
6985           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6986       }
6987     }
6988     break;
6989
6990   case Instruction::Shl:
6991     // Allow changing the sign of the source operand.  Do not allow 
6992     // changing the size of the shift, UNLESS the shift amount is a 
6993     // constant.  We must not change variable sized shifts to a smaller 
6994     // size, because it is undefined to shift more bits out than exist 
6995     // in the value.
6996     if (DestBitSize == SrcBitSize ||
6997         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6998       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6999           Instruction::BitCast : Instruction::Trunc);
7000       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7001       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7002       return BinaryOperator::createShl(Op0c, Op1c);
7003     }
7004     break;
7005   case Instruction::AShr:
7006     // If this is a signed shr, and if all bits shifted in are about to be
7007     // truncated off, turn it into an unsigned shr to allow greater
7008     // simplifications.
7009     if (DestBitSize < SrcBitSize &&
7010         isa<ConstantInt>(Op1)) {
7011       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7012       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7013         // Insert the new logical shift right.
7014         return BinaryOperator::createLShr(Op0, Op1);
7015       }
7016     }
7017     break;
7018   }
7019   return 0;
7020 }
7021
7022 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7023   if (Instruction *Result = commonIntCastTransforms(CI))
7024     return Result;
7025   
7026   Value *Src = CI.getOperand(0);
7027   const Type *Ty = CI.getType();
7028   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7029   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7030   
7031   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7032     switch (SrcI->getOpcode()) {
7033     default: break;
7034     case Instruction::LShr:
7035       // We can shrink lshr to something smaller if we know the bits shifted in
7036       // are already zeros.
7037       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7038         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7039         
7040         // Get a mask for the bits shifting in.
7041         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7042         Value* SrcIOp0 = SrcI->getOperand(0);
7043         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7044           if (ShAmt >= DestBitWidth)        // All zeros.
7045             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7046
7047           // Okay, we can shrink this.  Truncate the input, then return a new
7048           // shift.
7049           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7050           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7051                                        Ty, CI);
7052           return BinaryOperator::createLShr(V1, V2);
7053         }
7054       } else {     // This is a variable shr.
7055         
7056         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7057         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7058         // loop-invariant and CSE'd.
7059         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7060           Value *One = ConstantInt::get(SrcI->getType(), 1);
7061
7062           Value *V = InsertNewInstBefore(
7063               BinaryOperator::createShl(One, SrcI->getOperand(1),
7064                                      "tmp"), CI);
7065           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7066                                                             SrcI->getOperand(0),
7067                                                             "tmp"), CI);
7068           Value *Zero = Constant::getNullValue(V->getType());
7069           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7070         }
7071       }
7072       break;
7073     }
7074   }
7075   
7076   return 0;
7077 }
7078
7079 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7080   // If one of the common conversion will work ..
7081   if (Instruction *Result = commonIntCastTransforms(CI))
7082     return Result;
7083
7084   Value *Src = CI.getOperand(0);
7085
7086   // If this is a cast of a cast
7087   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7088     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7089     // types and if the sizes are just right we can convert this into a logical
7090     // 'and' which will be much cheaper than the pair of casts.
7091     if (isa<TruncInst>(CSrc)) {
7092       // Get the sizes of the types involved
7093       Value *A = CSrc->getOperand(0);
7094       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7095       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7096       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7097       // If we're actually extending zero bits and the trunc is a no-op
7098       if (MidSize < DstSize && SrcSize == DstSize) {
7099         // Replace both of the casts with an And of the type mask.
7100         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7101         Constant *AndConst = ConstantInt::get(AndValue);
7102         Instruction *And = 
7103           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7104         // Unfortunately, if the type changed, we need to cast it back.
7105         if (And->getType() != CI.getType()) {
7106           And->setName(CSrc->getName()+".mask");
7107           InsertNewInstBefore(And, CI);
7108           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7109         }
7110         return And;
7111       }
7112     }
7113   }
7114
7115   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7116     // If we are just checking for a icmp eq of a single bit and zext'ing it
7117     // to an integer, then shift the bit to the appropriate place and then
7118     // cast to integer to avoid the comparison.
7119     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7120       const APInt &Op1CV = Op1C->getValue();
7121       
7122       // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7123       // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7124       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7125           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7126         Value *In = ICI->getOperand(0);
7127         Value *Sh = ConstantInt::get(In->getType(),
7128                                     In->getType()->getPrimitiveSizeInBits()-1);
7129         In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7130                                                         In->getName()+".lobit"),
7131                                  CI);
7132         if (In->getType() != CI.getType())
7133           In = CastInst::createIntegerCast(In, CI.getType(),
7134                                            false/*ZExt*/, "tmp", &CI);
7135
7136         if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7137           Constant *One = ConstantInt::get(In->getType(), 1);
7138           In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7139                                                           In->getName()+".not"),
7140                                    CI);
7141         }
7142
7143         return ReplaceInstUsesWith(CI, In);
7144       }
7145       
7146       
7147       
7148       // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7149       // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7150       // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7151       // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7152       // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7153       // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7154       // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7155       // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7156       if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7157           // This only works for EQ and NE
7158           ICI->isEquality()) {
7159         // If Op1C some other power of two, convert:
7160         uint32_t BitWidth = Op1C->getType()->getBitWidth();
7161         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7162         APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7163         ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7164         
7165         APInt KnownZeroMask(~KnownZero);
7166         if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7167           bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7168           if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7169             // (X&4) == 2 --> false
7170             // (X&4) != 2 --> true
7171             Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7172             Res = ConstantExpr::getZExt(Res, CI.getType());
7173             return ReplaceInstUsesWith(CI, Res);
7174           }
7175           
7176           uint32_t ShiftAmt = KnownZeroMask.logBase2();
7177           Value *In = ICI->getOperand(0);
7178           if (ShiftAmt) {
7179             // Perform a logical shr by shiftamt.
7180             // Insert the shift to put the result in the low bit.
7181             In = InsertNewInstBefore(
7182                    BinaryOperator::createLShr(In,
7183                                      ConstantInt::get(In->getType(), ShiftAmt),
7184                                               In->getName()+".lobit"), CI);
7185           }
7186           
7187           if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7188             Constant *One = ConstantInt::get(In->getType(), 1);
7189             In = BinaryOperator::createXor(In, One, "tmp");
7190             InsertNewInstBefore(cast<Instruction>(In), CI);
7191           }
7192           
7193           if (CI.getType() == In->getType())
7194             return ReplaceInstUsesWith(CI, In);
7195           else
7196             return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7197         }
7198       }
7199     }
7200   }    
7201   return 0;
7202 }
7203
7204 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7205   if (Instruction *I = commonIntCastTransforms(CI))
7206     return I;
7207   
7208   Value *Src = CI.getOperand(0);
7209   
7210   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7211   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7212   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7213     // If we are just checking for a icmp eq of a single bit and zext'ing it
7214     // to an integer, then shift the bit to the appropriate place and then
7215     // cast to integer to avoid the comparison.
7216     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7217       const APInt &Op1CV = Op1C->getValue();
7218       
7219       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7220       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7221       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7222           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7223         Value *In = ICI->getOperand(0);
7224         Value *Sh = ConstantInt::get(In->getType(),
7225                                      In->getType()->getPrimitiveSizeInBits()-1);
7226         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7227                                                         In->getName()+".lobit"),
7228                                  CI);
7229         if (In->getType() != CI.getType())
7230           In = CastInst::createIntegerCast(In, CI.getType(),
7231                                            true/*SExt*/, "tmp", &CI);
7232         
7233         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7234           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7235                                      In->getName()+".not"), CI);
7236         
7237         return ReplaceInstUsesWith(CI, In);
7238       }
7239     }
7240   }
7241       
7242   return 0;
7243 }
7244
7245 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7246 /// in the specified FP type without changing its value.
7247 static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy, 
7248                               const fltSemantics &Sem) {
7249   APFloat F = CFP->getValueAPF();
7250   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7251     return ConstantFP::get(FPTy, F);
7252   return 0;
7253 }
7254
7255 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7256 /// through it until we get the source value.
7257 static Value *LookThroughFPExtensions(Value *V) {
7258   if (Instruction *I = dyn_cast<Instruction>(V))
7259     if (I->getOpcode() == Instruction::FPExt)
7260       return LookThroughFPExtensions(I->getOperand(0));
7261   
7262   // If this value is a constant, return the constant in the smallest FP type
7263   // that can accurately represent it.  This allows us to turn
7264   // (float)((double)X+2.0) into x+2.0f.
7265   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7266     if (CFP->getType() == Type::PPC_FP128Ty)
7267       return V;  // No constant folding of this.
7268     // See if the value can be truncated to float and then reextended.
7269     if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7270       return V;
7271     if (CFP->getType() == Type::DoubleTy)
7272       return V;  // Won't shrink.
7273     if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7274       return V;
7275     // Don't try to shrink to various long double types.
7276   }
7277   
7278   return V;
7279 }
7280
7281 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7282   if (Instruction *I = commonCastTransforms(CI))
7283     return I;
7284   
7285   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7286   // smaller than the destination type, we can eliminate the truncate by doing
7287   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7288   // many builtins (sqrt, etc).
7289   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7290   if (OpI && OpI->hasOneUse()) {
7291     switch (OpI->getOpcode()) {
7292     default: break;
7293     case Instruction::Add:
7294     case Instruction::Sub:
7295     case Instruction::Mul:
7296     case Instruction::FDiv:
7297     case Instruction::FRem:
7298       const Type *SrcTy = OpI->getType();
7299       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7300       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7301       if (LHSTrunc->getType() != SrcTy && 
7302           RHSTrunc->getType() != SrcTy) {
7303         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7304         // If the source types were both smaller than the destination type of
7305         // the cast, do this xform.
7306         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7307             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7308           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7309                                       CI.getType(), CI);
7310           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7311                                       CI.getType(), CI);
7312           return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7313         }
7314       }
7315       break;  
7316     }
7317   }
7318   return 0;
7319 }
7320
7321 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7322   return commonCastTransforms(CI);
7323 }
7324
7325 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7326   return commonCastTransforms(CI);
7327 }
7328
7329 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7330   return commonCastTransforms(CI);
7331 }
7332
7333 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7334   return commonCastTransforms(CI);
7335 }
7336
7337 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7338   return commonCastTransforms(CI);
7339 }
7340
7341 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7342   return commonPointerCastTransforms(CI);
7343 }
7344
7345 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7346   if (Instruction *I = commonCastTransforms(CI))
7347     return I;
7348   
7349   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7350   if (!DestPointee->isSized()) return 0;
7351
7352   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7353   ConstantInt *Cst;
7354   Value *X;
7355   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7356                                     m_ConstantInt(Cst)))) {
7357     // If the source and destination operands have the same type, see if this
7358     // is a single-index GEP.
7359     if (X->getType() == CI.getType()) {
7360       // Get the size of the pointee type.
7361       uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7362
7363       // Convert the constant to intptr type.
7364       APInt Offset = Cst->getValue();
7365       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7366
7367       // If Offset is evenly divisible by Size, we can do this xform.
7368       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7369         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7370         return new GetElementPtrInst(X, ConstantInt::get(Offset));
7371       }
7372     }
7373     // TODO: Could handle other cases, e.g. where add is indexing into field of
7374     // struct etc.
7375   } else if (CI.getOperand(0)->hasOneUse() &&
7376              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7377     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7378     // "inttoptr+GEP" instead of "add+intptr".
7379     
7380     // Get the size of the pointee type.
7381     uint64_t Size = TD->getABITypeSize(DestPointee);
7382     
7383     // Convert the constant to intptr type.
7384     APInt Offset = Cst->getValue();
7385     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7386     
7387     // If Offset is evenly divisible by Size, we can do this xform.
7388     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7389       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7390       
7391       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7392                                                             "tmp"), CI);
7393       return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7394     }
7395   }
7396   return 0;
7397 }
7398
7399 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7400   // If the operands are integer typed then apply the integer transforms,
7401   // otherwise just apply the common ones.
7402   Value *Src = CI.getOperand(0);
7403   const Type *SrcTy = Src->getType();
7404   const Type *DestTy = CI.getType();
7405
7406   if (SrcTy->isInteger() && DestTy->isInteger()) {
7407     if (Instruction *Result = commonIntCastTransforms(CI))
7408       return Result;
7409   } else if (isa<PointerType>(SrcTy)) {
7410     if (Instruction *I = commonPointerCastTransforms(CI))
7411       return I;
7412   } else {
7413     if (Instruction *Result = commonCastTransforms(CI))
7414       return Result;
7415   }
7416
7417
7418   // Get rid of casts from one type to the same type. These are useless and can
7419   // be replaced by the operand.
7420   if (DestTy == Src->getType())
7421     return ReplaceInstUsesWith(CI, Src);
7422
7423   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7424     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7425     const Type *DstElTy = DstPTy->getElementType();
7426     const Type *SrcElTy = SrcPTy->getElementType();
7427     
7428     // If we are casting a malloc or alloca to a pointer to a type of the same
7429     // size, rewrite the allocation instruction to allocate the "right" type.
7430     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7431       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7432         return V;
7433     
7434     // If the source and destination are pointers, and this cast is equivalent
7435     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7436     // This can enhance SROA and other transforms that want type-safe pointers.
7437     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7438     unsigned NumZeros = 0;
7439     while (SrcElTy != DstElTy && 
7440            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7441            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7442       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7443       ++NumZeros;
7444     }
7445
7446     // If we found a path from the src to dest, create the getelementptr now.
7447     if (SrcElTy == DstElTy) {
7448       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7449       return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "", 
7450                                    ((Instruction*) NULL));
7451     }
7452   }
7453
7454   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7455     if (SVI->hasOneUse()) {
7456       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7457       // a bitconvert to a vector with the same # elts.
7458       if (isa<VectorType>(DestTy) && 
7459           cast<VectorType>(DestTy)->getNumElements() == 
7460                 SVI->getType()->getNumElements()) {
7461         CastInst *Tmp;
7462         // If either of the operands is a cast from CI.getType(), then
7463         // evaluating the shuffle in the casted destination's type will allow
7464         // us to eliminate at least one cast.
7465         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7466              Tmp->getOperand(0)->getType() == DestTy) ||
7467             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7468              Tmp->getOperand(0)->getType() == DestTy)) {
7469           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7470                                                SVI->getOperand(0), DestTy, &CI);
7471           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7472                                                SVI->getOperand(1), DestTy, &CI);
7473           // Return a new shuffle vector.  Use the same element ID's, as we
7474           // know the vector types match #elts.
7475           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7476         }
7477       }
7478     }
7479   }
7480   return 0;
7481 }
7482
7483 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7484 ///   %C = or %A, %B
7485 ///   %D = select %cond, %C, %A
7486 /// into:
7487 ///   %C = select %cond, %B, 0
7488 ///   %D = or %A, %C
7489 ///
7490 /// Assuming that the specified instruction is an operand to the select, return
7491 /// a bitmask indicating which operands of this instruction are foldable if they
7492 /// equal the other incoming value of the select.
7493 ///
7494 static unsigned GetSelectFoldableOperands(Instruction *I) {
7495   switch (I->getOpcode()) {
7496   case Instruction::Add:
7497   case Instruction::Mul:
7498   case Instruction::And:
7499   case Instruction::Or:
7500   case Instruction::Xor:
7501     return 3;              // Can fold through either operand.
7502   case Instruction::Sub:   // Can only fold on the amount subtracted.
7503   case Instruction::Shl:   // Can only fold on the shift amount.
7504   case Instruction::LShr:
7505   case Instruction::AShr:
7506     return 1;
7507   default:
7508     return 0;              // Cannot fold
7509   }
7510 }
7511
7512 /// GetSelectFoldableConstant - For the same transformation as the previous
7513 /// function, return the identity constant that goes into the select.
7514 static Constant *GetSelectFoldableConstant(Instruction *I) {
7515   switch (I->getOpcode()) {
7516   default: assert(0 && "This cannot happen!"); abort();
7517   case Instruction::Add:
7518   case Instruction::Sub:
7519   case Instruction::Or:
7520   case Instruction::Xor:
7521   case Instruction::Shl:
7522   case Instruction::LShr:
7523   case Instruction::AShr:
7524     return Constant::getNullValue(I->getType());
7525   case Instruction::And:
7526     return Constant::getAllOnesValue(I->getType());
7527   case Instruction::Mul:
7528     return ConstantInt::get(I->getType(), 1);
7529   }
7530 }
7531
7532 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7533 /// have the same opcode and only one use each.  Try to simplify this.
7534 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7535                                           Instruction *FI) {
7536   if (TI->getNumOperands() == 1) {
7537     // If this is a non-volatile load or a cast from the same type,
7538     // merge.
7539     if (TI->isCast()) {
7540       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7541         return 0;
7542     } else {
7543       return 0;  // unknown unary op.
7544     }
7545
7546     // Fold this by inserting a select from the input values.
7547     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7548                                        FI->getOperand(0), SI.getName()+".v");
7549     InsertNewInstBefore(NewSI, SI);
7550     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7551                             TI->getType());
7552   }
7553
7554   // Only handle binary operators here.
7555   if (!isa<BinaryOperator>(TI))
7556     return 0;
7557
7558   // Figure out if the operations have any operands in common.
7559   Value *MatchOp, *OtherOpT, *OtherOpF;
7560   bool MatchIsOpZero;
7561   if (TI->getOperand(0) == FI->getOperand(0)) {
7562     MatchOp  = TI->getOperand(0);
7563     OtherOpT = TI->getOperand(1);
7564     OtherOpF = FI->getOperand(1);
7565     MatchIsOpZero = true;
7566   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7567     MatchOp  = TI->getOperand(1);
7568     OtherOpT = TI->getOperand(0);
7569     OtherOpF = FI->getOperand(0);
7570     MatchIsOpZero = false;
7571   } else if (!TI->isCommutative()) {
7572     return 0;
7573   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7574     MatchOp  = TI->getOperand(0);
7575     OtherOpT = TI->getOperand(1);
7576     OtherOpF = FI->getOperand(0);
7577     MatchIsOpZero = true;
7578   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7579     MatchOp  = TI->getOperand(1);
7580     OtherOpT = TI->getOperand(0);
7581     OtherOpF = FI->getOperand(1);
7582     MatchIsOpZero = true;
7583   } else {
7584     return 0;
7585   }
7586
7587   // If we reach here, they do have operations in common.
7588   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7589                                      OtherOpF, SI.getName()+".v");
7590   InsertNewInstBefore(NewSI, SI);
7591
7592   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7593     if (MatchIsOpZero)
7594       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7595     else
7596       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7597   }
7598   assert(0 && "Shouldn't get here");
7599   return 0;
7600 }
7601
7602 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7603   Value *CondVal = SI.getCondition();
7604   Value *TrueVal = SI.getTrueValue();
7605   Value *FalseVal = SI.getFalseValue();
7606
7607   // select true, X, Y  -> X
7608   // select false, X, Y -> Y
7609   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7610     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7611
7612   // select C, X, X -> X
7613   if (TrueVal == FalseVal)
7614     return ReplaceInstUsesWith(SI, TrueVal);
7615
7616   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7617     return ReplaceInstUsesWith(SI, FalseVal);
7618   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7619     return ReplaceInstUsesWith(SI, TrueVal);
7620   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7621     if (isa<Constant>(TrueVal))
7622       return ReplaceInstUsesWith(SI, TrueVal);
7623     else
7624       return ReplaceInstUsesWith(SI, FalseVal);
7625   }
7626
7627   if (SI.getType() == Type::Int1Ty) {
7628     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7629       if (C->getZExtValue()) {
7630         // Change: A = select B, true, C --> A = or B, C
7631         return BinaryOperator::createOr(CondVal, FalseVal);
7632       } else {
7633         // Change: A = select B, false, C --> A = and !B, C
7634         Value *NotCond =
7635           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7636                                              "not."+CondVal->getName()), SI);
7637         return BinaryOperator::createAnd(NotCond, FalseVal);
7638       }
7639     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7640       if (C->getZExtValue() == false) {
7641         // Change: A = select B, C, false --> A = and B, C
7642         return BinaryOperator::createAnd(CondVal, TrueVal);
7643       } else {
7644         // Change: A = select B, C, true --> A = or !B, C
7645         Value *NotCond =
7646           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7647                                              "not."+CondVal->getName()), SI);
7648         return BinaryOperator::createOr(NotCond, TrueVal);
7649       }
7650     }
7651     
7652     // select a, b, a  -> a&b
7653     // select a, a, b  -> a|b
7654     if (CondVal == TrueVal)
7655       return BinaryOperator::createOr(CondVal, FalseVal);
7656     else if (CondVal == FalseVal)
7657       return BinaryOperator::createAnd(CondVal, TrueVal);
7658   }
7659
7660   // Selecting between two integer constants?
7661   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7662     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7663       // select C, 1, 0 -> zext C to int
7664       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7665         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7666       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7667         // select C, 0, 1 -> zext !C to int
7668         Value *NotCond =
7669           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7670                                                "not."+CondVal->getName()), SI);
7671         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7672       }
7673       
7674       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7675
7676       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7677
7678         // (x <s 0) ? -1 : 0 -> ashr x, 31
7679         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7680           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7681             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7682               // The comparison constant and the result are not neccessarily the
7683               // same width. Make an all-ones value by inserting a AShr.
7684               Value *X = IC->getOperand(0);
7685               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7686               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7687               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7688                                                         ShAmt, "ones");
7689               InsertNewInstBefore(SRA, SI);
7690               
7691               // Finally, convert to the type of the select RHS.  We figure out
7692               // if this requires a SExt, Trunc or BitCast based on the sizes.
7693               Instruction::CastOps opc = Instruction::BitCast;
7694               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7695               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
7696               if (SRASize < SISize)
7697                 opc = Instruction::SExt;
7698               else if (SRASize > SISize)
7699                 opc = Instruction::Trunc;
7700               return CastInst::create(opc, SRA, SI.getType());
7701             }
7702           }
7703
7704
7705         // If one of the constants is zero (we know they can't both be) and we
7706         // have an icmp instruction with zero, and we have an 'and' with the
7707         // non-constant value, eliminate this whole mess.  This corresponds to
7708         // cases like this: ((X & 27) ? 27 : 0)
7709         if (TrueValC->isZero() || FalseValC->isZero())
7710           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7711               cast<Constant>(IC->getOperand(1))->isNullValue())
7712             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7713               if (ICA->getOpcode() == Instruction::And &&
7714                   isa<ConstantInt>(ICA->getOperand(1)) &&
7715                   (ICA->getOperand(1) == TrueValC ||
7716                    ICA->getOperand(1) == FalseValC) &&
7717                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7718                 // Okay, now we know that everything is set up, we just don't
7719                 // know whether we have a icmp_ne or icmp_eq and whether the 
7720                 // true or false val is the zero.
7721                 bool ShouldNotVal = !TrueValC->isZero();
7722                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7723                 Value *V = ICA;
7724                 if (ShouldNotVal)
7725                   V = InsertNewInstBefore(BinaryOperator::create(
7726                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
7727                 return ReplaceInstUsesWith(SI, V);
7728               }
7729       }
7730     }
7731
7732   // See if we are selecting two values based on a comparison of the two values.
7733   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7734     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7735       // Transform (X == Y) ? X : Y  -> Y
7736       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7737         // This is not safe in general for floating point:  
7738         // consider X== -0, Y== +0.
7739         // It becomes safe if either operand is a nonzero constant.
7740         ConstantFP *CFPt, *CFPf;
7741         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7742               !CFPt->getValueAPF().isZero()) ||
7743             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7744              !CFPf->getValueAPF().isZero()))
7745         return ReplaceInstUsesWith(SI, FalseVal);
7746       }
7747       // Transform (X != Y) ? X : Y  -> X
7748       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7749         return ReplaceInstUsesWith(SI, TrueVal);
7750       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7751
7752     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7753       // Transform (X == Y) ? Y : X  -> X
7754       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7755         // This is not safe in general for floating point:  
7756         // consider X== -0, Y== +0.
7757         // It becomes safe if either operand is a nonzero constant.
7758         ConstantFP *CFPt, *CFPf;
7759         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7760               !CFPt->getValueAPF().isZero()) ||
7761             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7762              !CFPf->getValueAPF().isZero()))
7763           return ReplaceInstUsesWith(SI, FalseVal);
7764       }
7765       // Transform (X != Y) ? Y : X  -> Y
7766       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7767         return ReplaceInstUsesWith(SI, TrueVal);
7768       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7769     }
7770   }
7771
7772   // See if we are selecting two values based on a comparison of the two values.
7773   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7774     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7775       // Transform (X == Y) ? X : Y  -> Y
7776       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7777         return ReplaceInstUsesWith(SI, FalseVal);
7778       // Transform (X != Y) ? X : Y  -> X
7779       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7780         return ReplaceInstUsesWith(SI, TrueVal);
7781       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7782
7783     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7784       // Transform (X == Y) ? Y : X  -> X
7785       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7786         return ReplaceInstUsesWith(SI, FalseVal);
7787       // Transform (X != Y) ? Y : X  -> Y
7788       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7789         return ReplaceInstUsesWith(SI, TrueVal);
7790       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7791     }
7792   }
7793
7794   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7795     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7796       if (TI->hasOneUse() && FI->hasOneUse()) {
7797         Instruction *AddOp = 0, *SubOp = 0;
7798
7799         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7800         if (TI->getOpcode() == FI->getOpcode())
7801           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7802             return IV;
7803
7804         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
7805         // even legal for FP.
7806         if (TI->getOpcode() == Instruction::Sub &&
7807             FI->getOpcode() == Instruction::Add) {
7808           AddOp = FI; SubOp = TI;
7809         } else if (FI->getOpcode() == Instruction::Sub &&
7810                    TI->getOpcode() == Instruction::Add) {
7811           AddOp = TI; SubOp = FI;
7812         }
7813
7814         if (AddOp) {
7815           Value *OtherAddOp = 0;
7816           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7817             OtherAddOp = AddOp->getOperand(1);
7818           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7819             OtherAddOp = AddOp->getOperand(0);
7820           }
7821
7822           if (OtherAddOp) {
7823             // So at this point we know we have (Y -> OtherAddOp):
7824             //        select C, (add X, Y), (sub X, Z)
7825             Value *NegVal;  // Compute -Z
7826             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7827               NegVal = ConstantExpr::getNeg(C);
7828             } else {
7829               NegVal = InsertNewInstBefore(
7830                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7831             }
7832
7833             Value *NewTrueOp = OtherAddOp;
7834             Value *NewFalseOp = NegVal;
7835             if (AddOp != TI)
7836               std::swap(NewTrueOp, NewFalseOp);
7837             Instruction *NewSel =
7838               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7839
7840             NewSel = InsertNewInstBefore(NewSel, SI);
7841             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7842           }
7843         }
7844       }
7845
7846   // See if we can fold the select into one of our operands.
7847   if (SI.getType()->isInteger()) {
7848     // See the comment above GetSelectFoldableOperands for a description of the
7849     // transformation we are doing here.
7850     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7851       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7852           !isa<Constant>(FalseVal))
7853         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7854           unsigned OpToFold = 0;
7855           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7856             OpToFold = 1;
7857           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7858             OpToFold = 2;
7859           }
7860
7861           if (OpToFold) {
7862             Constant *C = GetSelectFoldableConstant(TVI);
7863             Instruction *NewSel =
7864               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7865             InsertNewInstBefore(NewSel, SI);
7866             NewSel->takeName(TVI);
7867             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7868               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7869             else {
7870               assert(0 && "Unknown instruction!!");
7871             }
7872           }
7873         }
7874
7875     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7876       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7877           !isa<Constant>(TrueVal))
7878         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7879           unsigned OpToFold = 0;
7880           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7881             OpToFold = 1;
7882           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7883             OpToFold = 2;
7884           }
7885
7886           if (OpToFold) {
7887             Constant *C = GetSelectFoldableConstant(FVI);
7888             Instruction *NewSel =
7889               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7890             InsertNewInstBefore(NewSel, SI);
7891             NewSel->takeName(FVI);
7892             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7893               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7894             else
7895               assert(0 && "Unknown instruction!!");
7896           }
7897         }
7898   }
7899
7900   if (BinaryOperator::isNot(CondVal)) {
7901     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7902     SI.setOperand(1, FalseVal);
7903     SI.setOperand(2, TrueVal);
7904     return &SI;
7905   }
7906
7907   return 0;
7908 }
7909
7910 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7911 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
7912 /// and it is more than the alignment of the ultimate object, see if we can
7913 /// increase the alignment of the ultimate object, making this check succeed.
7914 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7915                                            unsigned PrefAlign = 0) {
7916   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7917     unsigned Align = GV->getAlignment();
7918     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
7919       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7920
7921     // If there is a large requested alignment and we can, bump up the alignment
7922     // of the global.
7923     if (PrefAlign > Align && GV->hasInitializer()) {
7924       GV->setAlignment(PrefAlign);
7925       Align = PrefAlign;
7926     }
7927     return Align;
7928   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7929     unsigned Align = AI->getAlignment();
7930     if (Align == 0 && TD) {
7931       if (isa<AllocaInst>(AI))
7932         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7933       else if (isa<MallocInst>(AI)) {
7934         // Malloc returns maximally aligned memory.
7935         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7936         Align =
7937           std::max(Align,
7938                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7939         Align =
7940           std::max(Align,
7941                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7942       }
7943     }
7944     
7945     // If there is a requested alignment and if this is an alloca, round up.  We
7946     // don't do this for malloc, because some systems can't respect the request.
7947     if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7948       AI->setAlignment(PrefAlign);
7949       Align = PrefAlign;
7950     }
7951     return Align;
7952   } else if (isa<BitCastInst>(V) ||
7953              (isa<ConstantExpr>(V) && 
7954               cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7955     return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7956                                       TD, PrefAlign);
7957   } else if (User *GEPI = dyn_castGetElementPtr(V)) {
7958     // If all indexes are zero, it is just the alignment of the base pointer.
7959     bool AllZeroOperands = true;
7960     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7961       if (!isa<Constant>(GEPI->getOperand(i)) ||
7962           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7963         AllZeroOperands = false;
7964         break;
7965       }
7966
7967     if (AllZeroOperands) {
7968       // Treat this like a bitcast.
7969       return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7970     }
7971
7972     unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7973     if (BaseAlignment == 0) return 0;
7974
7975     // Otherwise, if the base alignment is >= the alignment we expect for the
7976     // base pointer type, then we know that the resultant pointer is aligned at
7977     // least as much as its type requires.
7978     if (!TD) return 0;
7979
7980     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7981     const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7982     unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7983     if (Align <= BaseAlignment) {
7984       const Type *GEPTy = GEPI->getType();
7985       const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7986       Align = std::min(Align, (unsigned)
7987                        TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7988       return Align;
7989     }
7990     return 0;
7991   }
7992   return 0;
7993 }
7994
7995 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7996   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7997   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7998   unsigned MinAlign = std::min(DstAlign, SrcAlign);
7999   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8000
8001   if (CopyAlign < MinAlign) {
8002     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8003     return MI;
8004   }
8005   
8006   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8007   // load/store.
8008   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8009   if (MemOpLength == 0) return 0;
8010   
8011   // Source and destination pointer types are always "i8*" for intrinsic.  See
8012   // if the size is something we can handle with a single primitive load/store.
8013   // A single load+store correctly handles overlapping memory in the memmove
8014   // case.
8015   unsigned Size = MemOpLength->getZExtValue();
8016   if (Size == 0 || Size > 8 || (Size&(Size-1)))
8017     return 0;  // If not 1/2/4/8 bytes, exit.
8018   
8019   // Use an integer load+store unless we can find something better.
8020   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8021   
8022   // Memcpy forces the use of i8* for the source and destination.  That means
8023   // that if you're using memcpy to move one double around, you'll get a cast
8024   // from double* to i8*.  We'd much rather use a double load+store rather than
8025   // an i64 load+store, here because this improves the odds that the source or
8026   // dest address will be promotable.  See if we can find a better type than the
8027   // integer datatype.
8028   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8029     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8030     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8031       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8032       // down through these levels if so.
8033       while (!SrcETy->isFirstClassType()) {
8034         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8035           if (STy->getNumElements() == 1)
8036             SrcETy = STy->getElementType(0);
8037           else
8038             break;
8039         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8040           if (ATy->getNumElements() == 1)
8041             SrcETy = ATy->getElementType();
8042           else
8043             break;
8044         } else
8045           break;
8046       }
8047       
8048       if (SrcETy->isFirstClassType())
8049         NewPtrTy = PointerType::getUnqual(SrcETy);
8050     }
8051   }
8052   
8053   
8054   // If the memcpy/memmove provides better alignment info than we can
8055   // infer, use it.
8056   SrcAlign = std::max(SrcAlign, CopyAlign);
8057   DstAlign = std::max(DstAlign, CopyAlign);
8058   
8059   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8060   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8061   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8062   InsertNewInstBefore(L, *MI);
8063   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8064
8065   // Set the size of the copy to 0, it will be deleted on the next iteration.
8066   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8067   return MI;
8068 }
8069
8070 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8071 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8072 /// the heavy lifting.
8073 ///
8074 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8075   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8076   if (!II) return visitCallSite(&CI);
8077   
8078   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8079   // visitCallSite.
8080   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8081     bool Changed = false;
8082
8083     // memmove/cpy/set of zero bytes is a noop.
8084     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8085       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8086
8087       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8088         if (CI->getZExtValue() == 1) {
8089           // Replace the instruction with just byte operations.  We would
8090           // transform other cases to loads/stores, but we don't know if
8091           // alignment is sufficient.
8092         }
8093     }
8094
8095     // If we have a memmove and the source operation is a constant global,
8096     // then the source and dest pointers can't alias, so we can change this
8097     // into a call to memcpy.
8098     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8099       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8100         if (GVSrc->isConstant()) {
8101           Module *M = CI.getParent()->getParent()->getParent();
8102           Intrinsic::ID MemCpyID;
8103           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8104             MemCpyID = Intrinsic::memcpy_i32;
8105           else
8106             MemCpyID = Intrinsic::memcpy_i64;
8107           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8108           Changed = true;
8109         }
8110     }
8111
8112     // If we can determine a pointer alignment that is bigger than currently
8113     // set, update the alignment.
8114     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8115       if (Instruction *I = SimplifyMemTransfer(MI))
8116         return I;
8117     } else if (isa<MemSetInst>(MI)) {
8118       unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
8119       if (MI->getAlignment()->getZExtValue() < Alignment) {
8120         MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8121         Changed = true;
8122       }
8123     }
8124           
8125     if (Changed) return II;
8126   } else {
8127     switch (II->getIntrinsicID()) {
8128     default: break;
8129     case Intrinsic::ppc_altivec_lvx:
8130     case Intrinsic::ppc_altivec_lvxl:
8131     case Intrinsic::x86_sse_loadu_ps:
8132     case Intrinsic::x86_sse2_loadu_pd:
8133     case Intrinsic::x86_sse2_loadu_dq:
8134       // Turn PPC lvx     -> load if the pointer is known aligned.
8135       // Turn X86 loadups -> load if the pointer is known aligned.
8136       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8137         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8138                                          PointerType::getUnqual(II->getType()),
8139                                          CI);
8140         return new LoadInst(Ptr);
8141       }
8142       break;
8143     case Intrinsic::ppc_altivec_stvx:
8144     case Intrinsic::ppc_altivec_stvxl:
8145       // Turn stvx -> store if the pointer is known aligned.
8146       if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
8147         const Type *OpPtrTy = 
8148           PointerType::getUnqual(II->getOperand(1)->getType());
8149         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8150         return new StoreInst(II->getOperand(1), Ptr);
8151       }
8152       break;
8153     case Intrinsic::x86_sse_storeu_ps:
8154     case Intrinsic::x86_sse2_storeu_pd:
8155     case Intrinsic::x86_sse2_storeu_dq:
8156     case Intrinsic::x86_sse2_storel_dq:
8157       // Turn X86 storeu -> store if the pointer is known aligned.
8158       if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8159         const Type *OpPtrTy = 
8160           PointerType::getUnqual(II->getOperand(2)->getType());
8161         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8162         return new StoreInst(II->getOperand(2), Ptr);
8163       }
8164       break;
8165       
8166     case Intrinsic::x86_sse_cvttss2si: {
8167       // These intrinsics only demands the 0th element of its input vector.  If
8168       // we can simplify the input based on that, do so now.
8169       uint64_t UndefElts;
8170       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8171                                                 UndefElts)) {
8172         II->setOperand(1, V);
8173         return II;
8174       }
8175       break;
8176     }
8177       
8178     case Intrinsic::ppc_altivec_vperm:
8179       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8180       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8181         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8182         
8183         // Check that all of the elements are integer constants or undefs.
8184         bool AllEltsOk = true;
8185         for (unsigned i = 0; i != 16; ++i) {
8186           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8187               !isa<UndefValue>(Mask->getOperand(i))) {
8188             AllEltsOk = false;
8189             break;
8190           }
8191         }
8192         
8193         if (AllEltsOk) {
8194           // Cast the input vectors to byte vectors.
8195           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8196           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8197           Value *Result = UndefValue::get(Op0->getType());
8198           
8199           // Only extract each element once.
8200           Value *ExtractedElts[32];
8201           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8202           
8203           for (unsigned i = 0; i != 16; ++i) {
8204             if (isa<UndefValue>(Mask->getOperand(i)))
8205               continue;
8206             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8207             Idx &= 31;  // Match the hardware behavior.
8208             
8209             if (ExtractedElts[Idx] == 0) {
8210               Instruction *Elt = 
8211                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8212               InsertNewInstBefore(Elt, CI);
8213               ExtractedElts[Idx] = Elt;
8214             }
8215           
8216             // Insert this value into the result vector.
8217             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8218             InsertNewInstBefore(cast<Instruction>(Result), CI);
8219           }
8220           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8221         }
8222       }
8223       break;
8224
8225     case Intrinsic::stackrestore: {
8226       // If the save is right next to the restore, remove the restore.  This can
8227       // happen when variable allocas are DCE'd.
8228       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8229         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8230           BasicBlock::iterator BI = SS;
8231           if (&*++BI == II)
8232             return EraseInstFromFunction(CI);
8233         }
8234       }
8235       
8236       // Scan down this block to see if there is another stack restore in the
8237       // same block without an intervening call/alloca.
8238       BasicBlock::iterator BI = II;
8239       TerminatorInst *TI = II->getParent()->getTerminator();
8240       bool CannotRemove = false;
8241       for (++BI; &*BI != TI; ++BI) {
8242         if (isa<AllocaInst>(BI)) {
8243           CannotRemove = true;
8244           break;
8245         }
8246         if (isa<CallInst>(BI)) {
8247           if (!isa<IntrinsicInst>(BI)) {
8248             CannotRemove = true;
8249             break;
8250           }
8251           // If there is a stackrestore below this one, remove this one.
8252           return EraseInstFromFunction(CI);
8253         }
8254       }
8255       
8256       // If the stack restore is in a return/unwind block and if there are no
8257       // allocas or calls between the restore and the return, nuke the restore.
8258       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8259         return EraseInstFromFunction(CI);
8260       break;
8261     }
8262     }
8263   }
8264
8265   return visitCallSite(II);
8266 }
8267
8268 // InvokeInst simplification
8269 //
8270 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8271   return visitCallSite(&II);
8272 }
8273
8274 // visitCallSite - Improvements for call and invoke instructions.
8275 //
8276 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8277   bool Changed = false;
8278
8279   // If the callee is a constexpr cast of a function, attempt to move the cast
8280   // to the arguments of the call/invoke.
8281   if (transformConstExprCastCall(CS)) return 0;
8282
8283   Value *Callee = CS.getCalledValue();
8284
8285   if (Function *CalleeF = dyn_cast<Function>(Callee))
8286     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8287       Instruction *OldCall = CS.getInstruction();
8288       // If the call and callee calling conventions don't match, this call must
8289       // be unreachable, as the call is undefined.
8290       new StoreInst(ConstantInt::getTrue(),
8291                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8292                                     OldCall);
8293       if (!OldCall->use_empty())
8294         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8295       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8296         return EraseInstFromFunction(*OldCall);
8297       return 0;
8298     }
8299
8300   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8301     // This instruction is not reachable, just remove it.  We insert a store to
8302     // undef so that we know that this code is not reachable, despite the fact
8303     // that we can't modify the CFG here.
8304     new StoreInst(ConstantInt::getTrue(),
8305                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8306                   CS.getInstruction());
8307
8308     if (!CS.getInstruction()->use_empty())
8309       CS.getInstruction()->
8310         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8311
8312     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8313       // Don't break the CFG, insert a dummy cond branch.
8314       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8315                      ConstantInt::getTrue(), II);
8316     }
8317     return EraseInstFromFunction(*CS.getInstruction());
8318   }
8319
8320   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8321     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8322       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8323         return transformCallThroughTrampoline(CS);
8324
8325   const PointerType *PTy = cast<PointerType>(Callee->getType());
8326   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8327   if (FTy->isVarArg()) {
8328     // See if we can optimize any arguments passed through the varargs area of
8329     // the call.
8330     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8331            E = CS.arg_end(); I != E; ++I)
8332       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8333         // If this cast does not effect the value passed through the varargs
8334         // area, we can eliminate the use of the cast.
8335         Value *Op = CI->getOperand(0);
8336         if (CI->isLosslessCast()) {
8337           *I = Op;
8338           Changed = true;
8339         }
8340       }
8341   }
8342
8343   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8344     // Inline asm calls cannot throw - mark them 'nounwind'.
8345     CS.setDoesNotThrow();
8346     Changed = true;
8347   }
8348
8349   return Changed ? CS.getInstruction() : 0;
8350 }
8351
8352 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8353 // attempt to move the cast to the arguments of the call/invoke.
8354 //
8355 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8356   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8357   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8358   if (CE->getOpcode() != Instruction::BitCast || 
8359       !isa<Function>(CE->getOperand(0)))
8360     return false;
8361   Function *Callee = cast<Function>(CE->getOperand(0));
8362   Instruction *Caller = CS.getInstruction();
8363   const ParamAttrsList* CallerPAL = CS.getParamAttrs();
8364
8365   // Okay, this is a cast from a function to a different type.  Unless doing so
8366   // would cause a type conversion of one of our arguments, change this call to
8367   // be a direct call with arguments casted to the appropriate types.
8368   //
8369   const FunctionType *FT = Callee->getFunctionType();
8370   const Type *OldRetTy = Caller->getType();
8371
8372   // Check to see if we are changing the return type...
8373   if (OldRetTy != FT->getReturnType()) {
8374     if (Callee->isDeclaration() && !Caller->use_empty() && 
8375         // Conversion is ok if changing from pointer to int of same size.
8376         !(isa<PointerType>(FT->getReturnType()) &&
8377           TD->getIntPtrType() == OldRetTy))
8378       return false;   // Cannot transform this return value.
8379
8380     if (!Caller->use_empty() &&
8381         // void -> non-void is handled specially
8382         FT->getReturnType() != Type::VoidTy &&
8383         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8384       return false;   // Cannot transform this return value.
8385
8386     if (CallerPAL && !Caller->use_empty()) {
8387       ParameterAttributes RAttrs = CallerPAL->getParamAttrs(0);
8388       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8389         return false;   // Attribute not compatible with transformed value.
8390     }
8391
8392     // If the callsite is an invoke instruction, and the return value is used by
8393     // a PHI node in a successor, we cannot change the return type of the call
8394     // because there is no place to put the cast instruction (without breaking
8395     // the critical edge).  Bail out in this case.
8396     if (!Caller->use_empty())
8397       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8398         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8399              UI != E; ++UI)
8400           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8401             if (PN->getParent() == II->getNormalDest() ||
8402                 PN->getParent() == II->getUnwindDest())
8403               return false;
8404   }
8405
8406   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8407   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8408
8409   CallSite::arg_iterator AI = CS.arg_begin();
8410   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8411     const Type *ParamTy = FT->getParamType(i);
8412     const Type *ActTy = (*AI)->getType();
8413
8414     if (!CastInst::isCastable(ActTy, ParamTy))
8415       return false;   // Cannot transform this parameter value.
8416
8417     if (CallerPAL) {
8418       ParameterAttributes PAttrs = CallerPAL->getParamAttrs(i + 1);
8419       if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8420         return false;   // Attribute not compatible with transformed value.
8421     }
8422
8423     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8424     // Some conversions are safe even if we do not have a body.
8425     // Either we can cast directly, or we can upconvert the argument
8426     bool isConvertible = ActTy == ParamTy ||
8427       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8428       (ParamTy->isInteger() && ActTy->isInteger() &&
8429        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8430       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8431        && c->getValue().isStrictlyPositive());
8432     if (Callee->isDeclaration() && !isConvertible) return false;
8433   }
8434
8435   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8436       Callee->isDeclaration())
8437     return false;   // Do not delete arguments unless we have a function body...
8438
8439   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
8440     // In this case we have more arguments than the new function type, but we
8441     // won't be dropping them.  Check that these extra arguments have attributes
8442     // that are compatible with being a vararg call argument.
8443     for (unsigned i = CallerPAL->size(); i; --i) {
8444       if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8445         break;
8446       ParameterAttributes PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8447       if (PAttrs & ParamAttr::VarArgsIncompatible)
8448         return false;
8449     }
8450
8451   // Okay, we decided that this is a safe thing to do: go ahead and start
8452   // inserting cast instructions as necessary...
8453   std::vector<Value*> Args;
8454   Args.reserve(NumActualArgs);
8455   ParamAttrsVector attrVec;
8456   attrVec.reserve(NumCommonArgs);
8457
8458   // Get any return attributes.
8459   ParameterAttributes RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) :
8460                                            ParamAttr::None;
8461
8462   // If the return value is not being used, the type may not be compatible
8463   // with the existing attributes.  Wipe out any problematic attributes.
8464   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
8465
8466   // Add the new return attributes.
8467   if (RAttrs)
8468     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8469
8470   AI = CS.arg_begin();
8471   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8472     const Type *ParamTy = FT->getParamType(i);
8473     if ((*AI)->getType() == ParamTy) {
8474       Args.push_back(*AI);
8475     } else {
8476       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8477           false, ParamTy, false);
8478       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8479       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8480     }
8481
8482     // Add any parameter attributes.
8483     ParameterAttributes PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 
8484                                              ParamAttr::None;
8485     if (PAttrs)
8486       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8487   }
8488
8489   // If the function takes more arguments than the call was taking, add them
8490   // now...
8491   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8492     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8493
8494   // If we are removing arguments to the function, emit an obnoxious warning...
8495   if (FT->getNumParams() < NumActualArgs)
8496     if (!FT->isVarArg()) {
8497       cerr << "WARNING: While resolving call to function '"
8498            << Callee->getName() << "' arguments were dropped!\n";
8499     } else {
8500       // Add all of the arguments in their promoted form to the arg list...
8501       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8502         const Type *PTy = getPromotedType((*AI)->getType());
8503         if (PTy != (*AI)->getType()) {
8504           // Must promote to pass through va_arg area!
8505           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8506                                                                 PTy, false);
8507           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8508           InsertNewInstBefore(Cast, *Caller);
8509           Args.push_back(Cast);
8510         } else {
8511           Args.push_back(*AI);
8512         }
8513
8514         // Add any parameter attributes.
8515         ParameterAttributes PAttrs = CallerPAL ? 
8516                                      CallerPAL->getParamAttrs(i + 1) : 
8517                                      ParamAttr::None;
8518         if (PAttrs)
8519           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8520       }
8521     }
8522
8523   if (FT->getReturnType() == Type::VoidTy)
8524     Caller->setName("");   // Void type should not have a name.
8525
8526   const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8527
8528   Instruction *NC;
8529   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8530     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8531                         Args.begin(), Args.end(), Caller->getName(), Caller);
8532     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8533     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8534   } else {
8535     NC = new CallInst(Callee, Args.begin(), Args.end(),
8536                       Caller->getName(), Caller);
8537     CallInst *CI = cast<CallInst>(Caller);
8538     if (CI->isTailCall())
8539       cast<CallInst>(NC)->setTailCall();
8540     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8541     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8542   }
8543
8544   // Insert a cast of the return type as necessary.
8545   Value *NV = NC;
8546   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8547     if (NV->getType() != Type::VoidTy) {
8548       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8549                                                             OldRetTy, false);
8550       NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
8551
8552       // If this is an invoke instruction, we should insert it after the first
8553       // non-phi, instruction in the normal successor block.
8554       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8555         BasicBlock::iterator I = II->getNormalDest()->begin();
8556         while (isa<PHINode>(I)) ++I;
8557         InsertNewInstBefore(NC, *I);
8558       } else {
8559         // Otherwise, it's a call, just insert cast right after the call instr
8560         InsertNewInstBefore(NC, *Caller);
8561       }
8562       AddUsersToWorkList(*Caller);
8563     } else {
8564       NV = UndefValue::get(Caller->getType());
8565     }
8566   }
8567
8568   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8569     Caller->replaceAllUsesWith(NV);
8570   Caller->eraseFromParent();
8571   RemoveFromWorkList(Caller);
8572   return true;
8573 }
8574
8575 // transformCallThroughTrampoline - Turn a call to a function created by the
8576 // init_trampoline intrinsic into a direct call to the underlying function.
8577 //
8578 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8579   Value *Callee = CS.getCalledValue();
8580   const PointerType *PTy = cast<PointerType>(Callee->getType());
8581   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8582   const ParamAttrsList *Attrs = CS.getParamAttrs();
8583
8584   // If the call already has the 'nest' attribute somewhere then give up -
8585   // otherwise 'nest' would occur twice after splicing in the chain.
8586   if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8587     return 0;
8588
8589   IntrinsicInst *Tramp =
8590     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8591
8592   Function *NestF =
8593     cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8594   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8595   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8596
8597   if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
8598     unsigned NestIdx = 1;
8599     const Type *NestTy = 0;
8600     ParameterAttributes NestAttr = ParamAttr::None;
8601
8602     // Look for a parameter marked with the 'nest' attribute.
8603     for (FunctionType::param_iterator I = NestFTy->param_begin(),
8604          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8605       if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8606         // Record the parameter type and any other attributes.
8607         NestTy = *I;
8608         NestAttr = NestAttrs->getParamAttrs(NestIdx);
8609         break;
8610       }
8611
8612     if (NestTy) {
8613       Instruction *Caller = CS.getInstruction();
8614       std::vector<Value*> NewArgs;
8615       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8616
8617       ParamAttrsVector NewAttrs;
8618       NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8619
8620       // Insert the nest argument into the call argument list, which may
8621       // mean appending it.  Likewise for attributes.
8622
8623       // Add any function result attributes.
8624       ParameterAttributes Attr = Attrs ? Attrs->getParamAttrs(0) : 
8625                                          ParamAttr::None;
8626       if (Attr)
8627         NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8628
8629       {
8630         unsigned Idx = 1;
8631         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8632         do {
8633           if (Idx == NestIdx) {
8634             // Add the chain argument and attributes.
8635             Value *NestVal = Tramp->getOperand(3);
8636             if (NestVal->getType() != NestTy)
8637               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8638             NewArgs.push_back(NestVal);
8639             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8640           }
8641
8642           if (I == E)
8643             break;
8644
8645           // Add the original argument and attributes.
8646           NewArgs.push_back(*I);
8647           Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8648           if (Attr)
8649             NewAttrs.push_back
8650               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8651
8652           ++Idx, ++I;
8653         } while (1);
8654       }
8655
8656       // The trampoline may have been bitcast to a bogus type (FTy).
8657       // Handle this by synthesizing a new function type, equal to FTy
8658       // with the chain parameter inserted.
8659
8660       std::vector<const Type*> NewTypes;
8661       NewTypes.reserve(FTy->getNumParams()+1);
8662
8663       // Insert the chain's type into the list of parameter types, which may
8664       // mean appending it.
8665       {
8666         unsigned Idx = 1;
8667         FunctionType::param_iterator I = FTy->param_begin(),
8668           E = FTy->param_end();
8669
8670         do {
8671           if (Idx == NestIdx)
8672             // Add the chain's type.
8673             NewTypes.push_back(NestTy);
8674
8675           if (I == E)
8676             break;
8677
8678           // Add the original type.
8679           NewTypes.push_back(*I);
8680
8681           ++Idx, ++I;
8682         } while (1);
8683       }
8684
8685       // Replace the trampoline call with a direct call.  Let the generic
8686       // code sort out any function type mismatches.
8687       FunctionType *NewFTy =
8688         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8689       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8690         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8691       const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
8692
8693       Instruction *NewCaller;
8694       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8695         NewCaller = new InvokeInst(NewCallee,
8696                                    II->getNormalDest(), II->getUnwindDest(),
8697                                    NewArgs.begin(), NewArgs.end(),
8698                                    Caller->getName(), Caller);
8699         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8700         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8701       } else {
8702         NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8703                                  Caller->getName(), Caller);
8704         if (cast<CallInst>(Caller)->isTailCall())
8705           cast<CallInst>(NewCaller)->setTailCall();
8706         cast<CallInst>(NewCaller)->
8707           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8708         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8709       }
8710       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8711         Caller->replaceAllUsesWith(NewCaller);
8712       Caller->eraseFromParent();
8713       RemoveFromWorkList(Caller);
8714       return 0;
8715     }
8716   }
8717
8718   // Replace the trampoline call with a direct call.  Since there is no 'nest'
8719   // parameter, there is no need to adjust the argument list.  Let the generic
8720   // code sort out any function type mismatches.
8721   Constant *NewCallee =
8722     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8723   CS.setCalledFunction(NewCallee);
8724   return CS.getInstruction();
8725 }
8726
8727 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8728 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8729 /// and a single binop.
8730 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8731   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8732   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8733          isa<CmpInst>(FirstInst));
8734   unsigned Opc = FirstInst->getOpcode();
8735   Value *LHSVal = FirstInst->getOperand(0);
8736   Value *RHSVal = FirstInst->getOperand(1);
8737     
8738   const Type *LHSType = LHSVal->getType();
8739   const Type *RHSType = RHSVal->getType();
8740   
8741   // Scan to see if all operands are the same opcode, all have one use, and all
8742   // kill their operands (i.e. the operands have one use).
8743   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8744     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8745     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8746         // Verify type of the LHS matches so we don't fold cmp's of different
8747         // types or GEP's with different index types.
8748         I->getOperand(0)->getType() != LHSType ||
8749         I->getOperand(1)->getType() != RHSType)
8750       return 0;
8751
8752     // If they are CmpInst instructions, check their predicates
8753     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8754       if (cast<CmpInst>(I)->getPredicate() !=
8755           cast<CmpInst>(FirstInst)->getPredicate())
8756         return 0;
8757     
8758     // Keep track of which operand needs a phi node.
8759     if (I->getOperand(0) != LHSVal) LHSVal = 0;
8760     if (I->getOperand(1) != RHSVal) RHSVal = 0;
8761   }
8762   
8763   // Otherwise, this is safe to transform, determine if it is profitable.
8764
8765   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8766   // Indexes are often folded into load/store instructions, so we don't want to
8767   // hide them behind a phi.
8768   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8769     return 0;
8770   
8771   Value *InLHS = FirstInst->getOperand(0);
8772   Value *InRHS = FirstInst->getOperand(1);
8773   PHINode *NewLHS = 0, *NewRHS = 0;
8774   if (LHSVal == 0) {
8775     NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8776     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8777     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8778     InsertNewInstBefore(NewLHS, PN);
8779     LHSVal = NewLHS;
8780   }
8781   
8782   if (RHSVal == 0) {
8783     NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8784     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8785     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8786     InsertNewInstBefore(NewRHS, PN);
8787     RHSVal = NewRHS;
8788   }
8789   
8790   // Add all operands to the new PHIs.
8791   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8792     if (NewLHS) {
8793       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8794       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8795     }
8796     if (NewRHS) {
8797       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8798       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8799     }
8800   }
8801     
8802   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8803     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8804   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8805     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
8806                            RHSVal);
8807   else {
8808     assert(isa<GetElementPtrInst>(FirstInst));
8809     return new GetElementPtrInst(LHSVal, RHSVal);
8810   }
8811 }
8812
8813 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8814 /// of the block that defines it.  This means that it must be obvious the value
8815 /// of the load is not changed from the point of the load to the end of the
8816 /// block it is in.
8817 ///
8818 /// Finally, it is safe, but not profitable, to sink a load targetting a
8819 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
8820 /// to a register.
8821 static bool isSafeToSinkLoad(LoadInst *L) {
8822   BasicBlock::iterator BBI = L, E = L->getParent()->end();
8823   
8824   for (++BBI; BBI != E; ++BBI)
8825     if (BBI->mayWriteToMemory())
8826       return false;
8827   
8828   // Check for non-address taken alloca.  If not address-taken already, it isn't
8829   // profitable to do this xform.
8830   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8831     bool isAddressTaken = false;
8832     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8833          UI != E; ++UI) {
8834       if (isa<LoadInst>(UI)) continue;
8835       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8836         // If storing TO the alloca, then the address isn't taken.
8837         if (SI->getOperand(1) == AI) continue;
8838       }
8839       isAddressTaken = true;
8840       break;
8841     }
8842     
8843     if (!isAddressTaken)
8844       return false;
8845   }
8846   
8847   return true;
8848 }
8849
8850
8851 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8852 // operator and they all are only used by the PHI, PHI together their
8853 // inputs, and do the operation once, to the result of the PHI.
8854 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8855   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8856
8857   // Scan the instruction, looking for input operations that can be folded away.
8858   // If all input operands to the phi are the same instruction (e.g. a cast from
8859   // the same type or "+42") we can pull the operation through the PHI, reducing
8860   // code size and simplifying code.
8861   Constant *ConstantOp = 0;
8862   const Type *CastSrcTy = 0;
8863   bool isVolatile = false;
8864   if (isa<CastInst>(FirstInst)) {
8865     CastSrcTy = FirstInst->getOperand(0)->getType();
8866   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8867     // Can fold binop, compare or shift here if the RHS is a constant, 
8868     // otherwise call FoldPHIArgBinOpIntoPHI.
8869     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8870     if (ConstantOp == 0)
8871       return FoldPHIArgBinOpIntoPHI(PN);
8872   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8873     isVolatile = LI->isVolatile();
8874     // We can't sink the load if the loaded value could be modified between the
8875     // load and the PHI.
8876     if (LI->getParent() != PN.getIncomingBlock(0) ||
8877         !isSafeToSinkLoad(LI))
8878       return 0;
8879   } else if (isa<GetElementPtrInst>(FirstInst)) {
8880     if (FirstInst->getNumOperands() == 2)
8881       return FoldPHIArgBinOpIntoPHI(PN);
8882     // Can't handle general GEPs yet.
8883     return 0;
8884   } else {
8885     return 0;  // Cannot fold this operation.
8886   }
8887
8888   // Check to see if all arguments are the same operation.
8889   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8890     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8891     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8892     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8893       return 0;
8894     if (CastSrcTy) {
8895       if (I->getOperand(0)->getType() != CastSrcTy)
8896         return 0;  // Cast operation must match.
8897     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8898       // We can't sink the load if the loaded value could be modified between 
8899       // the load and the PHI.
8900       if (LI->isVolatile() != isVolatile ||
8901           LI->getParent() != PN.getIncomingBlock(i) ||
8902           !isSafeToSinkLoad(LI))
8903         return 0;
8904     } else if (I->getOperand(1) != ConstantOp) {
8905       return 0;
8906     }
8907   }
8908
8909   // Okay, they are all the same operation.  Create a new PHI node of the
8910   // correct type, and PHI together all of the LHS's of the instructions.
8911   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8912                                PN.getName()+".in");
8913   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8914
8915   Value *InVal = FirstInst->getOperand(0);
8916   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8917
8918   // Add all operands to the new PHI.
8919   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8920     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8921     if (NewInVal != InVal)
8922       InVal = 0;
8923     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8924   }
8925
8926   Value *PhiVal;
8927   if (InVal) {
8928     // The new PHI unions all of the same values together.  This is really
8929     // common, so we handle it intelligently here for compile-time speed.
8930     PhiVal = InVal;
8931     delete NewPN;
8932   } else {
8933     InsertNewInstBefore(NewPN, PN);
8934     PhiVal = NewPN;
8935   }
8936
8937   // Insert and return the new operation.
8938   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8939     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8940   else if (isa<LoadInst>(FirstInst))
8941     return new LoadInst(PhiVal, "", isVolatile);
8942   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8943     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8944   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8945     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
8946                            PhiVal, ConstantOp);
8947   else
8948     assert(0 && "Unknown operation");
8949   return 0;
8950 }
8951
8952 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8953 /// that is dead.
8954 static bool DeadPHICycle(PHINode *PN,
8955                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8956   if (PN->use_empty()) return true;
8957   if (!PN->hasOneUse()) return false;
8958
8959   // Remember this node, and if we find the cycle, return.
8960   if (!PotentiallyDeadPHIs.insert(PN))
8961     return true;
8962   
8963   // Don't scan crazily complex things.
8964   if (PotentiallyDeadPHIs.size() == 16)
8965     return false;
8966
8967   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8968     return DeadPHICycle(PU, PotentiallyDeadPHIs);
8969
8970   return false;
8971 }
8972
8973 /// PHIsEqualValue - Return true if this phi node is always equal to
8974 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
8975 ///   z = some value; x = phi (y, z); y = phi (x, z)
8976 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
8977                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8978   // See if we already saw this PHI node.
8979   if (!ValueEqualPHIs.insert(PN))
8980     return true;
8981   
8982   // Don't scan crazily complex things.
8983   if (ValueEqualPHIs.size() == 16)
8984     return false;
8985  
8986   // Scan the operands to see if they are either phi nodes or are equal to
8987   // the value.
8988   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8989     Value *Op = PN->getIncomingValue(i);
8990     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8991       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8992         return false;
8993     } else if (Op != NonPhiInVal)
8994       return false;
8995   }
8996   
8997   return true;
8998 }
8999
9000
9001 // PHINode simplification
9002 //
9003 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9004   // If LCSSA is around, don't mess with Phi nodes
9005   if (MustPreserveLCSSA) return 0;
9006   
9007   if (Value *V = PN.hasConstantValue())
9008     return ReplaceInstUsesWith(PN, V);
9009
9010   // If all PHI operands are the same operation, pull them through the PHI,
9011   // reducing code size.
9012   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9013       PN.getIncomingValue(0)->hasOneUse())
9014     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9015       return Result;
9016
9017   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9018   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9019   // PHI)... break the cycle.
9020   if (PN.hasOneUse()) {
9021     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9022     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9023       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9024       PotentiallyDeadPHIs.insert(&PN);
9025       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9026         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9027     }
9028    
9029     // If this phi has a single use, and if that use just computes a value for
9030     // the next iteration of a loop, delete the phi.  This occurs with unused
9031     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9032     // common case here is good because the only other things that catch this
9033     // are induction variable analysis (sometimes) and ADCE, which is only run
9034     // late.
9035     if (PHIUser->hasOneUse() &&
9036         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9037         PHIUser->use_back() == &PN) {
9038       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9039     }
9040   }
9041
9042   // We sometimes end up with phi cycles that non-obviously end up being the
9043   // same value, for example:
9044   //   z = some value; x = phi (y, z); y = phi (x, z)
9045   // where the phi nodes don't necessarily need to be in the same block.  Do a
9046   // quick check to see if the PHI node only contains a single non-phi value, if
9047   // so, scan to see if the phi cycle is actually equal to that value.
9048   {
9049     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9050     // Scan for the first non-phi operand.
9051     while (InValNo != NumOperandVals && 
9052            isa<PHINode>(PN.getIncomingValue(InValNo)))
9053       ++InValNo;
9054
9055     if (InValNo != NumOperandVals) {
9056       Value *NonPhiInVal = PN.getOperand(InValNo);
9057       
9058       // Scan the rest of the operands to see if there are any conflicts, if so
9059       // there is no need to recursively scan other phis.
9060       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9061         Value *OpVal = PN.getIncomingValue(InValNo);
9062         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9063           break;
9064       }
9065       
9066       // If we scanned over all operands, then we have one unique value plus
9067       // phi values.  Scan PHI nodes to see if they all merge in each other or
9068       // the value.
9069       if (InValNo == NumOperandVals) {
9070         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9071         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9072           return ReplaceInstUsesWith(PN, NonPhiInVal);
9073       }
9074     }
9075   }
9076   return 0;
9077 }
9078
9079 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9080                                    Instruction *InsertPoint,
9081                                    InstCombiner *IC) {
9082   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9083   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9084   // We must cast correctly to the pointer type. Ensure that we
9085   // sign extend the integer value if it is smaller as this is
9086   // used for address computation.
9087   Instruction::CastOps opcode = 
9088      (VTySize < PtrSize ? Instruction::SExt :
9089       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9090   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9091 }
9092
9093
9094 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9095   Value *PtrOp = GEP.getOperand(0);
9096   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9097   // If so, eliminate the noop.
9098   if (GEP.getNumOperands() == 1)
9099     return ReplaceInstUsesWith(GEP, PtrOp);
9100
9101   if (isa<UndefValue>(GEP.getOperand(0)))
9102     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9103
9104   bool HasZeroPointerIndex = false;
9105   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9106     HasZeroPointerIndex = C->isNullValue();
9107
9108   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9109     return ReplaceInstUsesWith(GEP, PtrOp);
9110
9111   // Eliminate unneeded casts for indices.
9112   bool MadeChange = false;
9113   
9114   gep_type_iterator GTI = gep_type_begin(GEP);
9115   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9116     if (isa<SequentialType>(*GTI)) {
9117       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9118         if (CI->getOpcode() == Instruction::ZExt ||
9119             CI->getOpcode() == Instruction::SExt) {
9120           const Type *SrcTy = CI->getOperand(0)->getType();
9121           // We can eliminate a cast from i32 to i64 iff the target 
9122           // is a 32-bit pointer target.
9123           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9124             MadeChange = true;
9125             GEP.setOperand(i, CI->getOperand(0));
9126           }
9127         }
9128       }
9129       // If we are using a wider index than needed for this platform, shrink it
9130       // to what we need.  If the incoming value needs a cast instruction,
9131       // insert it.  This explicit cast can make subsequent optimizations more
9132       // obvious.
9133       Value *Op = GEP.getOperand(i);
9134       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
9135         if (Constant *C = dyn_cast<Constant>(Op)) {
9136           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9137           MadeChange = true;
9138         } else {
9139           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9140                                 GEP);
9141           GEP.setOperand(i, Op);
9142           MadeChange = true;
9143         }
9144     }
9145   }
9146   if (MadeChange) return &GEP;
9147
9148   // If this GEP instruction doesn't move the pointer, and if the input operand
9149   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9150   // real input to the dest type.
9151   if (GEP.hasAllZeroIndices()) {
9152     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9153       // If the bitcast is of an allocation, and the allocation will be
9154       // converted to match the type of the cast, don't touch this.
9155       if (isa<AllocationInst>(BCI->getOperand(0))) {
9156         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9157         if (Instruction *I = visitBitCast(*BCI)) {
9158           if (I != BCI) {
9159             I->takeName(BCI);
9160             BCI->getParent()->getInstList().insert(BCI, I);
9161             ReplaceInstUsesWith(*BCI, I);
9162           }
9163           return &GEP;
9164         }
9165       }
9166       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9167     }
9168   }
9169   
9170   // Combine Indices - If the source pointer to this getelementptr instruction
9171   // is a getelementptr instruction, combine the indices of the two
9172   // getelementptr instructions into a single instruction.
9173   //
9174   SmallVector<Value*, 8> SrcGEPOperands;
9175   if (User *Src = dyn_castGetElementPtr(PtrOp))
9176     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9177
9178   if (!SrcGEPOperands.empty()) {
9179     // Note that if our source is a gep chain itself that we wait for that
9180     // chain to be resolved before we perform this transformation.  This
9181     // avoids us creating a TON of code in some cases.
9182     //
9183     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9184         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9185       return 0;   // Wait until our source is folded to completion.
9186
9187     SmallVector<Value*, 8> Indices;
9188
9189     // Find out whether the last index in the source GEP is a sequential idx.
9190     bool EndsWithSequential = false;
9191     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9192            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9193       EndsWithSequential = !isa<StructType>(*I);
9194
9195     // Can we combine the two pointer arithmetics offsets?
9196     if (EndsWithSequential) {
9197       // Replace: gep (gep %P, long B), long A, ...
9198       // With:    T = long A+B; gep %P, T, ...
9199       //
9200       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9201       if (SO1 == Constant::getNullValue(SO1->getType())) {
9202         Sum = GO1;
9203       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9204         Sum = SO1;
9205       } else {
9206         // If they aren't the same type, convert both to an integer of the
9207         // target's pointer size.
9208         if (SO1->getType() != GO1->getType()) {
9209           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9210             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9211           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9212             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9213           } else {
9214             unsigned PS = TD->getPointerSizeInBits();
9215             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9216               // Convert GO1 to SO1's type.
9217               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9218
9219             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9220               // Convert SO1 to GO1's type.
9221               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9222             } else {
9223               const Type *PT = TD->getIntPtrType();
9224               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9225               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9226             }
9227           }
9228         }
9229         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9230           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9231         else {
9232           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9233           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9234         }
9235       }
9236
9237       // Recycle the GEP we already have if possible.
9238       if (SrcGEPOperands.size() == 2) {
9239         GEP.setOperand(0, SrcGEPOperands[0]);
9240         GEP.setOperand(1, Sum);
9241         return &GEP;
9242       } else {
9243         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9244                        SrcGEPOperands.end()-1);
9245         Indices.push_back(Sum);
9246         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9247       }
9248     } else if (isa<Constant>(*GEP.idx_begin()) &&
9249                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9250                SrcGEPOperands.size() != 1) {
9251       // Otherwise we can do the fold if the first index of the GEP is a zero
9252       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9253                      SrcGEPOperands.end());
9254       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9255     }
9256
9257     if (!Indices.empty())
9258       return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9259                                    Indices.end(), GEP.getName());
9260
9261   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9262     // GEP of global variable.  If all of the indices for this GEP are
9263     // constants, we can promote this to a constexpr instead of an instruction.
9264
9265     // Scan for nonconstants...
9266     SmallVector<Constant*, 8> Indices;
9267     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9268     for (; I != E && isa<Constant>(*I); ++I)
9269       Indices.push_back(cast<Constant>(*I));
9270
9271     if (I == E) {  // If they are all constants...
9272       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9273                                                     &Indices[0],Indices.size());
9274
9275       // Replace all uses of the GEP with the new constexpr...
9276       return ReplaceInstUsesWith(GEP, CE);
9277     }
9278   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9279     if (!isa<PointerType>(X->getType())) {
9280       // Not interesting.  Source pointer must be a cast from pointer.
9281     } else if (HasZeroPointerIndex) {
9282       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9283       // into     : GEP [10 x i8]* X, i32 0, ...
9284       //
9285       // This occurs when the program declares an array extern like "int X[];"
9286       //
9287       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9288       const PointerType *XTy = cast<PointerType>(X->getType());
9289       if (const ArrayType *XATy =
9290           dyn_cast<ArrayType>(XTy->getElementType()))
9291         if (const ArrayType *CATy =
9292             dyn_cast<ArrayType>(CPTy->getElementType()))
9293           if (CATy->getElementType() == XATy->getElementType()) {
9294             // At this point, we know that the cast source type is a pointer
9295             // to an array of the same type as the destination pointer
9296             // array.  Because the array type is never stepped over (there
9297             // is a leading zero) we can fold the cast into this GEP.
9298             GEP.setOperand(0, X);
9299             return &GEP;
9300           }
9301     } else if (GEP.getNumOperands() == 2) {
9302       // Transform things like:
9303       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9304       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9305       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9306       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9307       if (isa<ArrayType>(SrcElTy) &&
9308           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9309           TD->getABITypeSize(ResElTy)) {
9310         Value *Idx[2];
9311         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9312         Idx[1] = GEP.getOperand(1);
9313         Value *V = InsertNewInstBefore(
9314                new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
9315         // V and GEP are both pointer types --> BitCast
9316         return new BitCastInst(V, GEP.getType());
9317       }
9318       
9319       // Transform things like:
9320       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9321       //   (where tmp = 8*tmp2) into:
9322       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9323       
9324       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9325         uint64_t ArrayEltSize =
9326             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9327         
9328         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9329         // allow either a mul, shift, or constant here.
9330         Value *NewIdx = 0;
9331         ConstantInt *Scale = 0;
9332         if (ArrayEltSize == 1) {
9333           NewIdx = GEP.getOperand(1);
9334           Scale = ConstantInt::get(NewIdx->getType(), 1);
9335         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9336           NewIdx = ConstantInt::get(CI->getType(), 1);
9337           Scale = CI;
9338         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9339           if (Inst->getOpcode() == Instruction::Shl &&
9340               isa<ConstantInt>(Inst->getOperand(1))) {
9341             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9342             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9343             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9344             NewIdx = Inst->getOperand(0);
9345           } else if (Inst->getOpcode() == Instruction::Mul &&
9346                      isa<ConstantInt>(Inst->getOperand(1))) {
9347             Scale = cast<ConstantInt>(Inst->getOperand(1));
9348             NewIdx = Inst->getOperand(0);
9349           }
9350         }
9351         
9352         // If the index will be to exactly the right offset with the scale taken
9353         // out, perform the transformation. Note, we don't know whether Scale is
9354         // signed or not. We'll use unsigned version of division/modulo
9355         // operation after making sure Scale doesn't have the sign bit set.
9356         if (Scale && Scale->getSExtValue() >= 0LL &&
9357             Scale->getZExtValue() % ArrayEltSize == 0) {
9358           Scale = ConstantInt::get(Scale->getType(),
9359                                    Scale->getZExtValue() / ArrayEltSize);
9360           if (Scale->getZExtValue() != 1) {
9361             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9362                                                        false /*ZExt*/);
9363             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9364             NewIdx = InsertNewInstBefore(Sc, GEP);
9365           }
9366
9367           // Insert the new GEP instruction.
9368           Value *Idx[2];
9369           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9370           Idx[1] = NewIdx;
9371           Instruction *NewGEP =
9372             new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9373           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9374           // The NewGEP must be pointer typed, so must the old one -> BitCast
9375           return new BitCastInst(NewGEP, GEP.getType());
9376         }
9377       }
9378     }
9379   }
9380
9381   return 0;
9382 }
9383
9384 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9385   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9386   if (AI.isArrayAllocation())    // Check C != 1
9387     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9388       const Type *NewTy = 
9389         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9390       AllocationInst *New = 0;
9391
9392       // Create and insert the replacement instruction...
9393       if (isa<MallocInst>(AI))
9394         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9395       else {
9396         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9397         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9398       }
9399
9400       InsertNewInstBefore(New, AI);
9401
9402       // Scan to the end of the allocation instructions, to skip over a block of
9403       // allocas if possible...
9404       //
9405       BasicBlock::iterator It = New;
9406       while (isa<AllocationInst>(*It)) ++It;
9407
9408       // Now that I is pointing to the first non-allocation-inst in the block,
9409       // insert our getelementptr instruction...
9410       //
9411       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9412       Value *Idx[2];
9413       Idx[0] = NullIdx;
9414       Idx[1] = NullIdx;
9415       Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9416                                        New->getName()+".sub", It);
9417
9418       // Now make everything use the getelementptr instead of the original
9419       // allocation.
9420       return ReplaceInstUsesWith(AI, V);
9421     } else if (isa<UndefValue>(AI.getArraySize())) {
9422       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9423     }
9424
9425   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9426   // Note that we only do this for alloca's, because malloc should allocate and
9427   // return a unique pointer, even for a zero byte allocation.
9428   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9429       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9430     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9431
9432   return 0;
9433 }
9434
9435 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9436   Value *Op = FI.getOperand(0);
9437
9438   // free undef -> unreachable.
9439   if (isa<UndefValue>(Op)) {
9440     // Insert a new store to null because we cannot modify the CFG here.
9441     new StoreInst(ConstantInt::getTrue(),
9442                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9443     return EraseInstFromFunction(FI);
9444   }
9445   
9446   // If we have 'free null' delete the instruction.  This can happen in stl code
9447   // when lots of inlining happens.
9448   if (isa<ConstantPointerNull>(Op))
9449     return EraseInstFromFunction(FI);
9450   
9451   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9452   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9453     FI.setOperand(0, CI->getOperand(0));
9454     return &FI;
9455   }
9456   
9457   // Change free (gep X, 0,0,0,0) into free(X)
9458   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9459     if (GEPI->hasAllZeroIndices()) {
9460       AddToWorkList(GEPI);
9461       FI.setOperand(0, GEPI->getOperand(0));
9462       return &FI;
9463     }
9464   }
9465   
9466   // Change free(malloc) into nothing, if the malloc has a single use.
9467   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9468     if (MI->hasOneUse()) {
9469       EraseInstFromFunction(FI);
9470       return EraseInstFromFunction(*MI);
9471     }
9472
9473   return 0;
9474 }
9475
9476
9477 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9478 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9479                                         const TargetData *TD) {
9480   User *CI = cast<User>(LI.getOperand(0));
9481   Value *CastOp = CI->getOperand(0);
9482
9483   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9484     // Instead of loading constant c string, use corresponding integer value
9485     // directly if string length is small enough.
9486     const std::string &Str = CE->getOperand(0)->getStringValue();
9487     if (!Str.empty()) {
9488       unsigned len = Str.length();
9489       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9490       unsigned numBits = Ty->getPrimitiveSizeInBits();
9491       // Replace LI with immediate integer store.
9492       if ((numBits >> 3) == len + 1) {
9493         APInt StrVal(numBits, 0);
9494         APInt SingleChar(numBits, 0);
9495         if (TD->isLittleEndian()) {
9496           for (signed i = len-1; i >= 0; i--) {
9497             SingleChar = (uint64_t) Str[i];
9498             StrVal = (StrVal << 8) | SingleChar;
9499           }
9500         } else {
9501           for (unsigned i = 0; i < len; i++) {
9502             SingleChar = (uint64_t) Str[i];
9503                 StrVal = (StrVal << 8) | SingleChar;
9504           }
9505           // Append NULL at the end.
9506           SingleChar = 0;
9507           StrVal = (StrVal << 8) | SingleChar;
9508         }
9509         Value *NL = ConstantInt::get(StrVal);
9510         return IC.ReplaceInstUsesWith(LI, NL);
9511       }
9512     }
9513   }
9514
9515   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9516   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9517     const Type *SrcPTy = SrcTy->getElementType();
9518
9519     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9520          isa<VectorType>(DestPTy)) {
9521       // If the source is an array, the code below will not succeed.  Check to
9522       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9523       // constants.
9524       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9525         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9526           if (ASrcTy->getNumElements() != 0) {
9527             Value *Idxs[2];
9528             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9529             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9530             SrcTy = cast<PointerType>(CastOp->getType());
9531             SrcPTy = SrcTy->getElementType();
9532           }
9533
9534       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9535             isa<VectorType>(SrcPTy)) &&
9536           // Do not allow turning this into a load of an integer, which is then
9537           // casted to a pointer, this pessimizes pointer analysis a lot.
9538           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9539           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9540                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9541
9542         // Okay, we are casting from one integer or pointer type to another of
9543         // the same size.  Instead of casting the pointer before the load, cast
9544         // the result of the loaded value.
9545         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9546                                                              CI->getName(),
9547                                                          LI.isVolatile()),LI);
9548         // Now cast the result of the load.
9549         return new BitCastInst(NewLoad, LI.getType());
9550       }
9551     }
9552   }
9553   return 0;
9554 }
9555
9556 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9557 /// from this value cannot trap.  If it is not obviously safe to load from the
9558 /// specified pointer, we do a quick local scan of the basic block containing
9559 /// ScanFrom, to determine if the address is already accessed.
9560 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9561   // If it is an alloca it is always safe to load from.
9562   if (isa<AllocaInst>(V)) return true;
9563
9564   // If it is a global variable it is mostly safe to load from.
9565   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9566     // Don't try to evaluate aliases.  External weak GV can be null.
9567     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9568
9569   // Otherwise, be a little bit agressive by scanning the local block where we
9570   // want to check to see if the pointer is already being loaded or stored
9571   // from/to.  If so, the previous load or store would have already trapped,
9572   // so there is no harm doing an extra load (also, CSE will later eliminate
9573   // the load entirely).
9574   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9575
9576   while (BBI != E) {
9577     --BBI;
9578
9579     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9580       if (LI->getOperand(0) == V) return true;
9581     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9582       if (SI->getOperand(1) == V) return true;
9583
9584   }
9585   return false;
9586 }
9587
9588 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9589 /// until we find the underlying object a pointer is referring to or something
9590 /// we don't understand.  Note that the returned pointer may be offset from the
9591 /// input, because we ignore GEP indices.
9592 static Value *GetUnderlyingObject(Value *Ptr) {
9593   while (1) {
9594     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9595       if (CE->getOpcode() == Instruction::BitCast ||
9596           CE->getOpcode() == Instruction::GetElementPtr)
9597         Ptr = CE->getOperand(0);
9598       else
9599         return Ptr;
9600     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9601       Ptr = BCI->getOperand(0);
9602     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9603       Ptr = GEP->getOperand(0);
9604     } else {
9605       return Ptr;
9606     }
9607   }
9608 }
9609
9610 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9611   Value *Op = LI.getOperand(0);
9612
9613   // Attempt to improve the alignment.
9614   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9615   if (KnownAlign > LI.getAlignment())
9616     LI.setAlignment(KnownAlign);
9617
9618   // load (cast X) --> cast (load X) iff safe
9619   if (isa<CastInst>(Op))
9620     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9621       return Res;
9622
9623   // None of the following transforms are legal for volatile loads.
9624   if (LI.isVolatile()) return 0;
9625   
9626   if (&LI.getParent()->front() != &LI) {
9627     BasicBlock::iterator BBI = &LI; --BBI;
9628     // If the instruction immediately before this is a store to the same
9629     // address, do a simple form of store->load forwarding.
9630     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9631       if (SI->getOperand(1) == LI.getOperand(0))
9632         return ReplaceInstUsesWith(LI, SI->getOperand(0));
9633     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9634       if (LIB->getOperand(0) == LI.getOperand(0))
9635         return ReplaceInstUsesWith(LI, LIB);
9636   }
9637
9638   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9639     const Value *GEPI0 = GEPI->getOperand(0);
9640     // TODO: Consider a target hook for valid address spaces for this xform.
9641     if (isa<ConstantPointerNull>(GEPI0) &&
9642         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
9643       // Insert a new store to null instruction before the load to indicate
9644       // that this code is not reachable.  We do this instead of inserting
9645       // an unreachable instruction directly because we cannot modify the
9646       // CFG.
9647       new StoreInst(UndefValue::get(LI.getType()),
9648                     Constant::getNullValue(Op->getType()), &LI);
9649       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9650     }
9651   } 
9652
9653   if (Constant *C = dyn_cast<Constant>(Op)) {
9654     // load null/undef -> undef
9655     // TODO: Consider a target hook for valid address spaces for this xform.
9656     if (isa<UndefValue>(C) || (C->isNullValue() && 
9657         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
9658       // Insert a new store to null instruction before the load to indicate that
9659       // this code is not reachable.  We do this instead of inserting an
9660       // unreachable instruction directly because we cannot modify the CFG.
9661       new StoreInst(UndefValue::get(LI.getType()),
9662                     Constant::getNullValue(Op->getType()), &LI);
9663       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9664     }
9665
9666     // Instcombine load (constant global) into the value loaded.
9667     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9668       if (GV->isConstant() && !GV->isDeclaration())
9669         return ReplaceInstUsesWith(LI, GV->getInitializer());
9670
9671     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9672     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9673       if (CE->getOpcode() == Instruction::GetElementPtr) {
9674         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9675           if (GV->isConstant() && !GV->isDeclaration())
9676             if (Constant *V = 
9677                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9678               return ReplaceInstUsesWith(LI, V);
9679         if (CE->getOperand(0)->isNullValue()) {
9680           // Insert a new store to null instruction before the load to indicate
9681           // that this code is not reachable.  We do this instead of inserting
9682           // an unreachable instruction directly because we cannot modify the
9683           // CFG.
9684           new StoreInst(UndefValue::get(LI.getType()),
9685                         Constant::getNullValue(Op->getType()), &LI);
9686           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9687         }
9688
9689       } else if (CE->isCast()) {
9690         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9691           return Res;
9692       }
9693   }
9694     
9695   // If this load comes from anywhere in a constant global, and if the global
9696   // is all undef or zero, we know what it loads.
9697   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9698     if (GV->isConstant() && GV->hasInitializer()) {
9699       if (GV->getInitializer()->isNullValue())
9700         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9701       else if (isa<UndefValue>(GV->getInitializer()))
9702         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9703     }
9704   }
9705
9706   if (Op->hasOneUse()) {
9707     // Change select and PHI nodes to select values instead of addresses: this
9708     // helps alias analysis out a lot, allows many others simplifications, and
9709     // exposes redundancy in the code.
9710     //
9711     // Note that we cannot do the transformation unless we know that the
9712     // introduced loads cannot trap!  Something like this is valid as long as
9713     // the condition is always false: load (select bool %C, int* null, int* %G),
9714     // but it would not be valid if we transformed it to load from null
9715     // unconditionally.
9716     //
9717     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9718       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
9719       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9720           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9721         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9722                                      SI->getOperand(1)->getName()+".val"), LI);
9723         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9724                                      SI->getOperand(2)->getName()+".val"), LI);
9725         return new SelectInst(SI->getCondition(), V1, V2);
9726       }
9727
9728       // load (select (cond, null, P)) -> load P
9729       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9730         if (C->isNullValue()) {
9731           LI.setOperand(0, SI->getOperand(2));
9732           return &LI;
9733         }
9734
9735       // load (select (cond, P, null)) -> load P
9736       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9737         if (C->isNullValue()) {
9738           LI.setOperand(0, SI->getOperand(1));
9739           return &LI;
9740         }
9741     }
9742   }
9743   return 0;
9744 }
9745
9746 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9747 /// when possible.
9748 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9749   User *CI = cast<User>(SI.getOperand(1));
9750   Value *CastOp = CI->getOperand(0);
9751
9752   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9753   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9754     const Type *SrcPTy = SrcTy->getElementType();
9755
9756     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9757       // If the source is an array, the code below will not succeed.  Check to
9758       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9759       // constants.
9760       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9761         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9762           if (ASrcTy->getNumElements() != 0) {
9763             Value* Idxs[2];
9764             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9765             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9766             SrcTy = cast<PointerType>(CastOp->getType());
9767             SrcPTy = SrcTy->getElementType();
9768           }
9769
9770       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9771           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9772                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9773
9774         // Okay, we are casting from one integer or pointer type to another of
9775         // the same size.  Instead of casting the pointer before 
9776         // the store, cast the value to be stored.
9777         Value *NewCast;
9778         Value *SIOp0 = SI.getOperand(0);
9779         Instruction::CastOps opcode = Instruction::BitCast;
9780         const Type* CastSrcTy = SIOp0->getType();
9781         const Type* CastDstTy = SrcPTy;
9782         if (isa<PointerType>(CastDstTy)) {
9783           if (CastSrcTy->isInteger())
9784             opcode = Instruction::IntToPtr;
9785         } else if (isa<IntegerType>(CastDstTy)) {
9786           if (isa<PointerType>(SIOp0->getType()))
9787             opcode = Instruction::PtrToInt;
9788         }
9789         if (Constant *C = dyn_cast<Constant>(SIOp0))
9790           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9791         else
9792           NewCast = IC.InsertNewInstBefore(
9793             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
9794             SI);
9795         return new StoreInst(NewCast, CastOp);
9796       }
9797     }
9798   }
9799   return 0;
9800 }
9801
9802 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9803   Value *Val = SI.getOperand(0);
9804   Value *Ptr = SI.getOperand(1);
9805
9806   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
9807     EraseInstFromFunction(SI);
9808     ++NumCombined;
9809     return 0;
9810   }
9811   
9812   // If the RHS is an alloca with a single use, zapify the store, making the
9813   // alloca dead.
9814   if (Ptr->hasOneUse()) {
9815     if (isa<AllocaInst>(Ptr)) {
9816       EraseInstFromFunction(SI);
9817       ++NumCombined;
9818       return 0;
9819     }
9820     
9821     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9822       if (isa<AllocaInst>(GEP->getOperand(0)) &&
9823           GEP->getOperand(0)->hasOneUse()) {
9824         EraseInstFromFunction(SI);
9825         ++NumCombined;
9826         return 0;
9827       }
9828   }
9829
9830   // Attempt to improve the alignment.
9831   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9832   if (KnownAlign > SI.getAlignment())
9833     SI.setAlignment(KnownAlign);
9834
9835   // Do really simple DSE, to catch cases where there are several consequtive
9836   // stores to the same location, separated by a few arithmetic operations. This
9837   // situation often occurs with bitfield accesses.
9838   BasicBlock::iterator BBI = &SI;
9839   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9840        --ScanInsts) {
9841     --BBI;
9842     
9843     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9844       // Prev store isn't volatile, and stores to the same location?
9845       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9846         ++NumDeadStore;
9847         ++BBI;
9848         EraseInstFromFunction(*PrevSI);
9849         continue;
9850       }
9851       break;
9852     }
9853     
9854     // If this is a load, we have to stop.  However, if the loaded value is from
9855     // the pointer we're loading and is producing the pointer we're storing,
9856     // then *this* store is dead (X = load P; store X -> P).
9857     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9858       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
9859         EraseInstFromFunction(SI);
9860         ++NumCombined;
9861         return 0;
9862       }
9863       // Otherwise, this is a load from some other location.  Stores before it
9864       // may not be dead.
9865       break;
9866     }
9867     
9868     // Don't skip over loads or things that can modify memory.
9869     if (BBI->mayWriteToMemory())
9870       break;
9871   }
9872   
9873   
9874   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
9875
9876   // store X, null    -> turns into 'unreachable' in SimplifyCFG
9877   if (isa<ConstantPointerNull>(Ptr)) {
9878     if (!isa<UndefValue>(Val)) {
9879       SI.setOperand(0, UndefValue::get(Val->getType()));
9880       if (Instruction *U = dyn_cast<Instruction>(Val))
9881         AddToWorkList(U);  // Dropped a use.
9882       ++NumCombined;
9883     }
9884     return 0;  // Do not modify these!
9885   }
9886
9887   // store undef, Ptr -> noop
9888   if (isa<UndefValue>(Val)) {
9889     EraseInstFromFunction(SI);
9890     ++NumCombined;
9891     return 0;
9892   }
9893
9894   // If the pointer destination is a cast, see if we can fold the cast into the
9895   // source instead.
9896   if (isa<CastInst>(Ptr))
9897     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9898       return Res;
9899   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9900     if (CE->isCast())
9901       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9902         return Res;
9903
9904   
9905   // If this store is the last instruction in the basic block, and if the block
9906   // ends with an unconditional branch, try to move it to the successor block.
9907   BBI = &SI; ++BBI;
9908   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9909     if (BI->isUnconditional())
9910       if (SimplifyStoreAtEndOfBlock(SI))
9911         return 0;  // xform done!
9912   
9913   return 0;
9914 }
9915
9916 /// SimplifyStoreAtEndOfBlock - Turn things like:
9917 ///   if () { *P = v1; } else { *P = v2 }
9918 /// into a phi node with a store in the successor.
9919 ///
9920 /// Simplify things like:
9921 ///   *P = v1; if () { *P = v2; }
9922 /// into a phi node with a store in the successor.
9923 ///
9924 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9925   BasicBlock *StoreBB = SI.getParent();
9926   
9927   // Check to see if the successor block has exactly two incoming edges.  If
9928   // so, see if the other predecessor contains a store to the same location.
9929   // if so, insert a PHI node (if needed) and move the stores down.
9930   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9931   
9932   // Determine whether Dest has exactly two predecessors and, if so, compute
9933   // the other predecessor.
9934   pred_iterator PI = pred_begin(DestBB);
9935   BasicBlock *OtherBB = 0;
9936   if (*PI != StoreBB)
9937     OtherBB = *PI;
9938   ++PI;
9939   if (PI == pred_end(DestBB))
9940     return false;
9941   
9942   if (*PI != StoreBB) {
9943     if (OtherBB)
9944       return false;
9945     OtherBB = *PI;
9946   }
9947   if (++PI != pred_end(DestBB))
9948     return false;
9949   
9950   
9951   // Verify that the other block ends in a branch and is not otherwise empty.
9952   BasicBlock::iterator BBI = OtherBB->getTerminator();
9953   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9954   if (!OtherBr || BBI == OtherBB->begin())
9955     return false;
9956   
9957   // If the other block ends in an unconditional branch, check for the 'if then
9958   // else' case.  there is an instruction before the branch.
9959   StoreInst *OtherStore = 0;
9960   if (OtherBr->isUnconditional()) {
9961     // If this isn't a store, or isn't a store to the same location, bail out.
9962     --BBI;
9963     OtherStore = dyn_cast<StoreInst>(BBI);
9964     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9965       return false;
9966   } else {
9967     // Otherwise, the other block ended with a conditional branch. If one of the
9968     // destinations is StoreBB, then we have the if/then case.
9969     if (OtherBr->getSuccessor(0) != StoreBB && 
9970         OtherBr->getSuccessor(1) != StoreBB)
9971       return false;
9972     
9973     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9974     // if/then triangle.  See if there is a store to the same ptr as SI that
9975     // lives in OtherBB.
9976     for (;; --BBI) {
9977       // Check to see if we find the matching store.
9978       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9979         if (OtherStore->getOperand(1) != SI.getOperand(1))
9980           return false;
9981         break;
9982       }
9983       // If we find something that may be using the stored value, or if we run
9984       // out of instructions, we can't do the xform.
9985       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9986           BBI == OtherBB->begin())
9987         return false;
9988     }
9989     
9990     // In order to eliminate the store in OtherBr, we have to
9991     // make sure nothing reads the stored value in StoreBB.
9992     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9993       // FIXME: This should really be AA driven.
9994       if (isa<LoadInst>(I) || I->mayWriteToMemory())
9995         return false;
9996     }
9997   }
9998   
9999   // Insert a PHI node now if we need it.
10000   Value *MergedVal = OtherStore->getOperand(0);
10001   if (MergedVal != SI.getOperand(0)) {
10002     PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10003     PN->reserveOperandSpace(2);
10004     PN->addIncoming(SI.getOperand(0), SI.getParent());
10005     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10006     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10007   }
10008   
10009   // Advance to a place where it is safe to insert the new store and
10010   // insert it.
10011   BBI = DestBB->begin();
10012   while (isa<PHINode>(BBI)) ++BBI;
10013   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10014                                     OtherStore->isVolatile()), *BBI);
10015   
10016   // Nuke the old stores.
10017   EraseInstFromFunction(SI);
10018   EraseInstFromFunction(*OtherStore);
10019   ++NumCombined;
10020   return true;
10021 }
10022
10023
10024 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10025   // Change br (not X), label True, label False to: br X, label False, True
10026   Value *X = 0;
10027   BasicBlock *TrueDest;
10028   BasicBlock *FalseDest;
10029   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10030       !isa<Constant>(X)) {
10031     // Swap Destinations and condition...
10032     BI.setCondition(X);
10033     BI.setSuccessor(0, FalseDest);
10034     BI.setSuccessor(1, TrueDest);
10035     return &BI;
10036   }
10037
10038   // Cannonicalize fcmp_one -> fcmp_oeq
10039   FCmpInst::Predicate FPred; Value *Y;
10040   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10041                              TrueDest, FalseDest)))
10042     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10043          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10044       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10045       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10046       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10047       NewSCC->takeName(I);
10048       // Swap Destinations and condition...
10049       BI.setCondition(NewSCC);
10050       BI.setSuccessor(0, FalseDest);
10051       BI.setSuccessor(1, TrueDest);
10052       RemoveFromWorkList(I);
10053       I->eraseFromParent();
10054       AddToWorkList(NewSCC);
10055       return &BI;
10056     }
10057
10058   // Cannonicalize icmp_ne -> icmp_eq
10059   ICmpInst::Predicate IPred;
10060   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10061                       TrueDest, FalseDest)))
10062     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10063          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10064          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10065       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10066       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10067       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10068       NewSCC->takeName(I);
10069       // Swap Destinations and condition...
10070       BI.setCondition(NewSCC);
10071       BI.setSuccessor(0, FalseDest);
10072       BI.setSuccessor(1, TrueDest);
10073       RemoveFromWorkList(I);
10074       I->eraseFromParent();;
10075       AddToWorkList(NewSCC);
10076       return &BI;
10077     }
10078
10079   return 0;
10080 }
10081
10082 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10083   Value *Cond = SI.getCondition();
10084   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10085     if (I->getOpcode() == Instruction::Add)
10086       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10087         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10088         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10089           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10090                                                 AddRHS));
10091         SI.setOperand(0, I->getOperand(0));
10092         AddToWorkList(I);
10093         return &SI;
10094       }
10095   }
10096   return 0;
10097 }
10098
10099 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10100 /// is to leave as a vector operation.
10101 static bool CheapToScalarize(Value *V, bool isConstant) {
10102   if (isa<ConstantAggregateZero>(V)) 
10103     return true;
10104   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10105     if (isConstant) return true;
10106     // If all elts are the same, we can extract.
10107     Constant *Op0 = C->getOperand(0);
10108     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10109       if (C->getOperand(i) != Op0)
10110         return false;
10111     return true;
10112   }
10113   Instruction *I = dyn_cast<Instruction>(V);
10114   if (!I) return false;
10115   
10116   // Insert element gets simplified to the inserted element or is deleted if
10117   // this is constant idx extract element and its a constant idx insertelt.
10118   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10119       isa<ConstantInt>(I->getOperand(2)))
10120     return true;
10121   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10122     return true;
10123   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10124     if (BO->hasOneUse() &&
10125         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10126          CheapToScalarize(BO->getOperand(1), isConstant)))
10127       return true;
10128   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10129     if (CI->hasOneUse() &&
10130         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10131          CheapToScalarize(CI->getOperand(1), isConstant)))
10132       return true;
10133   
10134   return false;
10135 }
10136
10137 /// Read and decode a shufflevector mask.
10138 ///
10139 /// It turns undef elements into values that are larger than the number of
10140 /// elements in the input.
10141 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10142   unsigned NElts = SVI->getType()->getNumElements();
10143   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10144     return std::vector<unsigned>(NElts, 0);
10145   if (isa<UndefValue>(SVI->getOperand(2)))
10146     return std::vector<unsigned>(NElts, 2*NElts);
10147
10148   std::vector<unsigned> Result;
10149   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10150   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10151     if (isa<UndefValue>(CP->getOperand(i)))
10152       Result.push_back(NElts*2);  // undef -> 8
10153     else
10154       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10155   return Result;
10156 }
10157
10158 /// FindScalarElement - Given a vector and an element number, see if the scalar
10159 /// value is already around as a register, for example if it were inserted then
10160 /// extracted from the vector.
10161 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10162   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10163   const VectorType *PTy = cast<VectorType>(V->getType());
10164   unsigned Width = PTy->getNumElements();
10165   if (EltNo >= Width)  // Out of range access.
10166     return UndefValue::get(PTy->getElementType());
10167   
10168   if (isa<UndefValue>(V))
10169     return UndefValue::get(PTy->getElementType());
10170   else if (isa<ConstantAggregateZero>(V))
10171     return Constant::getNullValue(PTy->getElementType());
10172   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10173     return CP->getOperand(EltNo);
10174   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10175     // If this is an insert to a variable element, we don't know what it is.
10176     if (!isa<ConstantInt>(III->getOperand(2))) 
10177       return 0;
10178     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10179     
10180     // If this is an insert to the element we are looking for, return the
10181     // inserted value.
10182     if (EltNo == IIElt) 
10183       return III->getOperand(1);
10184     
10185     // Otherwise, the insertelement doesn't modify the value, recurse on its
10186     // vector input.
10187     return FindScalarElement(III->getOperand(0), EltNo);
10188   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10189     unsigned InEl = getShuffleMask(SVI)[EltNo];
10190     if (InEl < Width)
10191       return FindScalarElement(SVI->getOperand(0), InEl);
10192     else if (InEl < Width*2)
10193       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10194     else
10195       return UndefValue::get(PTy->getElementType());
10196   }
10197   
10198   // Otherwise, we don't know.
10199   return 0;
10200 }
10201
10202 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10203
10204   // If vector val is undef, replace extract with scalar undef.
10205   if (isa<UndefValue>(EI.getOperand(0)))
10206     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10207
10208   // If vector val is constant 0, replace extract with scalar 0.
10209   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10210     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10211   
10212   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10213     // If vector val is constant with uniform operands, replace EI
10214     // with that operand
10215     Constant *op0 = C->getOperand(0);
10216     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10217       if (C->getOperand(i) != op0) {
10218         op0 = 0; 
10219         break;
10220       }
10221     if (op0)
10222       return ReplaceInstUsesWith(EI, op0);
10223   }
10224   
10225   // If extracting a specified index from the vector, see if we can recursively
10226   // find a previously computed scalar that was inserted into the vector.
10227   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10228     unsigned IndexVal = IdxC->getZExtValue();
10229     unsigned VectorWidth = 
10230       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10231       
10232     // If this is extracting an invalid index, turn this into undef, to avoid
10233     // crashing the code below.
10234     if (IndexVal >= VectorWidth)
10235       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10236     
10237     // This instruction only demands the single element from the input vector.
10238     // If the input vector has a single use, simplify it based on this use
10239     // property.
10240     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10241       uint64_t UndefElts;
10242       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10243                                                 1 << IndexVal,
10244                                                 UndefElts)) {
10245         EI.setOperand(0, V);
10246         return &EI;
10247       }
10248     }
10249     
10250     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10251       return ReplaceInstUsesWith(EI, Elt);
10252     
10253     // If the this extractelement is directly using a bitcast from a vector of
10254     // the same number of elements, see if we can find the source element from
10255     // it.  In this case, we will end up needing to bitcast the scalars.
10256     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10257       if (const VectorType *VT = 
10258               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10259         if (VT->getNumElements() == VectorWidth)
10260           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10261             return new BitCastInst(Elt, EI.getType());
10262     }
10263   }
10264   
10265   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10266     if (I->hasOneUse()) {
10267       // Push extractelement into predecessor operation if legal and
10268       // profitable to do so
10269       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10270         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10271         if (CheapToScalarize(BO, isConstantElt)) {
10272           ExtractElementInst *newEI0 = 
10273             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10274                                    EI.getName()+".lhs");
10275           ExtractElementInst *newEI1 =
10276             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10277                                    EI.getName()+".rhs");
10278           InsertNewInstBefore(newEI0, EI);
10279           InsertNewInstBefore(newEI1, EI);
10280           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10281         }
10282       } else if (isa<LoadInst>(I)) {
10283         unsigned AS = 
10284           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10285         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10286                                          PointerType::get(EI.getType(), AS),EI);
10287         GetElementPtrInst *GEP = 
10288           new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10289         InsertNewInstBefore(GEP, EI);
10290         return new LoadInst(GEP);
10291       }
10292     }
10293     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10294       // Extracting the inserted element?
10295       if (IE->getOperand(2) == EI.getOperand(1))
10296         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10297       // If the inserted and extracted elements are constants, they must not
10298       // be the same value, extract from the pre-inserted value instead.
10299       if (isa<Constant>(IE->getOperand(2)) &&
10300           isa<Constant>(EI.getOperand(1))) {
10301         AddUsesToWorkList(EI);
10302         EI.setOperand(0, IE->getOperand(0));
10303         return &EI;
10304       }
10305     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10306       // If this is extracting an element from a shufflevector, figure out where
10307       // it came from and extract from the appropriate input element instead.
10308       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10309         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10310         Value *Src;
10311         if (SrcIdx < SVI->getType()->getNumElements())
10312           Src = SVI->getOperand(0);
10313         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10314           SrcIdx -= SVI->getType()->getNumElements();
10315           Src = SVI->getOperand(1);
10316         } else {
10317           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10318         }
10319         return new ExtractElementInst(Src, SrcIdx);
10320       }
10321     }
10322   }
10323   return 0;
10324 }
10325
10326 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10327 /// elements from either LHS or RHS, return the shuffle mask and true. 
10328 /// Otherwise, return false.
10329 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10330                                          std::vector<Constant*> &Mask) {
10331   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10332          "Invalid CollectSingleShuffleElements");
10333   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10334
10335   if (isa<UndefValue>(V)) {
10336     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10337     return true;
10338   } else if (V == LHS) {
10339     for (unsigned i = 0; i != NumElts; ++i)
10340       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10341     return true;
10342   } else if (V == RHS) {
10343     for (unsigned i = 0; i != NumElts; ++i)
10344       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10345     return true;
10346   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10347     // If this is an insert of an extract from some other vector, include it.
10348     Value *VecOp    = IEI->getOperand(0);
10349     Value *ScalarOp = IEI->getOperand(1);
10350     Value *IdxOp    = IEI->getOperand(2);
10351     
10352     if (!isa<ConstantInt>(IdxOp))
10353       return false;
10354     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10355     
10356     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10357       // Okay, we can handle this if the vector we are insertinting into is
10358       // transitively ok.
10359       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10360         // If so, update the mask to reflect the inserted undef.
10361         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10362         return true;
10363       }      
10364     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10365       if (isa<ConstantInt>(EI->getOperand(1)) &&
10366           EI->getOperand(0)->getType() == V->getType()) {
10367         unsigned ExtractedIdx =
10368           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10369         
10370         // This must be extracting from either LHS or RHS.
10371         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10372           // Okay, we can handle this if the vector we are insertinting into is
10373           // transitively ok.
10374           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10375             // If so, update the mask to reflect the inserted value.
10376             if (EI->getOperand(0) == LHS) {
10377               Mask[InsertedIdx & (NumElts-1)] = 
10378                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10379             } else {
10380               assert(EI->getOperand(0) == RHS);
10381               Mask[InsertedIdx & (NumElts-1)] = 
10382                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10383               
10384             }
10385             return true;
10386           }
10387         }
10388       }
10389     }
10390   }
10391   // TODO: Handle shufflevector here!
10392   
10393   return false;
10394 }
10395
10396 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10397 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10398 /// that computes V and the LHS value of the shuffle.
10399 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10400                                      Value *&RHS) {
10401   assert(isa<VectorType>(V->getType()) && 
10402          (RHS == 0 || V->getType() == RHS->getType()) &&
10403          "Invalid shuffle!");
10404   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10405
10406   if (isa<UndefValue>(V)) {
10407     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10408     return V;
10409   } else if (isa<ConstantAggregateZero>(V)) {
10410     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10411     return V;
10412   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10413     // If this is an insert of an extract from some other vector, include it.
10414     Value *VecOp    = IEI->getOperand(0);
10415     Value *ScalarOp = IEI->getOperand(1);
10416     Value *IdxOp    = IEI->getOperand(2);
10417     
10418     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10419       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10420           EI->getOperand(0)->getType() == V->getType()) {
10421         unsigned ExtractedIdx =
10422           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10423         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10424         
10425         // Either the extracted from or inserted into vector must be RHSVec,
10426         // otherwise we'd end up with a shuffle of three inputs.
10427         if (EI->getOperand(0) == RHS || RHS == 0) {
10428           RHS = EI->getOperand(0);
10429           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10430           Mask[InsertedIdx & (NumElts-1)] = 
10431             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10432           return V;
10433         }
10434         
10435         if (VecOp == RHS) {
10436           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10437           // Everything but the extracted element is replaced with the RHS.
10438           for (unsigned i = 0; i != NumElts; ++i) {
10439             if (i != InsertedIdx)
10440               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10441           }
10442           return V;
10443         }
10444         
10445         // If this insertelement is a chain that comes from exactly these two
10446         // vectors, return the vector and the effective shuffle.
10447         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10448           return EI->getOperand(0);
10449         
10450       }
10451     }
10452   }
10453   // TODO: Handle shufflevector here!
10454   
10455   // Otherwise, can't do anything fancy.  Return an identity vector.
10456   for (unsigned i = 0; i != NumElts; ++i)
10457     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10458   return V;
10459 }
10460
10461 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10462   Value *VecOp    = IE.getOperand(0);
10463   Value *ScalarOp = IE.getOperand(1);
10464   Value *IdxOp    = IE.getOperand(2);
10465   
10466   // Inserting an undef or into an undefined place, remove this.
10467   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10468     ReplaceInstUsesWith(IE, VecOp);
10469   
10470   // If the inserted element was extracted from some other vector, and if the 
10471   // indexes are constant, try to turn this into a shufflevector operation.
10472   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10473     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10474         EI->getOperand(0)->getType() == IE.getType()) {
10475       unsigned NumVectorElts = IE.getType()->getNumElements();
10476       unsigned ExtractedIdx =
10477         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10478       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10479       
10480       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10481         return ReplaceInstUsesWith(IE, VecOp);
10482       
10483       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
10484         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10485       
10486       // If we are extracting a value from a vector, then inserting it right
10487       // back into the same place, just use the input vector.
10488       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10489         return ReplaceInstUsesWith(IE, VecOp);      
10490       
10491       // We could theoretically do this for ANY input.  However, doing so could
10492       // turn chains of insertelement instructions into a chain of shufflevector
10493       // instructions, and right now we do not merge shufflevectors.  As such,
10494       // only do this in a situation where it is clear that there is benefit.
10495       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10496         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
10497         // the values of VecOp, except then one read from EIOp0.
10498         // Build a new shuffle mask.
10499         std::vector<Constant*> Mask;
10500         if (isa<UndefValue>(VecOp))
10501           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10502         else {
10503           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10504           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10505                                                        NumVectorElts));
10506         } 
10507         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10508         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10509                                      ConstantVector::get(Mask));
10510       }
10511       
10512       // If this insertelement isn't used by some other insertelement, turn it
10513       // (and any insertelements it points to), into one big shuffle.
10514       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10515         std::vector<Constant*> Mask;
10516         Value *RHS = 0;
10517         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10518         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10519         // We now have a shuffle of LHS, RHS, Mask.
10520         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10521       }
10522     }
10523   }
10524
10525   return 0;
10526 }
10527
10528
10529 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10530   Value *LHS = SVI.getOperand(0);
10531   Value *RHS = SVI.getOperand(1);
10532   std::vector<unsigned> Mask = getShuffleMask(&SVI);
10533
10534   bool MadeChange = false;
10535   
10536   // Undefined shuffle mask -> undefined value.
10537   if (isa<UndefValue>(SVI.getOperand(2)))
10538     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10539   
10540   // If we have shuffle(x, undef, mask) and any elements of mask refer to
10541   // the undef, change them to undefs.
10542   if (isa<UndefValue>(SVI.getOperand(1))) {
10543     // Scan to see if there are any references to the RHS.  If so, replace them
10544     // with undef element refs and set MadeChange to true.
10545     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10546       if (Mask[i] >= e && Mask[i] != 2*e) {
10547         Mask[i] = 2*e;
10548         MadeChange = true;
10549       }
10550     }
10551     
10552     if (MadeChange) {
10553       // Remap any references to RHS to use LHS.
10554       std::vector<Constant*> Elts;
10555       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10556         if (Mask[i] == 2*e)
10557           Elts.push_back(UndefValue::get(Type::Int32Ty));
10558         else
10559           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10560       }
10561       SVI.setOperand(2, ConstantVector::get(Elts));
10562     }
10563   }
10564   
10565   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
10566   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10567   if (LHS == RHS || isa<UndefValue>(LHS)) {
10568     if (isa<UndefValue>(LHS) && LHS == RHS) {
10569       // shuffle(undef,undef,mask) -> undef.
10570       return ReplaceInstUsesWith(SVI, LHS);
10571     }
10572     
10573     // Remap any references to RHS to use LHS.
10574     std::vector<Constant*> Elts;
10575     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10576       if (Mask[i] >= 2*e)
10577         Elts.push_back(UndefValue::get(Type::Int32Ty));
10578       else {
10579         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10580             (Mask[i] <  e && isa<UndefValue>(LHS)))
10581           Mask[i] = 2*e;     // Turn into undef.
10582         else
10583           Mask[i] &= (e-1);  // Force to LHS.
10584         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10585       }
10586     }
10587     SVI.setOperand(0, SVI.getOperand(1));
10588     SVI.setOperand(1, UndefValue::get(RHS->getType()));
10589     SVI.setOperand(2, ConstantVector::get(Elts));
10590     LHS = SVI.getOperand(0);
10591     RHS = SVI.getOperand(1);
10592     MadeChange = true;
10593   }
10594   
10595   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10596   bool isLHSID = true, isRHSID = true;
10597     
10598   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10599     if (Mask[i] >= e*2) continue;  // Ignore undef values.
10600     // Is this an identity shuffle of the LHS value?
10601     isLHSID &= (Mask[i] == i);
10602       
10603     // Is this an identity shuffle of the RHS value?
10604     isRHSID &= (Mask[i]-e == i);
10605   }
10606
10607   // Eliminate identity shuffles.
10608   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10609   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10610   
10611   // If the LHS is a shufflevector itself, see if we can combine it with this
10612   // one without producing an unusual shuffle.  Here we are really conservative:
10613   // we are absolutely afraid of producing a shuffle mask not in the input
10614   // program, because the code gen may not be smart enough to turn a merged
10615   // shuffle into two specific shuffles: it may produce worse code.  As such,
10616   // we only merge two shuffles if the result is one of the two input shuffle
10617   // masks.  In this case, merging the shuffles just removes one instruction,
10618   // which we know is safe.  This is good for things like turning:
10619   // (splat(splat)) -> splat.
10620   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10621     if (isa<UndefValue>(RHS)) {
10622       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10623
10624       std::vector<unsigned> NewMask;
10625       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10626         if (Mask[i] >= 2*e)
10627           NewMask.push_back(2*e);
10628         else
10629           NewMask.push_back(LHSMask[Mask[i]]);
10630       
10631       // If the result mask is equal to the src shuffle or this shuffle mask, do
10632       // the replacement.
10633       if (NewMask == LHSMask || NewMask == Mask) {
10634         std::vector<Constant*> Elts;
10635         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10636           if (NewMask[i] >= e*2) {
10637             Elts.push_back(UndefValue::get(Type::Int32Ty));
10638           } else {
10639             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10640           }
10641         }
10642         return new ShuffleVectorInst(LHSSVI->getOperand(0),
10643                                      LHSSVI->getOperand(1),
10644                                      ConstantVector::get(Elts));
10645       }
10646     }
10647   }
10648
10649   return MadeChange ? &SVI : 0;
10650 }
10651
10652
10653
10654
10655 /// TryToSinkInstruction - Try to move the specified instruction from its
10656 /// current block into the beginning of DestBlock, which can only happen if it's
10657 /// safe to move the instruction past all of the instructions between it and the
10658 /// end of its block.
10659 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10660   assert(I->hasOneUse() && "Invariants didn't hold!");
10661
10662   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10663   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10664
10665   // Do not sink alloca instructions out of the entry block.
10666   if (isa<AllocaInst>(I) && I->getParent() ==
10667         &DestBlock->getParent()->getEntryBlock())
10668     return false;
10669
10670   // We can only sink load instructions if there is nothing between the load and
10671   // the end of block that could change the value.
10672   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10673     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10674          Scan != E; ++Scan)
10675       if (Scan->mayWriteToMemory())
10676         return false;
10677   }
10678
10679   BasicBlock::iterator InsertPos = DestBlock->begin();
10680   while (isa<PHINode>(InsertPos)) ++InsertPos;
10681
10682   I->moveBefore(InsertPos);
10683   ++NumSunkInst;
10684   return true;
10685 }
10686
10687
10688 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10689 /// all reachable code to the worklist.
10690 ///
10691 /// This has a couple of tricks to make the code faster and more powerful.  In
10692 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10693 /// them to the worklist (this significantly speeds up instcombine on code where
10694 /// many instructions are dead or constant).  Additionally, if we find a branch
10695 /// whose condition is a known constant, we only visit the reachable successors.
10696 ///
10697 static void AddReachableCodeToWorklist(BasicBlock *BB, 
10698                                        SmallPtrSet<BasicBlock*, 64> &Visited,
10699                                        InstCombiner &IC,
10700                                        const TargetData *TD) {
10701   std::vector<BasicBlock*> Worklist;
10702   Worklist.push_back(BB);
10703
10704   while (!Worklist.empty()) {
10705     BB = Worklist.back();
10706     Worklist.pop_back();
10707     
10708     // We have now visited this block!  If we've already been here, ignore it.
10709     if (!Visited.insert(BB)) continue;
10710     
10711     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10712       Instruction *Inst = BBI++;
10713       
10714       // DCE instruction if trivially dead.
10715       if (isInstructionTriviallyDead(Inst)) {
10716         ++NumDeadInst;
10717         DOUT << "IC: DCE: " << *Inst;
10718         Inst->eraseFromParent();
10719         continue;
10720       }
10721       
10722       // ConstantProp instruction if trivially constant.
10723       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10724         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10725         Inst->replaceAllUsesWith(C);
10726         ++NumConstProp;
10727         Inst->eraseFromParent();
10728         continue;
10729       }
10730      
10731       IC.AddToWorkList(Inst);
10732     }
10733
10734     // Recursively visit successors.  If this is a branch or switch on a
10735     // constant, only visit the reachable successor.
10736     TerminatorInst *TI = BB->getTerminator();
10737     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10738       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10739         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10740         Worklist.push_back(BI->getSuccessor(!CondVal));
10741         continue;
10742       }
10743     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10744       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10745         // See if this is an explicit destination.
10746         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10747           if (SI->getCaseValue(i) == Cond) {
10748             Worklist.push_back(SI->getSuccessor(i));
10749             continue;
10750           }
10751         
10752         // Otherwise it is the default destination.
10753         Worklist.push_back(SI->getSuccessor(0));
10754         continue;
10755       }
10756     }
10757     
10758     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10759       Worklist.push_back(TI->getSuccessor(i));
10760   }
10761 }
10762
10763 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10764   bool Changed = false;
10765   TD = &getAnalysis<TargetData>();
10766   
10767   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10768              << F.getNameStr() << "\n");
10769
10770   {
10771     // Do a depth-first traversal of the function, populate the worklist with
10772     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
10773     // track of which blocks we visit.
10774     SmallPtrSet<BasicBlock*, 64> Visited;
10775     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10776
10777     // Do a quick scan over the function.  If we find any blocks that are
10778     // unreachable, remove any instructions inside of them.  This prevents
10779     // the instcombine code from having to deal with some bad special cases.
10780     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10781       if (!Visited.count(BB)) {
10782         Instruction *Term = BB->getTerminator();
10783         while (Term != BB->begin()) {   // Remove instrs bottom-up
10784           BasicBlock::iterator I = Term; --I;
10785
10786           DOUT << "IC: DCE: " << *I;
10787           ++NumDeadInst;
10788
10789           if (!I->use_empty())
10790             I->replaceAllUsesWith(UndefValue::get(I->getType()));
10791           I->eraseFromParent();
10792         }
10793       }
10794   }
10795
10796   while (!Worklist.empty()) {
10797     Instruction *I = RemoveOneFromWorkList();
10798     if (I == 0) continue;  // skip null values.
10799
10800     // Check to see if we can DCE the instruction.
10801     if (isInstructionTriviallyDead(I)) {
10802       // Add operands to the worklist.
10803       if (I->getNumOperands() < 4)
10804         AddUsesToWorkList(*I);
10805       ++NumDeadInst;
10806
10807       DOUT << "IC: DCE: " << *I;
10808
10809       I->eraseFromParent();
10810       RemoveFromWorkList(I);
10811       continue;
10812     }
10813
10814     // Instruction isn't dead, see if we can constant propagate it.
10815     if (Constant *C = ConstantFoldInstruction(I, TD)) {
10816       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10817
10818       // Add operands to the worklist.
10819       AddUsesToWorkList(*I);
10820       ReplaceInstUsesWith(*I, C);
10821
10822       ++NumConstProp;
10823       I->eraseFromParent();
10824       RemoveFromWorkList(I);
10825       continue;
10826     }
10827
10828     // See if we can trivially sink this instruction to a successor basic block.
10829     if (I->hasOneUse()) {
10830       BasicBlock *BB = I->getParent();
10831       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10832       if (UserParent != BB) {
10833         bool UserIsSuccessor = false;
10834         // See if the user is one of our successors.
10835         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10836           if (*SI == UserParent) {
10837             UserIsSuccessor = true;
10838             break;
10839           }
10840
10841         // If the user is one of our immediate successors, and if that successor
10842         // only has us as a predecessors (we'd have to split the critical edge
10843         // otherwise), we can keep going.
10844         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10845             next(pred_begin(UserParent)) == pred_end(UserParent))
10846           // Okay, the CFG is simple enough, try to sink this instruction.
10847           Changed |= TryToSinkInstruction(I, UserParent);
10848       }
10849     }
10850
10851     // Now that we have an instruction, try combining it to simplify it...
10852 #ifndef NDEBUG
10853     std::string OrigI;
10854 #endif
10855     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10856     if (Instruction *Result = visit(*I)) {
10857       ++NumCombined;
10858       // Should we replace the old instruction with a new one?
10859       if (Result != I) {
10860         DOUT << "IC: Old = " << *I
10861              << "    New = " << *Result;
10862
10863         // Everything uses the new instruction now.
10864         I->replaceAllUsesWith(Result);
10865
10866         // Push the new instruction and any users onto the worklist.
10867         AddToWorkList(Result);
10868         AddUsersToWorkList(*Result);
10869
10870         // Move the name to the new instruction first.
10871         Result->takeName(I);
10872
10873         // Insert the new instruction into the basic block...
10874         BasicBlock *InstParent = I->getParent();
10875         BasicBlock::iterator InsertPos = I;
10876
10877         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
10878           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10879             ++InsertPos;
10880
10881         InstParent->getInstList().insert(InsertPos, Result);
10882
10883         // Make sure that we reprocess all operands now that we reduced their
10884         // use counts.
10885         AddUsesToWorkList(*I);
10886
10887         // Instructions can end up on the worklist more than once.  Make sure
10888         // we do not process an instruction that has been deleted.
10889         RemoveFromWorkList(I);
10890
10891         // Erase the old instruction.
10892         InstParent->getInstList().erase(I);
10893       } else {
10894 #ifndef NDEBUG
10895         DOUT << "IC: Mod = " << OrigI
10896              << "    New = " << *I;
10897 #endif
10898
10899         // If the instruction was modified, it's possible that it is now dead.
10900         // if so, remove it.
10901         if (isInstructionTriviallyDead(I)) {
10902           // Make sure we process all operands now that we are reducing their
10903           // use counts.
10904           AddUsesToWorkList(*I);
10905
10906           // Instructions may end up in the worklist more than once.  Erase all
10907           // occurrences of this instruction.
10908           RemoveFromWorkList(I);
10909           I->eraseFromParent();
10910         } else {
10911           AddToWorkList(I);
10912           AddUsersToWorkList(*I);
10913         }
10914       }
10915       Changed = true;
10916     }
10917   }
10918
10919   assert(WorklistMap.empty() && "Worklist empty, but map not?");
10920     
10921   // Do an explicit clear, this shrinks the map if needed.
10922   WorklistMap.clear();
10923   return Changed;
10924 }
10925
10926
10927 bool InstCombiner::runOnFunction(Function &F) {
10928   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10929   
10930   bool EverMadeChange = false;
10931
10932   // Iterate while there is work to do.
10933   unsigned Iteration = 0;
10934   while (DoOneIteration(F, Iteration++)) 
10935     EverMadeChange = true;
10936   return EverMadeChange;
10937 }
10938
10939 FunctionPass *llvm::createInstructionCombiningPass() {
10940   return new InstCombiner();
10941 }
10942