Turn StripPointerCast() into a method
[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/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/ConstantRange.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
59 #include <algorithm>
60 #include <climits>
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     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
241                                    bool DoXform = true);
242
243   public:
244     // InsertNewInstBefore - insert an instruction New before instruction Old
245     // in the program.  Add the new instruction to the worklist.
246     //
247     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
248       assert(New && New->getParent() == 0 &&
249              "New instruction already inserted into a basic block!");
250       BasicBlock *BB = Old.getParent();
251       BB->getInstList().insert(&Old, New);  // Insert inst
252       AddToWorkList(New);
253       return New;
254     }
255
256     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
257     /// This also adds the cast to the worklist.  Finally, this returns the
258     /// cast.
259     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
260                             Instruction &Pos) {
261       if (V->getType() == Ty) return V;
262
263       if (Constant *CV = dyn_cast<Constant>(V))
264         return ConstantExpr::getCast(opc, CV, Ty);
265       
266       Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
267       AddToWorkList(C);
268       return C;
269     }
270         
271     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
272       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
273     }
274
275
276     // ReplaceInstUsesWith - This method is to be used when an instruction is
277     // found to be dead, replacable with another preexisting expression.  Here
278     // we add all uses of I to the worklist, replace all uses of I with the new
279     // value, then return I, so that the inst combiner will know that I was
280     // modified.
281     //
282     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
283       AddUsersToWorkList(I);         // Add all modified instrs to worklist
284       if (&I != V) {
285         I.replaceAllUsesWith(V);
286         return &I;
287       } else {
288         // If we are replacing the instruction with itself, this must be in a
289         // segment of unreachable code, so just clobber the instruction.
290         I.replaceAllUsesWith(UndefValue::get(I.getType()));
291         return &I;
292       }
293     }
294
295     // UpdateValueUsesWith - This method is to be used when an value is
296     // found to be replacable with another preexisting expression or was
297     // updated.  Here we add all uses of I to the worklist, replace all uses of
298     // I with the new value (unless the instruction was just updated), then
299     // return true, so that the inst combiner will know that I was modified.
300     //
301     bool UpdateValueUsesWith(Value *Old, Value *New) {
302       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
303       if (Old != New)
304         Old->replaceAllUsesWith(New);
305       if (Instruction *I = dyn_cast<Instruction>(Old))
306         AddToWorkList(I);
307       if (Instruction *I = dyn_cast<Instruction>(New))
308         AddToWorkList(I);
309       return true;
310     }
311     
312     // EraseInstFromFunction - When dealing with an instruction that has side
313     // effects or produces a void value, we can't rely on DCE to delete the
314     // instruction.  Instead, visit methods should return the value returned by
315     // this function.
316     Instruction *EraseInstFromFunction(Instruction &I) {
317       assert(I.use_empty() && "Cannot erase instruction that is used!");
318       AddUsesToWorkList(I);
319       RemoveFromWorkList(&I);
320       I.eraseFromParent();
321       return 0;  // Don't do anything with FI
322     }
323
324   private:
325     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
326     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
327     /// casts that are known to not do anything...
328     ///
329     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
330                                    Value *V, const Type *DestTy,
331                                    Instruction *InsertBefore);
332
333     /// SimplifyCommutative - This performs a few simplifications for 
334     /// commutative operators.
335     bool SimplifyCommutative(BinaryOperator &I);
336
337     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338     /// most-complex to least-complex order.
339     bool SimplifyCompare(CmpInst &I);
340
341     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
342     /// on the demanded bits.
343     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
344                               APInt& KnownZero, APInt& KnownOne,
345                               unsigned Depth = 0);
346
347     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
348                                       uint64_t &UndefElts, unsigned Depth = 0);
349       
350     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
351     // PHI node as operand #0, see if we can fold the instruction into the PHI
352     // (which is only possible if all operands to the PHI are constants).
353     Instruction *FoldOpIntoPhi(Instruction &I);
354
355     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
356     // operator and they all are only used by the PHI, PHI together their
357     // inputs, and do the operation once, to the result of the PHI.
358     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
359     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
360     
361     
362     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
363                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
364     
365     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
366                               bool isSub, Instruction &I);
367     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
368                                  bool isSigned, bool Inside, Instruction &IB);
369     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
370     Instruction *MatchBSwap(BinaryOperator &I);
371     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
372     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
373     Instruction *SimplifyMemSet(MemSetInst *MI);
374
375
376     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
377
378     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero, 
379                            APInt& KnownOne, unsigned Depth = 0);
380     bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
381     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
382                                     unsigned CastOpc,
383                                     int &NumCastsRemoved);
384     unsigned GetOrEnforceKnownAlignment(Value *V,
385                                         unsigned PrefAlign = 0);
386   };
387
388   char InstCombiner::ID = 0;
389   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
390 }
391
392 // getComplexity:  Assign a complexity or rank value to LLVM Values...
393 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
394 static unsigned getComplexity(Value *V) {
395   if (isa<Instruction>(V)) {
396     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
397       return 3;
398     return 4;
399   }
400   if (isa<Argument>(V)) return 3;
401   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
402 }
403
404 // isOnlyUse - Return true if this instruction will be deleted if we stop using
405 // it.
406 static bool isOnlyUse(Value *V) {
407   return V->hasOneUse() || isa<Constant>(V);
408 }
409
410 // getPromotedType - Return the specified type promoted as it would be to pass
411 // though a va_arg area...
412 static const Type *getPromotedType(const Type *Ty) {
413   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
414     if (ITy->getBitWidth() < 32)
415       return Type::Int32Ty;
416   }
417   return Ty;
418 }
419
420 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
421 /// expression bitcast,  return the operand value, otherwise return null.
422 static Value *getBitCastOperand(Value *V) {
423   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
424     return I->getOperand(0);
425   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
426     if (CE->getOpcode() == Instruction::BitCast)
427       return CE->getOperand(0);
428   return 0;
429 }
430
431 /// This function is a wrapper around CastInst::isEliminableCastPair. It
432 /// simply extracts arguments and returns what that function returns.
433 static Instruction::CastOps 
434 isEliminableCastPair(
435   const CastInst *CI, ///< The first cast instruction
436   unsigned opcode,       ///< The opcode of the second cast instruction
437   const Type *DstTy,     ///< The target type for the second cast instruction
438   TargetData *TD         ///< The target data for pointer size
439 ) {
440   
441   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
442   const Type *MidTy = CI->getType();                  // B from above
443
444   // Get the opcodes of the two Cast instructions
445   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
446   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
447
448   return Instruction::CastOps(
449       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
450                                      DstTy, TD->getIntPtrType()));
451 }
452
453 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
454 /// in any code being generated.  It does not require codegen if V is simple
455 /// enough or if the cast can be folded into other casts.
456 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
457                               const Type *Ty, TargetData *TD) {
458   if (V->getType() == Ty || isa<Constant>(V)) return false;
459   
460   // If this is another cast that can be eliminated, it isn't codegen either.
461   if (const CastInst *CI = dyn_cast<CastInst>(V))
462     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
463       return false;
464   return true;
465 }
466
467 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
468 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
469 /// casts that are known to not do anything...
470 ///
471 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
472                                              Value *V, const Type *DestTy,
473                                              Instruction *InsertBefore) {
474   if (V->getType() == DestTy) return V;
475   if (Constant *C = dyn_cast<Constant>(V))
476     return ConstantExpr::getCast(opcode, C, DestTy);
477   
478   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
479 }
480
481 // SimplifyCommutative - This performs a few simplifications for commutative
482 // operators:
483 //
484 //  1. Order operands such that they are listed from right (least complex) to
485 //     left (most complex).  This puts constants before unary operators before
486 //     binary operators.
487 //
488 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
489 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
490 //
491 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
492   bool Changed = false;
493   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
494     Changed = !I.swapOperands();
495
496   if (!I.isAssociative()) return Changed;
497   Instruction::BinaryOps Opcode = I.getOpcode();
498   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
499     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
500       if (isa<Constant>(I.getOperand(1))) {
501         Constant *Folded = ConstantExpr::get(I.getOpcode(),
502                                              cast<Constant>(I.getOperand(1)),
503                                              cast<Constant>(Op->getOperand(1)));
504         I.setOperand(0, Op->getOperand(0));
505         I.setOperand(1, Folded);
506         return true;
507       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
508         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
509             isOnlyUse(Op) && isOnlyUse(Op1)) {
510           Constant *C1 = cast<Constant>(Op->getOperand(1));
511           Constant *C2 = cast<Constant>(Op1->getOperand(1));
512
513           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
514           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
515           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
516                                                     Op1->getOperand(0),
517                                                     Op1->getName(), &I);
518           AddToWorkList(New);
519           I.setOperand(0, New);
520           I.setOperand(1, Folded);
521           return true;
522         }
523     }
524   return Changed;
525 }
526
527 /// SimplifyCompare - For a CmpInst this function just orders the operands
528 /// so that theyare listed from right (least complex) to left (most complex).
529 /// This puts constants before unary operators before binary operators.
530 bool InstCombiner::SimplifyCompare(CmpInst &I) {
531   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
532     return false;
533   I.swapOperands();
534   // Compare instructions are not associative so there's nothing else we can do.
535   return true;
536 }
537
538 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
539 // if the LHS is a constant zero (which is the 'negate' form).
540 //
541 static inline Value *dyn_castNegVal(Value *V) {
542   if (BinaryOperator::isNeg(V))
543     return BinaryOperator::getNegArgument(V);
544
545   // Constants can be considered to be negated values if they can be folded.
546   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
547     return ConstantExpr::getNeg(C);
548   return 0;
549 }
550
551 static inline Value *dyn_castNotVal(Value *V) {
552   if (BinaryOperator::isNot(V))
553     return BinaryOperator::getNotArgument(V);
554
555   // Constants can be considered to be not'ed values...
556   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
557     return ConstantInt::get(~C->getValue());
558   return 0;
559 }
560
561 // dyn_castFoldableMul - If this value is a multiply that can be folded into
562 // other computations (because it has a constant operand), return the
563 // non-constant operand of the multiply, and set CST to point to the multiplier.
564 // Otherwise, return null.
565 //
566 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
567   if (V->hasOneUse() && V->getType()->isInteger())
568     if (Instruction *I = dyn_cast<Instruction>(V)) {
569       if (I->getOpcode() == Instruction::Mul)
570         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
571           return I->getOperand(0);
572       if (I->getOpcode() == Instruction::Shl)
573         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
574           // The multiplier is really 1 << CST.
575           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
576           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
577           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
578           return I->getOperand(0);
579         }
580     }
581   return 0;
582 }
583
584 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
585 /// expression, return it.
586 static User *dyn_castGetElementPtr(Value *V) {
587   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
588   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
589     if (CE->getOpcode() == Instruction::GetElementPtr)
590       return cast<User>(V);
591   return false;
592 }
593
594 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
595 /// opcode value. Otherwise return UserOp1.
596 static unsigned getOpcode(User *U) {
597   if (Instruction *I = dyn_cast<Instruction>(U))
598     return I->getOpcode();
599   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
600     return CE->getOpcode();
601   // Use UserOp1 to mean there's no opcode.
602   return Instruction::UserOp1;
603 }
604
605 /// AddOne - Add one to a ConstantInt
606 static ConstantInt *AddOne(ConstantInt *C) {
607   APInt Val(C->getValue());
608   return ConstantInt::get(++Val);
609 }
610 /// SubOne - Subtract one from a ConstantInt
611 static ConstantInt *SubOne(ConstantInt *C) {
612   APInt Val(C->getValue());
613   return ConstantInt::get(--Val);
614 }
615 /// Add - Add two ConstantInts together
616 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
617   return ConstantInt::get(C1->getValue() + C2->getValue());
618 }
619 /// And - Bitwise AND two ConstantInts together
620 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
621   return ConstantInt::get(C1->getValue() & C2->getValue());
622 }
623 /// Subtract - Subtract one ConstantInt from another
624 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
625   return ConstantInt::get(C1->getValue() - C2->getValue());
626 }
627 /// Multiply - Multiply two ConstantInts together
628 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
629   return ConstantInt::get(C1->getValue() * C2->getValue());
630 }
631 /// MultiplyOverflows - True if the multiply can not be expressed in an int
632 /// this size.
633 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
634   uint32_t W = C1->getBitWidth();
635   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
636   if (sign) {
637     LHSExt.sext(W * 2);
638     RHSExt.sext(W * 2);
639   } else {
640     LHSExt.zext(W * 2);
641     RHSExt.zext(W * 2);
642   }
643
644   APInt MulExt = LHSExt * RHSExt;
645
646   if (sign) {
647     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
648     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
649     return MulExt.slt(Min) || MulExt.sgt(Max);
650   } else 
651     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
652 }
653
654 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
655 /// known to be either zero or one and return them in the KnownZero/KnownOne
656 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
657 /// processing.
658 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
659 /// we cannot optimize based on the assumption that it is zero without changing
660 /// it to be an explicit zero.  If we don't change it to zero, other code could
661 /// optimized based on the contradictory assumption that it is non-zero.
662 /// Because instcombine aggressively folds operations with undef args anyway,
663 /// this won't lose us code quality.
664 void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
665                                      APInt& KnownZero, APInt& KnownOne,
666                                      unsigned Depth) {
667   assert(V && "No Value?");
668   assert(Depth <= 6 && "Limit Search Depth");
669   uint32_t BitWidth = Mask.getBitWidth();
670   assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
671          "Not integer or pointer type!");
672   assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
673          (!isa<IntegerType>(V->getType()) ||
674           V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
675          KnownZero.getBitWidth() == BitWidth && 
676          KnownOne.getBitWidth() == BitWidth &&
677          "V, Mask, KnownOne and KnownZero should have same BitWidth");
678   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
679     // We know all of the bits for a constant!
680     KnownOne = CI->getValue() & Mask;
681     KnownZero = ~KnownOne & Mask;
682     return;
683   }
684   // Null is all-zeros.
685   if (isa<ConstantPointerNull>(V)) {
686     KnownOne.clear();
687     KnownZero = Mask;
688     return;
689   }
690   // The address of an aligned GlobalValue has trailing zeros.
691   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
692     unsigned Align = GV->getAlignment();
693     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
694       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
695     if (Align > 0)
696       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
697                                               CountTrailingZeros_32(Align));
698     else
699       KnownZero.clear();
700     KnownOne.clear();
701     return;
702   }
703
704   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
705
706   if (Depth == 6 || Mask == 0)
707     return;  // Limit search depth.
708
709   User *I = dyn_cast<User>(V);
710   if (!I) return;
711
712   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
713   switch (getOpcode(I)) {
714   default: break;
715   case Instruction::And: {
716     // If either the LHS or the RHS are Zero, the result is zero.
717     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
718     APInt Mask2(Mask & ~KnownZero);
719     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
720     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
721     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
722     
723     // Output known-1 bits are only known if set in both the LHS & RHS.
724     KnownOne &= KnownOne2;
725     // Output known-0 are known to be clear if zero in either the LHS | RHS.
726     KnownZero |= KnownZero2;
727     return;
728   }
729   case Instruction::Or: {
730     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
731     APInt Mask2(Mask & ~KnownOne);
732     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
733     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
734     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
735     
736     // Output known-0 bits are only known if clear in both the LHS & RHS.
737     KnownZero &= KnownZero2;
738     // Output known-1 are known to be set if set in either the LHS | RHS.
739     KnownOne |= KnownOne2;
740     return;
741   }
742   case Instruction::Xor: {
743     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
744     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
745     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
746     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
747     
748     // Output known-0 bits are known if clear or set in both the LHS & RHS.
749     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
750     // Output known-1 are known to be set if set in only one of the LHS, RHS.
751     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
752     KnownZero = KnownZeroOut;
753     return;
754   }
755   case Instruction::Mul: {
756     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
757     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
758     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
759     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
760     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
761     
762     // If low bits are zero in either operand, output low known-0 bits.
763     // Also compute a conserative estimate for high known-0 bits.
764     // More trickiness is possible, but this is sufficient for the
765     // interesting case of alignment computation.
766     KnownOne.clear();
767     unsigned TrailZ = KnownZero.countTrailingOnes() +
768                       KnownZero2.countTrailingOnes();
769     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
770                                KnownZero2.countLeadingOnes(),
771                                BitWidth) - BitWidth;
772
773     TrailZ = std::min(TrailZ, BitWidth);
774     LeadZ = std::min(LeadZ, BitWidth);
775     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
776                 APInt::getHighBitsSet(BitWidth, LeadZ);
777     KnownZero &= Mask;
778     return;
779   }
780   case Instruction::UDiv: {
781     // For the purposes of computing leading zeros we can conservatively
782     // treat a udiv as a logical right shift by the power of 2 known to
783     // be less than the denominator.
784     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
785     ComputeMaskedBits(I->getOperand(0),
786                       AllOnes, KnownZero2, KnownOne2, Depth+1);
787     unsigned LeadZ = KnownZero2.countLeadingOnes();
788
789     KnownOne2.clear();
790     KnownZero2.clear();
791     ComputeMaskedBits(I->getOperand(1),
792                       AllOnes, KnownZero2, KnownOne2, Depth+1);
793     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
794     if (RHSUnknownLeadingOnes != BitWidth)
795       LeadZ = std::min(BitWidth,
796                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
797
798     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
799     return;
800   }
801   case Instruction::Select:
802     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
803     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
804     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
805     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
806
807     // Only known if known in both the LHS and RHS.
808     KnownOne &= KnownOne2;
809     KnownZero &= KnownZero2;
810     return;
811   case Instruction::FPTrunc:
812   case Instruction::FPExt:
813   case Instruction::FPToUI:
814   case Instruction::FPToSI:
815   case Instruction::SIToFP:
816   case Instruction::UIToFP:
817     return; // Can't work with floating point.
818   case Instruction::PtrToInt:
819   case Instruction::IntToPtr:
820     // We can't handle these if we don't know the pointer size.
821     if (!TD) return;
822     // Fall through and handle them the same as zext/trunc.
823   case Instruction::ZExt:
824   case Instruction::Trunc: {
825     // All these have integer operands
826     const Type *SrcTy = I->getOperand(0)->getType();
827     uint32_t SrcBitWidth = TD ?
828       TD->getTypeSizeInBits(SrcTy) :
829       SrcTy->getPrimitiveSizeInBits();
830     APInt MaskIn(Mask);
831     MaskIn.zextOrTrunc(SrcBitWidth);
832     KnownZero.zextOrTrunc(SrcBitWidth);
833     KnownOne.zextOrTrunc(SrcBitWidth);
834     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
835     KnownZero.zextOrTrunc(BitWidth);
836     KnownOne.zextOrTrunc(BitWidth);
837     // Any top bits are known to be zero.
838     if (BitWidth > SrcBitWidth)
839       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
840     return;
841   }
842   case Instruction::BitCast: {
843     const Type *SrcTy = I->getOperand(0)->getType();
844     if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
845       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
846       return;
847     }
848     break;
849   }
850   case Instruction::SExt: {
851     // Compute the bits in the result that are not present in the input.
852     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
853     uint32_t SrcBitWidth = SrcTy->getBitWidth();
854       
855     APInt MaskIn(Mask); 
856     MaskIn.trunc(SrcBitWidth);
857     KnownZero.trunc(SrcBitWidth);
858     KnownOne.trunc(SrcBitWidth);
859     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
860     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
861     KnownZero.zext(BitWidth);
862     KnownOne.zext(BitWidth);
863
864     // If the sign bit of the input is known set or clear, then we know the
865     // top bits of the result.
866     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
867       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
868     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
869       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
870     return;
871   }
872   case Instruction::Shl:
873     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
874     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
875       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
876       APInt Mask2(Mask.lshr(ShiftAmt));
877       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
878       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
879       KnownZero <<= ShiftAmt;
880       KnownOne  <<= ShiftAmt;
881       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
882       return;
883     }
884     break;
885   case Instruction::LShr:
886     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
887     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
888       // Compute the new bits that are at the top now.
889       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
890       
891       // Unsigned shift right.
892       APInt Mask2(Mask.shl(ShiftAmt));
893       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
894       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
895       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
896       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
897       // high bits known zero.
898       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
899       return;
900     }
901     break;
902   case Instruction::AShr:
903     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
904     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
905       // Compute the new bits that are at the top now.
906       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
907       
908       // Signed shift right.
909       APInt Mask2(Mask.shl(ShiftAmt));
910       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
911       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
912       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
913       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
914         
915       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
916       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
917         KnownZero |= HighBits;
918       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
919         KnownOne |= HighBits;
920       return;
921     }
922     break;
923   case Instruction::Sub: {
924     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
925       // We know that the top bits of C-X are clear if X contains less bits
926       // than C (i.e. no wrap-around can happen).  For example, 20-X is
927       // positive if we can prove that X is >= 0 and < 16.
928       if (!CLHS->getValue().isNegative()) {
929         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
930         // NLZ can't be BitWidth with no sign bit
931         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
932         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
933                           Depth+1);
934     
935         // If all of the MaskV bits are known to be zero, then we know the
936         // output top bits are zero, because we now know that the output is
937         // from [0-C].
938         if ((KnownZero2 & MaskV) == MaskV) {
939           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
940           // Top bits known zero.
941           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
942         }
943       }        
944     }
945   }
946   // fall through
947   case Instruction::Add: {
948     // Output known-0 bits are known if clear or set in both the low clear bits
949     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
950     // low 3 bits clear.
951     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
952     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
953     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
954     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
955
956     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
957     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
958     KnownZeroOut = std::min(KnownZeroOut, 
959                             KnownZero2.countTrailingOnes());
960
961     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
962     return;
963   }
964   case Instruction::SRem:
965     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
966       APInt RA = Rem->getValue();
967       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
968         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
969         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
970         ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
971
972         // The sign of a remainder is equal to the sign of the first
973         // operand (zero being positive).
974         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
975           KnownZero2 |= ~LowBits;
976         else if (KnownOne2[BitWidth-1])
977           KnownOne2 |= ~LowBits;
978
979         KnownZero |= KnownZero2 & Mask;
980         KnownOne |= KnownOne2 & Mask;
981
982         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
983       }
984     }
985     break;
986   case Instruction::URem: {
987     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
988       APInt RA = Rem->getValue();
989       if (RA.isPowerOf2()) {
990         APInt LowBits = (RA - 1);
991         APInt Mask2 = LowBits & Mask;
992         KnownZero |= ~LowBits & Mask;
993         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
994         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
995         break;
996       }
997     }
998
999     // Since the result is less than or equal to either operand, any leading
1000     // zero bits in either operand must also exist in the result.
1001     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1002     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1003                       Depth+1);
1004     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1005                       Depth+1);
1006
1007     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1008                                 KnownZero2.countLeadingOnes());
1009     KnownOne.clear();
1010     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1011     break;
1012   }
1013
1014   case Instruction::Alloca:
1015   case Instruction::Malloc: {
1016     AllocationInst *AI = cast<AllocationInst>(V);
1017     unsigned Align = AI->getAlignment();
1018     if (Align == 0 && TD) {
1019       if (isa<AllocaInst>(AI))
1020         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1021       else if (isa<MallocInst>(AI)) {
1022         // Malloc returns maximally aligned memory.
1023         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1024         Align =
1025           std::max(Align,
1026                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1027         Align =
1028           std::max(Align,
1029                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1030       }
1031     }
1032     
1033     if (Align > 0)
1034       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1035                                               CountTrailingZeros_32(Align));
1036     break;
1037   }
1038   case Instruction::GetElementPtr: {
1039     // Analyze all of the subscripts of this getelementptr instruction
1040     // to determine if we can prove known low zero bits.
1041     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1042     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1043     ComputeMaskedBits(I->getOperand(0), LocalMask,
1044                       LocalKnownZero, LocalKnownOne, Depth+1);
1045     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1046
1047     gep_type_iterator GTI = gep_type_begin(I);
1048     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1049       Value *Index = I->getOperand(i);
1050       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1051         // Handle struct member offset arithmetic.
1052         if (!TD) return;
1053         const StructLayout *SL = TD->getStructLayout(STy);
1054         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1055         uint64_t Offset = SL->getElementOffset(Idx);
1056         TrailZ = std::min(TrailZ,
1057                           CountTrailingZeros_64(Offset));
1058       } else {
1059         // Handle array index arithmetic.
1060         const Type *IndexedTy = GTI.getIndexedType();
1061         if (!IndexedTy->isSized()) return;
1062         unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1063         uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1064         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1065         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1066         ComputeMaskedBits(Index, LocalMask,
1067                           LocalKnownZero, LocalKnownOne, Depth+1);
1068         TrailZ = std::min(TrailZ,
1069                           CountTrailingZeros_64(TypeSize) +
1070                             LocalKnownZero.countTrailingOnes());
1071       }
1072     }
1073     
1074     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1075     break;
1076   }
1077   case Instruction::PHI: {
1078     PHINode *P = cast<PHINode>(I);
1079     // Handle the case of a simple two-predecessor recurrence PHI.
1080     // There's a lot more that could theoretically be done here, but
1081     // this is sufficient to catch some interesting cases.
1082     if (P->getNumIncomingValues() == 2) {
1083       for (unsigned i = 0; i != 2; ++i) {
1084         Value *L = P->getIncomingValue(i);
1085         Value *R = P->getIncomingValue(!i);
1086         User *LU = dyn_cast<User>(L);
1087         unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1088         // Check for operations that have the property that if
1089         // both their operands have low zero bits, the result
1090         // will have low zero bits.
1091         if (Opcode == Instruction::Add ||
1092             Opcode == Instruction::Sub ||
1093             Opcode == Instruction::And ||
1094             Opcode == Instruction::Or ||
1095             Opcode == Instruction::Mul) {
1096           Value *LL = LU->getOperand(0);
1097           Value *LR = LU->getOperand(1);
1098           // Find a recurrence.
1099           if (LL == I)
1100             L = LR;
1101           else if (LR == I)
1102             L = LL;
1103           else
1104             break;
1105           // Ok, we have a PHI of the form L op= R. Check for low
1106           // zero bits.
1107           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1108           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1109           Mask2 = APInt::getLowBitsSet(BitWidth,
1110                                        KnownZero2.countTrailingOnes());
1111           KnownOne2.clear();
1112           KnownZero2.clear();
1113           ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1114           KnownZero = Mask &
1115                       APInt::getLowBitsSet(BitWidth,
1116                                            KnownZero2.countTrailingOnes());
1117           break;
1118         }
1119       }
1120     }
1121     break;
1122   }
1123   case Instruction::Call:
1124     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1125       switch (II->getIntrinsicID()) {
1126       default: break;
1127       case Intrinsic::ctpop:
1128       case Intrinsic::ctlz:
1129       case Intrinsic::cttz: {
1130         unsigned LowBits = Log2_32(BitWidth)+1;
1131         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1132         break;
1133       }
1134       }
1135     }
1136     break;
1137   }
1138 }
1139
1140 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1141 /// this predicate to simplify operations downstream.  Mask is known to be zero
1142 /// for bits that V cannot have.
1143 bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1144                                      unsigned Depth) {
1145   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1146   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1147   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1148   return (KnownZero & Mask) == Mask;
1149 }
1150
1151 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1152 /// specified instruction is a constant integer.  If so, check to see if there
1153 /// are any bits set in the constant that are not demanded.  If so, shrink the
1154 /// constant and return true.
1155 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1156                                    APInt Demanded) {
1157   assert(I && "No instruction?");
1158   assert(OpNo < I->getNumOperands() && "Operand index too large");
1159
1160   // If the operand is not a constant integer, nothing to do.
1161   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1162   if (!OpC) return false;
1163
1164   // If there are no bits set that aren't demanded, nothing to do.
1165   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1166   if ((~Demanded & OpC->getValue()) == 0)
1167     return false;
1168
1169   // This instruction is producing bits that are not demanded. Shrink the RHS.
1170   Demanded &= OpC->getValue();
1171   I->setOperand(OpNo, ConstantInt::get(Demanded));
1172   return true;
1173 }
1174
1175 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1176 // set of known zero and one bits, compute the maximum and minimum values that
1177 // could have the specified known zero and known one bits, returning them in
1178 // min/max.
1179 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1180                                                    const APInt& KnownZero,
1181                                                    const APInt& KnownOne,
1182                                                    APInt& Min, APInt& Max) {
1183   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1184   assert(KnownZero.getBitWidth() == BitWidth && 
1185          KnownOne.getBitWidth() == BitWidth &&
1186          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1187          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1188   APInt UnknownBits = ~(KnownZero|KnownOne);
1189
1190   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1191   // bit if it is unknown.
1192   Min = KnownOne;
1193   Max = KnownOne|UnknownBits;
1194   
1195   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1196     Min.set(BitWidth-1);
1197     Max.clear(BitWidth-1);
1198   }
1199 }
1200
1201 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1202 // a set of known zero and one bits, compute the maximum and minimum values that
1203 // could have the specified known zero and known one bits, returning them in
1204 // min/max.
1205 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1206                                                      const APInt &KnownZero,
1207                                                      const APInt &KnownOne,
1208                                                      APInt &Min, APInt &Max) {
1209   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
1210   assert(KnownZero.getBitWidth() == BitWidth && 
1211          KnownOne.getBitWidth() == BitWidth &&
1212          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1213          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1214   APInt UnknownBits = ~(KnownZero|KnownOne);
1215   
1216   // The minimum value is when the unknown bits are all zeros.
1217   Min = KnownOne;
1218   // The maximum value is when the unknown bits are all ones.
1219   Max = KnownOne|UnknownBits;
1220 }
1221
1222 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1223 /// value based on the demanded bits. When this function is called, it is known
1224 /// that only the bits set in DemandedMask of the result of V are ever used
1225 /// downstream. Consequently, depending on the mask and V, it may be possible
1226 /// to replace V with a constant or one of its operands. In such cases, this
1227 /// function does the replacement and returns true. In all other cases, it
1228 /// returns false after analyzing the expression and setting KnownOne and known
1229 /// to be one in the expression. KnownZero contains all the bits that are known
1230 /// to be zero in the expression. These are provided to potentially allow the
1231 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1232 /// the expression. KnownOne and KnownZero always follow the invariant that 
1233 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1234 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1235 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1236 /// and KnownOne must all be the same.
1237 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1238                                         APInt& KnownZero, APInt& KnownOne,
1239                                         unsigned Depth) {
1240   assert(V != 0 && "Null pointer of Value???");
1241   assert(Depth <= 6 && "Limit Search Depth");
1242   uint32_t BitWidth = DemandedMask.getBitWidth();
1243   const IntegerType *VTy = cast<IntegerType>(V->getType());
1244   assert(VTy->getBitWidth() == BitWidth && 
1245          KnownZero.getBitWidth() == BitWidth && 
1246          KnownOne.getBitWidth() == BitWidth &&
1247          "Value *V, DemandedMask, KnownZero and KnownOne \
1248           must have same BitWidth");
1249   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1250     // We know all of the bits for a constant!
1251     KnownOne = CI->getValue() & DemandedMask;
1252     KnownZero = ~KnownOne & DemandedMask;
1253     return false;
1254   }
1255   
1256   KnownZero.clear(); 
1257   KnownOne.clear();
1258   if (!V->hasOneUse()) {    // Other users may use these bits.
1259     if (Depth != 0) {       // Not at the root.
1260       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1261       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1262       return false;
1263     }
1264     // If this is the root being simplified, allow it to have multiple uses,
1265     // just set the DemandedMask to all bits.
1266     DemandedMask = APInt::getAllOnesValue(BitWidth);
1267   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1268     if (V != UndefValue::get(VTy))
1269       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1270     return false;
1271   } else if (Depth == 6) {        // Limit search depth.
1272     return false;
1273   }
1274   
1275   Instruction *I = dyn_cast<Instruction>(V);
1276   if (!I) return false;        // Only analyze instructions.
1277
1278   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1279   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1280   switch (I->getOpcode()) {
1281   default:
1282     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1283     break;
1284   case Instruction::And:
1285     // If either the LHS or the RHS are Zero, the result is zero.
1286     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1287                              RHSKnownZero, RHSKnownOne, Depth+1))
1288       return true;
1289     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1290            "Bits known to be one AND zero?"); 
1291
1292     // If something is known zero on the RHS, the bits aren't demanded on the
1293     // LHS.
1294     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1295                              LHSKnownZero, LHSKnownOne, Depth+1))
1296       return true;
1297     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1298            "Bits known to be one AND zero?"); 
1299
1300     // If all of the demanded bits are known 1 on one side, return the other.
1301     // These bits cannot contribute to the result of the 'and'.
1302     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1303         (DemandedMask & ~LHSKnownZero))
1304       return UpdateValueUsesWith(I, I->getOperand(0));
1305     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1306         (DemandedMask & ~RHSKnownZero))
1307       return UpdateValueUsesWith(I, I->getOperand(1));
1308     
1309     // If all of the demanded bits in the inputs are known zeros, return zero.
1310     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1311       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1312       
1313     // If the RHS is a constant, see if we can simplify it.
1314     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1315       return UpdateValueUsesWith(I, I);
1316       
1317     // Output known-1 bits are only known if set in both the LHS & RHS.
1318     RHSKnownOne &= LHSKnownOne;
1319     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1320     RHSKnownZero |= LHSKnownZero;
1321     break;
1322   case Instruction::Or:
1323     // If either the LHS or the RHS are One, the result is One.
1324     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1325                              RHSKnownZero, RHSKnownOne, Depth+1))
1326       return true;
1327     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1328            "Bits known to be one AND zero?"); 
1329     // If something is known one on the RHS, the bits aren't demanded on the
1330     // LHS.
1331     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1332                              LHSKnownZero, LHSKnownOne, Depth+1))
1333       return true;
1334     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1335            "Bits known to be one AND zero?"); 
1336     
1337     // If all of the demanded bits are known zero on one side, return the other.
1338     // These bits cannot contribute to the result of the 'or'.
1339     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1340         (DemandedMask & ~LHSKnownOne))
1341       return UpdateValueUsesWith(I, I->getOperand(0));
1342     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1343         (DemandedMask & ~RHSKnownOne))
1344       return UpdateValueUsesWith(I, I->getOperand(1));
1345
1346     // If all of the potentially set bits on one side are known to be set on
1347     // the other side, just use the 'other' side.
1348     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1349         (DemandedMask & (~RHSKnownZero)))
1350       return UpdateValueUsesWith(I, I->getOperand(0));
1351     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1352         (DemandedMask & (~LHSKnownZero)))
1353       return UpdateValueUsesWith(I, I->getOperand(1));
1354         
1355     // If the RHS is a constant, see if we can simplify it.
1356     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1357       return UpdateValueUsesWith(I, I);
1358           
1359     // Output known-0 bits are only known if clear in both the LHS & RHS.
1360     RHSKnownZero &= LHSKnownZero;
1361     // Output known-1 are known to be set if set in either the LHS | RHS.
1362     RHSKnownOne |= LHSKnownOne;
1363     break;
1364   case Instruction::Xor: {
1365     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1366                              RHSKnownZero, RHSKnownOne, Depth+1))
1367       return true;
1368     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1369            "Bits known to be one AND zero?"); 
1370     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1371                              LHSKnownZero, LHSKnownOne, Depth+1))
1372       return true;
1373     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1374            "Bits known to be one AND zero?"); 
1375     
1376     // If all of the demanded bits are known zero on one side, return the other.
1377     // These bits cannot contribute to the result of the 'xor'.
1378     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1379       return UpdateValueUsesWith(I, I->getOperand(0));
1380     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1381       return UpdateValueUsesWith(I, I->getOperand(1));
1382     
1383     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1384     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1385                          (RHSKnownOne & LHSKnownOne);
1386     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1387     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1388                         (RHSKnownOne & LHSKnownZero);
1389     
1390     // If all of the demanded bits are known to be zero on one side or the
1391     // other, turn this into an *inclusive* or.
1392     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1393     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1394       Instruction *Or =
1395         BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1396                                  I->getName());
1397       InsertNewInstBefore(Or, *I);
1398       return UpdateValueUsesWith(I, Or);
1399     }
1400     
1401     // If all of the demanded bits on one side are known, and all of the set
1402     // bits on that side are also known to be set on the other side, turn this
1403     // into an AND, as we know the bits will be cleared.
1404     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1405     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1406       // all known
1407       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1408         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1409         Instruction *And = 
1410           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1411         InsertNewInstBefore(And, *I);
1412         return UpdateValueUsesWith(I, And);
1413       }
1414     }
1415     
1416     // If the RHS is a constant, see if we can simplify it.
1417     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1418     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1419       return UpdateValueUsesWith(I, I);
1420     
1421     RHSKnownZero = KnownZeroOut;
1422     RHSKnownOne  = KnownOneOut;
1423     break;
1424   }
1425   case Instruction::Select:
1426     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1427                              RHSKnownZero, RHSKnownOne, Depth+1))
1428       return true;
1429     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1430                              LHSKnownZero, LHSKnownOne, Depth+1))
1431       return true;
1432     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1433            "Bits known to be one AND zero?"); 
1434     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1435            "Bits known to be one AND zero?"); 
1436     
1437     // If the operands are constants, see if we can simplify them.
1438     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1439       return UpdateValueUsesWith(I, I);
1440     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1441       return UpdateValueUsesWith(I, I);
1442     
1443     // Only known if known in both the LHS and RHS.
1444     RHSKnownOne &= LHSKnownOne;
1445     RHSKnownZero &= LHSKnownZero;
1446     break;
1447   case Instruction::Trunc: {
1448     uint32_t truncBf = 
1449       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1450     DemandedMask.zext(truncBf);
1451     RHSKnownZero.zext(truncBf);
1452     RHSKnownOne.zext(truncBf);
1453     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1454                              RHSKnownZero, RHSKnownOne, Depth+1))
1455       return true;
1456     DemandedMask.trunc(BitWidth);
1457     RHSKnownZero.trunc(BitWidth);
1458     RHSKnownOne.trunc(BitWidth);
1459     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1460            "Bits known to be one AND zero?"); 
1461     break;
1462   }
1463   case Instruction::BitCast:
1464     if (!I->getOperand(0)->getType()->isInteger())
1465       return false;
1466       
1467     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1468                              RHSKnownZero, RHSKnownOne, Depth+1))
1469       return true;
1470     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1471            "Bits known to be one AND zero?"); 
1472     break;
1473   case Instruction::ZExt: {
1474     // Compute the bits in the result that are not present in the input.
1475     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1476     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1477     
1478     DemandedMask.trunc(SrcBitWidth);
1479     RHSKnownZero.trunc(SrcBitWidth);
1480     RHSKnownOne.trunc(SrcBitWidth);
1481     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482                              RHSKnownZero, RHSKnownOne, Depth+1))
1483       return true;
1484     DemandedMask.zext(BitWidth);
1485     RHSKnownZero.zext(BitWidth);
1486     RHSKnownOne.zext(BitWidth);
1487     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1488            "Bits known to be one AND zero?"); 
1489     // The top bits are known to be zero.
1490     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1491     break;
1492   }
1493   case Instruction::SExt: {
1494     // Compute the bits in the result that are not present in the input.
1495     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1496     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1497     
1498     APInt InputDemandedBits = DemandedMask & 
1499                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1500
1501     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1502     // If any of the sign extended bits are demanded, we know that the sign
1503     // bit is demanded.
1504     if ((NewBits & DemandedMask) != 0)
1505       InputDemandedBits.set(SrcBitWidth-1);
1506       
1507     InputDemandedBits.trunc(SrcBitWidth);
1508     RHSKnownZero.trunc(SrcBitWidth);
1509     RHSKnownOne.trunc(SrcBitWidth);
1510     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1511                              RHSKnownZero, RHSKnownOne, Depth+1))
1512       return true;
1513     InputDemandedBits.zext(BitWidth);
1514     RHSKnownZero.zext(BitWidth);
1515     RHSKnownOne.zext(BitWidth);
1516     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1517            "Bits known to be one AND zero?"); 
1518       
1519     // If the sign bit of the input is known set or clear, then we know the
1520     // top bits of the result.
1521
1522     // If the input sign bit is known zero, or if the NewBits are not demanded
1523     // convert this into a zero extension.
1524     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1525     {
1526       // Convert to ZExt cast
1527       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1528       return UpdateValueUsesWith(I, NewCast);
1529     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1530       RHSKnownOne |= NewBits;
1531     }
1532     break;
1533   }
1534   case Instruction::Add: {
1535     // Figure out what the input bits are.  If the top bits of the and result
1536     // are not demanded, then the add doesn't demand them from its input
1537     // either.
1538     uint32_t NLZ = DemandedMask.countLeadingZeros();
1539       
1540     // If there is a constant on the RHS, there are a variety of xformations
1541     // we can do.
1542     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1543       // If null, this should be simplified elsewhere.  Some of the xforms here
1544       // won't work if the RHS is zero.
1545       if (RHS->isZero())
1546         break;
1547       
1548       // If the top bit of the output is demanded, demand everything from the
1549       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1550       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1551
1552       // Find information about known zero/one bits in the input.
1553       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1554                                LHSKnownZero, LHSKnownOne, Depth+1))
1555         return true;
1556
1557       // If the RHS of the add has bits set that can't affect the input, reduce
1558       // the constant.
1559       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1560         return UpdateValueUsesWith(I, I);
1561       
1562       // Avoid excess work.
1563       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1564         break;
1565       
1566       // Turn it into OR if input bits are zero.
1567       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1568         Instruction *Or =
1569           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1570                                    I->getName());
1571         InsertNewInstBefore(Or, *I);
1572         return UpdateValueUsesWith(I, Or);
1573       }
1574       
1575       // We can say something about the output known-zero and known-one bits,
1576       // depending on potential carries from the input constant and the
1577       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1578       // bits set and the RHS constant is 0x01001, then we know we have a known
1579       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1580       
1581       // To compute this, we first compute the potential carry bits.  These are
1582       // the bits which may be modified.  I'm not aware of a better way to do
1583       // this scan.
1584       const APInt& RHSVal = RHS->getValue();
1585       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1586       
1587       // Now that we know which bits have carries, compute the known-1/0 sets.
1588       
1589       // Bits are known one if they are known zero in one operand and one in the
1590       // other, and there is no input carry.
1591       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1592                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1593       
1594       // Bits are known zero if they are known zero in both operands and there
1595       // is no input carry.
1596       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1597     } else {
1598       // If the high-bits of this ADD are not demanded, then it does not demand
1599       // the high bits of its LHS or RHS.
1600       if (DemandedMask[BitWidth-1] == 0) {
1601         // Right fill the mask of bits for this ADD to demand the most
1602         // significant bit and all those below it.
1603         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1604         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1605                                  LHSKnownZero, LHSKnownOne, Depth+1))
1606           return true;
1607         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1608                                  LHSKnownZero, LHSKnownOne, Depth+1))
1609           return true;
1610       }
1611     }
1612     break;
1613   }
1614   case Instruction::Sub:
1615     // If the high-bits of this SUB are not demanded, then it does not demand
1616     // the high bits of its LHS or RHS.
1617     if (DemandedMask[BitWidth-1] == 0) {
1618       // Right fill the mask of bits for this SUB to demand the most
1619       // significant bit and all those below it.
1620       uint32_t NLZ = DemandedMask.countLeadingZeros();
1621       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1622       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1623                                LHSKnownZero, LHSKnownOne, Depth+1))
1624         return true;
1625       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1626                                LHSKnownZero, LHSKnownOne, Depth+1))
1627         return true;
1628     }
1629     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1630     // the known zeros and ones.
1631     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1632     break;
1633   case Instruction::Shl:
1634     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1635       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1636       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1637       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1638                                RHSKnownZero, RHSKnownOne, Depth+1))
1639         return true;
1640       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1641              "Bits known to be one AND zero?"); 
1642       RHSKnownZero <<= ShiftAmt;
1643       RHSKnownOne  <<= ShiftAmt;
1644       // low bits known zero.
1645       if (ShiftAmt)
1646         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1647     }
1648     break;
1649   case Instruction::LShr:
1650     // For a logical shift right
1651     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1652       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1653       
1654       // Unsigned shift right.
1655       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1656       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1657                                RHSKnownZero, RHSKnownOne, Depth+1))
1658         return true;
1659       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1660              "Bits known to be one AND zero?"); 
1661       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1662       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1663       if (ShiftAmt) {
1664         // Compute the new bits that are at the top now.
1665         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1666         RHSKnownZero |= HighBits;  // high bits known zero.
1667       }
1668     }
1669     break;
1670   case Instruction::AShr:
1671     // If this is an arithmetic shift right and only the low-bit is set, we can
1672     // always convert this into a logical shr, even if the shift amount is
1673     // variable.  The low bit of the shift cannot be an input sign bit unless
1674     // the shift amount is >= the size of the datatype, which is undefined.
1675     if (DemandedMask == 1) {
1676       // Perform the logical shift right.
1677       Value *NewVal = BinaryOperator::createLShr(
1678                         I->getOperand(0), I->getOperand(1), I->getName());
1679       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1680       return UpdateValueUsesWith(I, NewVal);
1681     }    
1682
1683     // If the sign bit is the only bit demanded by this ashr, then there is no
1684     // need to do it, the shift doesn't change the high bit.
1685     if (DemandedMask.isSignBit())
1686       return UpdateValueUsesWith(I, I->getOperand(0));
1687     
1688     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1689       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1690       
1691       // Signed shift right.
1692       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1693       // If any of the "high bits" are demanded, we should set the sign bit as
1694       // demanded.
1695       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1696         DemandedMaskIn.set(BitWidth-1);
1697       if (SimplifyDemandedBits(I->getOperand(0),
1698                                DemandedMaskIn,
1699                                RHSKnownZero, RHSKnownOne, Depth+1))
1700         return true;
1701       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1702              "Bits known to be one AND zero?"); 
1703       // Compute the new bits that are at the top now.
1704       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1705       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1706       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1707         
1708       // Handle the sign bits.
1709       APInt SignBit(APInt::getSignBit(BitWidth));
1710       // Adjust to where it is now in the mask.
1711       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1712         
1713       // If the input sign bit is known to be zero, or if none of the top bits
1714       // are demanded, turn this into an unsigned shift right.
1715       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1716           (HighBits & ~DemandedMask) == HighBits) {
1717         // Perform the logical shift right.
1718         Value *NewVal = BinaryOperator::createLShr(
1719                           I->getOperand(0), SA, I->getName());
1720         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1721         return UpdateValueUsesWith(I, NewVal);
1722       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1723         RHSKnownOne |= HighBits;
1724       }
1725     }
1726     break;
1727   case Instruction::SRem:
1728     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1729       APInt RA = Rem->getValue();
1730       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1731         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1732         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1733         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1734                                  LHSKnownZero, LHSKnownOne, Depth+1))
1735           return true;
1736
1737         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1738           LHSKnownZero |= ~LowBits;
1739         else if (LHSKnownOne[BitWidth-1])
1740           LHSKnownOne |= ~LowBits;
1741
1742         KnownZero |= LHSKnownZero & DemandedMask;
1743         KnownOne |= LHSKnownOne & DemandedMask;
1744
1745         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1746       }
1747     }
1748     break;
1749   case Instruction::URem: {
1750     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1751       APInt RA = Rem->getValue();
1752       if (RA.isPowerOf2()) {
1753         APInt LowBits = (RA - 1);
1754         APInt Mask2 = LowBits & DemandedMask;
1755         KnownZero |= ~LowBits & DemandedMask;
1756         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1757                                  KnownZero, KnownOne, Depth+1))
1758           return true;
1759
1760         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1761         break;
1762       }
1763     }
1764
1765     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1766     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1767     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1768                              KnownZero2, KnownOne2, Depth+1))
1769       return true;
1770
1771     uint32_t Leaders = KnownZero2.countLeadingOnes();
1772     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1773                              KnownZero2, KnownOne2, Depth+1))
1774       return true;
1775
1776     Leaders = std::max(Leaders,
1777                        KnownZero2.countLeadingOnes());
1778     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1779     break;
1780   }
1781   }
1782   
1783   // If the client is only demanding bits that we know, return the known
1784   // constant.
1785   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1786     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1787   return false;
1788 }
1789
1790
1791 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1792 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1793 /// actually used by the caller.  This method analyzes which elements of the
1794 /// operand are undef and returns that information in UndefElts.
1795 ///
1796 /// If the information about demanded elements can be used to simplify the
1797 /// operation, the operation is simplified, then the resultant value is
1798 /// returned.  This returns null if no change was made.
1799 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1800                                                 uint64_t &UndefElts,
1801                                                 unsigned Depth) {
1802   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1803   assert(VWidth <= 64 && "Vector too wide to analyze!");
1804   uint64_t EltMask = ~0ULL >> (64-VWidth);
1805   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1806          "Invalid DemandedElts!");
1807
1808   if (isa<UndefValue>(V)) {
1809     // If the entire vector is undefined, just return this info.
1810     UndefElts = EltMask;
1811     return 0;
1812   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1813     UndefElts = EltMask;
1814     return UndefValue::get(V->getType());
1815   }
1816   
1817   UndefElts = 0;
1818   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1819     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1820     Constant *Undef = UndefValue::get(EltTy);
1821
1822     std::vector<Constant*> Elts;
1823     for (unsigned i = 0; i != VWidth; ++i)
1824       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1825         Elts.push_back(Undef);
1826         UndefElts |= (1ULL << i);
1827       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1828         Elts.push_back(Undef);
1829         UndefElts |= (1ULL << i);
1830       } else {                               // Otherwise, defined.
1831         Elts.push_back(CP->getOperand(i));
1832       }
1833         
1834     // If we changed the constant, return it.
1835     Constant *NewCP = ConstantVector::get(Elts);
1836     return NewCP != CP ? NewCP : 0;
1837   } else if (isa<ConstantAggregateZero>(V)) {
1838     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1839     // set to undef.
1840     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1841     Constant *Zero = Constant::getNullValue(EltTy);
1842     Constant *Undef = UndefValue::get(EltTy);
1843     std::vector<Constant*> Elts;
1844     for (unsigned i = 0; i != VWidth; ++i)
1845       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1846     UndefElts = DemandedElts ^ EltMask;
1847     return ConstantVector::get(Elts);
1848   }
1849   
1850   if (!V->hasOneUse()) {    // Other users may use these bits.
1851     if (Depth != 0) {       // Not at the root.
1852       // TODO: Just compute the UndefElts information recursively.
1853       return false;
1854     }
1855     return false;
1856   } else if (Depth == 10) {        // Limit search depth.
1857     return false;
1858   }
1859   
1860   Instruction *I = dyn_cast<Instruction>(V);
1861   if (!I) return false;        // Only analyze instructions.
1862   
1863   bool MadeChange = false;
1864   uint64_t UndefElts2;
1865   Value *TmpV;
1866   switch (I->getOpcode()) {
1867   default: break;
1868     
1869   case Instruction::InsertElement: {
1870     // If this is a variable index, we don't know which element it overwrites.
1871     // demand exactly the same input as we produce.
1872     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1873     if (Idx == 0) {
1874       // Note that we can't propagate undef elt info, because we don't know
1875       // which elt is getting updated.
1876       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1877                                         UndefElts2, Depth+1);
1878       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1879       break;
1880     }
1881     
1882     // If this is inserting an element that isn't demanded, remove this
1883     // insertelement.
1884     unsigned IdxNo = Idx->getZExtValue();
1885     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1886       return AddSoonDeadInstToWorklist(*I, 0);
1887     
1888     // Otherwise, the element inserted overwrites whatever was there, so the
1889     // input demanded set is simpler than the output set.
1890     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1891                                       DemandedElts & ~(1ULL << IdxNo),
1892                                       UndefElts, Depth+1);
1893     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1894
1895     // The inserted element is defined.
1896     UndefElts |= 1ULL << IdxNo;
1897     break;
1898   }
1899   case Instruction::BitCast: {
1900     // Vector->vector casts only.
1901     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1902     if (!VTy) break;
1903     unsigned InVWidth = VTy->getNumElements();
1904     uint64_t InputDemandedElts = 0;
1905     unsigned Ratio;
1906
1907     if (VWidth == InVWidth) {
1908       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1909       // elements as are demanded of us.
1910       Ratio = 1;
1911       InputDemandedElts = DemandedElts;
1912     } else if (VWidth > InVWidth) {
1913       // Untested so far.
1914       break;
1915       
1916       // If there are more elements in the result than there are in the source,
1917       // then an input element is live if any of the corresponding output
1918       // elements are live.
1919       Ratio = VWidth/InVWidth;
1920       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1921         if (DemandedElts & (1ULL << OutIdx))
1922           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1923       }
1924     } else {
1925       // Untested so far.
1926       break;
1927       
1928       // If there are more elements in the source than there are in the result,
1929       // then an input element is live if the corresponding output element is
1930       // live.
1931       Ratio = InVWidth/VWidth;
1932       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1933         if (DemandedElts & (1ULL << InIdx/Ratio))
1934           InputDemandedElts |= 1ULL << InIdx;
1935     }
1936     
1937     // div/rem demand all inputs, because they don't want divide by zero.
1938     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1939                                       UndefElts2, Depth+1);
1940     if (TmpV) {
1941       I->setOperand(0, TmpV);
1942       MadeChange = true;
1943     }
1944     
1945     UndefElts = UndefElts2;
1946     if (VWidth > InVWidth) {
1947       assert(0 && "Unimp");
1948       // If there are more elements in the result than there are in the source,
1949       // then an output element is undef if the corresponding input element is
1950       // undef.
1951       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1952         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1953           UndefElts |= 1ULL << OutIdx;
1954     } else if (VWidth < InVWidth) {
1955       assert(0 && "Unimp");
1956       // If there are more elements in the source than there are in the result,
1957       // then a result element is undef if all of the corresponding input
1958       // elements are undef.
1959       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1960       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1961         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1962           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1963     }
1964     break;
1965   }
1966   case Instruction::And:
1967   case Instruction::Or:
1968   case Instruction::Xor:
1969   case Instruction::Add:
1970   case Instruction::Sub:
1971   case Instruction::Mul:
1972     // div/rem demand all inputs, because they don't want divide by zero.
1973     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1974                                       UndefElts, Depth+1);
1975     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1976     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1977                                       UndefElts2, Depth+1);
1978     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1979       
1980     // Output elements are undefined if both are undefined.  Consider things
1981     // like undef&0.  The result is known zero, not undef.
1982     UndefElts &= UndefElts2;
1983     break;
1984     
1985   case Instruction::Call: {
1986     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1987     if (!II) break;
1988     switch (II->getIntrinsicID()) {
1989     default: break;
1990       
1991     // Binary vector operations that work column-wise.  A dest element is a
1992     // function of the corresponding input elements from the two inputs.
1993     case Intrinsic::x86_sse_sub_ss:
1994     case Intrinsic::x86_sse_mul_ss:
1995     case Intrinsic::x86_sse_min_ss:
1996     case Intrinsic::x86_sse_max_ss:
1997     case Intrinsic::x86_sse2_sub_sd:
1998     case Intrinsic::x86_sse2_mul_sd:
1999     case Intrinsic::x86_sse2_min_sd:
2000     case Intrinsic::x86_sse2_max_sd:
2001       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2002                                         UndefElts, Depth+1);
2003       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2004       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2005                                         UndefElts2, Depth+1);
2006       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2007
2008       // If only the low elt is demanded and this is a scalarizable intrinsic,
2009       // scalarize it now.
2010       if (DemandedElts == 1) {
2011         switch (II->getIntrinsicID()) {
2012         default: break;
2013         case Intrinsic::x86_sse_sub_ss:
2014         case Intrinsic::x86_sse_mul_ss:
2015         case Intrinsic::x86_sse2_sub_sd:
2016         case Intrinsic::x86_sse2_mul_sd:
2017           // TODO: Lower MIN/MAX/ABS/etc
2018           Value *LHS = II->getOperand(1);
2019           Value *RHS = II->getOperand(2);
2020           // Extract the element as scalars.
2021           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2022           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2023           
2024           switch (II->getIntrinsicID()) {
2025           default: assert(0 && "Case stmts out of sync!");
2026           case Intrinsic::x86_sse_sub_ss:
2027           case Intrinsic::x86_sse2_sub_sd:
2028             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
2029                                                         II->getName()), *II);
2030             break;
2031           case Intrinsic::x86_sse_mul_ss:
2032           case Intrinsic::x86_sse2_mul_sd:
2033             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
2034                                                          II->getName()), *II);
2035             break;
2036           }
2037           
2038           Instruction *New =
2039             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2040                                       II->getName());
2041           InsertNewInstBefore(New, *II);
2042           AddSoonDeadInstToWorklist(*II, 0);
2043           return New;
2044         }            
2045       }
2046         
2047       // Output elements are undefined if both are undefined.  Consider things
2048       // like undef&0.  The result is known zero, not undef.
2049       UndefElts &= UndefElts2;
2050       break;
2051     }
2052     break;
2053   }
2054   }
2055   return MadeChange ? I : 0;
2056 }
2057
2058 /// @returns true if the specified compare predicate is
2059 /// true when both operands are equal...
2060 /// @brief Determine if the icmp Predicate is true when both operands are equal
2061 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
2062   return pred == ICmpInst::ICMP_EQ  || pred == ICmpInst::ICMP_UGE ||
2063          pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
2064          pred == ICmpInst::ICMP_SLE;
2065 }
2066
2067 /// @returns true if the specified compare instruction is
2068 /// true when both operands are equal...
2069 /// @brief Determine if the ICmpInst returns true when both operands are equal
2070 static bool isTrueWhenEqual(ICmpInst &ICI) {
2071   return isTrueWhenEqual(ICI.getPredicate());
2072 }
2073
2074 /// AssociativeOpt - Perform an optimization on an associative operator.  This
2075 /// function is designed to check a chain of associative operators for a
2076 /// potential to apply a certain optimization.  Since the optimization may be
2077 /// applicable if the expression was reassociated, this checks the chain, then
2078 /// reassociates the expression as necessary to expose the optimization
2079 /// opportunity.  This makes use of a special Functor, which must define
2080 /// 'shouldApply' and 'apply' methods.
2081 ///
2082 template<typename Functor>
2083 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2084   unsigned Opcode = Root.getOpcode();
2085   Value *LHS = Root.getOperand(0);
2086
2087   // Quick check, see if the immediate LHS matches...
2088   if (F.shouldApply(LHS))
2089     return F.apply(Root);
2090
2091   // Otherwise, if the LHS is not of the same opcode as the root, return.
2092   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2093   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2094     // Should we apply this transform to the RHS?
2095     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2096
2097     // If not to the RHS, check to see if we should apply to the LHS...
2098     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2099       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
2100       ShouldApply = true;
2101     }
2102
2103     // If the functor wants to apply the optimization to the RHS of LHSI,
2104     // reassociate the expression from ((? op A) op B) to (? op (A op B))
2105     if (ShouldApply) {
2106       BasicBlock *BB = Root.getParent();
2107
2108       // Now all of the instructions are in the current basic block, go ahead
2109       // and perform the reassociation.
2110       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2111
2112       // First move the selected RHS to the LHS of the root...
2113       Root.setOperand(0, LHSI->getOperand(1));
2114
2115       // Make what used to be the LHS of the root be the user of the root...
2116       Value *ExtraOperand = TmpLHSI->getOperand(1);
2117       if (&Root == TmpLHSI) {
2118         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2119         return 0;
2120       }
2121       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
2122       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
2123       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2124       BasicBlock::iterator ARI = &Root; ++ARI;
2125       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
2126       ARI = Root;
2127
2128       // Now propagate the ExtraOperand down the chain of instructions until we
2129       // get to LHSI.
2130       while (TmpLHSI != LHSI) {
2131         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2132         // Move the instruction to immediately before the chain we are
2133         // constructing to avoid breaking dominance properties.
2134         NextLHSI->getParent()->getInstList().remove(NextLHSI);
2135         BB->getInstList().insert(ARI, NextLHSI);
2136         ARI = NextLHSI;
2137
2138         Value *NextOp = NextLHSI->getOperand(1);
2139         NextLHSI->setOperand(1, ExtraOperand);
2140         TmpLHSI = NextLHSI;
2141         ExtraOperand = NextOp;
2142       }
2143
2144       // Now that the instructions are reassociated, have the functor perform
2145       // the transformation...
2146       return F.apply(Root);
2147     }
2148
2149     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2150   }
2151   return 0;
2152 }
2153
2154
2155 // AddRHS - Implements: X + X --> X << 1
2156 struct AddRHS {
2157   Value *RHS;
2158   AddRHS(Value *rhs) : RHS(rhs) {}
2159   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2160   Instruction *apply(BinaryOperator &Add) const {
2161     return BinaryOperator::createShl(Add.getOperand(0),
2162                                   ConstantInt::get(Add.getType(), 1));
2163   }
2164 };
2165
2166 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2167 //                 iff C1&C2 == 0
2168 struct AddMaskingAnd {
2169   Constant *C2;
2170   AddMaskingAnd(Constant *c) : C2(c) {}
2171   bool shouldApply(Value *LHS) const {
2172     ConstantInt *C1;
2173     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2174            ConstantExpr::getAnd(C1, C2)->isNullValue();
2175   }
2176   Instruction *apply(BinaryOperator &Add) const {
2177     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
2178   }
2179 };
2180
2181 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2182                                              InstCombiner *IC) {
2183   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2184     if (Constant *SOC = dyn_cast<Constant>(SO))
2185       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2186
2187     return IC->InsertNewInstBefore(CastInst::create(
2188           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2189   }
2190
2191   // Figure out if the constant is the left or the right argument.
2192   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2193   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2194
2195   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2196     if (ConstIsRHS)
2197       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2198     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2199   }
2200
2201   Value *Op0 = SO, *Op1 = ConstOperand;
2202   if (!ConstIsRHS)
2203     std::swap(Op0, Op1);
2204   Instruction *New;
2205   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2206     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2207   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2208     New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
2209                           SO->getName()+".cmp");
2210   else {
2211     assert(0 && "Unknown binary instruction type!");
2212     abort();
2213   }
2214   return IC->InsertNewInstBefore(New, I);
2215 }
2216
2217 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2218 // constant as the other operand, try to fold the binary operator into the
2219 // select arguments.  This also works for Cast instructions, which obviously do
2220 // not have a second operand.
2221 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2222                                      InstCombiner *IC) {
2223   // Don't modify shared select instructions
2224   if (!SI->hasOneUse()) return 0;
2225   Value *TV = SI->getOperand(1);
2226   Value *FV = SI->getOperand(2);
2227
2228   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2229     // Bool selects with constant operands can be folded to logical ops.
2230     if (SI->getType() == Type::Int1Ty) return 0;
2231
2232     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2233     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2234
2235     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2236                               SelectFalseVal);
2237   }
2238   return 0;
2239 }
2240
2241
2242 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2243 /// node as operand #0, see if we can fold the instruction into the PHI (which
2244 /// is only possible if all operands to the PHI are constants).
2245 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2246   PHINode *PN = cast<PHINode>(I.getOperand(0));
2247   unsigned NumPHIValues = PN->getNumIncomingValues();
2248   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2249
2250   // Check to see if all of the operands of the PHI are constants.  If there is
2251   // one non-constant value, remember the BB it is.  If there is more than one
2252   // or if *it* is a PHI, bail out.
2253   BasicBlock *NonConstBB = 0;
2254   for (unsigned i = 0; i != NumPHIValues; ++i)
2255     if (!isa<Constant>(PN->getIncomingValue(i))) {
2256       if (NonConstBB) return 0;  // More than one non-const value.
2257       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2258       NonConstBB = PN->getIncomingBlock(i);
2259       
2260       // If the incoming non-constant value is in I's block, we have an infinite
2261       // loop.
2262       if (NonConstBB == I.getParent())
2263         return 0;
2264     }
2265   
2266   // If there is exactly one non-constant value, we can insert a copy of the
2267   // operation in that block.  However, if this is a critical edge, we would be
2268   // inserting the computation one some other paths (e.g. inside a loop).  Only
2269   // do this if the pred block is unconditionally branching into the phi block.
2270   if (NonConstBB) {
2271     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2272     if (!BI || !BI->isUnconditional()) return 0;
2273   }
2274
2275   // Okay, we can do the transformation: create the new PHI node.
2276   PHINode *NewPN = PHINode::Create(I.getType(), "");
2277   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2278   InsertNewInstBefore(NewPN, *PN);
2279   NewPN->takeName(PN);
2280
2281   // Next, add all of the operands to the PHI.
2282   if (I.getNumOperands() == 2) {
2283     Constant *C = cast<Constant>(I.getOperand(1));
2284     for (unsigned i = 0; i != NumPHIValues; ++i) {
2285       Value *InV = 0;
2286       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2287         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2288           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2289         else
2290           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2291       } else {
2292         assert(PN->getIncomingBlock(i) == NonConstBB);
2293         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2294           InV = BinaryOperator::create(BO->getOpcode(),
2295                                        PN->getIncomingValue(i), C, "phitmp",
2296                                        NonConstBB->getTerminator());
2297         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2298           InV = CmpInst::create(CI->getOpcode(), 
2299                                 CI->getPredicate(),
2300                                 PN->getIncomingValue(i), C, "phitmp",
2301                                 NonConstBB->getTerminator());
2302         else
2303           assert(0 && "Unknown binop!");
2304         
2305         AddToWorkList(cast<Instruction>(InV));
2306       }
2307       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2308     }
2309   } else { 
2310     CastInst *CI = cast<CastInst>(&I);
2311     const Type *RetTy = CI->getType();
2312     for (unsigned i = 0; i != NumPHIValues; ++i) {
2313       Value *InV;
2314       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2315         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2316       } else {
2317         assert(PN->getIncomingBlock(i) == NonConstBB);
2318         InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i), 
2319                                I.getType(), "phitmp", 
2320                                NonConstBB->getTerminator());
2321         AddToWorkList(cast<Instruction>(InV));
2322       }
2323       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2324     }
2325   }
2326   return ReplaceInstUsesWith(I, NewPN);
2327 }
2328
2329
2330 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
2331 /// value is never equal to -0.0.
2332 ///
2333 /// Note that this function will need to be revisited when we support nondefault
2334 /// rounding modes!
2335 ///
2336 static bool CannotBeNegativeZero(const Value *V) {
2337   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2338     return !CFP->getValueAPF().isNegZero();
2339
2340   // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2341   if (const Instruction *I = dyn_cast<Instruction>(V)) {
2342     if (I->getOpcode() == Instruction::Add &&
2343         isa<ConstantFP>(I->getOperand(1)) && 
2344         cast<ConstantFP>(I->getOperand(1))->isNullValue())
2345       return true;
2346     
2347     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2348       if (II->getIntrinsicID() == Intrinsic::sqrt)
2349         return CannotBeNegativeZero(II->getOperand(1));
2350     
2351     if (const CallInst *CI = dyn_cast<CallInst>(I))
2352       if (const Function *F = CI->getCalledFunction()) {
2353         if (F->isDeclaration()) {
2354           switch (F->getNameLen()) {
2355           case 3:  // abs(x) != -0.0
2356             if (!strcmp(F->getNameStart(), "abs")) return true;
2357             break;
2358           case 4:  // abs[lf](x) != -0.0
2359             if (!strcmp(F->getNameStart(), "absf")) return true;
2360             if (!strcmp(F->getNameStart(), "absl")) return true;
2361             break;
2362           }
2363         }
2364       }
2365   }
2366   
2367   return false;
2368 }
2369
2370
2371 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2372   bool Changed = SimplifyCommutative(I);
2373   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2374
2375   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2376     // X + undef -> undef
2377     if (isa<UndefValue>(RHS))
2378       return ReplaceInstUsesWith(I, RHS);
2379
2380     // X + 0 --> X
2381     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2382       if (RHSC->isNullValue())
2383         return ReplaceInstUsesWith(I, LHS);
2384     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2385       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2386                               (I.getType())->getValueAPF()))
2387         return ReplaceInstUsesWith(I, LHS);
2388     }
2389
2390     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2391       // X + (signbit) --> X ^ signbit
2392       const APInt& Val = CI->getValue();
2393       uint32_t BitWidth = Val.getBitWidth();
2394       if (Val == APInt::getSignBit(BitWidth))
2395         return BinaryOperator::createXor(LHS, RHS);
2396       
2397       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2398       // (X & 254)+1 -> (X&254)|1
2399       if (!isa<VectorType>(I.getType())) {
2400         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2401         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2402                                  KnownZero, KnownOne))
2403           return &I;
2404       }
2405     }
2406
2407     if (isa<PHINode>(LHS))
2408       if (Instruction *NV = FoldOpIntoPhi(I))
2409         return NV;
2410     
2411     ConstantInt *XorRHS = 0;
2412     Value *XorLHS = 0;
2413     if (isa<ConstantInt>(RHSC) &&
2414         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2415       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2416       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2417       
2418       uint32_t Size = TySizeBits / 2;
2419       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2420       APInt CFF80Val(-C0080Val);
2421       do {
2422         if (TySizeBits > Size) {
2423           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2424           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2425           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2426               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2427             // This is a sign extend if the top bits are known zero.
2428             if (!MaskedValueIsZero(XorLHS, 
2429                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2430               Size = 0;  // Not a sign ext, but can't be any others either.
2431             break;
2432           }
2433         }
2434         Size >>= 1;
2435         C0080Val = APIntOps::lshr(C0080Val, Size);
2436         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2437       } while (Size >= 1);
2438       
2439       // FIXME: This shouldn't be necessary. When the backends can handle types
2440       // with funny bit widths then this whole cascade of if statements should
2441       // be removed. It is just here to get the size of the "middle" type back
2442       // up to something that the back ends can handle.
2443       const Type *MiddleType = 0;
2444       switch (Size) {
2445         default: break;
2446         case 32: MiddleType = Type::Int32Ty; break;
2447         case 16: MiddleType = Type::Int16Ty; break;
2448         case  8: MiddleType = Type::Int8Ty; break;
2449       }
2450       if (MiddleType) {
2451         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2452         InsertNewInstBefore(NewTrunc, I);
2453         return new SExtInst(NewTrunc, I.getType(), I.getName());
2454       }
2455     }
2456   }
2457
2458   // X + X --> X << 1
2459   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2460     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2461
2462     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2463       if (RHSI->getOpcode() == Instruction::Sub)
2464         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2465           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2466     }
2467     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2468       if (LHSI->getOpcode() == Instruction::Sub)
2469         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2470           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2471     }
2472   }
2473
2474   // -A + B  -->  B - A
2475   // -A + -B  -->  -(A + B)
2476   if (Value *LHSV = dyn_castNegVal(LHS)) {
2477     if (LHS->getType()->isIntOrIntVector()) {
2478       if (Value *RHSV = dyn_castNegVal(RHS)) {
2479         Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2480         InsertNewInstBefore(NewAdd, I);
2481         return BinaryOperator::createNeg(NewAdd);
2482       }
2483     }
2484     
2485     return BinaryOperator::createSub(RHS, LHSV);
2486   }
2487
2488   // A + -B  -->  A - B
2489   if (!isa<Constant>(RHS))
2490     if (Value *V = dyn_castNegVal(RHS))
2491       return BinaryOperator::createSub(LHS, V);
2492
2493
2494   ConstantInt *C2;
2495   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2496     if (X == RHS)   // X*C + X --> X * (C+1)
2497       return BinaryOperator::createMul(RHS, AddOne(C2));
2498
2499     // X*C1 + X*C2 --> X * (C1+C2)
2500     ConstantInt *C1;
2501     if (X == dyn_castFoldableMul(RHS, C1))
2502       return BinaryOperator::createMul(X, Add(C1, C2));
2503   }
2504
2505   // X + X*C --> X * (C+1)
2506   if (dyn_castFoldableMul(RHS, C2) == LHS)
2507     return BinaryOperator::createMul(LHS, AddOne(C2));
2508
2509   // X + ~X --> -1   since   ~X = -X-1
2510   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2511     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2512   
2513
2514   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2515   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2516     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2517       return R;
2518
2519   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2520   if (I.getType()->isIntOrIntVector()) {
2521     Value *W, *X, *Y, *Z;
2522     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2523         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2524       if (W != Y) {
2525         if (W == Z) {
2526           std::swap(Y, Z);
2527         } else if (Y == X) {
2528           std::swap(W, X);
2529         } else if (X == Z) {
2530           std::swap(Y, Z);
2531           std::swap(W, X);
2532         }
2533       }
2534
2535       if (W == Y) {
2536         Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2537                                                             LHS->getName()), I);
2538         return BinaryOperator::createMul(W, NewAdd);
2539       }
2540     }
2541   }
2542
2543   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2544     Value *X = 0;
2545     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2546       return BinaryOperator::createSub(SubOne(CRHS), X);
2547
2548     // (X & FF00) + xx00  -> (X+xx00) & FF00
2549     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2550       Constant *Anded = And(CRHS, C2);
2551       if (Anded == CRHS) {
2552         // See if all bits from the first bit set in the Add RHS up are included
2553         // in the mask.  First, get the rightmost bit.
2554         const APInt& AddRHSV = CRHS->getValue();
2555
2556         // Form a mask of all bits from the lowest bit added through the top.
2557         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2558
2559         // See if the and mask includes all of these bits.
2560         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2561
2562         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2563           // Okay, the xform is safe.  Insert the new add pronto.
2564           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2565                                                             LHS->getName()), I);
2566           return BinaryOperator::createAnd(NewAdd, C2);
2567         }
2568       }
2569     }
2570
2571     // Try to fold constant add into select arguments.
2572     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2573       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2574         return R;
2575   }
2576
2577   // add (cast *A to intptrtype) B -> 
2578   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2579   {
2580     CastInst *CI = dyn_cast<CastInst>(LHS);
2581     Value *Other = RHS;
2582     if (!CI) {
2583       CI = dyn_cast<CastInst>(RHS);
2584       Other = LHS;
2585     }
2586     if (CI && CI->getType()->isSized() && 
2587         (CI->getType()->getPrimitiveSizeInBits() == 
2588          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2589         && isa<PointerType>(CI->getOperand(0)->getType())) {
2590       unsigned AS =
2591         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2592       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2593                                       PointerType::get(Type::Int8Ty, AS), I);
2594       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2595       return new PtrToIntInst(I2, CI->getType());
2596     }
2597   }
2598   
2599   // add (select X 0 (sub n A)) A  -->  select X A n
2600   {
2601     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2602     Value *Other = RHS;
2603     if (!SI) {
2604       SI = dyn_cast<SelectInst>(RHS);
2605       Other = LHS;
2606     }
2607     if (SI && SI->hasOneUse()) {
2608       Value *TV = SI->getTrueValue();
2609       Value *FV = SI->getFalseValue();
2610       Value *A, *N;
2611
2612       // Can we fold the add into the argument of the select?
2613       // We check both true and false select arguments for a matching subtract.
2614       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2615           A == Other)  // Fold the add into the true select value.
2616         return SelectInst::Create(SI->getCondition(), N, A);
2617       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2618           A == Other)  // Fold the add into the false select value.
2619         return SelectInst::Create(SI->getCondition(), A, N);
2620     }
2621   }
2622   
2623   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2624   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2625     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2626       return ReplaceInstUsesWith(I, LHS);
2627
2628   return Changed ? &I : 0;
2629 }
2630
2631 // isSignBit - Return true if the value represented by the constant only has the
2632 // highest order bit set.
2633 static bool isSignBit(ConstantInt *CI) {
2634   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2635   return CI->getValue() == APInt::getSignBit(NumBits);
2636 }
2637
2638 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2639   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2640
2641   if (Op0 == Op1)         // sub X, X  -> 0
2642     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2643
2644   // If this is a 'B = x-(-A)', change to B = x+A...
2645   if (Value *V = dyn_castNegVal(Op1))
2646     return BinaryOperator::createAdd(Op0, V);
2647
2648   if (isa<UndefValue>(Op0))
2649     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2650   if (isa<UndefValue>(Op1))
2651     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2652
2653   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2654     // Replace (-1 - A) with (~A)...
2655     if (C->isAllOnesValue())
2656       return BinaryOperator::createNot(Op1);
2657
2658     // C - ~X == X + (1+C)
2659     Value *X = 0;
2660     if (match(Op1, m_Not(m_Value(X))))
2661       return BinaryOperator::createAdd(X, AddOne(C));
2662
2663     // -(X >>u 31) -> (X >>s 31)
2664     // -(X >>s 31) -> (X >>u 31)
2665     if (C->isZero()) {
2666       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2667         if (SI->getOpcode() == Instruction::LShr) {
2668           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2669             // Check to see if we are shifting out everything but the sign bit.
2670             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2671                 SI->getType()->getPrimitiveSizeInBits()-1) {
2672               // Ok, the transformation is safe.  Insert AShr.
2673               return BinaryOperator::create(Instruction::AShr, 
2674                                           SI->getOperand(0), CU, SI->getName());
2675             }
2676           }
2677         }
2678         else if (SI->getOpcode() == Instruction::AShr) {
2679           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2680             // Check to see if we are shifting out everything but the sign bit.
2681             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2682                 SI->getType()->getPrimitiveSizeInBits()-1) {
2683               // Ok, the transformation is safe.  Insert LShr. 
2684               return BinaryOperator::createLShr(
2685                                           SI->getOperand(0), CU, SI->getName());
2686             }
2687           }
2688         }
2689       }
2690     }
2691
2692     // Try to fold constant sub into select arguments.
2693     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2694       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2695         return R;
2696
2697     if (isa<PHINode>(Op0))
2698       if (Instruction *NV = FoldOpIntoPhi(I))
2699         return NV;
2700   }
2701
2702   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2703     if (Op1I->getOpcode() == Instruction::Add &&
2704         !Op0->getType()->isFPOrFPVector()) {
2705       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2706         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2707       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2708         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2709       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2710         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2711           // C1-(X+C2) --> (C1-C2)-X
2712           return BinaryOperator::createSub(Subtract(CI1, CI2), 
2713                                            Op1I->getOperand(0));
2714       }
2715     }
2716
2717     if (Op1I->hasOneUse()) {
2718       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2719       // is not used by anyone else...
2720       //
2721       if (Op1I->getOpcode() == Instruction::Sub &&
2722           !Op1I->getType()->isFPOrFPVector()) {
2723         // Swap the two operands of the subexpr...
2724         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2725         Op1I->setOperand(0, IIOp1);
2726         Op1I->setOperand(1, IIOp0);
2727
2728         // Create the new top level add instruction...
2729         return BinaryOperator::createAdd(Op0, Op1);
2730       }
2731
2732       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2733       //
2734       if (Op1I->getOpcode() == Instruction::And &&
2735           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2736         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2737
2738         Value *NewNot =
2739           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2740         return BinaryOperator::createAnd(Op0, NewNot);
2741       }
2742
2743       // 0 - (X sdiv C)  -> (X sdiv -C)
2744       if (Op1I->getOpcode() == Instruction::SDiv)
2745         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2746           if (CSI->isZero())
2747             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2748               return BinaryOperator::createSDiv(Op1I->getOperand(0),
2749                                                ConstantExpr::getNeg(DivRHS));
2750
2751       // X - X*C --> X * (1-C)
2752       ConstantInt *C2 = 0;
2753       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2754         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2755         return BinaryOperator::createMul(Op0, CP1);
2756       }
2757
2758       // X - ((X / Y) * Y) --> X % Y
2759       if (Op1I->getOpcode() == Instruction::Mul)
2760         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2761           if (Op0 == I->getOperand(0) &&
2762               Op1I->getOperand(1) == I->getOperand(1)) {
2763             if (I->getOpcode() == Instruction::SDiv)
2764               return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2765             if (I->getOpcode() == Instruction::UDiv)
2766               return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2767           }
2768     }
2769   }
2770
2771   if (!Op0->getType()->isFPOrFPVector())
2772     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2773       if (Op0I->getOpcode() == Instruction::Add) {
2774         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2775           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2776         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2777           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2778       } else if (Op0I->getOpcode() == Instruction::Sub) {
2779         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2780           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2781       }
2782     }
2783
2784   ConstantInt *C1;
2785   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2786     if (X == Op1)  // X*C - X --> X * (C-1)
2787       return BinaryOperator::createMul(Op1, SubOne(C1));
2788
2789     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2790     if (X == dyn_castFoldableMul(Op1, C2))
2791       return BinaryOperator::createMul(X, Subtract(C1, C2));
2792   }
2793   return 0;
2794 }
2795
2796 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2797 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2798 /// TrueIfSigned if the result of the comparison is true when the input value is
2799 /// signed.
2800 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2801                            bool &TrueIfSigned) {
2802   switch (pred) {
2803   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2804     TrueIfSigned = true;
2805     return RHS->isZero();
2806   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2807     TrueIfSigned = true;
2808     return RHS->isAllOnesValue();
2809   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2810     TrueIfSigned = false;
2811     return RHS->isAllOnesValue();
2812   case ICmpInst::ICMP_UGT:
2813     // True if LHS u> RHS and RHS == high-bit-mask - 1
2814     TrueIfSigned = true;
2815     return RHS->getValue() ==
2816       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2817   case ICmpInst::ICMP_UGE: 
2818     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2819     TrueIfSigned = true;
2820     return RHS->getValue() == 
2821       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2822   default:
2823     return false;
2824   }
2825 }
2826
2827 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2828   bool Changed = SimplifyCommutative(I);
2829   Value *Op0 = I.getOperand(0);
2830
2831   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2832     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2833
2834   // Simplify mul instructions with a constant RHS...
2835   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2836     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2837
2838       // ((X << C1)*C2) == (X * (C2 << C1))
2839       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2840         if (SI->getOpcode() == Instruction::Shl)
2841           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2842             return BinaryOperator::createMul(SI->getOperand(0),
2843                                              ConstantExpr::getShl(CI, ShOp));
2844
2845       if (CI->isZero())
2846         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2847       if (CI->equalsInt(1))                  // X * 1  == X
2848         return ReplaceInstUsesWith(I, Op0);
2849       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2850         return BinaryOperator::createNeg(Op0, I.getName());
2851
2852       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2853       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2854         return BinaryOperator::createShl(Op0,
2855                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2856       }
2857     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2858       if (Op1F->isNullValue())
2859         return ReplaceInstUsesWith(I, Op1);
2860
2861       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2862       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2863       // We need a better interface for long double here.
2864       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2865         if (Op1F->isExactlyValue(1.0))
2866           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2867     }
2868     
2869     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2870       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2871           isa<ConstantInt>(Op0I->getOperand(1))) {
2872         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2873         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2874                                                      Op1, "tmp");
2875         InsertNewInstBefore(Add, I);
2876         Value *C1C2 = ConstantExpr::getMul(Op1, 
2877                                            cast<Constant>(Op0I->getOperand(1)));
2878         return BinaryOperator::createAdd(Add, C1C2);
2879         
2880       }
2881
2882     // Try to fold constant mul into select arguments.
2883     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2884       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2885         return R;
2886
2887     if (isa<PHINode>(Op0))
2888       if (Instruction *NV = FoldOpIntoPhi(I))
2889         return NV;
2890   }
2891
2892   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2893     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2894       return BinaryOperator::createMul(Op0v, Op1v);
2895
2896   // If one of the operands of the multiply is a cast from a boolean value, then
2897   // we know the bool is either zero or one, so this is a 'masking' multiply.
2898   // See if we can simplify things based on how the boolean was originally
2899   // formed.
2900   CastInst *BoolCast = 0;
2901   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2902     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2903       BoolCast = CI;
2904   if (!BoolCast)
2905     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2906       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2907         BoolCast = CI;
2908   if (BoolCast) {
2909     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2910       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2911       const Type *SCOpTy = SCIOp0->getType();
2912       bool TIS = false;
2913       
2914       // If the icmp is true iff the sign bit of X is set, then convert this
2915       // multiply into a shift/and combination.
2916       if (isa<ConstantInt>(SCIOp1) &&
2917           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2918           TIS) {
2919         // Shift the X value right to turn it into "all signbits".
2920         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2921                                           SCOpTy->getPrimitiveSizeInBits()-1);
2922         Value *V =
2923           InsertNewInstBefore(
2924             BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2925                                             BoolCast->getOperand(0)->getName()+
2926                                             ".mask"), I);
2927
2928         // If the multiply type is not the same as the source type, sign extend
2929         // or truncate to the multiply type.
2930         if (I.getType() != V->getType()) {
2931           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2932           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2933           Instruction::CastOps opcode = 
2934             (SrcBits == DstBits ? Instruction::BitCast : 
2935              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2936           V = InsertCastBefore(opcode, V, I.getType(), I);
2937         }
2938
2939         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2940         return BinaryOperator::createAnd(V, OtherOp);
2941       }
2942     }
2943   }
2944
2945   return Changed ? &I : 0;
2946 }
2947
2948 /// This function implements the transforms on div instructions that work
2949 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2950 /// used by the visitors to those instructions.
2951 /// @brief Transforms common to all three div instructions
2952 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2953   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2954
2955   // undef / X -> 0        for integer.
2956   // undef / X -> undef    for FP (the undef could be a snan).
2957   if (isa<UndefValue>(Op0)) {
2958     if (Op0->getType()->isFPOrFPVector())
2959       return ReplaceInstUsesWith(I, Op0);
2960     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2961   }
2962
2963   // X / undef -> undef
2964   if (isa<UndefValue>(Op1))
2965     return ReplaceInstUsesWith(I, Op1);
2966
2967   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2968   // This does not apply for fdiv.
2969   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2970     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2971     // the same basic block, then we replace the select with Y, and the
2972     // condition of the select with false (if the cond value is in the same BB).
2973     // If the select has uses other than the div, this allows them to be
2974     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2975     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2976       if (ST->isNullValue()) {
2977         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2978         if (CondI && CondI->getParent() == I.getParent())
2979           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2980         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2981           I.setOperand(1, SI->getOperand(2));
2982         else
2983           UpdateValueUsesWith(SI, SI->getOperand(2));
2984         return &I;
2985       }
2986
2987     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2988     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2989       if (ST->isNullValue()) {
2990         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2991         if (CondI && CondI->getParent() == I.getParent())
2992           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2993         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2994           I.setOperand(1, SI->getOperand(1));
2995         else
2996           UpdateValueUsesWith(SI, SI->getOperand(1));
2997         return &I;
2998       }
2999   }
3000
3001   return 0;
3002 }
3003
3004 /// This function implements the transforms common to both integer division
3005 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3006 /// division instructions.
3007 /// @brief Common integer divide transforms
3008 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3009   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3010
3011   if (Instruction *Common = commonDivTransforms(I))
3012     return Common;
3013
3014   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3015     // div X, 1 == X
3016     if (RHS->equalsInt(1))
3017       return ReplaceInstUsesWith(I, Op0);
3018
3019     // (X / C1) / C2  -> X / (C1*C2)
3020     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3021       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3022         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3023           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3024             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3025           else 
3026             return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
3027                                           Multiply(RHS, LHSRHS));
3028         }
3029
3030     if (!RHS->isZero()) { // avoid X udiv 0
3031       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3032         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3033           return R;
3034       if (isa<PHINode>(Op0))
3035         if (Instruction *NV = FoldOpIntoPhi(I))
3036           return NV;
3037     }
3038   }
3039
3040   // 0 / X == 0, we don't need to preserve faults!
3041   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3042     if (LHS->equalsInt(0))
3043       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3044
3045   return 0;
3046 }
3047
3048 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3049   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3050
3051   // Handle the integer div common cases
3052   if (Instruction *Common = commonIDivTransforms(I))
3053     return Common;
3054
3055   // X udiv C^2 -> X >> C
3056   // Check to see if this is an unsigned division with an exact power of 2,
3057   // if so, convert to a right shift.
3058   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3059     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3060       return BinaryOperator::createLShr(Op0, 
3061                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3062   }
3063
3064   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3065   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3066     if (RHSI->getOpcode() == Instruction::Shl &&
3067         isa<ConstantInt>(RHSI->getOperand(0))) {
3068       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3069       if (C1.isPowerOf2()) {
3070         Value *N = RHSI->getOperand(1);
3071         const Type *NTy = N->getType();
3072         if (uint32_t C2 = C1.logBase2()) {
3073           Constant *C2V = ConstantInt::get(NTy, C2);
3074           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
3075         }
3076         return BinaryOperator::createLShr(Op0, N);
3077       }
3078     }
3079   }
3080   
3081   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3082   // where C1&C2 are powers of two.
3083   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3084     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3085       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3086         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3087         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3088           // Compute the shift amounts
3089           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3090           // Construct the "on true" case of the select
3091           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3092           Instruction *TSI = BinaryOperator::createLShr(
3093                                                  Op0, TC, SI->getName()+".t");
3094           TSI = InsertNewInstBefore(TSI, I);
3095   
3096           // Construct the "on false" case of the select
3097           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3098           Instruction *FSI = BinaryOperator::createLShr(
3099                                                  Op0, FC, SI->getName()+".f");
3100           FSI = InsertNewInstBefore(FSI, I);
3101
3102           // construct the select instruction and return it.
3103           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3104         }
3105       }
3106   return 0;
3107 }
3108
3109 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3110   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3111
3112   // Handle the integer div common cases
3113   if (Instruction *Common = commonIDivTransforms(I))
3114     return Common;
3115
3116   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3117     // sdiv X, -1 == -X
3118     if (RHS->isAllOnesValue())
3119       return BinaryOperator::createNeg(Op0);
3120
3121     // -X/C -> X/-C
3122     if (Value *LHSNeg = dyn_castNegVal(Op0))
3123       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3124   }
3125
3126   // If the sign bits of both operands are zero (i.e. we can prove they are
3127   // unsigned inputs), turn this into a udiv.
3128   if (I.getType()->isInteger()) {
3129     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3130     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3131       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3132       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
3133     }
3134   }      
3135   
3136   return 0;
3137 }
3138
3139 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3140   return commonDivTransforms(I);
3141 }
3142
3143 /// This function implements the transforms on rem instructions that work
3144 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3145 /// is used by the visitors to those instructions.
3146 /// @brief Transforms common to all three rem instructions
3147 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3148   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3149
3150   // 0 % X == 0 for integer, we don't need to preserve faults!
3151   if (Constant *LHS = dyn_cast<Constant>(Op0))
3152     if (LHS->isNullValue())
3153       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3154
3155   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3156     if (I.getType()->isFPOrFPVector())
3157       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3158     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3159   }
3160   if (isa<UndefValue>(Op1))
3161     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3162
3163   // Handle cases involving: rem X, (select Cond, Y, Z)
3164   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3165     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
3166     // the same basic block, then we replace the select with Y, and the
3167     // condition of the select with false (if the cond value is in the same
3168     // BB).  If the select has uses other than the div, this allows them to be
3169     // simplified also.
3170     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3171       if (ST->isNullValue()) {
3172         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3173         if (CondI && CondI->getParent() == I.getParent())
3174           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3175         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3176           I.setOperand(1, SI->getOperand(2));
3177         else
3178           UpdateValueUsesWith(SI, SI->getOperand(2));
3179         return &I;
3180       }
3181     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3182     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3183       if (ST->isNullValue()) {
3184         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3185         if (CondI && CondI->getParent() == I.getParent())
3186           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3187         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3188           I.setOperand(1, SI->getOperand(1));
3189         else
3190           UpdateValueUsesWith(SI, SI->getOperand(1));
3191         return &I;
3192       }
3193   }
3194
3195   return 0;
3196 }
3197
3198 /// This function implements the transforms common to both integer remainder
3199 /// instructions (urem and srem). It is called by the visitors to those integer
3200 /// remainder instructions.
3201 /// @brief Common integer remainder transforms
3202 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3203   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205   if (Instruction *common = commonRemTransforms(I))
3206     return common;
3207
3208   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209     // X % 0 == undef, we don't need to preserve faults!
3210     if (RHS->equalsInt(0))
3211       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3212     
3213     if (RHS->equalsInt(1))  // X % 1 == 0
3214       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3215
3216     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3217       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3218         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3219           return R;
3220       } else if (isa<PHINode>(Op0I)) {
3221         if (Instruction *NV = FoldOpIntoPhi(I))
3222           return NV;
3223       }
3224
3225       // See if we can fold away this rem instruction.
3226       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3227       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3228       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3229                                KnownZero, KnownOne))
3230         return &I;
3231     }
3232   }
3233
3234   return 0;
3235 }
3236
3237 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3238   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3239
3240   if (Instruction *common = commonIRemTransforms(I))
3241     return common;
3242   
3243   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3244     // X urem C^2 -> X and C
3245     // Check to see if this is an unsigned remainder with an exact power of 2,
3246     // if so, convert to a bitwise and.
3247     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3248       if (C->getValue().isPowerOf2())
3249         return BinaryOperator::createAnd(Op0, SubOne(C));
3250   }
3251
3252   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3253     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3254     if (RHSI->getOpcode() == Instruction::Shl &&
3255         isa<ConstantInt>(RHSI->getOperand(0))) {
3256       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3257         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3258         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3259                                                                    "tmp"), I);
3260         return BinaryOperator::createAnd(Op0, Add);
3261       }
3262     }
3263   }
3264
3265   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3266   // where C1&C2 are powers of two.
3267   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3268     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3269       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3270         // STO == 0 and SFO == 0 handled above.
3271         if ((STO->getValue().isPowerOf2()) && 
3272             (SFO->getValue().isPowerOf2())) {
3273           Value *TrueAnd = InsertNewInstBefore(
3274             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3275           Value *FalseAnd = InsertNewInstBefore(
3276             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3277           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3278         }
3279       }
3280   }
3281   
3282   return 0;
3283 }
3284
3285 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3286   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3287
3288   // Handle the integer rem common cases
3289   if (Instruction *common = commonIRemTransforms(I))
3290     return common;
3291   
3292   if (Value *RHSNeg = dyn_castNegVal(Op1))
3293     if (!isa<ConstantInt>(RHSNeg) || 
3294         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3295       // X % -Y -> X % Y
3296       AddUsesToWorkList(I);
3297       I.setOperand(1, RHSNeg);
3298       return &I;
3299     }
3300  
3301   // If the sign bits of both operands are zero (i.e. we can prove they are
3302   // unsigned inputs), turn this into a urem.
3303   if (I.getType()->isInteger()) {
3304     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3305     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3306       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3307       return BinaryOperator::createURem(Op0, Op1, I.getName());
3308     }
3309   }
3310
3311   return 0;
3312 }
3313
3314 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3315   return commonRemTransforms(I);
3316 }
3317
3318 // isMaxValueMinusOne - return true if this is Max-1
3319 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3320   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3321   if (!isSigned)
3322     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3323   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3324 }
3325
3326 // isMinValuePlusOne - return true if this is Min+1
3327 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3328   if (!isSigned)
3329     return C->getValue() == 1; // unsigned
3330     
3331   // Calculate 1111111111000000000000
3332   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3333   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3334 }
3335
3336 // isOneBitSet - Return true if there is exactly one bit set in the specified
3337 // constant.
3338 static bool isOneBitSet(const ConstantInt *CI) {
3339   return CI->getValue().isPowerOf2();
3340 }
3341
3342 // isHighOnes - Return true if the constant is of the form 1+0+.
3343 // This is the same as lowones(~X).
3344 static bool isHighOnes(const ConstantInt *CI) {
3345   return (~CI->getValue() + 1).isPowerOf2();
3346 }
3347
3348 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3349 /// are carefully arranged to allow folding of expressions such as:
3350 ///
3351 ///      (A < B) | (A > B) --> (A != B)
3352 ///
3353 /// Note that this is only valid if the first and second predicates have the
3354 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3355 ///
3356 /// Three bits are used to represent the condition, as follows:
3357 ///   0  A > B
3358 ///   1  A == B
3359 ///   2  A < B
3360 ///
3361 /// <=>  Value  Definition
3362 /// 000     0   Always false
3363 /// 001     1   A >  B
3364 /// 010     2   A == B
3365 /// 011     3   A >= B
3366 /// 100     4   A <  B
3367 /// 101     5   A != B
3368 /// 110     6   A <= B
3369 /// 111     7   Always true
3370 ///  
3371 static unsigned getICmpCode(const ICmpInst *ICI) {
3372   switch (ICI->getPredicate()) {
3373     // False -> 0
3374   case ICmpInst::ICMP_UGT: return 1;  // 001
3375   case ICmpInst::ICMP_SGT: return 1;  // 001
3376   case ICmpInst::ICMP_EQ:  return 2;  // 010
3377   case ICmpInst::ICMP_UGE: return 3;  // 011
3378   case ICmpInst::ICMP_SGE: return 3;  // 011
3379   case ICmpInst::ICMP_ULT: return 4;  // 100
3380   case ICmpInst::ICMP_SLT: return 4;  // 100
3381   case ICmpInst::ICMP_NE:  return 5;  // 101
3382   case ICmpInst::ICMP_ULE: return 6;  // 110
3383   case ICmpInst::ICMP_SLE: return 6;  // 110
3384     // True -> 7
3385   default:
3386     assert(0 && "Invalid ICmp predicate!");
3387     return 0;
3388   }
3389 }
3390
3391 /// getICmpValue - This is the complement of getICmpCode, which turns an
3392 /// opcode and two operands into either a constant true or false, or a brand 
3393 /// new ICmp instruction. The sign is passed in to determine which kind
3394 /// of predicate to use in new icmp instructions.
3395 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3396   switch (code) {
3397   default: assert(0 && "Illegal ICmp code!");
3398   case  0: return ConstantInt::getFalse();
3399   case  1: 
3400     if (sign)
3401       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3402     else
3403       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3404   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3405   case  3: 
3406     if (sign)
3407       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3408     else
3409       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3410   case  4: 
3411     if (sign)
3412       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3413     else
3414       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3415   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3416   case  6: 
3417     if (sign)
3418       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3419     else
3420       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3421   case  7: return ConstantInt::getTrue();
3422   }
3423 }
3424
3425 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3426   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3427     (ICmpInst::isSignedPredicate(p1) && 
3428      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3429     (ICmpInst::isSignedPredicate(p2) && 
3430      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3431 }
3432
3433 namespace { 
3434 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3435 struct FoldICmpLogical {
3436   InstCombiner &IC;
3437   Value *LHS, *RHS;
3438   ICmpInst::Predicate pred;
3439   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3440     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3441       pred(ICI->getPredicate()) {}
3442   bool shouldApply(Value *V) const {
3443     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3444       if (PredicatesFoldable(pred, ICI->getPredicate()))
3445         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3446                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3447     return false;
3448   }
3449   Instruction *apply(Instruction &Log) const {
3450     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3451     if (ICI->getOperand(0) != LHS) {
3452       assert(ICI->getOperand(1) == LHS);
3453       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3454     }
3455
3456     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3457     unsigned LHSCode = getICmpCode(ICI);
3458     unsigned RHSCode = getICmpCode(RHSICI);
3459     unsigned Code;
3460     switch (Log.getOpcode()) {
3461     case Instruction::And: Code = LHSCode & RHSCode; break;
3462     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3463     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3464     default: assert(0 && "Illegal logical opcode!"); return 0;
3465     }
3466
3467     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3468                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3469       
3470     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3471     if (Instruction *I = dyn_cast<Instruction>(RV))
3472       return I;
3473     // Otherwise, it's a constant boolean value...
3474     return IC.ReplaceInstUsesWith(Log, RV);
3475   }
3476 };
3477 } // end anonymous namespace
3478
3479 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3480 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3481 // guaranteed to be a binary operator.
3482 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3483                                     ConstantInt *OpRHS,
3484                                     ConstantInt *AndRHS,
3485                                     BinaryOperator &TheAnd) {
3486   Value *X = Op->getOperand(0);
3487   Constant *Together = 0;
3488   if (!Op->isShift())
3489     Together = And(AndRHS, OpRHS);
3490
3491   switch (Op->getOpcode()) {
3492   case Instruction::Xor:
3493     if (Op->hasOneUse()) {
3494       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3495       Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3496       InsertNewInstBefore(And, TheAnd);
3497       And->takeName(Op);
3498       return BinaryOperator::createXor(And, Together);
3499     }
3500     break;
3501   case Instruction::Or:
3502     if (Together == AndRHS) // (X | C) & C --> C
3503       return ReplaceInstUsesWith(TheAnd, AndRHS);
3504
3505     if (Op->hasOneUse() && Together != OpRHS) {
3506       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3507       Instruction *Or = BinaryOperator::createOr(X, Together);
3508       InsertNewInstBefore(Or, TheAnd);
3509       Or->takeName(Op);
3510       return BinaryOperator::createAnd(Or, AndRHS);
3511     }
3512     break;
3513   case Instruction::Add:
3514     if (Op->hasOneUse()) {
3515       // Adding a one to a single bit bit-field should be turned into an XOR
3516       // of the bit.  First thing to check is to see if this AND is with a
3517       // single bit constant.
3518       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3519
3520       // If there is only one bit set...
3521       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3522         // Ok, at this point, we know that we are masking the result of the
3523         // ADD down to exactly one bit.  If the constant we are adding has
3524         // no bits set below this bit, then we can eliminate the ADD.
3525         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3526
3527         // Check to see if any bits below the one bit set in AndRHSV are set.
3528         if ((AddRHS & (AndRHSV-1)) == 0) {
3529           // If not, the only thing that can effect the output of the AND is
3530           // the bit specified by AndRHSV.  If that bit is set, the effect of
3531           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3532           // no effect.
3533           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3534             TheAnd.setOperand(0, X);
3535             return &TheAnd;
3536           } else {
3537             // Pull the XOR out of the AND.
3538             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3539             InsertNewInstBefore(NewAnd, TheAnd);
3540             NewAnd->takeName(Op);
3541             return BinaryOperator::createXor(NewAnd, AndRHS);
3542           }
3543         }
3544       }
3545     }
3546     break;
3547
3548   case Instruction::Shl: {
3549     // We know that the AND will not produce any of the bits shifted in, so if
3550     // the anded constant includes them, clear them now!
3551     //
3552     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3553     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3554     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3555     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3556
3557     if (CI->getValue() == ShlMask) { 
3558     // Masking out bits that the shift already masks
3559       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3560     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3561       TheAnd.setOperand(1, CI);
3562       return &TheAnd;
3563     }
3564     break;
3565   }
3566   case Instruction::LShr:
3567   {
3568     // We know that the AND will not produce any of the bits shifted in, so if
3569     // the anded constant includes them, clear them now!  This only applies to
3570     // unsigned shifts, because a signed shr may bring in set bits!
3571     //
3572     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3573     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3574     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3575     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3576
3577     if (CI->getValue() == ShrMask) {   
3578     // Masking out bits that the shift already masks.
3579       return ReplaceInstUsesWith(TheAnd, Op);
3580     } else if (CI != AndRHS) {
3581       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3582       return &TheAnd;
3583     }
3584     break;
3585   }
3586   case Instruction::AShr:
3587     // Signed shr.
3588     // See if this is shifting in some sign extension, then masking it out
3589     // with an and.
3590     if (Op->hasOneUse()) {
3591       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3592       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3593       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3594       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3595       if (C == AndRHS) {          // Masking out bits shifted in.
3596         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3597         // Make the argument unsigned.
3598         Value *ShVal = Op->getOperand(0);
3599         ShVal = InsertNewInstBefore(
3600             BinaryOperator::createLShr(ShVal, OpRHS, 
3601                                    Op->getName()), TheAnd);
3602         return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3603       }
3604     }
3605     break;
3606   }
3607   return 0;
3608 }
3609
3610
3611 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3612 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3613 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3614 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3615 /// insert new instructions.
3616 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3617                                            bool isSigned, bool Inside, 
3618                                            Instruction &IB) {
3619   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3620             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3621          "Lo is not <= Hi in range emission code!");
3622     
3623   if (Inside) {
3624     if (Lo == Hi)  // Trivially false.
3625       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3626
3627     // V >= Min && V < Hi --> V < Hi
3628     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3629       ICmpInst::Predicate pred = (isSigned ? 
3630         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3631       return new ICmpInst(pred, V, Hi);
3632     }
3633
3634     // Emit V-Lo <u Hi-Lo
3635     Constant *NegLo = ConstantExpr::getNeg(Lo);
3636     Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3637     InsertNewInstBefore(Add, IB);
3638     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3639     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3640   }
3641
3642   if (Lo == Hi)  // Trivially true.
3643     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3644
3645   // V < Min || V >= Hi -> V > Hi-1
3646   Hi = SubOne(cast<ConstantInt>(Hi));
3647   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3648     ICmpInst::Predicate pred = (isSigned ? 
3649         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3650     return new ICmpInst(pred, V, Hi);
3651   }
3652
3653   // Emit V-Lo >u Hi-1-Lo
3654   // Note that Hi has already had one subtracted from it, above.
3655   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3656   Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3657   InsertNewInstBefore(Add, IB);
3658   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3659   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3660 }
3661
3662 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3663 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3664 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3665 // not, since all 1s are not contiguous.
3666 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3667   const APInt& V = Val->getValue();
3668   uint32_t BitWidth = Val->getType()->getBitWidth();
3669   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3670
3671   // look for the first zero bit after the run of ones
3672   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3673   // look for the first non-zero bit
3674   ME = V.getActiveBits(); 
3675   return true;
3676 }
3677
3678 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3679 /// where isSub determines whether the operator is a sub.  If we can fold one of
3680 /// the following xforms:
3681 /// 
3682 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3683 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3684 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3685 ///
3686 /// return (A +/- B).
3687 ///
3688 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3689                                         ConstantInt *Mask, bool isSub,
3690                                         Instruction &I) {
3691   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3692   if (!LHSI || LHSI->getNumOperands() != 2 ||
3693       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3694
3695   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3696
3697   switch (LHSI->getOpcode()) {
3698   default: return 0;
3699   case Instruction::And:
3700     if (And(N, Mask) == Mask) {
3701       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3702       if ((Mask->getValue().countLeadingZeros() + 
3703            Mask->getValue().countPopulation()) == 
3704           Mask->getValue().getBitWidth())
3705         break;
3706
3707       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3708       // part, we don't need any explicit masks to take them out of A.  If that
3709       // is all N is, ignore it.
3710       uint32_t MB = 0, ME = 0;
3711       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3712         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3713         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3714         if (MaskedValueIsZero(RHS, Mask))
3715           break;
3716       }
3717     }
3718     return 0;
3719   case Instruction::Or:
3720   case Instruction::Xor:
3721     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3722     if ((Mask->getValue().countLeadingZeros() + 
3723          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3724         && And(N, Mask)->isZero())
3725       break;
3726     return 0;
3727   }
3728   
3729   Instruction *New;
3730   if (isSub)
3731     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3732   else
3733     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3734   return InsertNewInstBefore(New, I);
3735 }
3736
3737 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3738   bool Changed = SimplifyCommutative(I);
3739   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3740
3741   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3742     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3743
3744   // and X, X = X
3745   if (Op0 == Op1)
3746     return ReplaceInstUsesWith(I, Op1);
3747
3748   // See if we can simplify any instructions used by the instruction whose sole 
3749   // purpose is to compute bits we don't care about.
3750   if (!isa<VectorType>(I.getType())) {
3751     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3752     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3753     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3754                              KnownZero, KnownOne))
3755       return &I;
3756   } else {
3757     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3758       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3759         return ReplaceInstUsesWith(I, I.getOperand(0));
3760     } else if (isa<ConstantAggregateZero>(Op1)) {
3761       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3762     }
3763   }
3764   
3765   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3766     const APInt& AndRHSMask = AndRHS->getValue();
3767     APInt NotAndRHS(~AndRHSMask);
3768
3769     // Optimize a variety of ((val OP C1) & C2) combinations...
3770     if (isa<BinaryOperator>(Op0)) {
3771       Instruction *Op0I = cast<Instruction>(Op0);
3772       Value *Op0LHS = Op0I->getOperand(0);
3773       Value *Op0RHS = Op0I->getOperand(1);
3774       switch (Op0I->getOpcode()) {
3775       case Instruction::Xor:
3776       case Instruction::Or:
3777         // If the mask is only needed on one incoming arm, push it up.
3778         if (Op0I->hasOneUse()) {
3779           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3780             // Not masking anything out for the LHS, move to RHS.
3781             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3782                                                    Op0RHS->getName()+".masked");
3783             InsertNewInstBefore(NewRHS, I);
3784             return BinaryOperator::create(
3785                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3786           }
3787           if (!isa<Constant>(Op0RHS) &&
3788               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3789             // Not masking anything out for the RHS, move to LHS.
3790             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3791                                                    Op0LHS->getName()+".masked");
3792             InsertNewInstBefore(NewLHS, I);
3793             return BinaryOperator::create(
3794                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3795           }
3796         }
3797
3798         break;
3799       case Instruction::Add:
3800         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3801         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3802         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3803         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3804           return BinaryOperator::createAnd(V, AndRHS);
3805         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3806           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3807         break;
3808
3809       case Instruction::Sub:
3810         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3811         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3812         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3813         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3814           return BinaryOperator::createAnd(V, AndRHS);
3815         break;
3816       }
3817
3818       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3819         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3820           return Res;
3821     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3822       // If this is an integer truncation or change from signed-to-unsigned, and
3823       // if the source is an and/or with immediate, transform it.  This
3824       // frequently occurs for bitfield accesses.
3825       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3826         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3827             CastOp->getNumOperands() == 2)
3828           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3829             if (CastOp->getOpcode() == Instruction::And) {
3830               // Change: and (cast (and X, C1) to T), C2
3831               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3832               // This will fold the two constants together, which may allow 
3833               // other simplifications.
3834               Instruction *NewCast = CastInst::createTruncOrBitCast(
3835                 CastOp->getOperand(0), I.getType(), 
3836                 CastOp->getName()+".shrunk");
3837               NewCast = InsertNewInstBefore(NewCast, I);
3838               // trunc_or_bitcast(C1)&C2
3839               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3840               C3 = ConstantExpr::getAnd(C3, AndRHS);
3841               return BinaryOperator::createAnd(NewCast, C3);
3842             } else if (CastOp->getOpcode() == Instruction::Or) {
3843               // Change: and (cast (or X, C1) to T), C2
3844               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3845               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3846               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3847                 return ReplaceInstUsesWith(I, AndRHS);
3848             }
3849           }
3850       }
3851     }
3852
3853     // Try to fold constant and into select arguments.
3854     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3855       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3856         return R;
3857     if (isa<PHINode>(Op0))
3858       if (Instruction *NV = FoldOpIntoPhi(I))
3859         return NV;
3860   }
3861
3862   Value *Op0NotVal = dyn_castNotVal(Op0);
3863   Value *Op1NotVal = dyn_castNotVal(Op1);
3864
3865   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3866     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3867
3868   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3869   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3870     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3871                                                I.getName()+".demorgan");
3872     InsertNewInstBefore(Or, I);
3873     return BinaryOperator::createNot(Or);
3874   }
3875   
3876   {
3877     Value *A = 0, *B = 0, *C = 0, *D = 0;
3878     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3879       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3880         return ReplaceInstUsesWith(I, Op1);
3881     
3882       // (A|B) & ~(A&B) -> A^B
3883       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3884         if ((A == C && B == D) || (A == D && B == C))
3885           return BinaryOperator::createXor(A, B);
3886       }
3887     }
3888     
3889     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3890       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3891         return ReplaceInstUsesWith(I, Op0);
3892
3893       // ~(A&B) & (A|B) -> A^B
3894       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3895         if ((A == C && B == D) || (A == D && B == C))
3896           return BinaryOperator::createXor(A, B);
3897       }
3898     }
3899     
3900     if (Op0->hasOneUse() &&
3901         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3902       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3903         I.swapOperands();     // Simplify below
3904         std::swap(Op0, Op1);
3905       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3906         cast<BinaryOperator>(Op0)->swapOperands();
3907         I.swapOperands();     // Simplify below
3908         std::swap(Op0, Op1);
3909       }
3910     }
3911     if (Op1->hasOneUse() &&
3912         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3913       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3914         cast<BinaryOperator>(Op1)->swapOperands();
3915         std::swap(A, B);
3916       }
3917       if (A == Op0) {                                // A&(A^B) -> A & ~B
3918         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3919         InsertNewInstBefore(NotB, I);
3920         return BinaryOperator::createAnd(A, NotB);
3921       }
3922     }
3923   }
3924   
3925   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3926     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3927     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3928       return R;
3929
3930     Value *LHSVal, *RHSVal;
3931     ConstantInt *LHSCst, *RHSCst;
3932     ICmpInst::Predicate LHSCC, RHSCC;
3933     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3934       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3935         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3936             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3937             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3938             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3939             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3940             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3941             
3942             // Don't try to fold ICMP_SLT + ICMP_ULT.
3943             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3944              ICmpInst::isSignedPredicate(LHSCC) == 
3945                  ICmpInst::isSignedPredicate(RHSCC))) {
3946           // Ensure that the larger constant is on the RHS.
3947           ICmpInst::Predicate GT;
3948           if (ICmpInst::isSignedPredicate(LHSCC) ||
3949               (ICmpInst::isEquality(LHSCC) && 
3950                ICmpInst::isSignedPredicate(RHSCC)))
3951             GT = ICmpInst::ICMP_SGT;
3952           else
3953             GT = ICmpInst::ICMP_UGT;
3954           
3955           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3956           ICmpInst *LHS = cast<ICmpInst>(Op0);
3957           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3958             std::swap(LHS, RHS);
3959             std::swap(LHSCst, RHSCst);
3960             std::swap(LHSCC, RHSCC);
3961           }
3962
3963           // At this point, we know we have have two icmp instructions
3964           // comparing a value against two constants and and'ing the result
3965           // together.  Because of the above check, we know that we only have
3966           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3967           // (from the FoldICmpLogical check above), that the two constants 
3968           // are not equal and that the larger constant is on the RHS
3969           assert(LHSCst != RHSCst && "Compares not folded above?");
3970
3971           switch (LHSCC) {
3972           default: assert(0 && "Unknown integer condition code!");
3973           case ICmpInst::ICMP_EQ:
3974             switch (RHSCC) {
3975             default: assert(0 && "Unknown integer condition code!");
3976             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3977             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3978             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3979               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3980             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3981             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3982             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3983               return ReplaceInstUsesWith(I, LHS);
3984             }
3985           case ICmpInst::ICMP_NE:
3986             switch (RHSCC) {
3987             default: assert(0 && "Unknown integer condition code!");
3988             case ICmpInst::ICMP_ULT:
3989               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3990                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3991               break;                        // (X != 13 & X u< 15) -> no change
3992             case ICmpInst::ICMP_SLT:
3993               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3994                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3995               break;                        // (X != 13 & X s< 15) -> no change
3996             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3997             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3998             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3999               return ReplaceInstUsesWith(I, RHS);
4000             case ICmpInst::ICMP_NE:
4001               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4002                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4003                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4004                                                       LHSVal->getName()+".off");
4005                 InsertNewInstBefore(Add, I);
4006                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4007                                     ConstantInt::get(Add->getType(), 1));
4008               }
4009               break;                        // (X != 13 & X != 15) -> no change
4010             }
4011             break;
4012           case ICmpInst::ICMP_ULT:
4013             switch (RHSCC) {
4014             default: assert(0 && "Unknown integer condition code!");
4015             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4016             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4017               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4018             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4019               break;
4020             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4021             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4022               return ReplaceInstUsesWith(I, LHS);
4023             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4024               break;
4025             }
4026             break;
4027           case ICmpInst::ICMP_SLT:
4028             switch (RHSCC) {
4029             default: assert(0 && "Unknown integer condition code!");
4030             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4031             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4032               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4033             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4034               break;
4035             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4036             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4037               return ReplaceInstUsesWith(I, LHS);
4038             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4039               break;
4040             }
4041             break;
4042           case ICmpInst::ICMP_UGT:
4043             switch (RHSCC) {
4044             default: assert(0 && "Unknown integer condition code!");
4045             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
4046               return ReplaceInstUsesWith(I, LHS);
4047             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4048               return ReplaceInstUsesWith(I, RHS);
4049             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4050               break;
4051             case ICmpInst::ICMP_NE:
4052               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4053                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4054               break;                        // (X u> 13 & X != 15) -> no change
4055             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
4056               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
4057                                      true, I);
4058             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4059               break;
4060             }
4061             break;
4062           case ICmpInst::ICMP_SGT:
4063             switch (RHSCC) {
4064             default: assert(0 && "Unknown integer condition code!");
4065             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4066             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4067               return ReplaceInstUsesWith(I, RHS);
4068             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4069               break;
4070             case ICmpInst::ICMP_NE:
4071               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4072                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4073               break;                        // (X s> 13 & X != 15) -> no change
4074             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
4075               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
4076                                      true, I);
4077             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4078               break;
4079             }
4080             break;
4081           }
4082         }
4083   }
4084
4085   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4086   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4087     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4088       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4089         const Type *SrcTy = Op0C->getOperand(0)->getType();
4090         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4091             // Only do this if the casts both really cause code to be generated.
4092             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4093                               I.getType(), TD) &&
4094             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4095                               I.getType(), TD)) {
4096           Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
4097                                                          Op1C->getOperand(0),
4098                                                          I.getName());
4099           InsertNewInstBefore(NewOp, I);
4100           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4101         }
4102       }
4103     
4104   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4105   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4106     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4107       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4108           SI0->getOperand(1) == SI1->getOperand(1) &&
4109           (SI0->hasOneUse() || SI1->hasOneUse())) {
4110         Instruction *NewOp =
4111           InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
4112                                                         SI1->getOperand(0),
4113                                                         SI0->getName()), I);
4114         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4115                                       SI1->getOperand(1));
4116       }
4117   }
4118
4119   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4120   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4121     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4122       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4123           RHS->getPredicate() == FCmpInst::FCMP_ORD)
4124         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4125           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4126             // If either of the constants are nans, then the whole thing returns
4127             // false.
4128             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4129               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4130             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4131                                 RHS->getOperand(0));
4132           }
4133     }
4134   }
4135       
4136   return Changed ? &I : 0;
4137 }
4138
4139 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4140 /// in the result.  If it does, and if the specified byte hasn't been filled in
4141 /// yet, fill it in and return false.
4142 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4143   Instruction *I = dyn_cast<Instruction>(V);
4144   if (I == 0) return true;
4145
4146   // If this is an or instruction, it is an inner node of the bswap.
4147   if (I->getOpcode() == Instruction::Or)
4148     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4149            CollectBSwapParts(I->getOperand(1), ByteValues);
4150   
4151   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4152   // If this is a shift by a constant int, and it is "24", then its operand
4153   // defines a byte.  We only handle unsigned types here.
4154   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4155     // Not shifting the entire input by N-1 bytes?
4156     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4157         8*(ByteValues.size()-1))
4158       return true;
4159     
4160     unsigned DestNo;
4161     if (I->getOpcode() == Instruction::Shl) {
4162       // X << 24 defines the top byte with the lowest of the input bytes.
4163       DestNo = ByteValues.size()-1;
4164     } else {
4165       // X >>u 24 defines the low byte with the highest of the input bytes.
4166       DestNo = 0;
4167     }
4168     
4169     // If the destination byte value is already defined, the values are or'd
4170     // together, which isn't a bswap (unless it's an or of the same bits).
4171     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4172       return true;
4173     ByteValues[DestNo] = I->getOperand(0);
4174     return false;
4175   }
4176   
4177   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
4178   // don't have this.
4179   Value *Shift = 0, *ShiftLHS = 0;
4180   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4181   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4182       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4183     return true;
4184   Instruction *SI = cast<Instruction>(Shift);
4185
4186   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4187   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4188       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4189     return true;
4190   
4191   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4192   unsigned DestByte;
4193   if (AndAmt->getValue().getActiveBits() > 64)
4194     return true;
4195   uint64_t AndAmtVal = AndAmt->getZExtValue();
4196   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4197     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4198       break;
4199   // Unknown mask for bswap.
4200   if (DestByte == ByteValues.size()) return true;
4201   
4202   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4203   unsigned SrcByte;
4204   if (SI->getOpcode() == Instruction::Shl)
4205     SrcByte = DestByte - ShiftBytes;
4206   else
4207     SrcByte = DestByte + ShiftBytes;
4208   
4209   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4210   if (SrcByte != ByteValues.size()-DestByte-1)
4211     return true;
4212   
4213   // If the destination byte value is already defined, the values are or'd
4214   // together, which isn't a bswap (unless it's an or of the same bits).
4215   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4216     return true;
4217   ByteValues[DestByte] = SI->getOperand(0);
4218   return false;
4219 }
4220
4221 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4222 /// If so, insert the new bswap intrinsic and return it.
4223 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4224   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4225   if (!ITy || ITy->getBitWidth() % 16) 
4226     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4227   
4228   /// ByteValues - For each byte of the result, we keep track of which value
4229   /// defines each byte.
4230   SmallVector<Value*, 8> ByteValues;
4231   ByteValues.resize(ITy->getBitWidth()/8);
4232     
4233   // Try to find all the pieces corresponding to the bswap.
4234   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4235       CollectBSwapParts(I.getOperand(1), ByteValues))
4236     return 0;
4237   
4238   // Check to see if all of the bytes come from the same value.
4239   Value *V = ByteValues[0];
4240   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4241   
4242   // Check to make sure that all of the bytes come from the same value.
4243   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4244     if (ByteValues[i] != V)
4245       return 0;
4246   const Type *Tys[] = { ITy };
4247   Module *M = I.getParent()->getParent()->getParent();
4248   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4249   return CallInst::Create(F, V);
4250 }
4251
4252
4253 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4254   bool Changed = SimplifyCommutative(I);
4255   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4256
4257   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4258     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4259
4260   // or X, X = X
4261   if (Op0 == Op1)
4262     return ReplaceInstUsesWith(I, Op0);
4263
4264   // See if we can simplify any instructions used by the instruction whose sole 
4265   // purpose is to compute bits we don't care about.
4266   if (!isa<VectorType>(I.getType())) {
4267     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4268     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4269     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4270                              KnownZero, KnownOne))
4271       return &I;
4272   } else if (isa<ConstantAggregateZero>(Op1)) {
4273     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4274   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4275     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4276       return ReplaceInstUsesWith(I, I.getOperand(1));
4277   }
4278     
4279
4280   
4281   // or X, -1 == -1
4282   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4283     ConstantInt *C1 = 0; Value *X = 0;
4284     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4285     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4286       Instruction *Or = BinaryOperator::createOr(X, RHS);
4287       InsertNewInstBefore(Or, I);
4288       Or->takeName(Op0);
4289       return BinaryOperator::createAnd(Or, 
4290                ConstantInt::get(RHS->getValue() | C1->getValue()));
4291     }
4292
4293     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4294     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4295       Instruction *Or = BinaryOperator::createOr(X, RHS);
4296       InsertNewInstBefore(Or, I);
4297       Or->takeName(Op0);
4298       return BinaryOperator::createXor(Or,
4299                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4300     }
4301
4302     // Try to fold constant and into select arguments.
4303     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4304       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4305         return R;
4306     if (isa<PHINode>(Op0))
4307       if (Instruction *NV = FoldOpIntoPhi(I))
4308         return NV;
4309   }
4310
4311   Value *A = 0, *B = 0;
4312   ConstantInt *C1 = 0, *C2 = 0;
4313
4314   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4315     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4316       return ReplaceInstUsesWith(I, Op1);
4317   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4318     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4319       return ReplaceInstUsesWith(I, Op0);
4320
4321   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4322   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4323   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4324       match(Op1, m_Or(m_Value(), m_Value())) ||
4325       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4326        match(Op1, m_Shift(m_Value(), m_Value())))) {
4327     if (Instruction *BSwap = MatchBSwap(I))
4328       return BSwap;
4329   }
4330   
4331   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4332   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4333       MaskedValueIsZero(Op1, C1->getValue())) {
4334     Instruction *NOr = BinaryOperator::createOr(A, Op1);
4335     InsertNewInstBefore(NOr, I);
4336     NOr->takeName(Op0);
4337     return BinaryOperator::createXor(NOr, C1);
4338   }
4339
4340   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4341   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4342       MaskedValueIsZero(Op0, C1->getValue())) {
4343     Instruction *NOr = BinaryOperator::createOr(A, Op0);
4344     InsertNewInstBefore(NOr, I);
4345     NOr->takeName(Op0);
4346     return BinaryOperator::createXor(NOr, C1);
4347   }
4348
4349   // (A & C)|(B & D)
4350   Value *C = 0, *D = 0;
4351   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4352       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4353     Value *V1 = 0, *V2 = 0, *V3 = 0;
4354     C1 = dyn_cast<ConstantInt>(C);
4355     C2 = dyn_cast<ConstantInt>(D);
4356     if (C1 && C2) {  // (A & C1)|(B & C2)
4357       // If we have: ((V + N) & C1) | (V & C2)
4358       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4359       // replace with V+N.
4360       if (C1->getValue() == ~C2->getValue()) {
4361         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4362             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4363           // Add commutes, try both ways.
4364           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4365             return ReplaceInstUsesWith(I, A);
4366           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4367             return ReplaceInstUsesWith(I, A);
4368         }
4369         // Or commutes, try both ways.
4370         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4371             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4372           // Add commutes, try both ways.
4373           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4374             return ReplaceInstUsesWith(I, B);
4375           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4376             return ReplaceInstUsesWith(I, B);
4377         }
4378       }
4379       V1 = 0; V2 = 0; V3 = 0;
4380     }
4381     
4382     // Check to see if we have any common things being and'ed.  If so, find the
4383     // terms for V1 & (V2|V3).
4384     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4385       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4386         V1 = A, V2 = C, V3 = D;
4387       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4388         V1 = A, V2 = B, V3 = C;
4389       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4390         V1 = C, V2 = A, V3 = D;
4391       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4392         V1 = C, V2 = A, V3 = B;
4393       
4394       if (V1) {
4395         Value *Or =
4396           InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4397         return BinaryOperator::createAnd(V1, Or);
4398       }
4399     }
4400   }
4401   
4402   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4403   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4404     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4405       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4406           SI0->getOperand(1) == SI1->getOperand(1) &&
4407           (SI0->hasOneUse() || SI1->hasOneUse())) {
4408         Instruction *NewOp =
4409         InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4410                                                      SI1->getOperand(0),
4411                                                      SI0->getName()), I);
4412         return BinaryOperator::create(SI1->getOpcode(), NewOp, 
4413                                       SI1->getOperand(1));
4414       }
4415   }
4416
4417   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4418     if (A == Op1)   // ~A | A == -1
4419       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4420   } else {
4421     A = 0;
4422   }
4423   // Note, A is still live here!
4424   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4425     if (Op0 == B)
4426       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4427
4428     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4429     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4430       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4431                                               I.getName()+".demorgan"), I);
4432       return BinaryOperator::createNot(And);
4433     }
4434   }
4435
4436   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4437   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4438     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4439       return R;
4440
4441     Value *LHSVal, *RHSVal;
4442     ConstantInt *LHSCst, *RHSCst;
4443     ICmpInst::Predicate LHSCC, RHSCC;
4444     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4445       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4446         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4447             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4448             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4449             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4450             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4451             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4452             // We can't fold (ugt x, C) | (sgt x, C2).
4453             PredicatesFoldable(LHSCC, RHSCC)) {
4454           // Ensure that the larger constant is on the RHS.
4455           ICmpInst *LHS = cast<ICmpInst>(Op0);
4456           bool NeedsSwap;
4457           if (ICmpInst::isSignedPredicate(LHSCC))
4458             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4459           else
4460             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4461             
4462           if (NeedsSwap) {
4463             std::swap(LHS, RHS);
4464             std::swap(LHSCst, RHSCst);
4465             std::swap(LHSCC, RHSCC);
4466           }
4467
4468           // At this point, we know we have have two icmp instructions
4469           // comparing a value against two constants and or'ing the result
4470           // together.  Because of the above check, we know that we only have
4471           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4472           // FoldICmpLogical check above), that the two constants are not
4473           // equal.
4474           assert(LHSCst != RHSCst && "Compares not folded above?");
4475
4476           switch (LHSCC) {
4477           default: assert(0 && "Unknown integer condition code!");
4478           case ICmpInst::ICMP_EQ:
4479             switch (RHSCC) {
4480             default: assert(0 && "Unknown integer condition code!");
4481             case ICmpInst::ICMP_EQ:
4482               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4483                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4484                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4485                                                       LHSVal->getName()+".off");
4486                 InsertNewInstBefore(Add, I);
4487                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4488                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4489               }
4490               break;                         // (X == 13 | X == 15) -> no change
4491             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4492             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4493               break;
4494             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4495             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4496             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4497               return ReplaceInstUsesWith(I, RHS);
4498             }
4499             break;
4500           case ICmpInst::ICMP_NE:
4501             switch (RHSCC) {
4502             default: assert(0 && "Unknown integer condition code!");
4503             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4504             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4505             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4506               return ReplaceInstUsesWith(I, LHS);
4507             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4508             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4509             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4510               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4511             }
4512             break;
4513           case ICmpInst::ICMP_ULT:
4514             switch (RHSCC) {
4515             default: assert(0 && "Unknown integer condition code!");
4516             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4517               break;
4518             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4519               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4520               // this can cause overflow.
4521               if (RHSCst->isMaxValue(false))
4522                 return ReplaceInstUsesWith(I, LHS);
4523               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4524                                      false, I);
4525             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4526               break;
4527             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4528             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4529               return ReplaceInstUsesWith(I, RHS);
4530             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4531               break;
4532             }
4533             break;
4534           case ICmpInst::ICMP_SLT:
4535             switch (RHSCC) {
4536             default: assert(0 && "Unknown integer condition code!");
4537             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4538               break;
4539             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4540               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4541               // this can cause overflow.
4542               if (RHSCst->isMaxValue(true))
4543                 return ReplaceInstUsesWith(I, LHS);
4544               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4545                                      false, I);
4546             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4547               break;
4548             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4549             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4550               return ReplaceInstUsesWith(I, RHS);
4551             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4552               break;
4553             }
4554             break;
4555           case ICmpInst::ICMP_UGT:
4556             switch (RHSCC) {
4557             default: assert(0 && "Unknown integer condition code!");
4558             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4559             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4560               return ReplaceInstUsesWith(I, LHS);
4561             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4562               break;
4563             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4564             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4565               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4566             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4567               break;
4568             }
4569             break;
4570           case ICmpInst::ICMP_SGT:
4571             switch (RHSCC) {
4572             default: assert(0 && "Unknown integer condition code!");
4573             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4574             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4575               return ReplaceInstUsesWith(I, LHS);
4576             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4577               break;
4578             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4579             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4580               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4581             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4582               break;
4583             }
4584             break;
4585           }
4586         }
4587   }
4588     
4589   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4590   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4591     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4592       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4593         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4594             !isa<ICmpInst>(Op1C->getOperand(0))) {
4595           const Type *SrcTy = Op0C->getOperand(0)->getType();
4596           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4597               // Only do this if the casts both really cause code to be
4598               // generated.
4599               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4600                                 I.getType(), TD) &&
4601               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4602                                 I.getType(), TD)) {
4603             Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4604                                                           Op1C->getOperand(0),
4605                                                           I.getName());
4606             InsertNewInstBefore(NewOp, I);
4607             return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4608           }
4609         }
4610       }
4611   }
4612   
4613     
4614   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4615   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4616     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4617       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4618           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4619           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4620         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4621           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4622             // If either of the constants are nans, then the whole thing returns
4623             // true.
4624             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4625               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4626             
4627             // Otherwise, no need to compare the two constants, compare the
4628             // rest.
4629             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4630                                 RHS->getOperand(0));
4631           }
4632     }
4633   }
4634
4635   return Changed ? &I : 0;
4636 }
4637
4638 // XorSelf - Implements: X ^ X --> 0
4639 struct XorSelf {
4640   Value *RHS;
4641   XorSelf(Value *rhs) : RHS(rhs) {}
4642   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4643   Instruction *apply(BinaryOperator &Xor) const {
4644     return &Xor;
4645   }
4646 };
4647
4648
4649 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4650   bool Changed = SimplifyCommutative(I);
4651   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4652
4653   if (isa<UndefValue>(Op1)) {
4654     if (isa<UndefValue>(Op0))
4655       // Handle undef ^ undef -> 0 special case. This is a common
4656       // idiom (misuse).
4657       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4658     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4659   }
4660
4661   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4662   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4663     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4664     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4665   }
4666   
4667   // See if we can simplify any instructions used by the instruction whose sole 
4668   // purpose is to compute bits we don't care about.
4669   if (!isa<VectorType>(I.getType())) {
4670     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4671     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4672     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4673                              KnownZero, KnownOne))
4674       return &I;
4675   } else if (isa<ConstantAggregateZero>(Op1)) {
4676     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4677   }
4678
4679   // Is this a ~ operation?
4680   if (Value *NotOp = dyn_castNotVal(&I)) {
4681     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4682     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4683     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4684       if (Op0I->getOpcode() == Instruction::And || 
4685           Op0I->getOpcode() == Instruction::Or) {
4686         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4687         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4688           Instruction *NotY =
4689             BinaryOperator::createNot(Op0I->getOperand(1),
4690                                       Op0I->getOperand(1)->getName()+".not");
4691           InsertNewInstBefore(NotY, I);
4692           if (Op0I->getOpcode() == Instruction::And)
4693             return BinaryOperator::createOr(Op0NotVal, NotY);
4694           else
4695             return BinaryOperator::createAnd(Op0NotVal, NotY);
4696         }
4697       }
4698     }
4699   }
4700   
4701   
4702   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4703     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4704     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4705       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4706         return new ICmpInst(ICI->getInversePredicate(),
4707                             ICI->getOperand(0), ICI->getOperand(1));
4708
4709       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4710         return new FCmpInst(FCI->getInversePredicate(),
4711                             FCI->getOperand(0), FCI->getOperand(1));
4712     }
4713
4714     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4715       // ~(c-X) == X-c-1 == X+(-c-1)
4716       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4717         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4718           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4719           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4720                                               ConstantInt::get(I.getType(), 1));
4721           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4722         }
4723           
4724       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4725         if (Op0I->getOpcode() == Instruction::Add) {
4726           // ~(X-c) --> (-c-1)-X
4727           if (RHS->isAllOnesValue()) {
4728             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4729             return BinaryOperator::createSub(
4730                            ConstantExpr::getSub(NegOp0CI,
4731                                              ConstantInt::get(I.getType(), 1)),
4732                                           Op0I->getOperand(0));
4733           } else if (RHS->getValue().isSignBit()) {
4734             // (X + C) ^ signbit -> (X + C + signbit)
4735             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4736             return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4737
4738           }
4739         } else if (Op0I->getOpcode() == Instruction::Or) {
4740           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4741           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4742             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4743             // Anything in both C1 and C2 is known to be zero, remove it from
4744             // NewRHS.
4745             Constant *CommonBits = And(Op0CI, RHS);
4746             NewRHS = ConstantExpr::getAnd(NewRHS, 
4747                                           ConstantExpr::getNot(CommonBits));
4748             AddToWorkList(Op0I);
4749             I.setOperand(0, Op0I->getOperand(0));
4750             I.setOperand(1, NewRHS);
4751             return &I;
4752           }
4753         }
4754       }
4755     }
4756
4757     // Try to fold constant and into select arguments.
4758     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4759       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4760         return R;
4761     if (isa<PHINode>(Op0))
4762       if (Instruction *NV = FoldOpIntoPhi(I))
4763         return NV;
4764   }
4765
4766   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4767     if (X == Op1)
4768       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4769
4770   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4771     if (X == Op0)
4772       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4773
4774   
4775   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4776   if (Op1I) {
4777     Value *A, *B;
4778     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4779       if (A == Op0) {              // B^(B|A) == (A|B)^B
4780         Op1I->swapOperands();
4781         I.swapOperands();
4782         std::swap(Op0, Op1);
4783       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4784         I.swapOperands();     // Simplified below.
4785         std::swap(Op0, Op1);
4786       }
4787     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4788       if (Op0 == A)                                          // A^(A^B) == B
4789         return ReplaceInstUsesWith(I, B);
4790       else if (Op0 == B)                                     // A^(B^A) == B
4791         return ReplaceInstUsesWith(I, A);
4792     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4793       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4794         Op1I->swapOperands();
4795         std::swap(A, B);
4796       }
4797       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4798         I.swapOperands();     // Simplified below.
4799         std::swap(Op0, Op1);
4800       }
4801     }
4802   }
4803   
4804   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4805   if (Op0I) {
4806     Value *A, *B;
4807     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4808       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4809         std::swap(A, B);
4810       if (B == Op1) {                                // (A|B)^B == A & ~B
4811         Instruction *NotB =
4812           InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4813         return BinaryOperator::createAnd(A, NotB);
4814       }
4815     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4816       if (Op1 == A)                                          // (A^B)^A == B
4817         return ReplaceInstUsesWith(I, B);
4818       else if (Op1 == B)                                     // (B^A)^A == B
4819         return ReplaceInstUsesWith(I, A);
4820     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4821       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4822         std::swap(A, B);
4823       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4824           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4825         Instruction *N =
4826           InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4827         return BinaryOperator::createAnd(N, Op1);
4828       }
4829     }
4830   }
4831   
4832   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4833   if (Op0I && Op1I && Op0I->isShift() && 
4834       Op0I->getOpcode() == Op1I->getOpcode() && 
4835       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4836       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4837     Instruction *NewOp =
4838       InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4839                                                     Op1I->getOperand(0),
4840                                                     Op0I->getName()), I);
4841     return BinaryOperator::create(Op1I->getOpcode(), NewOp, 
4842                                   Op1I->getOperand(1));
4843   }
4844     
4845   if (Op0I && Op1I) {
4846     Value *A, *B, *C, *D;
4847     // (A & B)^(A | B) -> A ^ B
4848     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4849         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4850       if ((A == C && B == D) || (A == D && B == C)) 
4851         return BinaryOperator::createXor(A, B);
4852     }
4853     // (A | B)^(A & B) -> A ^ B
4854     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4855         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4856       if ((A == C && B == D) || (A == D && B == C)) 
4857         return BinaryOperator::createXor(A, B);
4858     }
4859     
4860     // (A & B)^(C & D)
4861     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4862         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4863         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4864       // (X & Y)^(X & Y) -> (Y^Z) & X
4865       Value *X = 0, *Y = 0, *Z = 0;
4866       if (A == C)
4867         X = A, Y = B, Z = D;
4868       else if (A == D)
4869         X = A, Y = B, Z = C;
4870       else if (B == C)
4871         X = B, Y = A, Z = D;
4872       else if (B == D)
4873         X = B, Y = A, Z = C;
4874       
4875       if (X) {
4876         Instruction *NewOp =
4877         InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4878         return BinaryOperator::createAnd(NewOp, X);
4879       }
4880     }
4881   }
4882     
4883   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4884   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4885     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4886       return R;
4887
4888   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4889   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4890     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4891       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4892         const Type *SrcTy = Op0C->getOperand(0)->getType();
4893         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4894             // Only do this if the casts both really cause code to be generated.
4895             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4896                               I.getType(), TD) &&
4897             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4898                               I.getType(), TD)) {
4899           Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4900                                                          Op1C->getOperand(0),
4901                                                          I.getName());
4902           InsertNewInstBefore(NewOp, I);
4903           return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4904         }
4905       }
4906   }
4907   return Changed ? &I : 0;
4908 }
4909
4910 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4911 /// overflowed for this type.
4912 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4913                             ConstantInt *In2, bool IsSigned = false) {
4914   Result = cast<ConstantInt>(Add(In1, In2));
4915
4916   if (IsSigned)
4917     if (In2->getValue().isNegative())
4918       return Result->getValue().sgt(In1->getValue());
4919     else
4920       return Result->getValue().slt(In1->getValue());
4921   else
4922     return Result->getValue().ult(In1->getValue());
4923 }
4924
4925 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4926 /// code necessary to compute the offset from the base pointer (without adding
4927 /// in the base pointer).  Return the result as a signed integer of intptr size.
4928 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4929   TargetData &TD = IC.getTargetData();
4930   gep_type_iterator GTI = gep_type_begin(GEP);
4931   const Type *IntPtrTy = TD.getIntPtrType();
4932   Value *Result = Constant::getNullValue(IntPtrTy);
4933
4934   // Build a mask for high order bits.
4935   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4936   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4937
4938   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4939     Value *Op = GEP->getOperand(i);
4940     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4941     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4942       if (OpC->isZero()) continue;
4943       
4944       // Handle a struct index, which adds its field offset to the pointer.
4945       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4946         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4947         
4948         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4949           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4950         else
4951           Result = IC.InsertNewInstBefore(
4952                    BinaryOperator::createAdd(Result,
4953                                              ConstantInt::get(IntPtrTy, Size),
4954                                              GEP->getName()+".offs"), I);
4955         continue;
4956       }
4957       
4958       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4959       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4960       Scale = ConstantExpr::getMul(OC, Scale);
4961       if (Constant *RC = dyn_cast<Constant>(Result))
4962         Result = ConstantExpr::getAdd(RC, Scale);
4963       else {
4964         // Emit an add instruction.
4965         Result = IC.InsertNewInstBefore(
4966            BinaryOperator::createAdd(Result, Scale,
4967                                      GEP->getName()+".offs"), I);
4968       }
4969       continue;
4970     }
4971     // Convert to correct type.
4972     if (Op->getType() != IntPtrTy) {
4973       if (Constant *OpC = dyn_cast<Constant>(Op))
4974         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4975       else
4976         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4977                                                  Op->getName()+".c"), I);
4978     }
4979     if (Size != 1) {
4980       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4981       if (Constant *OpC = dyn_cast<Constant>(Op))
4982         Op = ConstantExpr::getMul(OpC, Scale);
4983       else    // We'll let instcombine(mul) convert this to a shl if possible.
4984         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4985                                                   GEP->getName()+".idx"), I);
4986     }
4987
4988     // Emit an add instruction.
4989     if (isa<Constant>(Op) && isa<Constant>(Result))
4990       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4991                                     cast<Constant>(Result));
4992     else
4993       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4994                                                   GEP->getName()+".offs"), I);
4995   }
4996   return Result;
4997 }
4998
4999
5000 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5001 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5002 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5003 /// complex, and scales are involved.  The above expression would also be legal
5004 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5005 /// later form is less amenable to optimization though, and we are allowed to
5006 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5007 ///
5008 /// If we can't emit an optimized form for this expression, this returns null.
5009 /// 
5010 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5011                                           InstCombiner &IC) {
5012   TargetData &TD = IC.getTargetData();
5013   gep_type_iterator GTI = gep_type_begin(GEP);
5014
5015   // Check to see if this gep only has a single variable index.  If so, and if
5016   // any constant indices are a multiple of its scale, then we can compute this
5017   // in terms of the scale of the variable index.  For example, if the GEP
5018   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5019   // because the expression will cross zero at the same point.
5020   unsigned i, e = GEP->getNumOperands();
5021   int64_t Offset = 0;
5022   for (i = 1; i != e; ++i, ++GTI) {
5023     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5024       // Compute the aggregate offset of constant indices.
5025       if (CI->isZero()) continue;
5026
5027       // Handle a struct index, which adds its field offset to the pointer.
5028       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5029         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5030       } else {
5031         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5032         Offset += Size*CI->getSExtValue();
5033       }
5034     } else {
5035       // Found our variable index.
5036       break;
5037     }
5038   }
5039   
5040   // If there are no variable indices, we must have a constant offset, just
5041   // evaluate it the general way.
5042   if (i == e) return 0;
5043   
5044   Value *VariableIdx = GEP->getOperand(i);
5045   // Determine the scale factor of the variable element.  For example, this is
5046   // 4 if the variable index is into an array of i32.
5047   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5048   
5049   // Verify that there are no other variable indices.  If so, emit the hard way.
5050   for (++i, ++GTI; i != e; ++i, ++GTI) {
5051     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5052     if (!CI) return 0;
5053    
5054     // Compute the aggregate offset of constant indices.
5055     if (CI->isZero()) continue;
5056     
5057     // Handle a struct index, which adds its field offset to the pointer.
5058     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5059       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5060     } else {
5061       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5062       Offset += Size*CI->getSExtValue();
5063     }
5064   }
5065   
5066   // Okay, we know we have a single variable index, which must be a
5067   // pointer/array/vector index.  If there is no offset, life is simple, return
5068   // the index.
5069   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5070   if (Offset == 0) {
5071     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5072     // we don't need to bother extending: the extension won't affect where the
5073     // computation crosses zero.
5074     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5075       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5076                                   VariableIdx->getNameStart(), &I);
5077     return VariableIdx;
5078   }
5079   
5080   // Otherwise, there is an index.  The computation we will do will be modulo
5081   // the pointer size, so get it.
5082   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5083   
5084   Offset &= PtrSizeMask;
5085   VariableScale &= PtrSizeMask;
5086
5087   // To do this transformation, any constant index must be a multiple of the
5088   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5089   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5090   // multiple of the variable scale.
5091   int64_t NewOffs = Offset / (int64_t)VariableScale;
5092   if (Offset != NewOffs*(int64_t)VariableScale)
5093     return 0;
5094
5095   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5096   const Type *IntPtrTy = TD.getIntPtrType();
5097   if (VariableIdx->getType() != IntPtrTy)
5098     VariableIdx = CastInst::createIntegerCast(VariableIdx, IntPtrTy,
5099                                               true /*SExt*/, 
5100                                               VariableIdx->getNameStart(), &I);
5101   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5102   return BinaryOperator::createAdd(VariableIdx, OffsetVal, "offset", &I);
5103 }
5104
5105
5106 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5107 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5108 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5109                                        ICmpInst::Predicate Cond,
5110                                        Instruction &I) {
5111   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5112
5113   // Look through bitcasts.
5114   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5115     RHS = BCI->getOperand(0);
5116
5117   Value *PtrBase = GEPLHS->getOperand(0);
5118   if (PtrBase == RHS) {
5119     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5120     // This transformation (ignoring the base and scales) is valid because we
5121     // know pointers can't overflow.  See if we can output an optimized form.
5122     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5123     
5124     // If not, synthesize the offset the hard way.
5125     if (Offset == 0)
5126       Offset = EmitGEPOffset(GEPLHS, I, *this);
5127     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5128                         Constant::getNullValue(Offset->getType()));
5129   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5130     // If the base pointers are different, but the indices are the same, just
5131     // compare the base pointer.
5132     if (PtrBase != GEPRHS->getOperand(0)) {
5133       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5134       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5135                         GEPRHS->getOperand(0)->getType();
5136       if (IndicesTheSame)
5137         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5138           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5139             IndicesTheSame = false;
5140             break;
5141           }
5142
5143       // If all indices are the same, just compare the base pointers.
5144       if (IndicesTheSame)
5145         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5146                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5147
5148       // Otherwise, the base pointers are different and the indices are
5149       // different, bail out.
5150       return 0;
5151     }
5152
5153     // If one of the GEPs has all zero indices, recurse.
5154     bool AllZeros = true;
5155     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5156       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5157           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5158         AllZeros = false;
5159         break;
5160       }
5161     if (AllZeros)
5162       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5163                           ICmpInst::getSwappedPredicate(Cond), I);
5164
5165     // If the other GEP has all zero indices, recurse.
5166     AllZeros = true;
5167     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5168       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5169           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5170         AllZeros = false;
5171         break;
5172       }
5173     if (AllZeros)
5174       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5175
5176     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5177       // If the GEPs only differ by one index, compare it.
5178       unsigned NumDifferences = 0;  // Keep track of # differences.
5179       unsigned DiffOperand = 0;     // The operand that differs.
5180       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5181         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5182           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5183                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5184             // Irreconcilable differences.
5185             NumDifferences = 2;
5186             break;
5187           } else {
5188             if (NumDifferences++) break;
5189             DiffOperand = i;
5190           }
5191         }
5192
5193       if (NumDifferences == 0)   // SAME GEP?
5194         return ReplaceInstUsesWith(I, // No comparison is needed here.
5195                                    ConstantInt::get(Type::Int1Ty,
5196                                                     isTrueWhenEqual(Cond)));
5197
5198       else if (NumDifferences == 1) {
5199         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5200         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5201         // Make sure we do a signed comparison here.
5202         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5203       }
5204     }
5205
5206     // Only lower this if the icmp is the only user of the GEP or if we expect
5207     // the result to fold to a constant!
5208     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5209         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5210       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5211       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5212       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5213       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5214     }
5215   }
5216   return 0;
5217 }
5218
5219 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5220   bool Changed = SimplifyCompare(I);
5221   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5222
5223   // Fold trivial predicates.
5224   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5225     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5226   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5227     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5228   
5229   // Simplify 'fcmp pred X, X'
5230   if (Op0 == Op1) {
5231     switch (I.getPredicate()) {
5232     default: assert(0 && "Unknown predicate!");
5233     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5234     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5235     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5236       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5237     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5238     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5239     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5240       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5241       
5242     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5243     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5244     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5245     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5246       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5247       I.setPredicate(FCmpInst::FCMP_UNO);
5248       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5249       return &I;
5250       
5251     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5252     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5253     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5254     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5255       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5256       I.setPredicate(FCmpInst::FCMP_ORD);
5257       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5258       return &I;
5259     }
5260   }
5261     
5262   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5263     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5264
5265   // Handle fcmp with constant RHS
5266   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5267     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5268       switch (LHSI->getOpcode()) {
5269       case Instruction::PHI:
5270         if (Instruction *NV = FoldOpIntoPhi(I))
5271           return NV;
5272         break;
5273       case Instruction::Select:
5274         // If either operand of the select is a constant, we can fold the
5275         // comparison into the select arms, which will cause one to be
5276         // constant folded and the select turned into a bitwise or.
5277         Value *Op1 = 0, *Op2 = 0;
5278         if (LHSI->hasOneUse()) {
5279           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5280             // Fold the known value into the constant operand.
5281             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5282             // Insert a new FCmp of the other select operand.
5283             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5284                                                       LHSI->getOperand(2), RHSC,
5285                                                       I.getName()), I);
5286           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5287             // Fold the known value into the constant operand.
5288             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5289             // Insert a new FCmp of the other select operand.
5290             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5291                                                       LHSI->getOperand(1), RHSC,
5292                                                       I.getName()), I);
5293           }
5294         }
5295
5296         if (Op1)
5297           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5298         break;
5299       }
5300   }
5301
5302   return Changed ? &I : 0;
5303 }
5304
5305 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5306   bool Changed = SimplifyCompare(I);
5307   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5308   const Type *Ty = Op0->getType();
5309
5310   // icmp X, X
5311   if (Op0 == Op1)
5312     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5313                                                    isTrueWhenEqual(I)));
5314
5315   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5316     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5317   
5318   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5319   // addresses never equal each other!  We already know that Op0 != Op1.
5320   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5321        isa<ConstantPointerNull>(Op0)) &&
5322       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5323        isa<ConstantPointerNull>(Op1)))
5324     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5325                                                    !isTrueWhenEqual(I)));
5326
5327   // icmp's with boolean values can always be turned into bitwise operations
5328   if (Ty == Type::Int1Ty) {
5329     switch (I.getPredicate()) {
5330     default: assert(0 && "Invalid icmp instruction!");
5331     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5332       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
5333       InsertNewInstBefore(Xor, I);
5334       return BinaryOperator::createNot(Xor);
5335     }
5336     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5337       return BinaryOperator::createXor(Op0, Op1);
5338
5339     case ICmpInst::ICMP_UGT:
5340     case ICmpInst::ICMP_SGT:
5341       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5342       // FALL THROUGH
5343     case ICmpInst::ICMP_ULT:
5344     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5345       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5346       InsertNewInstBefore(Not, I);
5347       return BinaryOperator::createAnd(Not, Op1);
5348     }
5349     case ICmpInst::ICMP_UGE:
5350     case ICmpInst::ICMP_SGE:
5351       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5352       // FALL THROUGH
5353     case ICmpInst::ICMP_ULE:
5354     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5355       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5356       InsertNewInstBefore(Not, I);
5357       return BinaryOperator::createOr(Not, Op1);
5358     }
5359     }
5360   }
5361
5362   // See if we are doing a comparison between a constant and an instruction that
5363   // can be folded into the comparison.
5364   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5365       Value *A, *B;
5366     
5367     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5368     if (I.isEquality() && CI->isNullValue() &&
5369         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5370       // (icmp cond A B) if cond is equality
5371       return new ICmpInst(I.getPredicate(), A, B);
5372     }
5373     
5374     switch (I.getPredicate()) {
5375     default: break;
5376     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5377       if (CI->isMinValue(false))
5378         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5379       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5380         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5381       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5382         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5383       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5384       if (CI->isMinValue(true))
5385         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5386                             ConstantInt::getAllOnesValue(Op0->getType()));
5387           
5388       break;
5389
5390     case ICmpInst::ICMP_SLT:
5391       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5392         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5393       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5394         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5395       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5396         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5397       break;
5398
5399     case ICmpInst::ICMP_UGT:
5400       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5401         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5402       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5403         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5404       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5405         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5406         
5407       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5408       if (CI->isMaxValue(true))
5409         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5410                             ConstantInt::getNullValue(Op0->getType()));
5411       break;
5412
5413     case ICmpInst::ICMP_SGT:
5414       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5415         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5416       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5417         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5418       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5419         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5420       break;
5421
5422     case ICmpInst::ICMP_ULE:
5423       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5424         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5425       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5426         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5427       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5428         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5429       break;
5430
5431     case ICmpInst::ICMP_SLE:
5432       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5433         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5434       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5435         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5436       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5437         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5438       break;
5439
5440     case ICmpInst::ICMP_UGE:
5441       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5442         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5443       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5444         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5445       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5446         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5447       break;
5448
5449     case ICmpInst::ICMP_SGE:
5450       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5451         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5452       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5453         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5454       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5455         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5456       break;
5457     }
5458
5459     // If we still have a icmp le or icmp ge instruction, turn it into the
5460     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5461     // already been handled above, this requires little checking.
5462     //
5463     switch (I.getPredicate()) {
5464     default: break;
5465     case ICmpInst::ICMP_ULE: 
5466       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5467     case ICmpInst::ICMP_SLE:
5468       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5469     case ICmpInst::ICMP_UGE:
5470       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5471     case ICmpInst::ICMP_SGE:
5472       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5473     }
5474     
5475     // See if we can fold the comparison based on bits known to be zero or one
5476     // in the input.  If this comparison is a normal comparison, it demands all
5477     // bits, if it is a sign bit comparison, it only demands the sign bit.
5478     
5479     bool UnusedBit;
5480     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5481     
5482     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5483     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5484     if (SimplifyDemandedBits(Op0, 
5485                              isSignBit ? APInt::getSignBit(BitWidth)
5486                                        : APInt::getAllOnesValue(BitWidth),
5487                              KnownZero, KnownOne, 0))
5488       return &I;
5489         
5490     // Given the known and unknown bits, compute a range that the LHS could be
5491     // in.
5492     if ((KnownOne | KnownZero) != 0) {
5493       // Compute the Min, Max and RHS values based on the known bits. For the
5494       // EQ and NE we use unsigned values.
5495       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5496       const APInt& RHSVal = CI->getValue();
5497       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5498         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5499                                                Max);
5500       } else {
5501         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5502                                                  Max);
5503       }
5504       switch (I.getPredicate()) {  // LE/GE have been folded already.
5505       default: assert(0 && "Unknown icmp opcode!");
5506       case ICmpInst::ICMP_EQ:
5507         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5508           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5509         break;
5510       case ICmpInst::ICMP_NE:
5511         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5512           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5513         break;
5514       case ICmpInst::ICMP_ULT:
5515         if (Max.ult(RHSVal))
5516           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5517         if (Min.uge(RHSVal))
5518           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5519         break;
5520       case ICmpInst::ICMP_UGT:
5521         if (Min.ugt(RHSVal))
5522           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5523         if (Max.ule(RHSVal))
5524           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5525         break;
5526       case ICmpInst::ICMP_SLT:
5527         if (Max.slt(RHSVal))
5528           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5529         if (Min.sgt(RHSVal))
5530           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5531         break;
5532       case ICmpInst::ICMP_SGT: 
5533         if (Min.sgt(RHSVal))
5534           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5535         if (Max.sle(RHSVal))
5536           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5537         break;
5538       }
5539     }
5540           
5541     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5542     // instruction, see if that instruction also has constants so that the 
5543     // instruction can be folded into the icmp 
5544     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5545       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5546         return Res;
5547   }
5548
5549   // Handle icmp with constant (but not simple integer constant) RHS
5550   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5551     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5552       switch (LHSI->getOpcode()) {
5553       case Instruction::GetElementPtr:
5554         if (RHSC->isNullValue()) {
5555           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5556           bool isAllZeros = true;
5557           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5558             if (!isa<Constant>(LHSI->getOperand(i)) ||
5559                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5560               isAllZeros = false;
5561               break;
5562             }
5563           if (isAllZeros)
5564             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5565                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5566         }
5567         break;
5568
5569       case Instruction::PHI:
5570         if (Instruction *NV = FoldOpIntoPhi(I))
5571           return NV;
5572         break;
5573       case Instruction::Select: {
5574         // If either operand of the select is a constant, we can fold the
5575         // comparison into the select arms, which will cause one to be
5576         // constant folded and the select turned into a bitwise or.
5577         Value *Op1 = 0, *Op2 = 0;
5578         if (LHSI->hasOneUse()) {
5579           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5580             // Fold the known value into the constant operand.
5581             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5582             // Insert a new ICmp of the other select operand.
5583             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5584                                                    LHSI->getOperand(2), RHSC,
5585                                                    I.getName()), I);
5586           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5587             // Fold the known value into the constant operand.
5588             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5589             // Insert a new ICmp of the other select operand.
5590             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5591                                                    LHSI->getOperand(1), RHSC,
5592                                                    I.getName()), I);
5593           }
5594         }
5595
5596         if (Op1)
5597           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5598         break;
5599       }
5600       case Instruction::Malloc:
5601         // If we have (malloc != null), and if the malloc has a single use, we
5602         // can assume it is successful and remove the malloc.
5603         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5604           AddToWorkList(LHSI);
5605           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5606                                                          !isTrueWhenEqual(I)));
5607         }
5608         break;
5609       }
5610   }
5611
5612   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5613   if (User *GEP = dyn_castGetElementPtr(Op0))
5614     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5615       return NI;
5616   if (User *GEP = dyn_castGetElementPtr(Op1))
5617     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5618                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5619       return NI;
5620
5621   // Test to see if the operands of the icmp are casted versions of other
5622   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5623   // now.
5624   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5625     if (isa<PointerType>(Op0->getType()) && 
5626         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5627       // We keep moving the cast from the left operand over to the right
5628       // operand, where it can often be eliminated completely.
5629       Op0 = CI->getOperand(0);
5630
5631       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5632       // so eliminate it as well.
5633       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5634         Op1 = CI2->getOperand(0);
5635
5636       // If Op1 is a constant, we can fold the cast into the constant.
5637       if (Op0->getType() != Op1->getType()) {
5638         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5639           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5640         } else {
5641           // Otherwise, cast the RHS right before the icmp
5642           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5643         }
5644       }
5645       return new ICmpInst(I.getPredicate(), Op0, Op1);
5646     }
5647   }
5648   
5649   if (isa<CastInst>(Op0)) {
5650     // Handle the special case of: icmp (cast bool to X), <cst>
5651     // This comes up when you have code like
5652     //   int X = A < B;
5653     //   if (X) ...
5654     // For generality, we handle any zero-extension of any operand comparison
5655     // with a constant or another cast from the same type.
5656     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5657       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5658         return R;
5659   }
5660   
5661   if (I.isEquality()) {
5662     Value *A, *B, *C, *D;
5663     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5664       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5665         Value *OtherVal = A == Op1 ? B : A;
5666         return new ICmpInst(I.getPredicate(), OtherVal,
5667                             Constant::getNullValue(A->getType()));
5668       }
5669
5670       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5671         // A^c1 == C^c2 --> A == C^(c1^c2)
5672         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5673           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5674             if (Op1->hasOneUse()) {
5675               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5676               Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5677               return new ICmpInst(I.getPredicate(), A,
5678                                   InsertNewInstBefore(Xor, I));
5679             }
5680         
5681         // A^B == A^D -> B == D
5682         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5683         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5684         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5685         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5686       }
5687     }
5688     
5689     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5690         (A == Op0 || B == Op0)) {
5691       // A == (A^B)  ->  B == 0
5692       Value *OtherVal = A == Op0 ? B : A;
5693       return new ICmpInst(I.getPredicate(), OtherVal,
5694                           Constant::getNullValue(A->getType()));
5695     }
5696     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5697       // (A-B) == A  ->  B == 0
5698       return new ICmpInst(I.getPredicate(), B,
5699                           Constant::getNullValue(B->getType()));
5700     }
5701     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5702       // A == (A-B)  ->  B == 0
5703       return new ICmpInst(I.getPredicate(), B,
5704                           Constant::getNullValue(B->getType()));
5705     }
5706     
5707     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5708     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5709         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5710         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5711       Value *X = 0, *Y = 0, *Z = 0;
5712       
5713       if (A == C) {
5714         X = B; Y = D; Z = A;
5715       } else if (A == D) {
5716         X = B; Y = C; Z = A;
5717       } else if (B == C) {
5718         X = A; Y = D; Z = B;
5719       } else if (B == D) {
5720         X = A; Y = C; Z = B;
5721       }
5722       
5723       if (X) {   // Build (X^Y) & Z
5724         Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5725         Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5726         I.setOperand(0, Op1);
5727         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5728         return &I;
5729       }
5730     }
5731   }
5732   return Changed ? &I : 0;
5733 }
5734
5735
5736 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5737 /// and CmpRHS are both known to be integer constants.
5738 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5739                                           ConstantInt *DivRHS) {
5740   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5741   const APInt &CmpRHSV = CmpRHS->getValue();
5742   
5743   // FIXME: If the operand types don't match the type of the divide 
5744   // then don't attempt this transform. The code below doesn't have the
5745   // logic to deal with a signed divide and an unsigned compare (and
5746   // vice versa). This is because (x /s C1) <s C2  produces different 
5747   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5748   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5749   // work. :(  The if statement below tests that condition and bails 
5750   // if it finds it. 
5751   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5752   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5753     return 0;
5754   if (DivRHS->isZero())
5755     return 0; // The ProdOV computation fails on divide by zero.
5756
5757   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5758   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5759   // C2 (CI). By solving for X we can turn this into a range check 
5760   // instead of computing a divide. 
5761   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5762
5763   // Determine if the product overflows by seeing if the product is
5764   // not equal to the divide. Make sure we do the same kind of divide
5765   // as in the LHS instruction that we're folding. 
5766   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5767                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5768
5769   // Get the ICmp opcode
5770   ICmpInst::Predicate Pred = ICI.getPredicate();
5771
5772   // Figure out the interval that is being checked.  For example, a comparison
5773   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5774   // Compute this interval based on the constants involved and the signedness of
5775   // the compare/divide.  This computes a half-open interval, keeping track of
5776   // whether either value in the interval overflows.  After analysis each
5777   // overflow variable is set to 0 if it's corresponding bound variable is valid
5778   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5779   int LoOverflow = 0, HiOverflow = 0;
5780   ConstantInt *LoBound = 0, *HiBound = 0;
5781   
5782   
5783   if (!DivIsSigned) {  // udiv
5784     // e.g. X/5 op 3  --> [15, 20)
5785     LoBound = Prod;
5786     HiOverflow = LoOverflow = ProdOV;
5787     if (!HiOverflow)
5788       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5789   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5790     if (CmpRHSV == 0) {       // (X / pos) op 0
5791       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5792       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5793       HiBound = DivRHS;
5794     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5795       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5796       HiOverflow = LoOverflow = ProdOV;
5797       if (!HiOverflow)
5798         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5799     } else {                       // (X / pos) op neg
5800       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5801       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5802       LoOverflow = AddWithOverflow(LoBound, Prod,
5803                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5804       HiBound = AddOne(Prod);
5805       HiOverflow = ProdOV ? -1 : 0;
5806     }
5807   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5808     if (CmpRHSV == 0) {       // (X / neg) op 0
5809       // e.g. X/-5 op 0  --> [-4, 5)
5810       LoBound = AddOne(DivRHS);
5811       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5812       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5813         HiOverflow = 1;            // [INTMIN+1, overflow)
5814         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5815       }
5816     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5817       // e.g. X/-5 op 3  --> [-19, -14)
5818       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5819       if (!LoOverflow)
5820         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5821       HiBound = AddOne(Prod);
5822     } else {                       // (X / neg) op neg
5823       // e.g. X/-5 op -3  --> [15, 20)
5824       LoBound = Prod;
5825       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5826       HiBound = Subtract(Prod, DivRHS);
5827     }
5828     
5829     // Dividing by a negative swaps the condition.  LT <-> GT
5830     Pred = ICmpInst::getSwappedPredicate(Pred);
5831   }
5832
5833   Value *X = DivI->getOperand(0);
5834   switch (Pred) {
5835   default: assert(0 && "Unhandled icmp opcode!");
5836   case ICmpInst::ICMP_EQ:
5837     if (LoOverflow && HiOverflow)
5838       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5839     else if (HiOverflow)
5840       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5841                           ICmpInst::ICMP_UGE, X, LoBound);
5842     else if (LoOverflow)
5843       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5844                           ICmpInst::ICMP_ULT, X, HiBound);
5845     else
5846       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5847   case ICmpInst::ICMP_NE:
5848     if (LoOverflow && HiOverflow)
5849       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5850     else if (HiOverflow)
5851       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5852                           ICmpInst::ICMP_ULT, X, LoBound);
5853     else if (LoOverflow)
5854       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5855                           ICmpInst::ICMP_UGE, X, HiBound);
5856     else
5857       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5858   case ICmpInst::ICMP_ULT:
5859   case ICmpInst::ICMP_SLT:
5860     if (LoOverflow == +1)   // Low bound is greater than input range.
5861       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5862     if (LoOverflow == -1)   // Low bound is less than input range.
5863       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5864     return new ICmpInst(Pred, X, LoBound);
5865   case ICmpInst::ICMP_UGT:
5866   case ICmpInst::ICMP_SGT:
5867     if (HiOverflow == +1)       // High bound greater than input range.
5868       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5869     else if (HiOverflow == -1)  // High bound less than input range.
5870       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5871     if (Pred == ICmpInst::ICMP_UGT)
5872       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5873     else
5874       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5875   }
5876 }
5877
5878
5879 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5880 ///
5881 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5882                                                           Instruction *LHSI,
5883                                                           ConstantInt *RHS) {
5884   const APInt &RHSV = RHS->getValue();
5885   
5886   switch (LHSI->getOpcode()) {
5887   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5888     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5889       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5890       // fold the xor.
5891       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5892           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5893         Value *CompareVal = LHSI->getOperand(0);
5894         
5895         // If the sign bit of the XorCST is not set, there is no change to
5896         // the operation, just stop using the Xor.
5897         if (!XorCST->getValue().isNegative()) {
5898           ICI.setOperand(0, CompareVal);
5899           AddToWorkList(LHSI);
5900           return &ICI;
5901         }
5902         
5903         // Was the old condition true if the operand is positive?
5904         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5905         
5906         // If so, the new one isn't.
5907         isTrueIfPositive ^= true;
5908         
5909         if (isTrueIfPositive)
5910           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5911         else
5912           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5913       }
5914     }
5915     break;
5916   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5917     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5918         LHSI->getOperand(0)->hasOneUse()) {
5919       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5920       
5921       // If the LHS is an AND of a truncating cast, we can widen the
5922       // and/compare to be the input width without changing the value
5923       // produced, eliminating a cast.
5924       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5925         // We can do this transformation if either the AND constant does not
5926         // have its sign bit set or if it is an equality comparison. 
5927         // Extending a relational comparison when we're checking the sign
5928         // bit would not work.
5929         if (Cast->hasOneUse() &&
5930             (ICI.isEquality() ||
5931              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5932           uint32_t BitWidth = 
5933             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5934           APInt NewCST = AndCST->getValue();
5935           NewCST.zext(BitWidth);
5936           APInt NewCI = RHSV;
5937           NewCI.zext(BitWidth);
5938           Instruction *NewAnd = 
5939             BinaryOperator::createAnd(Cast->getOperand(0),
5940                                       ConstantInt::get(NewCST),LHSI->getName());
5941           InsertNewInstBefore(NewAnd, ICI);
5942           return new ICmpInst(ICI.getPredicate(), NewAnd,
5943                               ConstantInt::get(NewCI));
5944         }
5945       }
5946       
5947       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5948       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5949       // happens a LOT in code produced by the C front-end, for bitfield
5950       // access.
5951       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5952       if (Shift && !Shift->isShift())
5953         Shift = 0;
5954       
5955       ConstantInt *ShAmt;
5956       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5957       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5958       const Type *AndTy = AndCST->getType();          // Type of the and.
5959       
5960       // We can fold this as long as we can't shift unknown bits
5961       // into the mask.  This can only happen with signed shift
5962       // rights, as they sign-extend.
5963       if (ShAmt) {
5964         bool CanFold = Shift->isLogicalShift();
5965         if (!CanFold) {
5966           // To test for the bad case of the signed shr, see if any
5967           // of the bits shifted in could be tested after the mask.
5968           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5969           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5970           
5971           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5972           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5973                AndCST->getValue()) == 0)
5974             CanFold = true;
5975         }
5976         
5977         if (CanFold) {
5978           Constant *NewCst;
5979           if (Shift->getOpcode() == Instruction::Shl)
5980             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5981           else
5982             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5983           
5984           // Check to see if we are shifting out any of the bits being
5985           // compared.
5986           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5987             // If we shifted bits out, the fold is not going to work out.
5988             // As a special case, check to see if this means that the
5989             // result is always true or false now.
5990             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5991               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5992             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5993               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5994           } else {
5995             ICI.setOperand(1, NewCst);
5996             Constant *NewAndCST;
5997             if (Shift->getOpcode() == Instruction::Shl)
5998               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5999             else
6000               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6001             LHSI->setOperand(1, NewAndCST);
6002             LHSI->setOperand(0, Shift->getOperand(0));
6003             AddToWorkList(Shift); // Shift is dead.
6004             AddUsesToWorkList(ICI);
6005             return &ICI;
6006           }
6007         }
6008       }
6009       
6010       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6011       // preferable because it allows the C<<Y expression to be hoisted out
6012       // of a loop if Y is invariant and X is not.
6013       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6014           ICI.isEquality() && !Shift->isArithmeticShift() &&
6015           isa<Instruction>(Shift->getOperand(0))) {
6016         // Compute C << Y.
6017         Value *NS;
6018         if (Shift->getOpcode() == Instruction::LShr) {
6019           NS = BinaryOperator::createShl(AndCST, 
6020                                          Shift->getOperand(1), "tmp");
6021         } else {
6022           // Insert a logical shift.
6023           NS = BinaryOperator::createLShr(AndCST,
6024                                           Shift->getOperand(1), "tmp");
6025         }
6026         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6027         
6028         // Compute X & (C << Y).
6029         Instruction *NewAnd = 
6030           BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
6031         InsertNewInstBefore(NewAnd, ICI);
6032         
6033         ICI.setOperand(0, NewAnd);
6034         return &ICI;
6035       }
6036     }
6037     break;
6038     
6039   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6040     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6041     if (!ShAmt) break;
6042     
6043     uint32_t TypeBits = RHSV.getBitWidth();
6044     
6045     // Check that the shift amount is in range.  If not, don't perform
6046     // undefined shifts.  When the shift is visited it will be
6047     // simplified.
6048     if (ShAmt->uge(TypeBits))
6049       break;
6050     
6051     if (ICI.isEquality()) {
6052       // If we are comparing against bits always shifted out, the
6053       // comparison cannot succeed.
6054       Constant *Comp =
6055         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6056       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6057         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6058         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6059         return ReplaceInstUsesWith(ICI, Cst);
6060       }
6061       
6062       if (LHSI->hasOneUse()) {
6063         // Otherwise strength reduce the shift into an and.
6064         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6065         Constant *Mask =
6066           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6067         
6068         Instruction *AndI =
6069           BinaryOperator::createAnd(LHSI->getOperand(0),
6070                                     Mask, LHSI->getName()+".mask");
6071         Value *And = InsertNewInstBefore(AndI, ICI);
6072         return new ICmpInst(ICI.getPredicate(), And,
6073                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6074       }
6075     }
6076     
6077     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6078     bool TrueIfSigned = false;
6079     if (LHSI->hasOneUse() &&
6080         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6081       // (X << 31) <s 0  --> (X&1) != 0
6082       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6083                                            (TypeBits-ShAmt->getZExtValue()-1));
6084       Instruction *AndI =
6085         BinaryOperator::createAnd(LHSI->getOperand(0),
6086                                   Mask, LHSI->getName()+".mask");
6087       Value *And = InsertNewInstBefore(AndI, ICI);
6088       
6089       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6090                           And, Constant::getNullValue(And->getType()));
6091     }
6092     break;
6093   }
6094     
6095   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6096   case Instruction::AShr: {
6097     // Only handle equality comparisons of shift-by-constant.
6098     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6099     if (!ShAmt || !ICI.isEquality()) break;
6100
6101     // Check that the shift amount is in range.  If not, don't perform
6102     // undefined shifts.  When the shift is visited it will be
6103     // simplified.
6104     uint32_t TypeBits = RHSV.getBitWidth();
6105     if (ShAmt->uge(TypeBits))
6106       break;
6107     
6108     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6109       
6110     // If we are comparing against bits always shifted out, the
6111     // comparison cannot succeed.
6112     APInt Comp = RHSV << ShAmtVal;
6113     if (LHSI->getOpcode() == Instruction::LShr)
6114       Comp = Comp.lshr(ShAmtVal);
6115     else
6116       Comp = Comp.ashr(ShAmtVal);
6117     
6118     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6119       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6120       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6121       return ReplaceInstUsesWith(ICI, Cst);
6122     }
6123     
6124     // Otherwise, check to see if the bits shifted out are known to be zero.
6125     // If so, we can compare against the unshifted value:
6126     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6127     if (LHSI->hasOneUse() &&
6128         MaskedValueIsZero(LHSI->getOperand(0), 
6129                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6130       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6131                           ConstantExpr::getShl(RHS, ShAmt));
6132     }
6133       
6134     if (LHSI->hasOneUse()) {
6135       // Otherwise strength reduce the shift into an and.
6136       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6137       Constant *Mask = ConstantInt::get(Val);
6138       
6139       Instruction *AndI =
6140         BinaryOperator::createAnd(LHSI->getOperand(0),
6141                                   Mask, LHSI->getName()+".mask");
6142       Value *And = InsertNewInstBefore(AndI, ICI);
6143       return new ICmpInst(ICI.getPredicate(), And,
6144                           ConstantExpr::getShl(RHS, ShAmt));
6145     }
6146     break;
6147   }
6148     
6149   case Instruction::SDiv:
6150   case Instruction::UDiv:
6151     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6152     // Fold this div into the comparison, producing a range check. 
6153     // Determine, based on the divide type, what the range is being 
6154     // checked.  If there is an overflow on the low or high side, remember 
6155     // it, otherwise compute the range [low, hi) bounding the new value.
6156     // See: InsertRangeTest above for the kinds of replacements possible.
6157     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6158       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6159                                           DivRHS))
6160         return R;
6161     break;
6162
6163   case Instruction::Add:
6164     // Fold: icmp pred (add, X, C1), C2
6165
6166     if (!ICI.isEquality()) {
6167       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6168       if (!LHSC) break;
6169       const APInt &LHSV = LHSC->getValue();
6170
6171       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6172                             .subtract(LHSV);
6173
6174       if (ICI.isSignedPredicate()) {
6175         if (CR.getLower().isSignBit()) {
6176           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6177                               ConstantInt::get(CR.getUpper()));
6178         } else if (CR.getUpper().isSignBit()) {
6179           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6180                               ConstantInt::get(CR.getLower()));
6181         }
6182       } else {
6183         if (CR.getLower().isMinValue()) {
6184           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6185                               ConstantInt::get(CR.getUpper()));
6186         } else if (CR.getUpper().isMinValue()) {
6187           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6188                               ConstantInt::get(CR.getLower()));
6189         }
6190       }
6191     }
6192     break;
6193   }
6194   
6195   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6196   if (ICI.isEquality()) {
6197     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6198     
6199     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6200     // the second operand is a constant, simplify a bit.
6201     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6202       switch (BO->getOpcode()) {
6203       case Instruction::SRem:
6204         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6205         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6206           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6207           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6208             Instruction *NewRem =
6209               BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
6210                                          BO->getName());
6211             InsertNewInstBefore(NewRem, ICI);
6212             return new ICmpInst(ICI.getPredicate(), NewRem, 
6213                                 Constant::getNullValue(BO->getType()));
6214           }
6215         }
6216         break;
6217       case Instruction::Add:
6218         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6219         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6220           if (BO->hasOneUse())
6221             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6222                                 Subtract(RHS, BOp1C));
6223         } else if (RHSV == 0) {
6224           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6225           // efficiently invertible, or if the add has just this one use.
6226           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6227           
6228           if (Value *NegVal = dyn_castNegVal(BOp1))
6229             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6230           else if (Value *NegVal = dyn_castNegVal(BOp0))
6231             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6232           else if (BO->hasOneUse()) {
6233             Instruction *Neg = BinaryOperator::createNeg(BOp1);
6234             InsertNewInstBefore(Neg, ICI);
6235             Neg->takeName(BO);
6236             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6237           }
6238         }
6239         break;
6240       case Instruction::Xor:
6241         // For the xor case, we can xor two constants together, eliminating
6242         // the explicit xor.
6243         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6244           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6245                               ConstantExpr::getXor(RHS, BOC));
6246         
6247         // FALLTHROUGH
6248       case Instruction::Sub:
6249         // Replace (([sub|xor] A, B) != 0) with (A != B)
6250         if (RHSV == 0)
6251           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6252                               BO->getOperand(1));
6253         break;
6254         
6255       case Instruction::Or:
6256         // If bits are being or'd in that are not present in the constant we
6257         // are comparing against, then the comparison could never succeed!
6258         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6259           Constant *NotCI = ConstantExpr::getNot(RHS);
6260           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6261             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6262                                                              isICMP_NE));
6263         }
6264         break;
6265         
6266       case Instruction::And:
6267         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6268           // If bits are being compared against that are and'd out, then the
6269           // comparison can never succeed!
6270           if ((RHSV & ~BOC->getValue()) != 0)
6271             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6272                                                              isICMP_NE));
6273           
6274           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6275           if (RHS == BOC && RHSV.isPowerOf2())
6276             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6277                                 ICmpInst::ICMP_NE, LHSI,
6278                                 Constant::getNullValue(RHS->getType()));
6279           
6280           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6281           if (isSignBit(BOC)) {
6282             Value *X = BO->getOperand(0);
6283             Constant *Zero = Constant::getNullValue(X->getType());
6284             ICmpInst::Predicate pred = isICMP_NE ? 
6285               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6286             return new ICmpInst(pred, X, Zero);
6287           }
6288           
6289           // ((X & ~7) == 0) --> X < 8
6290           if (RHSV == 0 && isHighOnes(BOC)) {
6291             Value *X = BO->getOperand(0);
6292             Constant *NegX = ConstantExpr::getNeg(BOC);
6293             ICmpInst::Predicate pred = isICMP_NE ? 
6294               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6295             return new ICmpInst(pred, X, NegX);
6296           }
6297         }
6298       default: break;
6299       }
6300     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6301       // Handle icmp {eq|ne} <intrinsic>, intcst.
6302       if (II->getIntrinsicID() == Intrinsic::bswap) {
6303         AddToWorkList(II);
6304         ICI.setOperand(0, II->getOperand(1));
6305         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6306         return &ICI;
6307       }
6308     }
6309   } else {  // Not a ICMP_EQ/ICMP_NE
6310             // If the LHS is a cast from an integral value of the same size, 
6311             // then since we know the RHS is a constant, try to simlify.
6312     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6313       Value *CastOp = Cast->getOperand(0);
6314       const Type *SrcTy = CastOp->getType();
6315       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6316       if (SrcTy->isInteger() && 
6317           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6318         // If this is an unsigned comparison, try to make the comparison use
6319         // smaller constant values.
6320         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6321           // X u< 128 => X s> -1
6322           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6323                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6324         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6325                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6326           // X u> 127 => X s< 0
6327           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6328                               Constant::getNullValue(SrcTy));
6329         }
6330       }
6331     }
6332   }
6333   return 0;
6334 }
6335
6336 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6337 /// We only handle extending casts so far.
6338 ///
6339 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6340   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6341   Value *LHSCIOp        = LHSCI->getOperand(0);
6342   const Type *SrcTy     = LHSCIOp->getType();
6343   const Type *DestTy    = LHSCI->getType();
6344   Value *RHSCIOp;
6345
6346   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6347   // integer type is the same size as the pointer type.
6348   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6349       getTargetData().getPointerSizeInBits() == 
6350          cast<IntegerType>(DestTy)->getBitWidth()) {
6351     Value *RHSOp = 0;
6352     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6353       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6354     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6355       RHSOp = RHSC->getOperand(0);
6356       // If the pointer types don't match, insert a bitcast.
6357       if (LHSCIOp->getType() != RHSOp->getType())
6358         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6359     }
6360
6361     if (RHSOp)
6362       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6363   }
6364   
6365   // The code below only handles extension cast instructions, so far.
6366   // Enforce this.
6367   if (LHSCI->getOpcode() != Instruction::ZExt &&
6368       LHSCI->getOpcode() != Instruction::SExt)
6369     return 0;
6370
6371   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6372   bool isSignedCmp = ICI.isSignedPredicate();
6373
6374   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6375     // Not an extension from the same type?
6376     RHSCIOp = CI->getOperand(0);
6377     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6378       return 0;
6379     
6380     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6381     // and the other is a zext), then we can't handle this.
6382     if (CI->getOpcode() != LHSCI->getOpcode())
6383       return 0;
6384
6385     // Deal with equality cases early.
6386     if (ICI.isEquality())
6387       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6388
6389     // A signed comparison of sign extended values simplifies into a
6390     // signed comparison.
6391     if (isSignedCmp && isSignedExt)
6392       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6393
6394     // The other three cases all fold into an unsigned comparison.
6395     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6396   }
6397
6398   // If we aren't dealing with a constant on the RHS, exit early
6399   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6400   if (!CI)
6401     return 0;
6402
6403   // Compute the constant that would happen if we truncated to SrcTy then
6404   // reextended to DestTy.
6405   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6406   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6407
6408   // If the re-extended constant didn't change...
6409   if (Res2 == CI) {
6410     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6411     // For example, we might have:
6412     //    %A = sext short %X to uint
6413     //    %B = icmp ugt uint %A, 1330
6414     // It is incorrect to transform this into 
6415     //    %B = icmp ugt short %X, 1330 
6416     // because %A may have negative value. 
6417     //
6418     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6419     // OR operation is EQ/NE.
6420     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6421       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6422     else
6423       return 0;
6424   }
6425
6426   // The re-extended constant changed so the constant cannot be represented 
6427   // in the shorter type. Consequently, we cannot emit a simple comparison.
6428
6429   // First, handle some easy cases. We know the result cannot be equal at this
6430   // point so handle the ICI.isEquality() cases
6431   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6432     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6433   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6434     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6435
6436   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6437   // should have been folded away previously and not enter in here.
6438   Value *Result;
6439   if (isSignedCmp) {
6440     // We're performing a signed comparison.
6441     if (cast<ConstantInt>(CI)->getValue().isNegative())
6442       Result = ConstantInt::getFalse();          // X < (small) --> false
6443     else
6444       Result = ConstantInt::getTrue();           // X < (large) --> true
6445   } else {
6446     // We're performing an unsigned comparison.
6447     if (isSignedExt) {
6448       // We're performing an unsigned comp with a sign extended value.
6449       // This is true if the input is >= 0. [aka >s -1]
6450       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6451       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6452                                    NegOne, ICI.getName()), ICI);
6453     } else {
6454       // Unsigned extend & unsigned compare -> always true.
6455       Result = ConstantInt::getTrue();
6456     }
6457   }
6458
6459   // Finally, return the value computed.
6460   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6461       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6462     return ReplaceInstUsesWith(ICI, Result);
6463   } else {
6464     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6465             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6466            "ICmp should be folded!");
6467     if (Constant *CI = dyn_cast<Constant>(Result))
6468       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6469     else
6470       return BinaryOperator::createNot(Result);
6471   }
6472 }
6473
6474 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6475   return commonShiftTransforms(I);
6476 }
6477
6478 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6479   return commonShiftTransforms(I);
6480 }
6481
6482 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6483   if (Instruction *R = commonShiftTransforms(I))
6484     return R;
6485   
6486   Value *Op0 = I.getOperand(0);
6487   
6488   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6489   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6490     if (CSI->isAllOnesValue())
6491       return ReplaceInstUsesWith(I, CSI);
6492   
6493   // See if we can turn a signed shr into an unsigned shr.
6494   if (MaskedValueIsZero(Op0, 
6495                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6496     return BinaryOperator::createLShr(Op0, I.getOperand(1));
6497   
6498   return 0;
6499 }
6500
6501 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6502   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6503   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6504
6505   // shl X, 0 == X and shr X, 0 == X
6506   // shl 0, X == 0 and shr 0, X == 0
6507   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6508       Op0 == Constant::getNullValue(Op0->getType()))
6509     return ReplaceInstUsesWith(I, Op0);
6510   
6511   if (isa<UndefValue>(Op0)) {            
6512     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6513       return ReplaceInstUsesWith(I, Op0);
6514     else                                    // undef << X -> 0, undef >>u X -> 0
6515       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6516   }
6517   if (isa<UndefValue>(Op1)) {
6518     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6519       return ReplaceInstUsesWith(I, Op0);          
6520     else                                     // X << undef, X >>u undef -> 0
6521       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6522   }
6523
6524   // Try to fold constant and into select arguments.
6525   if (isa<Constant>(Op0))
6526     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6527       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6528         return R;
6529
6530   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6531     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6532       return Res;
6533   return 0;
6534 }
6535
6536 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6537                                                BinaryOperator &I) {
6538   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6539
6540   // See if we can simplify any instructions used by the instruction whose sole 
6541   // purpose is to compute bits we don't care about.
6542   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6543   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6544   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6545                            KnownZero, KnownOne))
6546     return &I;
6547   
6548   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6549   // of a signed value.
6550   //
6551   if (Op1->uge(TypeBits)) {
6552     if (I.getOpcode() != Instruction::AShr)
6553       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6554     else {
6555       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6556       return &I;
6557     }
6558   }
6559   
6560   // ((X*C1) << C2) == (X * (C1 << C2))
6561   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6562     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6563       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6564         return BinaryOperator::createMul(BO->getOperand(0),
6565                                          ConstantExpr::getShl(BOOp, Op1));
6566   
6567   // Try to fold constant and into select arguments.
6568   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6569     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6570       return R;
6571   if (isa<PHINode>(Op0))
6572     if (Instruction *NV = FoldOpIntoPhi(I))
6573       return NV;
6574   
6575   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6576   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6577     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6578     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6579     // place.  Don't try to do this transformation in this case.  Also, we
6580     // require that the input operand is a shift-by-constant so that we have
6581     // confidence that the shifts will get folded together.  We could do this
6582     // xform in more cases, but it is unlikely to be profitable.
6583     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6584         isa<ConstantInt>(TrOp->getOperand(1))) {
6585       // Okay, we'll do this xform.  Make the shift of shift.
6586       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6587       Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6588                                                 I.getName());
6589       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6590
6591       // For logical shifts, the truncation has the effect of making the high
6592       // part of the register be zeros.  Emulate this by inserting an AND to
6593       // clear the top bits as needed.  This 'and' will usually be zapped by
6594       // other xforms later if dead.
6595       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6596       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6597       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6598       
6599       // The mask we constructed says what the trunc would do if occurring
6600       // between the shifts.  We want to know the effect *after* the second
6601       // shift.  We know that it is a logical shift by a constant, so adjust the
6602       // mask as appropriate.
6603       if (I.getOpcode() == Instruction::Shl)
6604         MaskV <<= Op1->getZExtValue();
6605       else {
6606         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6607         MaskV = MaskV.lshr(Op1->getZExtValue());
6608       }
6609
6610       Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6611                                                    TI->getName());
6612       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6613
6614       // Return the value truncated to the interesting size.
6615       return new TruncInst(And, I.getType());
6616     }
6617   }
6618   
6619   if (Op0->hasOneUse()) {
6620     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6621       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6622       Value *V1, *V2;
6623       ConstantInt *CC;
6624       switch (Op0BO->getOpcode()) {
6625         default: break;
6626         case Instruction::Add:
6627         case Instruction::And:
6628         case Instruction::Or:
6629         case Instruction::Xor: {
6630           // These operators commute.
6631           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6632           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6633               match(Op0BO->getOperand(1),
6634                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6635             Instruction *YS = BinaryOperator::createShl(
6636                                             Op0BO->getOperand(0), Op1,
6637                                             Op0BO->getName());
6638             InsertNewInstBefore(YS, I); // (Y << C)
6639             Instruction *X = 
6640               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6641                                      Op0BO->getOperand(1)->getName());
6642             InsertNewInstBefore(X, I);  // (X + (Y << C))
6643             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6644             return BinaryOperator::createAnd(X, ConstantInt::get(
6645                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6646           }
6647           
6648           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6649           Value *Op0BOOp1 = Op0BO->getOperand(1);
6650           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6651               match(Op0BOOp1, 
6652                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6653               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6654               V2 == Op1) {
6655             Instruction *YS = BinaryOperator::createShl(
6656                                                      Op0BO->getOperand(0), Op1,
6657                                                      Op0BO->getName());
6658             InsertNewInstBefore(YS, I); // (Y << C)
6659             Instruction *XM =
6660               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6661                                         V1->getName()+".mask");
6662             InsertNewInstBefore(XM, I); // X & (CC << C)
6663             
6664             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6665           }
6666         }
6667           
6668         // FALL THROUGH.
6669         case Instruction::Sub: {
6670           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6671           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6672               match(Op0BO->getOperand(0),
6673                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6674             Instruction *YS = BinaryOperator::createShl(
6675                                                      Op0BO->getOperand(1), Op1,
6676                                                      Op0BO->getName());
6677             InsertNewInstBefore(YS, I); // (Y << C)
6678             Instruction *X =
6679               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6680                                      Op0BO->getOperand(0)->getName());
6681             InsertNewInstBefore(X, I);  // (X + (Y << C))
6682             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6683             return BinaryOperator::createAnd(X, ConstantInt::get(
6684                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6685           }
6686           
6687           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6688           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6689               match(Op0BO->getOperand(0),
6690                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6691                           m_ConstantInt(CC))) && V2 == Op1 &&
6692               cast<BinaryOperator>(Op0BO->getOperand(0))
6693                   ->getOperand(0)->hasOneUse()) {
6694             Instruction *YS = BinaryOperator::createShl(
6695                                                      Op0BO->getOperand(1), Op1,
6696                                                      Op0BO->getName());
6697             InsertNewInstBefore(YS, I); // (Y << C)
6698             Instruction *XM =
6699               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6700                                         V1->getName()+".mask");
6701             InsertNewInstBefore(XM, I); // X & (CC << C)
6702             
6703             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6704           }
6705           
6706           break;
6707         }
6708       }
6709       
6710       
6711       // If the operand is an bitwise operator with a constant RHS, and the
6712       // shift is the only use, we can pull it out of the shift.
6713       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6714         bool isValid = true;     // Valid only for And, Or, Xor
6715         bool highBitSet = false; // Transform if high bit of constant set?
6716         
6717         switch (Op0BO->getOpcode()) {
6718           default: isValid = false; break;   // Do not perform transform!
6719           case Instruction::Add:
6720             isValid = isLeftShift;
6721             break;
6722           case Instruction::Or:
6723           case Instruction::Xor:
6724             highBitSet = false;
6725             break;
6726           case Instruction::And:
6727             highBitSet = true;
6728             break;
6729         }
6730         
6731         // If this is a signed shift right, and the high bit is modified
6732         // by the logical operation, do not perform the transformation.
6733         // The highBitSet boolean indicates the value of the high bit of
6734         // the constant which would cause it to be modified for this
6735         // operation.
6736         //
6737         if (isValid && I.getOpcode() == Instruction::AShr)
6738           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6739         
6740         if (isValid) {
6741           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6742           
6743           Instruction *NewShift =
6744             BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6745           InsertNewInstBefore(NewShift, I);
6746           NewShift->takeName(Op0BO);
6747           
6748           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6749                                         NewRHS);
6750         }
6751       }
6752     }
6753   }
6754   
6755   // Find out if this is a shift of a shift by a constant.
6756   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6757   if (ShiftOp && !ShiftOp->isShift())
6758     ShiftOp = 0;
6759   
6760   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6761     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6762     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6763     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6764     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6765     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6766     Value *X = ShiftOp->getOperand(0);
6767     
6768     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6769     if (AmtSum > TypeBits)
6770       AmtSum = TypeBits;
6771     
6772     const IntegerType *Ty = cast<IntegerType>(I.getType());
6773     
6774     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6775     if (I.getOpcode() == ShiftOp->getOpcode()) {
6776       return BinaryOperator::create(I.getOpcode(), X,
6777                                     ConstantInt::get(Ty, AmtSum));
6778     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6779                I.getOpcode() == Instruction::AShr) {
6780       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6781       return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6782     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6783                I.getOpcode() == Instruction::LShr) {
6784       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6785       Instruction *Shift =
6786         BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6787       InsertNewInstBefore(Shift, I);
6788
6789       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6790       return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6791     }
6792     
6793     // Okay, if we get here, one shift must be left, and the other shift must be
6794     // right.  See if the amounts are equal.
6795     if (ShiftAmt1 == ShiftAmt2) {
6796       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6797       if (I.getOpcode() == Instruction::Shl) {
6798         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6799         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6800       }
6801       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6802       if (I.getOpcode() == Instruction::LShr) {
6803         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6804         return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6805       }
6806       // We can simplify ((X << C) >>s C) into a trunc + sext.
6807       // NOTE: we could do this for any C, but that would make 'unusual' integer
6808       // types.  For now, just stick to ones well-supported by the code
6809       // generators.
6810       const Type *SExtType = 0;
6811       switch (Ty->getBitWidth() - ShiftAmt1) {
6812       case 1  :
6813       case 8  :
6814       case 16 :
6815       case 32 :
6816       case 64 :
6817       case 128:
6818         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6819         break;
6820       default: break;
6821       }
6822       if (SExtType) {
6823         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6824         InsertNewInstBefore(NewTrunc, I);
6825         return new SExtInst(NewTrunc, Ty);
6826       }
6827       // Otherwise, we can't handle it yet.
6828     } else if (ShiftAmt1 < ShiftAmt2) {
6829       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6830       
6831       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6832       if (I.getOpcode() == Instruction::Shl) {
6833         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6834                ShiftOp->getOpcode() == Instruction::AShr);
6835         Instruction *Shift =
6836           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6837         InsertNewInstBefore(Shift, I);
6838         
6839         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6840         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6841       }
6842       
6843       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6844       if (I.getOpcode() == Instruction::LShr) {
6845         assert(ShiftOp->getOpcode() == Instruction::Shl);
6846         Instruction *Shift =
6847           BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6848         InsertNewInstBefore(Shift, I);
6849         
6850         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6851         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6852       }
6853       
6854       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6855     } else {
6856       assert(ShiftAmt2 < ShiftAmt1);
6857       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6858
6859       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6860       if (I.getOpcode() == Instruction::Shl) {
6861         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6862                ShiftOp->getOpcode() == Instruction::AShr);
6863         Instruction *Shift =
6864           BinaryOperator::create(ShiftOp->getOpcode(), X,
6865                                  ConstantInt::get(Ty, ShiftDiff));
6866         InsertNewInstBefore(Shift, I);
6867         
6868         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6869         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6870       }
6871       
6872       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6873       if (I.getOpcode() == Instruction::LShr) {
6874         assert(ShiftOp->getOpcode() == Instruction::Shl);
6875         Instruction *Shift =
6876           BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6877         InsertNewInstBefore(Shift, I);
6878         
6879         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6880         return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6881       }
6882       
6883       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6884     }
6885   }
6886   return 0;
6887 }
6888
6889
6890 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6891 /// expression.  If so, decompose it, returning some value X, such that Val is
6892 /// X*Scale+Offset.
6893 ///
6894 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6895                                         int &Offset) {
6896   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6897   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6898     Offset = CI->getZExtValue();
6899     Scale  = 0;
6900     return ConstantInt::get(Type::Int32Ty, 0);
6901   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6902     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6903       if (I->getOpcode() == Instruction::Shl) {
6904         // This is a value scaled by '1 << the shift amt'.
6905         Scale = 1U << RHS->getZExtValue();
6906         Offset = 0;
6907         return I->getOperand(0);
6908       } else if (I->getOpcode() == Instruction::Mul) {
6909         // This value is scaled by 'RHS'.
6910         Scale = RHS->getZExtValue();
6911         Offset = 0;
6912         return I->getOperand(0);
6913       } else if (I->getOpcode() == Instruction::Add) {
6914         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6915         // where C1 is divisible by C2.
6916         unsigned SubScale;
6917         Value *SubVal = 
6918           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6919         Offset += RHS->getZExtValue();
6920         Scale = SubScale;
6921         return SubVal;
6922       }
6923     }
6924   }
6925
6926   // Otherwise, we can't look past this.
6927   Scale = 1;
6928   Offset = 0;
6929   return Val;
6930 }
6931
6932
6933 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6934 /// try to eliminate the cast by moving the type information into the alloc.
6935 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6936                                                    AllocationInst &AI) {
6937   const PointerType *PTy = cast<PointerType>(CI.getType());
6938   
6939   // Remove any uses of AI that are dead.
6940   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6941   
6942   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6943     Instruction *User = cast<Instruction>(*UI++);
6944     if (isInstructionTriviallyDead(User)) {
6945       while (UI != E && *UI == User)
6946         ++UI; // If this instruction uses AI more than once, don't break UI.
6947       
6948       ++NumDeadInst;
6949       DOUT << "IC: DCE: " << *User;
6950       EraseInstFromFunction(*User);
6951     }
6952   }
6953   
6954   // Get the type really allocated and the type casted to.
6955   const Type *AllocElTy = AI.getAllocatedType();
6956   const Type *CastElTy = PTy->getElementType();
6957   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6958
6959   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6960   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6961   if (CastElTyAlign < AllocElTyAlign) return 0;
6962
6963   // If the allocation has multiple uses, only promote it if we are strictly
6964   // increasing the alignment of the resultant allocation.  If we keep it the
6965   // same, we open the door to infinite loops of various kinds.
6966   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6967
6968   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6969   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6970   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6971
6972   // See if we can satisfy the modulus by pulling a scale out of the array
6973   // size argument.
6974   unsigned ArraySizeScale;
6975   int ArrayOffset;
6976   Value *NumElements = // See if the array size is a decomposable linear expr.
6977     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6978  
6979   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6980   // do the xform.
6981   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6982       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6983
6984   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6985   Value *Amt = 0;
6986   if (Scale == 1) {
6987     Amt = NumElements;
6988   } else {
6989     // If the allocation size is constant, form a constant mul expression
6990     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6991     if (isa<ConstantInt>(NumElements))
6992       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6993     // otherwise multiply the amount and the number of elements
6994     else if (Scale != 1) {
6995       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6996       Amt = InsertNewInstBefore(Tmp, AI);
6997     }
6998   }
6999   
7000   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7001     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7002     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
7003     Amt = InsertNewInstBefore(Tmp, AI);
7004   }
7005   
7006   AllocationInst *New;
7007   if (isa<MallocInst>(AI))
7008     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7009   else
7010     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7011   InsertNewInstBefore(New, AI);
7012   New->takeName(&AI);
7013   
7014   // If the allocation has multiple uses, insert a cast and change all things
7015   // that used it to use the new cast.  This will also hack on CI, but it will
7016   // die soon.
7017   if (!AI.hasOneUse()) {
7018     AddUsesToWorkList(AI);
7019     // New is the allocation instruction, pointer typed. AI is the original
7020     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7021     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7022     InsertNewInstBefore(NewCast, AI);
7023     AI.replaceAllUsesWith(NewCast);
7024   }
7025   return ReplaceInstUsesWith(CI, New);
7026 }
7027
7028 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7029 /// and return it as type Ty without inserting any new casts and without
7030 /// changing the computed value.  This is used by code that tries to decide
7031 /// whether promoting or shrinking integer operations to wider or smaller types
7032 /// will allow us to eliminate a truncate or extend.
7033 ///
7034 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7035 /// extension operation if Ty is larger.
7036 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7037                                               unsigned CastOpc,
7038                                               int &NumCastsRemoved) {
7039   // We can always evaluate constants in another type.
7040   if (isa<ConstantInt>(V))
7041     return true;
7042   
7043   Instruction *I = dyn_cast<Instruction>(V);
7044   if (!I) return false;
7045   
7046   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7047   
7048   // If this is an extension or truncate, we can often eliminate it.
7049   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7050     // If this is a cast from the destination type, we can trivially eliminate
7051     // it, and this will remove a cast overall.
7052     if (I->getOperand(0)->getType() == Ty) {
7053       // If the first operand is itself a cast, and is eliminable, do not count
7054       // this as an eliminable cast.  We would prefer to eliminate those two
7055       // casts first.
7056       if (!isa<CastInst>(I->getOperand(0)))
7057         ++NumCastsRemoved;
7058       return true;
7059     }
7060   }
7061
7062   // We can't extend or shrink something that has multiple uses: doing so would
7063   // require duplicating the instruction in general, which isn't profitable.
7064   if (!I->hasOneUse()) return false;
7065
7066   switch (I->getOpcode()) {
7067   case Instruction::Add:
7068   case Instruction::Sub:
7069   case Instruction::And:
7070   case Instruction::Or:
7071   case Instruction::Xor:
7072     // These operators can all arbitrarily be extended or truncated.
7073     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7074                                       NumCastsRemoved) &&
7075            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7076                                       NumCastsRemoved);
7077
7078   case Instruction::Mul:
7079     // A multiply can be truncated by truncating its operands.
7080     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
7081            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7082                                       NumCastsRemoved) &&
7083            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7084                                       NumCastsRemoved);
7085
7086   case Instruction::Shl:
7087     // If we are truncating the result of this SHL, and if it's a shift of a
7088     // constant amount, we can always perform a SHL in a smaller type.
7089     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7090       uint32_t BitWidth = Ty->getBitWidth();
7091       if (BitWidth < OrigTy->getBitWidth() && 
7092           CI->getLimitedValue(BitWidth) < BitWidth)
7093         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7094                                           NumCastsRemoved);
7095     }
7096     break;
7097   case Instruction::LShr:
7098     // If this is a truncate of a logical shr, we can truncate it to a smaller
7099     // lshr iff we know that the bits we would otherwise be shifting in are
7100     // already zeros.
7101     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7102       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7103       uint32_t BitWidth = Ty->getBitWidth();
7104       if (BitWidth < OrigBitWidth &&
7105           MaskedValueIsZero(I->getOperand(0),
7106             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7107           CI->getLimitedValue(BitWidth) < BitWidth) {
7108         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7109                                           NumCastsRemoved);
7110       }
7111     }
7112     break;
7113   case Instruction::ZExt:
7114   case Instruction::SExt:
7115   case Instruction::Trunc:
7116     // If this is the same kind of case as our original (e.g. zext+zext), we
7117     // can safely replace it.  Note that replacing it does not reduce the number
7118     // of casts in the input.
7119     if (I->getOpcode() == CastOpc)
7120       return true;
7121     
7122     break;
7123   default:
7124     // TODO: Can handle more cases here.
7125     break;
7126   }
7127   
7128   return false;
7129 }
7130
7131 /// EvaluateInDifferentType - Given an expression that 
7132 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7133 /// evaluate the expression.
7134 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7135                                              bool isSigned) {
7136   if (Constant *C = dyn_cast<Constant>(V))
7137     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7138
7139   // Otherwise, it must be an instruction.
7140   Instruction *I = cast<Instruction>(V);
7141   Instruction *Res = 0;
7142   switch (I->getOpcode()) {
7143   case Instruction::Add:
7144   case Instruction::Sub:
7145   case Instruction::Mul:
7146   case Instruction::And:
7147   case Instruction::Or:
7148   case Instruction::Xor:
7149   case Instruction::AShr:
7150   case Instruction::LShr:
7151   case Instruction::Shl: {
7152     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7153     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7154     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
7155                                  LHS, RHS, I->getName());
7156     break;
7157   }    
7158   case Instruction::Trunc:
7159   case Instruction::ZExt:
7160   case Instruction::SExt:
7161     // If the source type of the cast is the type we're trying for then we can
7162     // just return the source.  There's no need to insert it because it is not
7163     // new.
7164     if (I->getOperand(0)->getType() == Ty)
7165       return I->getOperand(0);
7166     
7167     // Otherwise, must be the same type of case, so just reinsert a new one.
7168     Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7169                            Ty, I->getName());
7170     break;
7171   default: 
7172     // TODO: Can handle more cases here.
7173     assert(0 && "Unreachable!");
7174     break;
7175   }
7176   
7177   return InsertNewInstBefore(Res, *I);
7178 }
7179
7180 /// @brief Implement the transforms common to all CastInst visitors.
7181 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7182   Value *Src = CI.getOperand(0);
7183
7184   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7185   // eliminate it now.
7186   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7187     if (Instruction::CastOps opc = 
7188         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7189       // The first cast (CSrc) is eliminable so we need to fix up or replace
7190       // the second cast (CI). CSrc will then have a good chance of being dead.
7191       return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
7192     }
7193   }
7194
7195   // If we are casting a select then fold the cast into the select
7196   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7197     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7198       return NV;
7199
7200   // If we are casting a PHI then fold the cast into the PHI
7201   if (isa<PHINode>(Src))
7202     if (Instruction *NV = FoldOpIntoPhi(CI))
7203       return NV;
7204   
7205   return 0;
7206 }
7207
7208 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7209 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7210   Value *Src = CI.getOperand(0);
7211   
7212   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7213     // If casting the result of a getelementptr instruction with no offset, turn
7214     // this into a cast of the original pointer!
7215     if (GEP->hasAllZeroIndices()) {
7216       // Changing the cast operand is usually not a good idea but it is safe
7217       // here because the pointer operand is being replaced with another 
7218       // pointer operand so the opcode doesn't need to change.
7219       AddToWorkList(GEP);
7220       CI.setOperand(0, GEP->getOperand(0));
7221       return &CI;
7222     }
7223     
7224     // If the GEP has a single use, and the base pointer is a bitcast, and the
7225     // GEP computes a constant offset, see if we can convert these three
7226     // instructions into fewer.  This typically happens with unions and other
7227     // non-type-safe code.
7228     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7229       if (GEP->hasAllConstantIndices()) {
7230         // We are guaranteed to get a constant from EmitGEPOffset.
7231         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7232         int64_t Offset = OffsetV->getSExtValue();
7233         
7234         // Get the base pointer input of the bitcast, and the type it points to.
7235         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7236         const Type *GEPIdxTy =
7237           cast<PointerType>(OrigBase->getType())->getElementType();
7238         if (GEPIdxTy->isSized()) {
7239           SmallVector<Value*, 8> NewIndices;
7240           
7241           // Start with the index over the outer type.  Note that the type size
7242           // might be zero (even if the offset isn't zero) if the indexed type
7243           // is something like [0 x {int, int}]
7244           const Type *IntPtrTy = TD->getIntPtrType();
7245           int64_t FirstIdx = 0;
7246           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7247             FirstIdx = Offset/TySize;
7248             Offset %= TySize;
7249           
7250             // Handle silly modulus not returning values values [0..TySize).
7251             if (Offset < 0) {
7252               --FirstIdx;
7253               Offset += TySize;
7254               assert(Offset >= 0);
7255             }
7256             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7257           }
7258           
7259           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7260
7261           // Index into the types.  If we fail, set OrigBase to null.
7262           while (Offset) {
7263             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7264               const StructLayout *SL = TD->getStructLayout(STy);
7265               if (Offset < (int64_t)SL->getSizeInBytes()) {
7266                 unsigned Elt = SL->getElementContainingOffset(Offset);
7267                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7268               
7269                 Offset -= SL->getElementOffset(Elt);
7270                 GEPIdxTy = STy->getElementType(Elt);
7271               } else {
7272                 // Otherwise, we can't index into this, bail out.
7273                 Offset = 0;
7274                 OrigBase = 0;
7275               }
7276             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7277               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7278               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7279                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7280                 Offset %= EltSize;
7281               } else {
7282                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7283               }
7284               GEPIdxTy = STy->getElementType();
7285             } else {
7286               // Otherwise, we can't index into this, bail out.
7287               Offset = 0;
7288               OrigBase = 0;
7289             }
7290           }
7291           if (OrigBase) {
7292             // If we were able to index down into an element, create the GEP
7293             // and bitcast the result.  This eliminates one bitcast, potentially
7294             // two.
7295             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7296                                                           NewIndices.begin(),
7297                                                           NewIndices.end(), "");
7298             InsertNewInstBefore(NGEP, CI);
7299             NGEP->takeName(GEP);
7300             
7301             if (isa<BitCastInst>(CI))
7302               return new BitCastInst(NGEP, CI.getType());
7303             assert(isa<PtrToIntInst>(CI));
7304             return new PtrToIntInst(NGEP, CI.getType());
7305           }
7306         }
7307       }      
7308     }
7309   }
7310     
7311   return commonCastTransforms(CI);
7312 }
7313
7314
7315
7316 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7317 /// integer types. This function implements the common transforms for all those
7318 /// cases.
7319 /// @brief Implement the transforms common to CastInst with integer operands
7320 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7321   if (Instruction *Result = commonCastTransforms(CI))
7322     return Result;
7323
7324   Value *Src = CI.getOperand(0);
7325   const Type *SrcTy = Src->getType();
7326   const Type *DestTy = CI.getType();
7327   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7328   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7329
7330   // See if we can simplify any instructions used by the LHS whose sole 
7331   // purpose is to compute bits we don't care about.
7332   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7333   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7334                            KnownZero, KnownOne))
7335     return &CI;
7336
7337   // If the source isn't an instruction or has more than one use then we
7338   // can't do anything more. 
7339   Instruction *SrcI = dyn_cast<Instruction>(Src);
7340   if (!SrcI || !Src->hasOneUse())
7341     return 0;
7342
7343   // Attempt to propagate the cast into the instruction for int->int casts.
7344   int NumCastsRemoved = 0;
7345   if (!isa<BitCastInst>(CI) &&
7346       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7347                                  CI.getOpcode(), NumCastsRemoved)) {
7348     // If this cast is a truncate, evaluting in a different type always
7349     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7350     // we need to do an AND to maintain the clear top-part of the computation,
7351     // so we require that the input have eliminated at least one cast.  If this
7352     // is a sign extension, we insert two new casts (to do the extension) so we
7353     // require that two casts have been eliminated.
7354     bool DoXForm;
7355     switch (CI.getOpcode()) {
7356     default:
7357       // All the others use floating point so we shouldn't actually 
7358       // get here because of the check above.
7359       assert(0 && "Unknown cast type");
7360     case Instruction::Trunc:
7361       DoXForm = true;
7362       break;
7363     case Instruction::ZExt:
7364       DoXForm = NumCastsRemoved >= 1;
7365       break;
7366     case Instruction::SExt:
7367       DoXForm = NumCastsRemoved >= 2;
7368       break;
7369     }
7370     
7371     if (DoXForm) {
7372       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7373                                            CI.getOpcode() == Instruction::SExt);
7374       assert(Res->getType() == DestTy);
7375       switch (CI.getOpcode()) {
7376       default: assert(0 && "Unknown cast type!");
7377       case Instruction::Trunc:
7378       case Instruction::BitCast:
7379         // Just replace this cast with the result.
7380         return ReplaceInstUsesWith(CI, Res);
7381       case Instruction::ZExt: {
7382         // We need to emit an AND to clear the high bits.
7383         assert(SrcBitSize < DestBitSize && "Not a zext?");
7384         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7385                                                             SrcBitSize));
7386         return BinaryOperator::createAnd(Res, C);
7387       }
7388       case Instruction::SExt:
7389         // We need to emit a cast to truncate, then a cast to sext.
7390         return CastInst::create(Instruction::SExt,
7391             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7392                              CI), DestTy);
7393       }
7394     }
7395   }
7396   
7397   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7398   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7399
7400   switch (SrcI->getOpcode()) {
7401   case Instruction::Add:
7402   case Instruction::Mul:
7403   case Instruction::And:
7404   case Instruction::Or:
7405   case Instruction::Xor:
7406     // If we are discarding information, rewrite.
7407     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7408       // Don't insert two casts if they cannot be eliminated.  We allow 
7409       // two casts to be inserted if the sizes are the same.  This could 
7410       // only be converting signedness, which is a noop.
7411       if (DestBitSize == SrcBitSize || 
7412           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7413           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7414         Instruction::CastOps opcode = CI.getOpcode();
7415         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7416         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7417         return BinaryOperator::create(
7418             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7419       }
7420     }
7421
7422     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7423     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7424         SrcI->getOpcode() == Instruction::Xor &&
7425         Op1 == ConstantInt::getTrue() &&
7426         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7427       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7428       return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7429     }
7430     break;
7431   case Instruction::SDiv:
7432   case Instruction::UDiv:
7433   case Instruction::SRem:
7434   case Instruction::URem:
7435     // If we are just changing the sign, rewrite.
7436     if (DestBitSize == SrcBitSize) {
7437       // Don't insert two casts if they cannot be eliminated.  We allow 
7438       // two casts to be inserted if the sizes are the same.  This could 
7439       // only be converting signedness, which is a noop.
7440       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7441           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7442         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7443                                               Op0, DestTy, SrcI);
7444         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7445                                               Op1, DestTy, SrcI);
7446         return BinaryOperator::create(
7447           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7448       }
7449     }
7450     break;
7451
7452   case Instruction::Shl:
7453     // Allow changing the sign of the source operand.  Do not allow 
7454     // changing the size of the shift, UNLESS the shift amount is a 
7455     // constant.  We must not change variable sized shifts to a smaller 
7456     // size, because it is undefined to shift more bits out than exist 
7457     // in the value.
7458     if (DestBitSize == SrcBitSize ||
7459         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7460       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7461           Instruction::BitCast : Instruction::Trunc);
7462       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7463       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7464       return BinaryOperator::createShl(Op0c, Op1c);
7465     }
7466     break;
7467   case Instruction::AShr:
7468     // If this is a signed shr, and if all bits shifted in are about to be
7469     // truncated off, turn it into an unsigned shr to allow greater
7470     // simplifications.
7471     if (DestBitSize < SrcBitSize &&
7472         isa<ConstantInt>(Op1)) {
7473       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7474       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7475         // Insert the new logical shift right.
7476         return BinaryOperator::createLShr(Op0, Op1);
7477       }
7478     }
7479     break;
7480   }
7481   return 0;
7482 }
7483
7484 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7485   if (Instruction *Result = commonIntCastTransforms(CI))
7486     return Result;
7487   
7488   Value *Src = CI.getOperand(0);
7489   const Type *Ty = CI.getType();
7490   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7491   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7492   
7493   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7494     switch (SrcI->getOpcode()) {
7495     default: break;
7496     case Instruction::LShr:
7497       // We can shrink lshr to something smaller if we know the bits shifted in
7498       // are already zeros.
7499       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7500         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7501         
7502         // Get a mask for the bits shifting in.
7503         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7504         Value* SrcIOp0 = SrcI->getOperand(0);
7505         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7506           if (ShAmt >= DestBitWidth)        // All zeros.
7507             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7508
7509           // Okay, we can shrink this.  Truncate the input, then return a new
7510           // shift.
7511           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7512           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7513                                        Ty, CI);
7514           return BinaryOperator::createLShr(V1, V2);
7515         }
7516       } else {     // This is a variable shr.
7517         
7518         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7519         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7520         // loop-invariant and CSE'd.
7521         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7522           Value *One = ConstantInt::get(SrcI->getType(), 1);
7523
7524           Value *V = InsertNewInstBefore(
7525               BinaryOperator::createShl(One, SrcI->getOperand(1),
7526                                      "tmp"), CI);
7527           V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7528                                                             SrcI->getOperand(0),
7529                                                             "tmp"), CI);
7530           Value *Zero = Constant::getNullValue(V->getType());
7531           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7532         }
7533       }
7534       break;
7535     }
7536   }
7537   
7538   return 0;
7539 }
7540
7541 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7542 /// in order to eliminate the icmp.
7543 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7544                                              bool DoXform) {
7545   // If we are just checking for a icmp eq of a single bit and zext'ing it
7546   // to an integer, then shift the bit to the appropriate place and then
7547   // cast to integer to avoid the comparison.
7548   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7549     const APInt &Op1CV = Op1C->getValue();
7550       
7551     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7552     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7553     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7554         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7555       if (!DoXform) return ICI;
7556
7557       Value *In = ICI->getOperand(0);
7558       Value *Sh = ConstantInt::get(In->getType(),
7559                                    In->getType()->getPrimitiveSizeInBits()-1);
7560       In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7561                                                         In->getName()+".lobit"),
7562                                CI);
7563       if (In->getType() != CI.getType())
7564         In = CastInst::createIntegerCast(In, CI.getType(),
7565                                          false/*ZExt*/, "tmp", &CI);
7566
7567       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7568         Constant *One = ConstantInt::get(In->getType(), 1);
7569         In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7570                                                          In->getName()+".not"),
7571                                  CI);
7572       }
7573
7574       return ReplaceInstUsesWith(CI, In);
7575     }
7576       
7577       
7578       
7579     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7580     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7581     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7582     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7583     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7584     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7585     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7586     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7587     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7588         // This only works for EQ and NE
7589         ICI->isEquality()) {
7590       // If Op1C some other power of two, convert:
7591       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7592       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7593       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7594       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7595         
7596       APInt KnownZeroMask(~KnownZero);
7597       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7598         if (!DoXform) return ICI;
7599
7600         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7601         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7602           // (X&4) == 2 --> false
7603           // (X&4) != 2 --> true
7604           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7605           Res = ConstantExpr::getZExt(Res, CI.getType());
7606           return ReplaceInstUsesWith(CI, Res);
7607         }
7608           
7609         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7610         Value *In = ICI->getOperand(0);
7611         if (ShiftAmt) {
7612           // Perform a logical shr by shiftamt.
7613           // Insert the shift to put the result in the low bit.
7614           In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7615                                   ConstantInt::get(In->getType(), ShiftAmt),
7616                                                    In->getName()+".lobit"), CI);
7617         }
7618           
7619         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7620           Constant *One = ConstantInt::get(In->getType(), 1);
7621           In = BinaryOperator::createXor(In, One, "tmp");
7622           InsertNewInstBefore(cast<Instruction>(In), CI);
7623         }
7624           
7625         if (CI.getType() == In->getType())
7626           return ReplaceInstUsesWith(CI, In);
7627         else
7628           return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7629       }
7630     }
7631   }
7632
7633   return 0;
7634 }
7635
7636 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7637   // If one of the common conversion will work ..
7638   if (Instruction *Result = commonIntCastTransforms(CI))
7639     return Result;
7640
7641   Value *Src = CI.getOperand(0);
7642
7643   // If this is a cast of a cast
7644   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7645     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7646     // types and if the sizes are just right we can convert this into a logical
7647     // 'and' which will be much cheaper than the pair of casts.
7648     if (isa<TruncInst>(CSrc)) {
7649       // Get the sizes of the types involved
7650       Value *A = CSrc->getOperand(0);
7651       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7652       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7653       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7654       // If we're actually extending zero bits and the trunc is a no-op
7655       if (MidSize < DstSize && SrcSize == DstSize) {
7656         // Replace both of the casts with an And of the type mask.
7657         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7658         Constant *AndConst = ConstantInt::get(AndValue);
7659         Instruction *And = 
7660           BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7661         // Unfortunately, if the type changed, we need to cast it back.
7662         if (And->getType() != CI.getType()) {
7663           And->setName(CSrc->getName()+".mask");
7664           InsertNewInstBefore(And, CI);
7665           And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7666         }
7667         return And;
7668       }
7669     }
7670   }
7671
7672   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7673     return transformZExtICmp(ICI, CI);
7674
7675   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7676   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7677     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7678     // of the (zext icmp) will be transformed.
7679     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7680     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7681     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7682         (transformZExtICmp(LHS, CI, false) ||
7683          transformZExtICmp(RHS, CI, false))) {
7684       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7685       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7686       return BinaryOperator::create(Instruction::Or, LCast, RCast);
7687     }
7688   }
7689
7690   return 0;
7691 }
7692
7693 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7694   if (Instruction *I = commonIntCastTransforms(CI))
7695     return I;
7696   
7697   Value *Src = CI.getOperand(0);
7698   
7699   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7700   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7701   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7702     // If we are just checking for a icmp eq of a single bit and zext'ing it
7703     // to an integer, then shift the bit to the appropriate place and then
7704     // cast to integer to avoid the comparison.
7705     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7706       const APInt &Op1CV = Op1C->getValue();
7707       
7708       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7709       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7710       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7711           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7712         Value *In = ICI->getOperand(0);
7713         Value *Sh = ConstantInt::get(In->getType(),
7714                                      In->getType()->getPrimitiveSizeInBits()-1);
7715         In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7716                                                         In->getName()+".lobit"),
7717                                  CI);
7718         if (In->getType() != CI.getType())
7719           In = CastInst::createIntegerCast(In, CI.getType(),
7720                                            true/*SExt*/, "tmp", &CI);
7721         
7722         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7723           In = InsertNewInstBefore(BinaryOperator::createNot(In,
7724                                      In->getName()+".not"), CI);
7725         
7726         return ReplaceInstUsesWith(CI, In);
7727       }
7728     }
7729   }
7730       
7731   return 0;
7732 }
7733
7734 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7735 /// in the specified FP type without changing its value.
7736 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7737   APFloat F = CFP->getValueAPF();
7738   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7739     return ConstantFP::get(F);
7740   return 0;
7741 }
7742
7743 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7744 /// through it until we get the source value.
7745 static Value *LookThroughFPExtensions(Value *V) {
7746   if (Instruction *I = dyn_cast<Instruction>(V))
7747     if (I->getOpcode() == Instruction::FPExt)
7748       return LookThroughFPExtensions(I->getOperand(0));
7749   
7750   // If this value is a constant, return the constant in the smallest FP type
7751   // that can accurately represent it.  This allows us to turn
7752   // (float)((double)X+2.0) into x+2.0f.
7753   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7754     if (CFP->getType() == Type::PPC_FP128Ty)
7755       return V;  // No constant folding of this.
7756     // See if the value can be truncated to float and then reextended.
7757     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7758       return V;
7759     if (CFP->getType() == Type::DoubleTy)
7760       return V;  // Won't shrink.
7761     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7762       return V;
7763     // Don't try to shrink to various long double types.
7764   }
7765   
7766   return V;
7767 }
7768
7769 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7770   if (Instruction *I = commonCastTransforms(CI))
7771     return I;
7772   
7773   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7774   // smaller than the destination type, we can eliminate the truncate by doing
7775   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7776   // many builtins (sqrt, etc).
7777   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7778   if (OpI && OpI->hasOneUse()) {
7779     switch (OpI->getOpcode()) {
7780     default: break;
7781     case Instruction::Add:
7782     case Instruction::Sub:
7783     case Instruction::Mul:
7784     case Instruction::FDiv:
7785     case Instruction::FRem:
7786       const Type *SrcTy = OpI->getType();
7787       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7788       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7789       if (LHSTrunc->getType() != SrcTy && 
7790           RHSTrunc->getType() != SrcTy) {
7791         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7792         // If the source types were both smaller than the destination type of
7793         // the cast, do this xform.
7794         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7795             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7796           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7797                                       CI.getType(), CI);
7798           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7799                                       CI.getType(), CI);
7800           return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7801         }
7802       }
7803       break;  
7804     }
7805   }
7806   return 0;
7807 }
7808
7809 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7810   return commonCastTransforms(CI);
7811 }
7812
7813 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7814   return commonCastTransforms(CI);
7815 }
7816
7817 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7818   return commonCastTransforms(CI);
7819 }
7820
7821 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7822   return commonCastTransforms(CI);
7823 }
7824
7825 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7826   return commonCastTransforms(CI);
7827 }
7828
7829 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7830   return commonPointerCastTransforms(CI);
7831 }
7832
7833 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7834   if (Instruction *I = commonCastTransforms(CI))
7835     return I;
7836   
7837   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7838   if (!DestPointee->isSized()) return 0;
7839
7840   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7841   ConstantInt *Cst;
7842   Value *X;
7843   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7844                                     m_ConstantInt(Cst)))) {
7845     // If the source and destination operands have the same type, see if this
7846     // is a single-index GEP.
7847     if (X->getType() == CI.getType()) {
7848       // Get the size of the pointee type.
7849       uint64_t Size = TD->getABITypeSize(DestPointee);
7850
7851       // Convert the constant to intptr type.
7852       APInt Offset = Cst->getValue();
7853       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7854
7855       // If Offset is evenly divisible by Size, we can do this xform.
7856       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7857         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7858         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7859       }
7860     }
7861     // TODO: Could handle other cases, e.g. where add is indexing into field of
7862     // struct etc.
7863   } else if (CI.getOperand(0)->hasOneUse() &&
7864              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7865     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7866     // "inttoptr+GEP" instead of "add+intptr".
7867     
7868     // Get the size of the pointee type.
7869     uint64_t Size = TD->getABITypeSize(DestPointee);
7870     
7871     // Convert the constant to intptr type.
7872     APInt Offset = Cst->getValue();
7873     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7874     
7875     // If Offset is evenly divisible by Size, we can do this xform.
7876     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7877       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7878       
7879       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7880                                                             "tmp"), CI);
7881       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7882     }
7883   }
7884   return 0;
7885 }
7886
7887 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7888   // If the operands are integer typed then apply the integer transforms,
7889   // otherwise just apply the common ones.
7890   Value *Src = CI.getOperand(0);
7891   const Type *SrcTy = Src->getType();
7892   const Type *DestTy = CI.getType();
7893
7894   if (SrcTy->isInteger() && DestTy->isInteger()) {
7895     if (Instruction *Result = commonIntCastTransforms(CI))
7896       return Result;
7897   } else if (isa<PointerType>(SrcTy)) {
7898     if (Instruction *I = commonPointerCastTransforms(CI))
7899       return I;
7900   } else {
7901     if (Instruction *Result = commonCastTransforms(CI))
7902       return Result;
7903   }
7904
7905
7906   // Get rid of casts from one type to the same type. These are useless and can
7907   // be replaced by the operand.
7908   if (DestTy == Src->getType())
7909     return ReplaceInstUsesWith(CI, Src);
7910
7911   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7912     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7913     const Type *DstElTy = DstPTy->getElementType();
7914     const Type *SrcElTy = SrcPTy->getElementType();
7915     
7916     // If the address spaces don't match, don't eliminate the bitcast, which is
7917     // required for changing types.
7918     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7919       return 0;
7920     
7921     // If we are casting a malloc or alloca to a pointer to a type of the same
7922     // size, rewrite the allocation instruction to allocate the "right" type.
7923     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7924       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7925         return V;
7926     
7927     // If the source and destination are pointers, and this cast is equivalent
7928     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7929     // This can enhance SROA and other transforms that want type-safe pointers.
7930     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7931     unsigned NumZeros = 0;
7932     while (SrcElTy != DstElTy && 
7933            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7934            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7935       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7936       ++NumZeros;
7937     }
7938
7939     // If we found a path from the src to dest, create the getelementptr now.
7940     if (SrcElTy == DstElTy) {
7941       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7942       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7943                                        ((Instruction*) NULL));
7944     }
7945   }
7946
7947   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7948     if (SVI->hasOneUse()) {
7949       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7950       // a bitconvert to a vector with the same # elts.
7951       if (isa<VectorType>(DestTy) && 
7952           cast<VectorType>(DestTy)->getNumElements() == 
7953                 SVI->getType()->getNumElements()) {
7954         CastInst *Tmp;
7955         // If either of the operands is a cast from CI.getType(), then
7956         // evaluating the shuffle in the casted destination's type will allow
7957         // us to eliminate at least one cast.
7958         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7959              Tmp->getOperand(0)->getType() == DestTy) ||
7960             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7961              Tmp->getOperand(0)->getType() == DestTy)) {
7962           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7963                                                SVI->getOperand(0), DestTy, &CI);
7964           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7965                                                SVI->getOperand(1), DestTy, &CI);
7966           // Return a new shuffle vector.  Use the same element ID's, as we
7967           // know the vector types match #elts.
7968           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7969         }
7970       }
7971     }
7972   }
7973   return 0;
7974 }
7975
7976 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7977 ///   %C = or %A, %B
7978 ///   %D = select %cond, %C, %A
7979 /// into:
7980 ///   %C = select %cond, %B, 0
7981 ///   %D = or %A, %C
7982 ///
7983 /// Assuming that the specified instruction is an operand to the select, return
7984 /// a bitmask indicating which operands of this instruction are foldable if they
7985 /// equal the other incoming value of the select.
7986 ///
7987 static unsigned GetSelectFoldableOperands(Instruction *I) {
7988   switch (I->getOpcode()) {
7989   case Instruction::Add:
7990   case Instruction::Mul:
7991   case Instruction::And:
7992   case Instruction::Or:
7993   case Instruction::Xor:
7994     return 3;              // Can fold through either operand.
7995   case Instruction::Sub:   // Can only fold on the amount subtracted.
7996   case Instruction::Shl:   // Can only fold on the shift amount.
7997   case Instruction::LShr:
7998   case Instruction::AShr:
7999     return 1;
8000   default:
8001     return 0;              // Cannot fold
8002   }
8003 }
8004
8005 /// GetSelectFoldableConstant - For the same transformation as the previous
8006 /// function, return the identity constant that goes into the select.
8007 static Constant *GetSelectFoldableConstant(Instruction *I) {
8008   switch (I->getOpcode()) {
8009   default: assert(0 && "This cannot happen!"); abort();
8010   case Instruction::Add:
8011   case Instruction::Sub:
8012   case Instruction::Or:
8013   case Instruction::Xor:
8014   case Instruction::Shl:
8015   case Instruction::LShr:
8016   case Instruction::AShr:
8017     return Constant::getNullValue(I->getType());
8018   case Instruction::And:
8019     return Constant::getAllOnesValue(I->getType());
8020   case Instruction::Mul:
8021     return ConstantInt::get(I->getType(), 1);
8022   }
8023 }
8024
8025 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8026 /// have the same opcode and only one use each.  Try to simplify this.
8027 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8028                                           Instruction *FI) {
8029   if (TI->getNumOperands() == 1) {
8030     // If this is a non-volatile load or a cast from the same type,
8031     // merge.
8032     if (TI->isCast()) {
8033       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8034         return 0;
8035     } else {
8036       return 0;  // unknown unary op.
8037     }
8038
8039     // Fold this by inserting a select from the input values.
8040     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8041                                            FI->getOperand(0), SI.getName()+".v");
8042     InsertNewInstBefore(NewSI, SI);
8043     return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8044                             TI->getType());
8045   }
8046
8047   // Only handle binary operators here.
8048   if (!isa<BinaryOperator>(TI))
8049     return 0;
8050
8051   // Figure out if the operations have any operands in common.
8052   Value *MatchOp, *OtherOpT, *OtherOpF;
8053   bool MatchIsOpZero;
8054   if (TI->getOperand(0) == FI->getOperand(0)) {
8055     MatchOp  = TI->getOperand(0);
8056     OtherOpT = TI->getOperand(1);
8057     OtherOpF = FI->getOperand(1);
8058     MatchIsOpZero = true;
8059   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8060     MatchOp  = TI->getOperand(1);
8061     OtherOpT = TI->getOperand(0);
8062     OtherOpF = FI->getOperand(0);
8063     MatchIsOpZero = false;
8064   } else if (!TI->isCommutative()) {
8065     return 0;
8066   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8067     MatchOp  = TI->getOperand(0);
8068     OtherOpT = TI->getOperand(1);
8069     OtherOpF = FI->getOperand(0);
8070     MatchIsOpZero = true;
8071   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8072     MatchOp  = TI->getOperand(1);
8073     OtherOpT = TI->getOperand(0);
8074     OtherOpF = FI->getOperand(1);
8075     MatchIsOpZero = true;
8076   } else {
8077     return 0;
8078   }
8079
8080   // If we reach here, they do have operations in common.
8081   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8082                                          OtherOpF, SI.getName()+".v");
8083   InsertNewInstBefore(NewSI, SI);
8084
8085   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8086     if (MatchIsOpZero)
8087       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
8088     else
8089       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
8090   }
8091   assert(0 && "Shouldn't get here");
8092   return 0;
8093 }
8094
8095 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8096   Value *CondVal = SI.getCondition();
8097   Value *TrueVal = SI.getTrueValue();
8098   Value *FalseVal = SI.getFalseValue();
8099
8100   // select true, X, Y  -> X
8101   // select false, X, Y -> Y
8102   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8103     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8104
8105   // select C, X, X -> X
8106   if (TrueVal == FalseVal)
8107     return ReplaceInstUsesWith(SI, TrueVal);
8108
8109   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8110     return ReplaceInstUsesWith(SI, FalseVal);
8111   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8112     return ReplaceInstUsesWith(SI, TrueVal);
8113   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8114     if (isa<Constant>(TrueVal))
8115       return ReplaceInstUsesWith(SI, TrueVal);
8116     else
8117       return ReplaceInstUsesWith(SI, FalseVal);
8118   }
8119
8120   if (SI.getType() == Type::Int1Ty) {
8121     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8122       if (C->getZExtValue()) {
8123         // Change: A = select B, true, C --> A = or B, C
8124         return BinaryOperator::createOr(CondVal, FalseVal);
8125       } else {
8126         // Change: A = select B, false, C --> A = and !B, C
8127         Value *NotCond =
8128           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8129                                              "not."+CondVal->getName()), SI);
8130         return BinaryOperator::createAnd(NotCond, FalseVal);
8131       }
8132     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8133       if (C->getZExtValue() == false) {
8134         // Change: A = select B, C, false --> A = and B, C
8135         return BinaryOperator::createAnd(CondVal, TrueVal);
8136       } else {
8137         // Change: A = select B, C, true --> A = or !B, C
8138         Value *NotCond =
8139           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8140                                              "not."+CondVal->getName()), SI);
8141         return BinaryOperator::createOr(NotCond, TrueVal);
8142       }
8143     }
8144     
8145     // select a, b, a  -> a&b
8146     // select a, a, b  -> a|b
8147     if (CondVal == TrueVal)
8148       return BinaryOperator::createOr(CondVal, FalseVal);
8149     else if (CondVal == FalseVal)
8150       return BinaryOperator::createAnd(CondVal, TrueVal);
8151   }
8152
8153   // Selecting between two integer constants?
8154   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8155     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8156       // select C, 1, 0 -> zext C to int
8157       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8158         return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
8159       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8160         // select C, 0, 1 -> zext !C to int
8161         Value *NotCond =
8162           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
8163                                                "not."+CondVal->getName()), SI);
8164         return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
8165       }
8166       
8167       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8168
8169       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8170
8171         // (x <s 0) ? -1 : 0 -> ashr x, 31
8172         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8173           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8174             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8175               // The comparison constant and the result are not neccessarily the
8176               // same width. Make an all-ones value by inserting a AShr.
8177               Value *X = IC->getOperand(0);
8178               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8179               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8180               Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
8181                                                         ShAmt, "ones");
8182               InsertNewInstBefore(SRA, SI);
8183               
8184               // Finally, convert to the type of the select RHS.  We figure out
8185               // if this requires a SExt, Trunc or BitCast based on the sizes.
8186               Instruction::CastOps opc = Instruction::BitCast;
8187               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8188               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8189               if (SRASize < SISize)
8190                 opc = Instruction::SExt;
8191               else if (SRASize > SISize)
8192                 opc = Instruction::Trunc;
8193               return CastInst::create(opc, SRA, SI.getType());
8194             }
8195           }
8196
8197
8198         // If one of the constants is zero (we know they can't both be) and we
8199         // have an icmp instruction with zero, and we have an 'and' with the
8200         // non-constant value, eliminate this whole mess.  This corresponds to
8201         // cases like this: ((X & 27) ? 27 : 0)
8202         if (TrueValC->isZero() || FalseValC->isZero())
8203           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8204               cast<Constant>(IC->getOperand(1))->isNullValue())
8205             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8206               if (ICA->getOpcode() == Instruction::And &&
8207                   isa<ConstantInt>(ICA->getOperand(1)) &&
8208                   (ICA->getOperand(1) == TrueValC ||
8209                    ICA->getOperand(1) == FalseValC) &&
8210                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8211                 // Okay, now we know that everything is set up, we just don't
8212                 // know whether we have a icmp_ne or icmp_eq and whether the 
8213                 // true or false val is the zero.
8214                 bool ShouldNotVal = !TrueValC->isZero();
8215                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8216                 Value *V = ICA;
8217                 if (ShouldNotVal)
8218                   V = InsertNewInstBefore(BinaryOperator::create(
8219                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8220                 return ReplaceInstUsesWith(SI, V);
8221               }
8222       }
8223     }
8224
8225   // See if we are selecting two values based on a comparison of the two values.
8226   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8227     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8228       // Transform (X == Y) ? X : Y  -> Y
8229       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8230         // This is not safe in general for floating point:  
8231         // consider X== -0, Y== +0.
8232         // It becomes safe if either operand is a nonzero constant.
8233         ConstantFP *CFPt, *CFPf;
8234         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8235               !CFPt->getValueAPF().isZero()) ||
8236             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8237              !CFPf->getValueAPF().isZero()))
8238         return ReplaceInstUsesWith(SI, FalseVal);
8239       }
8240       // Transform (X != Y) ? X : Y  -> X
8241       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8242         return ReplaceInstUsesWith(SI, TrueVal);
8243       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8244
8245     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8246       // Transform (X == Y) ? Y : X  -> X
8247       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8248         // This is not safe in general for floating point:  
8249         // consider X== -0, Y== +0.
8250         // It becomes safe if either operand is a nonzero constant.
8251         ConstantFP *CFPt, *CFPf;
8252         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8253               !CFPt->getValueAPF().isZero()) ||
8254             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8255              !CFPf->getValueAPF().isZero()))
8256           return ReplaceInstUsesWith(SI, FalseVal);
8257       }
8258       // Transform (X != Y) ? Y : X  -> Y
8259       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8260         return ReplaceInstUsesWith(SI, TrueVal);
8261       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8262     }
8263   }
8264
8265   // See if we are selecting two values based on a comparison of the two values.
8266   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8267     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8268       // Transform (X == Y) ? X : Y  -> Y
8269       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8270         return ReplaceInstUsesWith(SI, FalseVal);
8271       // Transform (X != Y) ? X : Y  -> X
8272       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8273         return ReplaceInstUsesWith(SI, TrueVal);
8274       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8275
8276     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8277       // Transform (X == Y) ? Y : X  -> X
8278       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8279         return ReplaceInstUsesWith(SI, FalseVal);
8280       // Transform (X != Y) ? Y : X  -> Y
8281       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8282         return ReplaceInstUsesWith(SI, TrueVal);
8283       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8284     }
8285   }
8286
8287   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8288     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8289       if (TI->hasOneUse() && FI->hasOneUse()) {
8290         Instruction *AddOp = 0, *SubOp = 0;
8291
8292         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8293         if (TI->getOpcode() == FI->getOpcode())
8294           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8295             return IV;
8296
8297         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8298         // even legal for FP.
8299         if (TI->getOpcode() == Instruction::Sub &&
8300             FI->getOpcode() == Instruction::Add) {
8301           AddOp = FI; SubOp = TI;
8302         } else if (FI->getOpcode() == Instruction::Sub &&
8303                    TI->getOpcode() == Instruction::Add) {
8304           AddOp = TI; SubOp = FI;
8305         }
8306
8307         if (AddOp) {
8308           Value *OtherAddOp = 0;
8309           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8310             OtherAddOp = AddOp->getOperand(1);
8311           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8312             OtherAddOp = AddOp->getOperand(0);
8313           }
8314
8315           if (OtherAddOp) {
8316             // So at this point we know we have (Y -> OtherAddOp):
8317             //        select C, (add X, Y), (sub X, Z)
8318             Value *NegVal;  // Compute -Z
8319             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8320               NegVal = ConstantExpr::getNeg(C);
8321             } else {
8322               NegVal = InsertNewInstBefore(
8323                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
8324             }
8325
8326             Value *NewTrueOp = OtherAddOp;
8327             Value *NewFalseOp = NegVal;
8328             if (AddOp != TI)
8329               std::swap(NewTrueOp, NewFalseOp);
8330             Instruction *NewSel =
8331               SelectInst::Create(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
8332
8333             NewSel = InsertNewInstBefore(NewSel, SI);
8334             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
8335           }
8336         }
8337       }
8338
8339   // See if we can fold the select into one of our operands.
8340   if (SI.getType()->isInteger()) {
8341     // See the comment above GetSelectFoldableOperands for a description of the
8342     // transformation we are doing here.
8343     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8344       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8345           !isa<Constant>(FalseVal))
8346         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8347           unsigned OpToFold = 0;
8348           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8349             OpToFold = 1;
8350           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8351             OpToFold = 2;
8352           }
8353
8354           if (OpToFold) {
8355             Constant *C = GetSelectFoldableConstant(TVI);
8356             Instruction *NewSel =
8357               SelectInst::Create(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
8358             InsertNewInstBefore(NewSel, SI);
8359             NewSel->takeName(TVI);
8360             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8361               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
8362             else {
8363               assert(0 && "Unknown instruction!!");
8364             }
8365           }
8366         }
8367
8368     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8369       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8370           !isa<Constant>(TrueVal))
8371         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8372           unsigned OpToFold = 0;
8373           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8374             OpToFold = 1;
8375           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8376             OpToFold = 2;
8377           }
8378
8379           if (OpToFold) {
8380             Constant *C = GetSelectFoldableConstant(FVI);
8381             Instruction *NewSel =
8382               SelectInst::Create(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
8383             InsertNewInstBefore(NewSel, SI);
8384             NewSel->takeName(FVI);
8385             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8386               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
8387             else
8388               assert(0 && "Unknown instruction!!");
8389           }
8390         }
8391   }
8392
8393   if (BinaryOperator::isNot(CondVal)) {
8394     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8395     SI.setOperand(1, FalseVal);
8396     SI.setOperand(2, TrueVal);
8397     return &SI;
8398   }
8399
8400   return 0;
8401 }
8402
8403 /// EnforceKnownAlignment - If the specified pointer points to an object that
8404 /// we control, modify the object's alignment to PrefAlign. This isn't
8405 /// often possible though. If alignment is important, a more reliable approach
8406 /// is to simply align all global variables and allocation instructions to
8407 /// their preferred alignment from the beginning.
8408 ///
8409 static unsigned EnforceKnownAlignment(Value *V,
8410                                       unsigned Align, unsigned PrefAlign) {
8411
8412   User *U = dyn_cast<User>(V);
8413   if (!U) return Align;
8414
8415   switch (getOpcode(U)) {
8416   default: break;
8417   case Instruction::BitCast:
8418     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8419   case Instruction::GetElementPtr: {
8420     // If all indexes are zero, it is just the alignment of the base pointer.
8421     bool AllZeroOperands = true;
8422     for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8423       if (!isa<Constant>(U->getOperand(i)) ||
8424           !cast<Constant>(U->getOperand(i))->isNullValue()) {
8425         AllZeroOperands = false;
8426         break;
8427       }
8428
8429     if (AllZeroOperands) {
8430       // Treat this like a bitcast.
8431       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8432     }
8433     break;
8434   }
8435   }
8436
8437   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8438     // If there is a large requested alignment and we can, bump up the alignment
8439     // of the global.
8440     if (!GV->isDeclaration()) {
8441       GV->setAlignment(PrefAlign);
8442       Align = PrefAlign;
8443     }
8444   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8445     // If there is a requested alignment and if this is an alloca, round up.  We
8446     // don't do this for malloc, because some systems can't respect the request.
8447     if (isa<AllocaInst>(AI)) {
8448       AI->setAlignment(PrefAlign);
8449       Align = PrefAlign;
8450     }
8451   }
8452
8453   return Align;
8454 }
8455
8456 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8457 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8458 /// and it is more than the alignment of the ultimate object, see if we can
8459 /// increase the alignment of the ultimate object, making this check succeed.
8460 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8461                                                   unsigned PrefAlign) {
8462   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8463                       sizeof(PrefAlign) * CHAR_BIT;
8464   APInt Mask = APInt::getAllOnesValue(BitWidth);
8465   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8466   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8467   unsigned TrailZ = KnownZero.countTrailingOnes();
8468   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8469
8470   if (PrefAlign > Align)
8471     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8472   
8473     // We don't need to make any adjustment.
8474   return Align;
8475 }
8476
8477 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8478   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8479   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8480   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8481   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8482
8483   if (CopyAlign < MinAlign) {
8484     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8485     return MI;
8486   }
8487   
8488   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8489   // load/store.
8490   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8491   if (MemOpLength == 0) return 0;
8492   
8493   // Source and destination pointer types are always "i8*" for intrinsic.  See
8494   // if the size is something we can handle with a single primitive load/store.
8495   // A single load+store correctly handles overlapping memory in the memmove
8496   // case.
8497   unsigned Size = MemOpLength->getZExtValue();
8498   if (Size == 0) return MI;  // Delete this mem transfer.
8499   
8500   if (Size > 8 || (Size&(Size-1)))
8501     return 0;  // If not 1/2/4/8 bytes, exit.
8502   
8503   // Use an integer load+store unless we can find something better.
8504   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8505   
8506   // Memcpy forces the use of i8* for the source and destination.  That means
8507   // that if you're using memcpy to move one double around, you'll get a cast
8508   // from double* to i8*.  We'd much rather use a double load+store rather than
8509   // an i64 load+store, here because this improves the odds that the source or
8510   // dest address will be promotable.  See if we can find a better type than the
8511   // integer datatype.
8512   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8513     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8514     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8515       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8516       // down through these levels if so.
8517       while (!SrcETy->isFirstClassType()) {
8518         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8519           if (STy->getNumElements() == 1)
8520             SrcETy = STy->getElementType(0);
8521           else
8522             break;
8523         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8524           if (ATy->getNumElements() == 1)
8525             SrcETy = ATy->getElementType();
8526           else
8527             break;
8528         } else
8529           break;
8530       }
8531       
8532       if (SrcETy->isFirstClassType())
8533         NewPtrTy = PointerType::getUnqual(SrcETy);
8534     }
8535   }
8536   
8537   
8538   // If the memcpy/memmove provides better alignment info than we can
8539   // infer, use it.
8540   SrcAlign = std::max(SrcAlign, CopyAlign);
8541   DstAlign = std::max(DstAlign, CopyAlign);
8542   
8543   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8544   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8545   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8546   InsertNewInstBefore(L, *MI);
8547   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8548
8549   // Set the size of the copy to 0, it will be deleted on the next iteration.
8550   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8551   return MI;
8552 }
8553
8554 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8555   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8556   if (MI->getAlignment()->getZExtValue() < Alignment) {
8557     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8558     return MI;
8559   }
8560   
8561   // Extract the length and alignment and fill if they are constant.
8562   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8563   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8564   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8565     return 0;
8566   uint64_t Len = LenC->getZExtValue();
8567   Alignment = MI->getAlignment()->getZExtValue();
8568   
8569   // If the length is zero, this is a no-op
8570   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8571   
8572   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8573   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8574     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8575     
8576     Value *Dest = MI->getDest();
8577     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8578
8579     // Alignment 0 is identity for alignment 1 for memset, but not store.
8580     if (Alignment == 0) Alignment = 1;
8581     
8582     // Extract the fill value and store.
8583     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8584     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8585                                       Alignment), *MI);
8586     
8587     // Set the size of the copy to 0, it will be deleted on the next iteration.
8588     MI->setLength(Constant::getNullValue(LenC->getType()));
8589     return MI;
8590   }
8591
8592   return 0;
8593 }
8594
8595
8596 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8597 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8598 /// the heavy lifting.
8599 ///
8600 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8601   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8602   if (!II) return visitCallSite(&CI);
8603   
8604   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8605   // visitCallSite.
8606   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8607     bool Changed = false;
8608
8609     // memmove/cpy/set of zero bytes is a noop.
8610     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8611       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8612
8613       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8614         if (CI->getZExtValue() == 1) {
8615           // Replace the instruction with just byte operations.  We would
8616           // transform other cases to loads/stores, but we don't know if
8617           // alignment is sufficient.
8618         }
8619     }
8620
8621     // If we have a memmove and the source operation is a constant global,
8622     // then the source and dest pointers can't alias, so we can change this
8623     // into a call to memcpy.
8624     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8625       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8626         if (GVSrc->isConstant()) {
8627           Module *M = CI.getParent()->getParent()->getParent();
8628           Intrinsic::ID MemCpyID;
8629           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8630             MemCpyID = Intrinsic::memcpy_i32;
8631           else
8632             MemCpyID = Intrinsic::memcpy_i64;
8633           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8634           Changed = true;
8635         }
8636     }
8637
8638     // If we can determine a pointer alignment that is bigger than currently
8639     // set, update the alignment.
8640     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8641       if (Instruction *I = SimplifyMemTransfer(MI))
8642         return I;
8643     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8644       if (Instruction *I = SimplifyMemSet(MSI))
8645         return I;
8646     }
8647           
8648     if (Changed) return II;
8649   } else {
8650     switch (II->getIntrinsicID()) {
8651     default: break;
8652     case Intrinsic::ppc_altivec_lvx:
8653     case Intrinsic::ppc_altivec_lvxl:
8654     case Intrinsic::x86_sse_loadu_ps:
8655     case Intrinsic::x86_sse2_loadu_pd:
8656     case Intrinsic::x86_sse2_loadu_dq:
8657       // Turn PPC lvx     -> load if the pointer is known aligned.
8658       // Turn X86 loadups -> load if the pointer is known aligned.
8659       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8660         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8661                                          PointerType::getUnqual(II->getType()),
8662                                          CI);
8663         return new LoadInst(Ptr);
8664       }
8665       break;
8666     case Intrinsic::ppc_altivec_stvx:
8667     case Intrinsic::ppc_altivec_stvxl:
8668       // Turn stvx -> store if the pointer is known aligned.
8669       if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8670         const Type *OpPtrTy = 
8671           PointerType::getUnqual(II->getOperand(1)->getType());
8672         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8673         return new StoreInst(II->getOperand(1), Ptr);
8674       }
8675       break;
8676     case Intrinsic::x86_sse_storeu_ps:
8677     case Intrinsic::x86_sse2_storeu_pd:
8678     case Intrinsic::x86_sse2_storeu_dq:
8679     case Intrinsic::x86_sse2_storel_dq:
8680       // Turn X86 storeu -> store if the pointer is known aligned.
8681       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8682         const Type *OpPtrTy = 
8683           PointerType::getUnqual(II->getOperand(2)->getType());
8684         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8685         return new StoreInst(II->getOperand(2), Ptr);
8686       }
8687       break;
8688       
8689     case Intrinsic::x86_sse_cvttss2si: {
8690       // These intrinsics only demands the 0th element of its input vector.  If
8691       // we can simplify the input based on that, do so now.
8692       uint64_t UndefElts;
8693       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8694                                                 UndefElts)) {
8695         II->setOperand(1, V);
8696         return II;
8697       }
8698       break;
8699     }
8700       
8701     case Intrinsic::ppc_altivec_vperm:
8702       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8703       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8704         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8705         
8706         // Check that all of the elements are integer constants or undefs.
8707         bool AllEltsOk = true;
8708         for (unsigned i = 0; i != 16; ++i) {
8709           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8710               !isa<UndefValue>(Mask->getOperand(i))) {
8711             AllEltsOk = false;
8712             break;
8713           }
8714         }
8715         
8716         if (AllEltsOk) {
8717           // Cast the input vectors to byte vectors.
8718           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8719           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8720           Value *Result = UndefValue::get(Op0->getType());
8721           
8722           // Only extract each element once.
8723           Value *ExtractedElts[32];
8724           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8725           
8726           for (unsigned i = 0; i != 16; ++i) {
8727             if (isa<UndefValue>(Mask->getOperand(i)))
8728               continue;
8729             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8730             Idx &= 31;  // Match the hardware behavior.
8731             
8732             if (ExtractedElts[Idx] == 0) {
8733               Instruction *Elt = 
8734                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8735               InsertNewInstBefore(Elt, CI);
8736               ExtractedElts[Idx] = Elt;
8737             }
8738           
8739             // Insert this value into the result vector.
8740             Result = InsertElementInst::Create(Result, ExtractedElts[Idx], i, "tmp");
8741             InsertNewInstBefore(cast<Instruction>(Result), CI);
8742           }
8743           return CastInst::create(Instruction::BitCast, Result, CI.getType());
8744         }
8745       }
8746       break;
8747
8748     case Intrinsic::stackrestore: {
8749       // If the save is right next to the restore, remove the restore.  This can
8750       // happen when variable allocas are DCE'd.
8751       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8752         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8753           BasicBlock::iterator BI = SS;
8754           if (&*++BI == II)
8755             return EraseInstFromFunction(CI);
8756         }
8757       }
8758       
8759       // Scan down this block to see if there is another stack restore in the
8760       // same block without an intervening call/alloca.
8761       BasicBlock::iterator BI = II;
8762       TerminatorInst *TI = II->getParent()->getTerminator();
8763       bool CannotRemove = false;
8764       for (++BI; &*BI != TI; ++BI) {
8765         if (isa<AllocaInst>(BI)) {
8766           CannotRemove = true;
8767           break;
8768         }
8769         if (isa<CallInst>(BI)) {
8770           if (!isa<IntrinsicInst>(BI)) {
8771             CannotRemove = true;
8772             break;
8773           }
8774           // If there is a stackrestore below this one, remove this one.
8775           return EraseInstFromFunction(CI);
8776         }
8777       }
8778       
8779       // If the stack restore is in a return/unwind block and if there are no
8780       // allocas or calls between the restore and the return, nuke the restore.
8781       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8782         return EraseInstFromFunction(CI);
8783       break;
8784     }
8785     }
8786   }
8787
8788   return visitCallSite(II);
8789 }
8790
8791 // InvokeInst simplification
8792 //
8793 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8794   return visitCallSite(&II);
8795 }
8796
8797 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8798 /// passed through the varargs area, we can eliminate the use of the cast.
8799 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8800                                          const CastInst * const CI,
8801                                          const TargetData * const TD,
8802                                          const int ix) {
8803   if (!CI->isLosslessCast())
8804     return false;
8805
8806   // The size of ByVal arguments is derived from the type, so we
8807   // can't change to a type with a different size.  If the size were
8808   // passed explicitly we could avoid this check.
8809   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8810     return true;
8811
8812   const Type* SrcTy = 
8813             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8814   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8815   if (!SrcTy->isSized() || !DstTy->isSized())
8816     return false;
8817   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8818     return false;
8819   return true;
8820 }
8821
8822 // visitCallSite - Improvements for call and invoke instructions.
8823 //
8824 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8825   bool Changed = false;
8826
8827   // If the callee is a constexpr cast of a function, attempt to move the cast
8828   // to the arguments of the call/invoke.
8829   if (transformConstExprCastCall(CS)) return 0;
8830
8831   Value *Callee = CS.getCalledValue();
8832
8833   if (Function *CalleeF = dyn_cast<Function>(Callee))
8834     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8835       Instruction *OldCall = CS.getInstruction();
8836       // If the call and callee calling conventions don't match, this call must
8837       // be unreachable, as the call is undefined.
8838       new StoreInst(ConstantInt::getTrue(),
8839                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8840                                     OldCall);
8841       if (!OldCall->use_empty())
8842         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8843       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8844         return EraseInstFromFunction(*OldCall);
8845       return 0;
8846     }
8847
8848   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8849     // This instruction is not reachable, just remove it.  We insert a store to
8850     // undef so that we know that this code is not reachable, despite the fact
8851     // that we can't modify the CFG here.
8852     new StoreInst(ConstantInt::getTrue(),
8853                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8854                   CS.getInstruction());
8855
8856     if (!CS.getInstruction()->use_empty())
8857       CS.getInstruction()->
8858         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8859
8860     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8861       // Don't break the CFG, insert a dummy cond branch.
8862       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8863                          ConstantInt::getTrue(), II);
8864     }
8865     return EraseInstFromFunction(*CS.getInstruction());
8866   }
8867
8868   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8869     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8870       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8871         return transformCallThroughTrampoline(CS);
8872
8873   const PointerType *PTy = cast<PointerType>(Callee->getType());
8874   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8875   if (FTy->isVarArg()) {
8876     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8877     // See if we can optimize any arguments passed through the varargs area of
8878     // the call.
8879     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8880            E = CS.arg_end(); I != E; ++I, ++ix) {
8881       CastInst *CI = dyn_cast<CastInst>(*I);
8882       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8883         *I = CI->getOperand(0);
8884         Changed = true;
8885       }
8886     }
8887   }
8888
8889   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8890     // Inline asm calls cannot throw - mark them 'nounwind'.
8891     CS.setDoesNotThrow();
8892     Changed = true;
8893   }
8894
8895   return Changed ? CS.getInstruction() : 0;
8896 }
8897
8898 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8899 // attempt to move the cast to the arguments of the call/invoke.
8900 //
8901 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8902   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8903   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8904   if (CE->getOpcode() != Instruction::BitCast || 
8905       !isa<Function>(CE->getOperand(0)))
8906     return false;
8907   Function *Callee = cast<Function>(CE->getOperand(0));
8908   Instruction *Caller = CS.getInstruction();
8909   const PAListPtr &CallerPAL = CS.getParamAttrs();
8910
8911   // Okay, this is a cast from a function to a different type.  Unless doing so
8912   // would cause a type conversion of one of our arguments, change this call to
8913   // be a direct call with arguments casted to the appropriate types.
8914   //
8915   const FunctionType *FT = Callee->getFunctionType();
8916   const Type *OldRetTy = Caller->getType();
8917
8918   if (isa<StructType>(FT->getReturnType()))
8919     return false; // TODO: Handle multiple return values.
8920
8921   // Check to see if we are changing the return type...
8922   if (OldRetTy != FT->getReturnType()) {
8923     if (Callee->isDeclaration() && !Caller->use_empty() && 
8924         // Conversion is ok if changing from pointer to int of same size.
8925         !(isa<PointerType>(FT->getReturnType()) &&
8926           TD->getIntPtrType() == OldRetTy))
8927       return false;   // Cannot transform this return value.
8928
8929     if (!Caller->use_empty() &&
8930         // void -> non-void is handled specially
8931         FT->getReturnType() != Type::VoidTy &&
8932         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8933       return false;   // Cannot transform this return value.
8934
8935     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8936       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8937       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8938         return false;   // Attribute not compatible with transformed value.
8939     }
8940
8941     // If the callsite is an invoke instruction, and the return value is used by
8942     // a PHI node in a successor, we cannot change the return type of the call
8943     // because there is no place to put the cast instruction (without breaking
8944     // the critical edge).  Bail out in this case.
8945     if (!Caller->use_empty())
8946       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8947         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8948              UI != E; ++UI)
8949           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8950             if (PN->getParent() == II->getNormalDest() ||
8951                 PN->getParent() == II->getUnwindDest())
8952               return false;
8953   }
8954
8955   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8956   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8957
8958   CallSite::arg_iterator AI = CS.arg_begin();
8959   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8960     const Type *ParamTy = FT->getParamType(i);
8961     const Type *ActTy = (*AI)->getType();
8962
8963     if (!CastInst::isCastable(ActTy, ParamTy))
8964       return false;   // Cannot transform this parameter value.
8965
8966     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8967       return false;   // Attribute not compatible with transformed value.
8968
8969     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8970     // Some conversions are safe even if we do not have a body.
8971     // Either we can cast directly, or we can upconvert the argument
8972     bool isConvertible = ActTy == ParamTy ||
8973       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8974       (ParamTy->isInteger() && ActTy->isInteger() &&
8975        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8976       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8977        && c->getValue().isStrictlyPositive());
8978     if (Callee->isDeclaration() && !isConvertible) return false;
8979   }
8980
8981   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8982       Callee->isDeclaration())
8983     return false;   // Do not delete arguments unless we have a function body.
8984
8985   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8986       !CallerPAL.isEmpty())
8987     // In this case we have more arguments than the new function type, but we
8988     // won't be dropping them.  Check that these extra arguments have attributes
8989     // that are compatible with being a vararg call argument.
8990     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8991       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8992         break;
8993       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8994       if (PAttrs & ParamAttr::VarArgsIncompatible)
8995         return false;
8996     }
8997
8998   // Okay, we decided that this is a safe thing to do: go ahead and start
8999   // inserting cast instructions as necessary...
9000   std::vector<Value*> Args;
9001   Args.reserve(NumActualArgs);
9002   SmallVector<ParamAttrsWithIndex, 8> attrVec;
9003   attrVec.reserve(NumCommonArgs);
9004
9005   // Get any return attributes.
9006   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9007
9008   // If the return value is not being used, the type may not be compatible
9009   // with the existing attributes.  Wipe out any problematic attributes.
9010   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
9011
9012   // Add the new return attributes.
9013   if (RAttrs)
9014     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9015
9016   AI = CS.arg_begin();
9017   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9018     const Type *ParamTy = FT->getParamType(i);
9019     if ((*AI)->getType() == ParamTy) {
9020       Args.push_back(*AI);
9021     } else {
9022       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9023           false, ParamTy, false);
9024       CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
9025       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9026     }
9027
9028     // Add any parameter attributes.
9029     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9030       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9031   }
9032
9033   // If the function takes more arguments than the call was taking, add them
9034   // now...
9035   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9036     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9037
9038   // If we are removing arguments to the function, emit an obnoxious warning...
9039   if (FT->getNumParams() < NumActualArgs) {
9040     if (!FT->isVarArg()) {
9041       cerr << "WARNING: While resolving call to function '"
9042            << Callee->getName() << "' arguments were dropped!\n";
9043     } else {
9044       // Add all of the arguments in their promoted form to the arg list...
9045       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9046         const Type *PTy = getPromotedType((*AI)->getType());
9047         if (PTy != (*AI)->getType()) {
9048           // Must promote to pass through va_arg area!
9049           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9050                                                                 PTy, false);
9051           Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
9052           InsertNewInstBefore(Cast, *Caller);
9053           Args.push_back(Cast);
9054         } else {
9055           Args.push_back(*AI);
9056         }
9057
9058         // Add any parameter attributes.
9059         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9060           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9061       }
9062     }
9063   }
9064
9065   if (FT->getReturnType() == Type::VoidTy)
9066     Caller->setName("");   // Void type should not have a name.
9067
9068   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9069
9070   Instruction *NC;
9071   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9072     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9073                             Args.begin(), Args.end(), Caller->getName(), Caller);
9074     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9075     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9076   } else {
9077     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9078                           Caller->getName(), Caller);
9079     CallInst *CI = cast<CallInst>(Caller);
9080     if (CI->isTailCall())
9081       cast<CallInst>(NC)->setTailCall();
9082     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9083     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9084   }
9085
9086   // Insert a cast of the return type as necessary.
9087   Value *NV = NC;
9088   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9089     if (NV->getType() != Type::VoidTy) {
9090       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9091                                                             OldRetTy, false);
9092       NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
9093
9094       // If this is an invoke instruction, we should insert it after the first
9095       // non-phi, instruction in the normal successor block.
9096       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9097         BasicBlock::iterator I = II->getNormalDest()->begin();
9098         while (isa<PHINode>(I)) ++I;
9099         InsertNewInstBefore(NC, *I);
9100       } else {
9101         // Otherwise, it's a call, just insert cast right after the call instr
9102         InsertNewInstBefore(NC, *Caller);
9103       }
9104       AddUsersToWorkList(*Caller);
9105     } else {
9106       NV = UndefValue::get(Caller->getType());
9107     }
9108   }
9109
9110   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9111     Caller->replaceAllUsesWith(NV);
9112   Caller->eraseFromParent();
9113   RemoveFromWorkList(Caller);
9114   return true;
9115 }
9116
9117 // transformCallThroughTrampoline - Turn a call to a function created by the
9118 // init_trampoline intrinsic into a direct call to the underlying function.
9119 //
9120 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9121   Value *Callee = CS.getCalledValue();
9122   const PointerType *PTy = cast<PointerType>(Callee->getType());
9123   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9124   const PAListPtr &Attrs = CS.getParamAttrs();
9125
9126   // If the call already has the 'nest' attribute somewhere then give up -
9127   // otherwise 'nest' would occur twice after splicing in the chain.
9128   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9129     return 0;
9130
9131   IntrinsicInst *Tramp =
9132     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9133
9134   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9135   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9136   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9137
9138   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9139   if (!NestAttrs.isEmpty()) {
9140     unsigned NestIdx = 1;
9141     const Type *NestTy = 0;
9142     ParameterAttributes NestAttr = ParamAttr::None;
9143
9144     // Look for a parameter marked with the 'nest' attribute.
9145     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9146          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9147       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9148         // Record the parameter type and any other attributes.
9149         NestTy = *I;
9150         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9151         break;
9152       }
9153
9154     if (NestTy) {
9155       Instruction *Caller = CS.getInstruction();
9156       std::vector<Value*> NewArgs;
9157       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9158
9159       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9160       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9161
9162       // Insert the nest argument into the call argument list, which may
9163       // mean appending it.  Likewise for attributes.
9164
9165       // Add any function result attributes.
9166       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9167         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9168
9169       {
9170         unsigned Idx = 1;
9171         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9172         do {
9173           if (Idx == NestIdx) {
9174             // Add the chain argument and attributes.
9175             Value *NestVal = Tramp->getOperand(3);
9176             if (NestVal->getType() != NestTy)
9177               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9178             NewArgs.push_back(NestVal);
9179             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9180           }
9181
9182           if (I == E)
9183             break;
9184
9185           // Add the original argument and attributes.
9186           NewArgs.push_back(*I);
9187           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9188             NewAttrs.push_back
9189               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9190
9191           ++Idx, ++I;
9192         } while (1);
9193       }
9194
9195       // The trampoline may have been bitcast to a bogus type (FTy).
9196       // Handle this by synthesizing a new function type, equal to FTy
9197       // with the chain parameter inserted.
9198
9199       std::vector<const Type*> NewTypes;
9200       NewTypes.reserve(FTy->getNumParams()+1);
9201
9202       // Insert the chain's type into the list of parameter types, which may
9203       // mean appending it.
9204       {
9205         unsigned Idx = 1;
9206         FunctionType::param_iterator I = FTy->param_begin(),
9207           E = FTy->param_end();
9208
9209         do {
9210           if (Idx == NestIdx)
9211             // Add the chain's type.
9212             NewTypes.push_back(NestTy);
9213
9214           if (I == E)
9215             break;
9216
9217           // Add the original type.
9218           NewTypes.push_back(*I);
9219
9220           ++Idx, ++I;
9221         } while (1);
9222       }
9223
9224       // Replace the trampoline call with a direct call.  Let the generic
9225       // code sort out any function type mismatches.
9226       FunctionType *NewFTy =
9227         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9228       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9229         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9230       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9231
9232       Instruction *NewCaller;
9233       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9234         NewCaller = InvokeInst::Create(NewCallee,
9235                                        II->getNormalDest(), II->getUnwindDest(),
9236                                        NewArgs.begin(), NewArgs.end(),
9237                                        Caller->getName(), Caller);
9238         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9239         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9240       } else {
9241         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9242                                      Caller->getName(), Caller);
9243         if (cast<CallInst>(Caller)->isTailCall())
9244           cast<CallInst>(NewCaller)->setTailCall();
9245         cast<CallInst>(NewCaller)->
9246           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9247         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9248       }
9249       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9250         Caller->replaceAllUsesWith(NewCaller);
9251       Caller->eraseFromParent();
9252       RemoveFromWorkList(Caller);
9253       return 0;
9254     }
9255   }
9256
9257   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9258   // parameter, there is no need to adjust the argument list.  Let the generic
9259   // code sort out any function type mismatches.
9260   Constant *NewCallee =
9261     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9262   CS.setCalledFunction(NewCallee);
9263   return CS.getInstruction();
9264 }
9265
9266 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9267 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9268 /// and a single binop.
9269 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9270   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9271   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9272          isa<CmpInst>(FirstInst));
9273   unsigned Opc = FirstInst->getOpcode();
9274   Value *LHSVal = FirstInst->getOperand(0);
9275   Value *RHSVal = FirstInst->getOperand(1);
9276     
9277   const Type *LHSType = LHSVal->getType();
9278   const Type *RHSType = RHSVal->getType();
9279   
9280   // Scan to see if all operands are the same opcode, all have one use, and all
9281   // kill their operands (i.e. the operands have one use).
9282   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9283     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9284     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9285         // Verify type of the LHS matches so we don't fold cmp's of different
9286         // types or GEP's with different index types.
9287         I->getOperand(0)->getType() != LHSType ||
9288         I->getOperand(1)->getType() != RHSType)
9289       return 0;
9290
9291     // If they are CmpInst instructions, check their predicates
9292     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9293       if (cast<CmpInst>(I)->getPredicate() !=
9294           cast<CmpInst>(FirstInst)->getPredicate())
9295         return 0;
9296     
9297     // Keep track of which operand needs a phi node.
9298     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9299     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9300   }
9301   
9302   // Otherwise, this is safe to transform, determine if it is profitable.
9303
9304   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9305   // Indexes are often folded into load/store instructions, so we don't want to
9306   // hide them behind a phi.
9307   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9308     return 0;
9309   
9310   Value *InLHS = FirstInst->getOperand(0);
9311   Value *InRHS = FirstInst->getOperand(1);
9312   PHINode *NewLHS = 0, *NewRHS = 0;
9313   if (LHSVal == 0) {
9314     NewLHS = PHINode::Create(LHSType, FirstInst->getOperand(0)->getName()+".pn");
9315     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9316     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9317     InsertNewInstBefore(NewLHS, PN);
9318     LHSVal = NewLHS;
9319   }
9320   
9321   if (RHSVal == 0) {
9322     NewRHS = PHINode::Create(RHSType, FirstInst->getOperand(1)->getName()+".pn");
9323     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9324     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9325     InsertNewInstBefore(NewRHS, PN);
9326     RHSVal = NewRHS;
9327   }
9328   
9329   // Add all operands to the new PHIs.
9330   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9331     if (NewLHS) {
9332       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9333       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9334     }
9335     if (NewRHS) {
9336       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9337       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9338     }
9339   }
9340     
9341   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9342     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
9343   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9344     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9345                            RHSVal);
9346   else {
9347     assert(isa<GetElementPtrInst>(FirstInst));
9348     return GetElementPtrInst::Create(LHSVal, RHSVal);
9349   }
9350 }
9351
9352 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9353 /// of the block that defines it.  This means that it must be obvious the value
9354 /// of the load is not changed from the point of the load to the end of the
9355 /// block it is in.
9356 ///
9357 /// Finally, it is safe, but not profitable, to sink a load targetting a
9358 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9359 /// to a register.
9360 static bool isSafeToSinkLoad(LoadInst *L) {
9361   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9362   
9363   for (++BBI; BBI != E; ++BBI)
9364     if (BBI->mayWriteToMemory())
9365       return false;
9366   
9367   // Check for non-address taken alloca.  If not address-taken already, it isn't
9368   // profitable to do this xform.
9369   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9370     bool isAddressTaken = false;
9371     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9372          UI != E; ++UI) {
9373       if (isa<LoadInst>(UI)) continue;
9374       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9375         // If storing TO the alloca, then the address isn't taken.
9376         if (SI->getOperand(1) == AI) continue;
9377       }
9378       isAddressTaken = true;
9379       break;
9380     }
9381     
9382     if (!isAddressTaken)
9383       return false;
9384   }
9385   
9386   return true;
9387 }
9388
9389
9390 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9391 // operator and they all are only used by the PHI, PHI together their
9392 // inputs, and do the operation once, to the result of the PHI.
9393 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9394   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9395
9396   // Scan the instruction, looking for input operations that can be folded away.
9397   // If all input operands to the phi are the same instruction (e.g. a cast from
9398   // the same type or "+42") we can pull the operation through the PHI, reducing
9399   // code size and simplifying code.
9400   Constant *ConstantOp = 0;
9401   const Type *CastSrcTy = 0;
9402   bool isVolatile = false;
9403   if (isa<CastInst>(FirstInst)) {
9404     CastSrcTy = FirstInst->getOperand(0)->getType();
9405   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9406     // Can fold binop, compare or shift here if the RHS is a constant, 
9407     // otherwise call FoldPHIArgBinOpIntoPHI.
9408     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9409     if (ConstantOp == 0)
9410       return FoldPHIArgBinOpIntoPHI(PN);
9411   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9412     isVolatile = LI->isVolatile();
9413     // We can't sink the load if the loaded value could be modified between the
9414     // load and the PHI.
9415     if (LI->getParent() != PN.getIncomingBlock(0) ||
9416         !isSafeToSinkLoad(LI))
9417       return 0;
9418   } else if (isa<GetElementPtrInst>(FirstInst)) {
9419     if (FirstInst->getNumOperands() == 2)
9420       return FoldPHIArgBinOpIntoPHI(PN);
9421     // Can't handle general GEPs yet.
9422     return 0;
9423   } else {
9424     return 0;  // Cannot fold this operation.
9425   }
9426
9427   // Check to see if all arguments are the same operation.
9428   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9429     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9430     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9431     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9432       return 0;
9433     if (CastSrcTy) {
9434       if (I->getOperand(0)->getType() != CastSrcTy)
9435         return 0;  // Cast operation must match.
9436     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9437       // We can't sink the load if the loaded value could be modified between 
9438       // the load and the PHI.
9439       if (LI->isVolatile() != isVolatile ||
9440           LI->getParent() != PN.getIncomingBlock(i) ||
9441           !isSafeToSinkLoad(LI))
9442         return 0;
9443       
9444       // If the PHI is volatile and its block has multiple successors, sinking
9445       // it would remove a load of the volatile value from the path through the
9446       // other successor.
9447       if (isVolatile &&
9448           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9449         return 0;
9450
9451       
9452     } else if (I->getOperand(1) != ConstantOp) {
9453       return 0;
9454     }
9455   }
9456
9457   // Okay, they are all the same operation.  Create a new PHI node of the
9458   // correct type, and PHI together all of the LHS's of the instructions.
9459   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9460                                    PN.getName()+".in");
9461   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9462
9463   Value *InVal = FirstInst->getOperand(0);
9464   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9465
9466   // Add all operands to the new PHI.
9467   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9468     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9469     if (NewInVal != InVal)
9470       InVal = 0;
9471     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9472   }
9473
9474   Value *PhiVal;
9475   if (InVal) {
9476     // The new PHI unions all of the same values together.  This is really
9477     // common, so we handle it intelligently here for compile-time speed.
9478     PhiVal = InVal;
9479     delete NewPN;
9480   } else {
9481     InsertNewInstBefore(NewPN, PN);
9482     PhiVal = NewPN;
9483   }
9484
9485   // Insert and return the new operation.
9486   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9487     return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
9488   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9489     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
9490   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9491     return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), 
9492                            PhiVal, ConstantOp);
9493   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9494   
9495   // If this was a volatile load that we are merging, make sure to loop through
9496   // and mark all the input loads as non-volatile.  If we don't do this, we will
9497   // insert a new volatile load and the old ones will not be deletable.
9498   if (isVolatile)
9499     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9500       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9501   
9502   return new LoadInst(PhiVal, "", isVolatile);
9503 }
9504
9505 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9506 /// that is dead.
9507 static bool DeadPHICycle(PHINode *PN,
9508                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9509   if (PN->use_empty()) return true;
9510   if (!PN->hasOneUse()) return false;
9511
9512   // Remember this node, and if we find the cycle, return.
9513   if (!PotentiallyDeadPHIs.insert(PN))
9514     return true;
9515   
9516   // Don't scan crazily complex things.
9517   if (PotentiallyDeadPHIs.size() == 16)
9518     return false;
9519
9520   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9521     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9522
9523   return false;
9524 }
9525
9526 /// PHIsEqualValue - Return true if this phi node is always equal to
9527 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9528 ///   z = some value; x = phi (y, z); y = phi (x, z)
9529 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9530                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9531   // See if we already saw this PHI node.
9532   if (!ValueEqualPHIs.insert(PN))
9533     return true;
9534   
9535   // Don't scan crazily complex things.
9536   if (ValueEqualPHIs.size() == 16)
9537     return false;
9538  
9539   // Scan the operands to see if they are either phi nodes or are equal to
9540   // the value.
9541   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9542     Value *Op = PN->getIncomingValue(i);
9543     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9544       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9545         return false;
9546     } else if (Op != NonPhiInVal)
9547       return false;
9548   }
9549   
9550   return true;
9551 }
9552
9553
9554 // PHINode simplification
9555 //
9556 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9557   // If LCSSA is around, don't mess with Phi nodes
9558   if (MustPreserveLCSSA) return 0;
9559   
9560   if (Value *V = PN.hasConstantValue())
9561     return ReplaceInstUsesWith(PN, V);
9562
9563   // If all PHI operands are the same operation, pull them through the PHI,
9564   // reducing code size.
9565   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9566       PN.getIncomingValue(0)->hasOneUse())
9567     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9568       return Result;
9569
9570   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9571   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9572   // PHI)... break the cycle.
9573   if (PN.hasOneUse()) {
9574     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9575     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9576       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9577       PotentiallyDeadPHIs.insert(&PN);
9578       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9579         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9580     }
9581    
9582     // If this phi has a single use, and if that use just computes a value for
9583     // the next iteration of a loop, delete the phi.  This occurs with unused
9584     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9585     // common case here is good because the only other things that catch this
9586     // are induction variable analysis (sometimes) and ADCE, which is only run
9587     // late.
9588     if (PHIUser->hasOneUse() &&
9589         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9590         PHIUser->use_back() == &PN) {
9591       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9592     }
9593   }
9594
9595   // We sometimes end up with phi cycles that non-obviously end up being the
9596   // same value, for example:
9597   //   z = some value; x = phi (y, z); y = phi (x, z)
9598   // where the phi nodes don't necessarily need to be in the same block.  Do a
9599   // quick check to see if the PHI node only contains a single non-phi value, if
9600   // so, scan to see if the phi cycle is actually equal to that value.
9601   {
9602     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9603     // Scan for the first non-phi operand.
9604     while (InValNo != NumOperandVals && 
9605            isa<PHINode>(PN.getIncomingValue(InValNo)))
9606       ++InValNo;
9607
9608     if (InValNo != NumOperandVals) {
9609       Value *NonPhiInVal = PN.getOperand(InValNo);
9610       
9611       // Scan the rest of the operands to see if there are any conflicts, if so
9612       // there is no need to recursively scan other phis.
9613       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9614         Value *OpVal = PN.getIncomingValue(InValNo);
9615         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9616           break;
9617       }
9618       
9619       // If we scanned over all operands, then we have one unique value plus
9620       // phi values.  Scan PHI nodes to see if they all merge in each other or
9621       // the value.
9622       if (InValNo == NumOperandVals) {
9623         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9624         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9625           return ReplaceInstUsesWith(PN, NonPhiInVal);
9626       }
9627     }
9628   }
9629   return 0;
9630 }
9631
9632 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9633                                    Instruction *InsertPoint,
9634                                    InstCombiner *IC) {
9635   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9636   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9637   // We must cast correctly to the pointer type. Ensure that we
9638   // sign extend the integer value if it is smaller as this is
9639   // used for address computation.
9640   Instruction::CastOps opcode = 
9641      (VTySize < PtrSize ? Instruction::SExt :
9642       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9643   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9644 }
9645
9646
9647 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9648   Value *PtrOp = GEP.getOperand(0);
9649   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9650   // If so, eliminate the noop.
9651   if (GEP.getNumOperands() == 1)
9652     return ReplaceInstUsesWith(GEP, PtrOp);
9653
9654   if (isa<UndefValue>(GEP.getOperand(0)))
9655     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9656
9657   bool HasZeroPointerIndex = false;
9658   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9659     HasZeroPointerIndex = C->isNullValue();
9660
9661   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9662     return ReplaceInstUsesWith(GEP, PtrOp);
9663
9664   // Eliminate unneeded casts for indices.
9665   bool MadeChange = false;
9666   
9667   gep_type_iterator GTI = gep_type_begin(GEP);
9668   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9669     if (isa<SequentialType>(*GTI)) {
9670       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9671         if (CI->getOpcode() == Instruction::ZExt ||
9672             CI->getOpcode() == Instruction::SExt) {
9673           const Type *SrcTy = CI->getOperand(0)->getType();
9674           // We can eliminate a cast from i32 to i64 iff the target 
9675           // is a 32-bit pointer target.
9676           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9677             MadeChange = true;
9678             GEP.setOperand(i, CI->getOperand(0));
9679           }
9680         }
9681       }
9682       // If we are using a wider index than needed for this platform, shrink it
9683       // to what we need.  If the incoming value needs a cast instruction,
9684       // insert it.  This explicit cast can make subsequent optimizations more
9685       // obvious.
9686       Value *Op = GEP.getOperand(i);
9687       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9688         if (Constant *C = dyn_cast<Constant>(Op)) {
9689           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9690           MadeChange = true;
9691         } else {
9692           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9693                                 GEP);
9694           GEP.setOperand(i, Op);
9695           MadeChange = true;
9696         }
9697       }
9698     }
9699   }
9700   if (MadeChange) return &GEP;
9701
9702   // If this GEP instruction doesn't move the pointer, and if the input operand
9703   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9704   // real input to the dest type.
9705   if (GEP.hasAllZeroIndices()) {
9706     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9707       // If the bitcast is of an allocation, and the allocation will be
9708       // converted to match the type of the cast, don't touch this.
9709       if (isa<AllocationInst>(BCI->getOperand(0))) {
9710         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9711         if (Instruction *I = visitBitCast(*BCI)) {
9712           if (I != BCI) {
9713             I->takeName(BCI);
9714             BCI->getParent()->getInstList().insert(BCI, I);
9715             ReplaceInstUsesWith(*BCI, I);
9716           }
9717           return &GEP;
9718         }
9719       }
9720       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9721     }
9722   }
9723   
9724   // Combine Indices - If the source pointer to this getelementptr instruction
9725   // is a getelementptr instruction, combine the indices of the two
9726   // getelementptr instructions into a single instruction.
9727   //
9728   SmallVector<Value*, 8> SrcGEPOperands;
9729   if (User *Src = dyn_castGetElementPtr(PtrOp))
9730     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9731
9732   if (!SrcGEPOperands.empty()) {
9733     // Note that if our source is a gep chain itself that we wait for that
9734     // chain to be resolved before we perform this transformation.  This
9735     // avoids us creating a TON of code in some cases.
9736     //
9737     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9738         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9739       return 0;   // Wait until our source is folded to completion.
9740
9741     SmallVector<Value*, 8> Indices;
9742
9743     // Find out whether the last index in the source GEP is a sequential idx.
9744     bool EndsWithSequential = false;
9745     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9746            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9747       EndsWithSequential = !isa<StructType>(*I);
9748
9749     // Can we combine the two pointer arithmetics offsets?
9750     if (EndsWithSequential) {
9751       // Replace: gep (gep %P, long B), long A, ...
9752       // With:    T = long A+B; gep %P, T, ...
9753       //
9754       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9755       if (SO1 == Constant::getNullValue(SO1->getType())) {
9756         Sum = GO1;
9757       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9758         Sum = SO1;
9759       } else {
9760         // If they aren't the same type, convert both to an integer of the
9761         // target's pointer size.
9762         if (SO1->getType() != GO1->getType()) {
9763           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9764             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9765           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9766             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9767           } else {
9768             unsigned PS = TD->getPointerSizeInBits();
9769             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9770               // Convert GO1 to SO1's type.
9771               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9772
9773             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9774               // Convert SO1 to GO1's type.
9775               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9776             } else {
9777               const Type *PT = TD->getIntPtrType();
9778               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9779               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9780             }
9781           }
9782         }
9783         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9784           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9785         else {
9786           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9787           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9788         }
9789       }
9790
9791       // Recycle the GEP we already have if possible.
9792       if (SrcGEPOperands.size() == 2) {
9793         GEP.setOperand(0, SrcGEPOperands[0]);
9794         GEP.setOperand(1, Sum);
9795         return &GEP;
9796       } else {
9797         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9798                        SrcGEPOperands.end()-1);
9799         Indices.push_back(Sum);
9800         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9801       }
9802     } else if (isa<Constant>(*GEP.idx_begin()) &&
9803                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9804                SrcGEPOperands.size() != 1) {
9805       // Otherwise we can do the fold if the first index of the GEP is a zero
9806       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9807                      SrcGEPOperands.end());
9808       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9809     }
9810
9811     if (!Indices.empty())
9812       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9813                                        Indices.end(), GEP.getName());
9814
9815   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9816     // GEP of global variable.  If all of the indices for this GEP are
9817     // constants, we can promote this to a constexpr instead of an instruction.
9818
9819     // Scan for nonconstants...
9820     SmallVector<Constant*, 8> Indices;
9821     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9822     for (; I != E && isa<Constant>(*I); ++I)
9823       Indices.push_back(cast<Constant>(*I));
9824
9825     if (I == E) {  // If they are all constants...
9826       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9827                                                     &Indices[0],Indices.size());
9828
9829       // Replace all uses of the GEP with the new constexpr...
9830       return ReplaceInstUsesWith(GEP, CE);
9831     }
9832   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9833     if (!isa<PointerType>(X->getType())) {
9834       // Not interesting.  Source pointer must be a cast from pointer.
9835     } else if (HasZeroPointerIndex) {
9836       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9837       // into     : GEP [10 x i8]* X, i32 0, ...
9838       //
9839       // This occurs when the program declares an array extern like "int X[];"
9840       //
9841       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9842       const PointerType *XTy = cast<PointerType>(X->getType());
9843       if (const ArrayType *XATy =
9844           dyn_cast<ArrayType>(XTy->getElementType()))
9845         if (const ArrayType *CATy =
9846             dyn_cast<ArrayType>(CPTy->getElementType()))
9847           if (CATy->getElementType() == XATy->getElementType()) {
9848             // At this point, we know that the cast source type is a pointer
9849             // to an array of the same type as the destination pointer
9850             // array.  Because the array type is never stepped over (there
9851             // is a leading zero) we can fold the cast into this GEP.
9852             GEP.setOperand(0, X);
9853             return &GEP;
9854           }
9855     } else if (GEP.getNumOperands() == 2) {
9856       // Transform things like:
9857       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9858       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9859       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9860       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9861       if (isa<ArrayType>(SrcElTy) &&
9862           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9863           TD->getABITypeSize(ResElTy)) {
9864         Value *Idx[2];
9865         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9866         Idx[1] = GEP.getOperand(1);
9867         Value *V = InsertNewInstBefore(
9868                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9869         // V and GEP are both pointer types --> BitCast
9870         return new BitCastInst(V, GEP.getType());
9871       }
9872       
9873       // Transform things like:
9874       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9875       //   (where tmp = 8*tmp2) into:
9876       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9877       
9878       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9879         uint64_t ArrayEltSize =
9880             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9881         
9882         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9883         // allow either a mul, shift, or constant here.
9884         Value *NewIdx = 0;
9885         ConstantInt *Scale = 0;
9886         if (ArrayEltSize == 1) {
9887           NewIdx = GEP.getOperand(1);
9888           Scale = ConstantInt::get(NewIdx->getType(), 1);
9889         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9890           NewIdx = ConstantInt::get(CI->getType(), 1);
9891           Scale = CI;
9892         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9893           if (Inst->getOpcode() == Instruction::Shl &&
9894               isa<ConstantInt>(Inst->getOperand(1))) {
9895             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9896             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9897             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9898             NewIdx = Inst->getOperand(0);
9899           } else if (Inst->getOpcode() == Instruction::Mul &&
9900                      isa<ConstantInt>(Inst->getOperand(1))) {
9901             Scale = cast<ConstantInt>(Inst->getOperand(1));
9902             NewIdx = Inst->getOperand(0);
9903           }
9904         }
9905         
9906         // If the index will be to exactly the right offset with the scale taken
9907         // out, perform the transformation. Note, we don't know whether Scale is
9908         // signed or not. We'll use unsigned version of division/modulo
9909         // operation after making sure Scale doesn't have the sign bit set.
9910         if (Scale && Scale->getSExtValue() >= 0LL &&
9911             Scale->getZExtValue() % ArrayEltSize == 0) {
9912           Scale = ConstantInt::get(Scale->getType(),
9913                                    Scale->getZExtValue() / ArrayEltSize);
9914           if (Scale->getZExtValue() != 1) {
9915             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9916                                                        false /*ZExt*/);
9917             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9918             NewIdx = InsertNewInstBefore(Sc, GEP);
9919           }
9920
9921           // Insert the new GEP instruction.
9922           Value *Idx[2];
9923           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9924           Idx[1] = NewIdx;
9925           Instruction *NewGEP =
9926             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9927           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9928           // The NewGEP must be pointer typed, so must the old one -> BitCast
9929           return new BitCastInst(NewGEP, GEP.getType());
9930         }
9931       }
9932     }
9933   }
9934
9935   return 0;
9936 }
9937
9938 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9939   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9940   if (AI.isArrayAllocation()) {  // Check C != 1
9941     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9942       const Type *NewTy = 
9943         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9944       AllocationInst *New = 0;
9945
9946       // Create and insert the replacement instruction...
9947       if (isa<MallocInst>(AI))
9948         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9949       else {
9950         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9951         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9952       }
9953
9954       InsertNewInstBefore(New, AI);
9955
9956       // Scan to the end of the allocation instructions, to skip over a block of
9957       // allocas if possible...
9958       //
9959       BasicBlock::iterator It = New;
9960       while (isa<AllocationInst>(*It)) ++It;
9961
9962       // Now that I is pointing to the first non-allocation-inst in the block,
9963       // insert our getelementptr instruction...
9964       //
9965       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9966       Value *Idx[2];
9967       Idx[0] = NullIdx;
9968       Idx[1] = NullIdx;
9969       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9970                                            New->getName()+".sub", It);
9971
9972       // Now make everything use the getelementptr instead of the original
9973       // allocation.
9974       return ReplaceInstUsesWith(AI, V);
9975     } else if (isa<UndefValue>(AI.getArraySize())) {
9976       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9977     }
9978   }
9979
9980   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9981   // Note that we only do this for alloca's, because malloc should allocate and
9982   // return a unique pointer, even for a zero byte allocation.
9983   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9984       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9985     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9986
9987   return 0;
9988 }
9989
9990 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9991   Value *Op = FI.getOperand(0);
9992
9993   // free undef -> unreachable.
9994   if (isa<UndefValue>(Op)) {
9995     // Insert a new store to null because we cannot modify the CFG here.
9996     new StoreInst(ConstantInt::getTrue(),
9997                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9998     return EraseInstFromFunction(FI);
9999   }
10000   
10001   // If we have 'free null' delete the instruction.  This can happen in stl code
10002   // when lots of inlining happens.
10003   if (isa<ConstantPointerNull>(Op))
10004     return EraseInstFromFunction(FI);
10005   
10006   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10007   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10008     FI.setOperand(0, CI->getOperand(0));
10009     return &FI;
10010   }
10011   
10012   // Change free (gep X, 0,0,0,0) into free(X)
10013   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10014     if (GEPI->hasAllZeroIndices()) {
10015       AddToWorkList(GEPI);
10016       FI.setOperand(0, GEPI->getOperand(0));
10017       return &FI;
10018     }
10019   }
10020   
10021   // Change free(malloc) into nothing, if the malloc has a single use.
10022   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10023     if (MI->hasOneUse()) {
10024       EraseInstFromFunction(FI);
10025       return EraseInstFromFunction(*MI);
10026     }
10027
10028   return 0;
10029 }
10030
10031
10032 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10033 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10034                                         const TargetData *TD) {
10035   User *CI = cast<User>(LI.getOperand(0));
10036   Value *CastOp = CI->getOperand(0);
10037
10038   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10039     // Instead of loading constant c string, use corresponding integer value
10040     // directly if string length is small enough.
10041     const std::string &Str = CE->getOperand(0)->getStringValue();
10042     if (!Str.empty()) {
10043       unsigned len = Str.length();
10044       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10045       unsigned numBits = Ty->getPrimitiveSizeInBits();
10046       // Replace LI with immediate integer store.
10047       if ((numBits >> 3) == len + 1) {
10048         APInt StrVal(numBits, 0);
10049         APInt SingleChar(numBits, 0);
10050         if (TD->isLittleEndian()) {
10051           for (signed i = len-1; i >= 0; i--) {
10052             SingleChar = (uint64_t) Str[i];
10053             StrVal = (StrVal << 8) | SingleChar;
10054           }
10055         } else {
10056           for (unsigned i = 0; i < len; i++) {
10057             SingleChar = (uint64_t) Str[i];
10058             StrVal = (StrVal << 8) | SingleChar;
10059           }
10060           // Append NULL at the end.
10061           SingleChar = 0;
10062           StrVal = (StrVal << 8) | SingleChar;
10063         }
10064         Value *NL = ConstantInt::get(StrVal);
10065         return IC.ReplaceInstUsesWith(LI, NL);
10066       }
10067     }
10068   }
10069
10070   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10071   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10072     const Type *SrcPTy = SrcTy->getElementType();
10073
10074     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10075          isa<VectorType>(DestPTy)) {
10076       // If the source is an array, the code below will not succeed.  Check to
10077       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10078       // constants.
10079       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10080         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10081           if (ASrcTy->getNumElements() != 0) {
10082             Value *Idxs[2];
10083             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10084             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10085             SrcTy = cast<PointerType>(CastOp->getType());
10086             SrcPTy = SrcTy->getElementType();
10087           }
10088
10089       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10090             isa<VectorType>(SrcPTy)) &&
10091           // Do not allow turning this into a load of an integer, which is then
10092           // casted to a pointer, this pessimizes pointer analysis a lot.
10093           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10094           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10095                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10096
10097         // Okay, we are casting from one integer or pointer type to another of
10098         // the same size.  Instead of casting the pointer before the load, cast
10099         // the result of the loaded value.
10100         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10101                                                              CI->getName(),
10102                                                          LI.isVolatile()),LI);
10103         // Now cast the result of the load.
10104         return new BitCastInst(NewLoad, LI.getType());
10105       }
10106     }
10107   }
10108   return 0;
10109 }
10110
10111 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10112 /// from this value cannot trap.  If it is not obviously safe to load from the
10113 /// specified pointer, we do a quick local scan of the basic block containing
10114 /// ScanFrom, to determine if the address is already accessed.
10115 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10116   // If it is an alloca it is always safe to load from.
10117   if (isa<AllocaInst>(V)) return true;
10118
10119   // If it is a global variable it is mostly safe to load from.
10120   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10121     // Don't try to evaluate aliases.  External weak GV can be null.
10122     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10123
10124   // Otherwise, be a little bit agressive by scanning the local block where we
10125   // want to check to see if the pointer is already being loaded or stored
10126   // from/to.  If so, the previous load or store would have already trapped,
10127   // so there is no harm doing an extra load (also, CSE will later eliminate
10128   // the load entirely).
10129   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10130
10131   while (BBI != E) {
10132     --BBI;
10133
10134     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10135       if (LI->getOperand(0) == V) return true;
10136     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10137       if (SI->getOperand(1) == V) return true;
10138
10139   }
10140   return false;
10141 }
10142
10143 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10144 /// until we find the underlying object a pointer is referring to or something
10145 /// we don't understand.  Note that the returned pointer may be offset from the
10146 /// input, because we ignore GEP indices.
10147 static Value *GetUnderlyingObject(Value *Ptr) {
10148   while (1) {
10149     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10150       if (CE->getOpcode() == Instruction::BitCast ||
10151           CE->getOpcode() == Instruction::GetElementPtr)
10152         Ptr = CE->getOperand(0);
10153       else
10154         return Ptr;
10155     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10156       Ptr = BCI->getOperand(0);
10157     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10158       Ptr = GEP->getOperand(0);
10159     } else {
10160       return Ptr;
10161     }
10162   }
10163 }
10164
10165 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10166   Value *Op = LI.getOperand(0);
10167
10168   // Attempt to improve the alignment.
10169   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10170   if (KnownAlign >
10171       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10172                                 LI.getAlignment()))
10173     LI.setAlignment(KnownAlign);
10174
10175   // load (cast X) --> cast (load X) iff safe
10176   if (isa<CastInst>(Op))
10177     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10178       return Res;
10179
10180   // None of the following transforms are legal for volatile loads.
10181   if (LI.isVolatile()) return 0;
10182   
10183   if (&LI.getParent()->front() != &LI) {
10184     BasicBlock::iterator BBI = &LI; --BBI;
10185     // If the instruction immediately before this is a store to the same
10186     // address, do a simple form of store->load forwarding.
10187     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10188       if (SI->getOperand(1) == LI.getOperand(0))
10189         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10190     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10191       if (LIB->getOperand(0) == LI.getOperand(0))
10192         return ReplaceInstUsesWith(LI, LIB);
10193   }
10194
10195   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10196     const Value *GEPI0 = GEPI->getOperand(0);
10197     // TODO: Consider a target hook for valid address spaces for this xform.
10198     if (isa<ConstantPointerNull>(GEPI0) &&
10199         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10200       // Insert a new store to null instruction before the load to indicate
10201       // that this code is not reachable.  We do this instead of inserting
10202       // an unreachable instruction directly because we cannot modify the
10203       // CFG.
10204       new StoreInst(UndefValue::get(LI.getType()),
10205                     Constant::getNullValue(Op->getType()), &LI);
10206       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10207     }
10208   } 
10209
10210   if (Constant *C = dyn_cast<Constant>(Op)) {
10211     // load null/undef -> undef
10212     // TODO: Consider a target hook for valid address spaces for this xform.
10213     if (isa<UndefValue>(C) || (C->isNullValue() && 
10214         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10215       // Insert a new store to null instruction before the load to indicate that
10216       // this code is not reachable.  We do this instead of inserting an
10217       // unreachable instruction directly because we cannot modify the CFG.
10218       new StoreInst(UndefValue::get(LI.getType()),
10219                     Constant::getNullValue(Op->getType()), &LI);
10220       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10221     }
10222
10223     // Instcombine load (constant global) into the value loaded.
10224     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10225       if (GV->isConstant() && !GV->isDeclaration())
10226         return ReplaceInstUsesWith(LI, GV->getInitializer());
10227
10228     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10229     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10230       if (CE->getOpcode() == Instruction::GetElementPtr) {
10231         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10232           if (GV->isConstant() && !GV->isDeclaration())
10233             if (Constant *V = 
10234                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10235               return ReplaceInstUsesWith(LI, V);
10236         if (CE->getOperand(0)->isNullValue()) {
10237           // Insert a new store to null instruction before the load to indicate
10238           // that this code is not reachable.  We do this instead of inserting
10239           // an unreachable instruction directly because we cannot modify the
10240           // CFG.
10241           new StoreInst(UndefValue::get(LI.getType()),
10242                         Constant::getNullValue(Op->getType()), &LI);
10243           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10244         }
10245
10246       } else if (CE->isCast()) {
10247         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10248           return Res;
10249       }
10250     }
10251   }
10252     
10253   // If this load comes from anywhere in a constant global, and if the global
10254   // is all undef or zero, we know what it loads.
10255   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10256     if (GV->isConstant() && GV->hasInitializer()) {
10257       if (GV->getInitializer()->isNullValue())
10258         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10259       else if (isa<UndefValue>(GV->getInitializer()))
10260         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10261     }
10262   }
10263
10264   if (Op->hasOneUse()) {
10265     // Change select and PHI nodes to select values instead of addresses: this
10266     // helps alias analysis out a lot, allows many others simplifications, and
10267     // exposes redundancy in the code.
10268     //
10269     // Note that we cannot do the transformation unless we know that the
10270     // introduced loads cannot trap!  Something like this is valid as long as
10271     // the condition is always false: load (select bool %C, int* null, int* %G),
10272     // but it would not be valid if we transformed it to load from null
10273     // unconditionally.
10274     //
10275     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10276       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10277       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10278           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10279         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10280                                      SI->getOperand(1)->getName()+".val"), LI);
10281         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10282                                      SI->getOperand(2)->getName()+".val"), LI);
10283         return SelectInst::Create(SI->getCondition(), V1, V2);
10284       }
10285
10286       // load (select (cond, null, P)) -> load P
10287       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10288         if (C->isNullValue()) {
10289           LI.setOperand(0, SI->getOperand(2));
10290           return &LI;
10291         }
10292
10293       // load (select (cond, P, null)) -> load P
10294       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10295         if (C->isNullValue()) {
10296           LI.setOperand(0, SI->getOperand(1));
10297           return &LI;
10298         }
10299     }
10300   }
10301   return 0;
10302 }
10303
10304 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10305 /// when possible.
10306 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10307   User *CI = cast<User>(SI.getOperand(1));
10308   Value *CastOp = CI->getOperand(0);
10309
10310   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10311   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10312     const Type *SrcPTy = SrcTy->getElementType();
10313
10314     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10315       // If the source is an array, the code below will not succeed.  Check to
10316       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10317       // constants.
10318       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10319         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10320           if (ASrcTy->getNumElements() != 0) {
10321             Value* Idxs[2];
10322             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10323             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10324             SrcTy = cast<PointerType>(CastOp->getType());
10325             SrcPTy = SrcTy->getElementType();
10326           }
10327
10328       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10329           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10330                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10331
10332         // Okay, we are casting from one integer or pointer type to another of
10333         // the same size.  Instead of casting the pointer before 
10334         // the store, cast the value to be stored.
10335         Value *NewCast;
10336         Value *SIOp0 = SI.getOperand(0);
10337         Instruction::CastOps opcode = Instruction::BitCast;
10338         const Type* CastSrcTy = SIOp0->getType();
10339         const Type* CastDstTy = SrcPTy;
10340         if (isa<PointerType>(CastDstTy)) {
10341           if (CastSrcTy->isInteger())
10342             opcode = Instruction::IntToPtr;
10343         } else if (isa<IntegerType>(CastDstTy)) {
10344           if (isa<PointerType>(SIOp0->getType()))
10345             opcode = Instruction::PtrToInt;
10346         }
10347         if (Constant *C = dyn_cast<Constant>(SIOp0))
10348           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10349         else
10350           NewCast = IC.InsertNewInstBefore(
10351             CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10352             SI);
10353         return new StoreInst(NewCast, CastOp);
10354       }
10355     }
10356   }
10357   return 0;
10358 }
10359
10360 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10361   Value *Val = SI.getOperand(0);
10362   Value *Ptr = SI.getOperand(1);
10363
10364   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10365     EraseInstFromFunction(SI);
10366     ++NumCombined;
10367     return 0;
10368   }
10369   
10370   // If the RHS is an alloca with a single use, zapify the store, making the
10371   // alloca dead.
10372   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10373     if (isa<AllocaInst>(Ptr)) {
10374       EraseInstFromFunction(SI);
10375       ++NumCombined;
10376       return 0;
10377     }
10378     
10379     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10380       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10381           GEP->getOperand(0)->hasOneUse()) {
10382         EraseInstFromFunction(SI);
10383         ++NumCombined;
10384         return 0;
10385       }
10386   }
10387
10388   // Attempt to improve the alignment.
10389   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10390   if (KnownAlign >
10391       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10392                                 SI.getAlignment()))
10393     SI.setAlignment(KnownAlign);
10394
10395   // Do really simple DSE, to catch cases where there are several consequtive
10396   // stores to the same location, separated by a few arithmetic operations. This
10397   // situation often occurs with bitfield accesses.
10398   BasicBlock::iterator BBI = &SI;
10399   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10400        --ScanInsts) {
10401     --BBI;
10402     
10403     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10404       // Prev store isn't volatile, and stores to the same location?
10405       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10406         ++NumDeadStore;
10407         ++BBI;
10408         EraseInstFromFunction(*PrevSI);
10409         continue;
10410       }
10411       break;
10412     }
10413     
10414     // If this is a load, we have to stop.  However, if the loaded value is from
10415     // the pointer we're loading and is producing the pointer we're storing,
10416     // then *this* store is dead (X = load P; store X -> P).
10417     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10418       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10419         EraseInstFromFunction(SI);
10420         ++NumCombined;
10421         return 0;
10422       }
10423       // Otherwise, this is a load from some other location.  Stores before it
10424       // may not be dead.
10425       break;
10426     }
10427     
10428     // Don't skip over loads or things that can modify memory.
10429     if (BBI->mayWriteToMemory())
10430       break;
10431   }
10432   
10433   
10434   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10435
10436   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10437   if (isa<ConstantPointerNull>(Ptr)) {
10438     if (!isa<UndefValue>(Val)) {
10439       SI.setOperand(0, UndefValue::get(Val->getType()));
10440       if (Instruction *U = dyn_cast<Instruction>(Val))
10441         AddToWorkList(U);  // Dropped a use.
10442       ++NumCombined;
10443     }
10444     return 0;  // Do not modify these!
10445   }
10446
10447   // store undef, Ptr -> noop
10448   if (isa<UndefValue>(Val)) {
10449     EraseInstFromFunction(SI);
10450     ++NumCombined;
10451     return 0;
10452   }
10453
10454   // If the pointer destination is a cast, see if we can fold the cast into the
10455   // source instead.
10456   if (isa<CastInst>(Ptr))
10457     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10458       return Res;
10459   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10460     if (CE->isCast())
10461       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10462         return Res;
10463
10464   
10465   // If this store is the last instruction in the basic block, and if the block
10466   // ends with an unconditional branch, try to move it to the successor block.
10467   BBI = &SI; ++BBI;
10468   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10469     if (BI->isUnconditional())
10470       if (SimplifyStoreAtEndOfBlock(SI))
10471         return 0;  // xform done!
10472   
10473   return 0;
10474 }
10475
10476 /// SimplifyStoreAtEndOfBlock - Turn things like:
10477 ///   if () { *P = v1; } else { *P = v2 }
10478 /// into a phi node with a store in the successor.
10479 ///
10480 /// Simplify things like:
10481 ///   *P = v1; if () { *P = v2; }
10482 /// into a phi node with a store in the successor.
10483 ///
10484 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10485   BasicBlock *StoreBB = SI.getParent();
10486   
10487   // Check to see if the successor block has exactly two incoming edges.  If
10488   // so, see if the other predecessor contains a store to the same location.
10489   // if so, insert a PHI node (if needed) and move the stores down.
10490   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10491   
10492   // Determine whether Dest has exactly two predecessors and, if so, compute
10493   // the other predecessor.
10494   pred_iterator PI = pred_begin(DestBB);
10495   BasicBlock *OtherBB = 0;
10496   if (*PI != StoreBB)
10497     OtherBB = *PI;
10498   ++PI;
10499   if (PI == pred_end(DestBB))
10500     return false;
10501   
10502   if (*PI != StoreBB) {
10503     if (OtherBB)
10504       return false;
10505     OtherBB = *PI;
10506   }
10507   if (++PI != pred_end(DestBB))
10508     return false;
10509   
10510   
10511   // Verify that the other block ends in a branch and is not otherwise empty.
10512   BasicBlock::iterator BBI = OtherBB->getTerminator();
10513   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10514   if (!OtherBr || BBI == OtherBB->begin())
10515     return false;
10516   
10517   // If the other block ends in an unconditional branch, check for the 'if then
10518   // else' case.  there is an instruction before the branch.
10519   StoreInst *OtherStore = 0;
10520   if (OtherBr->isUnconditional()) {
10521     // If this isn't a store, or isn't a store to the same location, bail out.
10522     --BBI;
10523     OtherStore = dyn_cast<StoreInst>(BBI);
10524     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10525       return false;
10526   } else {
10527     // Otherwise, the other block ended with a conditional branch. If one of the
10528     // destinations is StoreBB, then we have the if/then case.
10529     if (OtherBr->getSuccessor(0) != StoreBB && 
10530         OtherBr->getSuccessor(1) != StoreBB)
10531       return false;
10532     
10533     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10534     // if/then triangle.  See if there is a store to the same ptr as SI that
10535     // lives in OtherBB.
10536     for (;; --BBI) {
10537       // Check to see if we find the matching store.
10538       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10539         if (OtherStore->getOperand(1) != SI.getOperand(1))
10540           return false;
10541         break;
10542       }
10543       // If we find something that may be using the stored value, or if we run
10544       // out of instructions, we can't do the xform.
10545       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10546           BBI == OtherBB->begin())
10547         return false;
10548     }
10549     
10550     // In order to eliminate the store in OtherBr, we have to
10551     // make sure nothing reads the stored value in StoreBB.
10552     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10553       // FIXME: This should really be AA driven.
10554       if (isa<LoadInst>(I) || I->mayWriteToMemory())
10555         return false;
10556     }
10557   }
10558   
10559   // Insert a PHI node now if we need it.
10560   Value *MergedVal = OtherStore->getOperand(0);
10561   if (MergedVal != SI.getOperand(0)) {
10562     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10563     PN->reserveOperandSpace(2);
10564     PN->addIncoming(SI.getOperand(0), SI.getParent());
10565     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10566     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10567   }
10568   
10569   // Advance to a place where it is safe to insert the new store and
10570   // insert it.
10571   BBI = DestBB->begin();
10572   while (isa<PHINode>(BBI)) ++BBI;
10573   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10574                                     OtherStore->isVolatile()), *BBI);
10575   
10576   // Nuke the old stores.
10577   EraseInstFromFunction(SI);
10578   EraseInstFromFunction(*OtherStore);
10579   ++NumCombined;
10580   return true;
10581 }
10582
10583
10584 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10585   // Change br (not X), label True, label False to: br X, label False, True
10586   Value *X = 0;
10587   BasicBlock *TrueDest;
10588   BasicBlock *FalseDest;
10589   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10590       !isa<Constant>(X)) {
10591     // Swap Destinations and condition...
10592     BI.setCondition(X);
10593     BI.setSuccessor(0, FalseDest);
10594     BI.setSuccessor(1, TrueDest);
10595     return &BI;
10596   }
10597
10598   // Cannonicalize fcmp_one -> fcmp_oeq
10599   FCmpInst::Predicate FPred; Value *Y;
10600   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10601                              TrueDest, FalseDest)))
10602     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10603          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10604       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10605       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10606       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10607       NewSCC->takeName(I);
10608       // Swap Destinations and condition...
10609       BI.setCondition(NewSCC);
10610       BI.setSuccessor(0, FalseDest);
10611       BI.setSuccessor(1, TrueDest);
10612       RemoveFromWorkList(I);
10613       I->eraseFromParent();
10614       AddToWorkList(NewSCC);
10615       return &BI;
10616     }
10617
10618   // Cannonicalize icmp_ne -> icmp_eq
10619   ICmpInst::Predicate IPred;
10620   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10621                       TrueDest, FalseDest)))
10622     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10623          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10624          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10625       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10626       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10627       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10628       NewSCC->takeName(I);
10629       // Swap Destinations and condition...
10630       BI.setCondition(NewSCC);
10631       BI.setSuccessor(0, FalseDest);
10632       BI.setSuccessor(1, TrueDest);
10633       RemoveFromWorkList(I);
10634       I->eraseFromParent();;
10635       AddToWorkList(NewSCC);
10636       return &BI;
10637     }
10638
10639   return 0;
10640 }
10641
10642 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10643   Value *Cond = SI.getCondition();
10644   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10645     if (I->getOpcode() == Instruction::Add)
10646       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10647         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10648         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10649           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10650                                                 AddRHS));
10651         SI.setOperand(0, I->getOperand(0));
10652         AddToWorkList(I);
10653         return &SI;
10654       }
10655   }
10656   return 0;
10657 }
10658
10659 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10660 /// is to leave as a vector operation.
10661 static bool CheapToScalarize(Value *V, bool isConstant) {
10662   if (isa<ConstantAggregateZero>(V)) 
10663     return true;
10664   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10665     if (isConstant) return true;
10666     // If all elts are the same, we can extract.
10667     Constant *Op0 = C->getOperand(0);
10668     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10669       if (C->getOperand(i) != Op0)
10670         return false;
10671     return true;
10672   }
10673   Instruction *I = dyn_cast<Instruction>(V);
10674   if (!I) return false;
10675   
10676   // Insert element gets simplified to the inserted element or is deleted if
10677   // this is constant idx extract element and its a constant idx insertelt.
10678   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10679       isa<ConstantInt>(I->getOperand(2)))
10680     return true;
10681   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10682     return true;
10683   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10684     if (BO->hasOneUse() &&
10685         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10686          CheapToScalarize(BO->getOperand(1), isConstant)))
10687       return true;
10688   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10689     if (CI->hasOneUse() &&
10690         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10691          CheapToScalarize(CI->getOperand(1), isConstant)))
10692       return true;
10693   
10694   return false;
10695 }
10696
10697 /// Read and decode a shufflevector mask.
10698 ///
10699 /// It turns undef elements into values that are larger than the number of
10700 /// elements in the input.
10701 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10702   unsigned NElts = SVI->getType()->getNumElements();
10703   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10704     return std::vector<unsigned>(NElts, 0);
10705   if (isa<UndefValue>(SVI->getOperand(2)))
10706     return std::vector<unsigned>(NElts, 2*NElts);
10707
10708   std::vector<unsigned> Result;
10709   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10710   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10711     if (isa<UndefValue>(CP->getOperand(i)))
10712       Result.push_back(NElts*2);  // undef -> 8
10713     else
10714       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10715   return Result;
10716 }
10717
10718 /// FindScalarElement - Given a vector and an element number, see if the scalar
10719 /// value is already around as a register, for example if it were inserted then
10720 /// extracted from the vector.
10721 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10722   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10723   const VectorType *PTy = cast<VectorType>(V->getType());
10724   unsigned Width = PTy->getNumElements();
10725   if (EltNo >= Width)  // Out of range access.
10726     return UndefValue::get(PTy->getElementType());
10727   
10728   if (isa<UndefValue>(V))
10729     return UndefValue::get(PTy->getElementType());
10730   else if (isa<ConstantAggregateZero>(V))
10731     return Constant::getNullValue(PTy->getElementType());
10732   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10733     return CP->getOperand(EltNo);
10734   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10735     // If this is an insert to a variable element, we don't know what it is.
10736     if (!isa<ConstantInt>(III->getOperand(2))) 
10737       return 0;
10738     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10739     
10740     // If this is an insert to the element we are looking for, return the
10741     // inserted value.
10742     if (EltNo == IIElt) 
10743       return III->getOperand(1);
10744     
10745     // Otherwise, the insertelement doesn't modify the value, recurse on its
10746     // vector input.
10747     return FindScalarElement(III->getOperand(0), EltNo);
10748   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10749     unsigned InEl = getShuffleMask(SVI)[EltNo];
10750     if (InEl < Width)
10751       return FindScalarElement(SVI->getOperand(0), InEl);
10752     else if (InEl < Width*2)
10753       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10754     else
10755       return UndefValue::get(PTy->getElementType());
10756   }
10757   
10758   // Otherwise, we don't know.
10759   return 0;
10760 }
10761
10762 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10763
10764   // If vector val is undef, replace extract with scalar undef.
10765   if (isa<UndefValue>(EI.getOperand(0)))
10766     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10767
10768   // If vector val is constant 0, replace extract with scalar 0.
10769   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10770     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10771   
10772   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10773     // If vector val is constant with uniform operands, replace EI
10774     // with that operand
10775     Constant *op0 = C->getOperand(0);
10776     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10777       if (C->getOperand(i) != op0) {
10778         op0 = 0; 
10779         break;
10780       }
10781     if (op0)
10782       return ReplaceInstUsesWith(EI, op0);
10783   }
10784   
10785   // If extracting a specified index from the vector, see if we can recursively
10786   // find a previously computed scalar that was inserted into the vector.
10787   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10788     unsigned IndexVal = IdxC->getZExtValue();
10789     unsigned VectorWidth = 
10790       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10791       
10792     // If this is extracting an invalid index, turn this into undef, to avoid
10793     // crashing the code below.
10794     if (IndexVal >= VectorWidth)
10795       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10796     
10797     // This instruction only demands the single element from the input vector.
10798     // If the input vector has a single use, simplify it based on this use
10799     // property.
10800     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10801       uint64_t UndefElts;
10802       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10803                                                 1 << IndexVal,
10804                                                 UndefElts)) {
10805         EI.setOperand(0, V);
10806         return &EI;
10807       }
10808     }
10809     
10810     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10811       return ReplaceInstUsesWith(EI, Elt);
10812     
10813     // If the this extractelement is directly using a bitcast from a vector of
10814     // the same number of elements, see if we can find the source element from
10815     // it.  In this case, we will end up needing to bitcast the scalars.
10816     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10817       if (const VectorType *VT = 
10818               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10819         if (VT->getNumElements() == VectorWidth)
10820           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10821             return new BitCastInst(Elt, EI.getType());
10822     }
10823   }
10824   
10825   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10826     if (I->hasOneUse()) {
10827       // Push extractelement into predecessor operation if legal and
10828       // profitable to do so
10829       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10830         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10831         if (CheapToScalarize(BO, isConstantElt)) {
10832           ExtractElementInst *newEI0 = 
10833             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10834                                    EI.getName()+".lhs");
10835           ExtractElementInst *newEI1 =
10836             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10837                                    EI.getName()+".rhs");
10838           InsertNewInstBefore(newEI0, EI);
10839           InsertNewInstBefore(newEI1, EI);
10840           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10841         }
10842       } else if (isa<LoadInst>(I)) {
10843         unsigned AS = 
10844           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10845         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10846                                          PointerType::get(EI.getType(), AS),EI);
10847         GetElementPtrInst *GEP = 
10848           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName() + ".gep");
10849         InsertNewInstBefore(GEP, EI);
10850         return new LoadInst(GEP);
10851       }
10852     }
10853     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10854       // Extracting the inserted element?
10855       if (IE->getOperand(2) == EI.getOperand(1))
10856         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10857       // If the inserted and extracted elements are constants, they must not
10858       // be the same value, extract from the pre-inserted value instead.
10859       if (isa<Constant>(IE->getOperand(2)) &&
10860           isa<Constant>(EI.getOperand(1))) {
10861         AddUsesToWorkList(EI);
10862         EI.setOperand(0, IE->getOperand(0));
10863         return &EI;
10864       }
10865     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10866       // If this is extracting an element from a shufflevector, figure out where
10867       // it came from and extract from the appropriate input element instead.
10868       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10869         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10870         Value *Src;
10871         if (SrcIdx < SVI->getType()->getNumElements())
10872           Src = SVI->getOperand(0);
10873         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10874           SrcIdx -= SVI->getType()->getNumElements();
10875           Src = SVI->getOperand(1);
10876         } else {
10877           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10878         }
10879         return new ExtractElementInst(Src, SrcIdx);
10880       }
10881     }
10882   }
10883   return 0;
10884 }
10885
10886 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10887 /// elements from either LHS or RHS, return the shuffle mask and true. 
10888 /// Otherwise, return false.
10889 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10890                                          std::vector<Constant*> &Mask) {
10891   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10892          "Invalid CollectSingleShuffleElements");
10893   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10894
10895   if (isa<UndefValue>(V)) {
10896     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10897     return true;
10898   } else if (V == LHS) {
10899     for (unsigned i = 0; i != NumElts; ++i)
10900       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10901     return true;
10902   } else if (V == RHS) {
10903     for (unsigned i = 0; i != NumElts; ++i)
10904       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10905     return true;
10906   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10907     // If this is an insert of an extract from some other vector, include it.
10908     Value *VecOp    = IEI->getOperand(0);
10909     Value *ScalarOp = IEI->getOperand(1);
10910     Value *IdxOp    = IEI->getOperand(2);
10911     
10912     if (!isa<ConstantInt>(IdxOp))
10913       return false;
10914     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10915     
10916     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10917       // Okay, we can handle this if the vector we are insertinting into is
10918       // transitively ok.
10919       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10920         // If so, update the mask to reflect the inserted undef.
10921         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10922         return true;
10923       }      
10924     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10925       if (isa<ConstantInt>(EI->getOperand(1)) &&
10926           EI->getOperand(0)->getType() == V->getType()) {
10927         unsigned ExtractedIdx =
10928           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10929         
10930         // This must be extracting from either LHS or RHS.
10931         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10932           // Okay, we can handle this if the vector we are insertinting into is
10933           // transitively ok.
10934           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10935             // If so, update the mask to reflect the inserted value.
10936             if (EI->getOperand(0) == LHS) {
10937               Mask[InsertedIdx & (NumElts-1)] = 
10938                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10939             } else {
10940               assert(EI->getOperand(0) == RHS);
10941               Mask[InsertedIdx & (NumElts-1)] = 
10942                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10943               
10944             }
10945             return true;
10946           }
10947         }
10948       }
10949     }
10950   }
10951   // TODO: Handle shufflevector here!
10952   
10953   return false;
10954 }
10955
10956 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10957 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10958 /// that computes V and the LHS value of the shuffle.
10959 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10960                                      Value *&RHS) {
10961   assert(isa<VectorType>(V->getType()) && 
10962          (RHS == 0 || V->getType() == RHS->getType()) &&
10963          "Invalid shuffle!");
10964   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10965
10966   if (isa<UndefValue>(V)) {
10967     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10968     return V;
10969   } else if (isa<ConstantAggregateZero>(V)) {
10970     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10971     return V;
10972   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10973     // If this is an insert of an extract from some other vector, include it.
10974     Value *VecOp    = IEI->getOperand(0);
10975     Value *ScalarOp = IEI->getOperand(1);
10976     Value *IdxOp    = IEI->getOperand(2);
10977     
10978     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10979       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10980           EI->getOperand(0)->getType() == V->getType()) {
10981         unsigned ExtractedIdx =
10982           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10983         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10984         
10985         // Either the extracted from or inserted into vector must be RHSVec,
10986         // otherwise we'd end up with a shuffle of three inputs.
10987         if (EI->getOperand(0) == RHS || RHS == 0) {
10988           RHS = EI->getOperand(0);
10989           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10990           Mask[InsertedIdx & (NumElts-1)] = 
10991             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10992           return V;
10993         }
10994         
10995         if (VecOp == RHS) {
10996           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10997           // Everything but the extracted element is replaced with the RHS.
10998           for (unsigned i = 0; i != NumElts; ++i) {
10999             if (i != InsertedIdx)
11000               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11001           }
11002           return V;
11003         }
11004         
11005         // If this insertelement is a chain that comes from exactly these two
11006         // vectors, return the vector and the effective shuffle.
11007         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11008           return EI->getOperand(0);
11009         
11010       }
11011     }
11012   }
11013   // TODO: Handle shufflevector here!
11014   
11015   // Otherwise, can't do anything fancy.  Return an identity vector.
11016   for (unsigned i = 0; i != NumElts; ++i)
11017     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11018   return V;
11019 }
11020
11021 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11022   Value *VecOp    = IE.getOperand(0);
11023   Value *ScalarOp = IE.getOperand(1);
11024   Value *IdxOp    = IE.getOperand(2);
11025   
11026   // Inserting an undef or into an undefined place, remove this.
11027   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11028     ReplaceInstUsesWith(IE, VecOp);
11029   
11030   // If the inserted element was extracted from some other vector, and if the 
11031   // indexes are constant, try to turn this into a shufflevector operation.
11032   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11033     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11034         EI->getOperand(0)->getType() == IE.getType()) {
11035       unsigned NumVectorElts = IE.getType()->getNumElements();
11036       unsigned ExtractedIdx =
11037         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11038       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11039       
11040       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11041         return ReplaceInstUsesWith(IE, VecOp);
11042       
11043       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11044         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11045       
11046       // If we are extracting a value from a vector, then inserting it right
11047       // back into the same place, just use the input vector.
11048       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11049         return ReplaceInstUsesWith(IE, VecOp);      
11050       
11051       // We could theoretically do this for ANY input.  However, doing so could
11052       // turn chains of insertelement instructions into a chain of shufflevector
11053       // instructions, and right now we do not merge shufflevectors.  As such,
11054       // only do this in a situation where it is clear that there is benefit.
11055       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11056         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11057         // the values of VecOp, except then one read from EIOp0.
11058         // Build a new shuffle mask.
11059         std::vector<Constant*> Mask;
11060         if (isa<UndefValue>(VecOp))
11061           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11062         else {
11063           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11064           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11065                                                        NumVectorElts));
11066         } 
11067         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11068         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11069                                      ConstantVector::get(Mask));
11070       }
11071       
11072       // If this insertelement isn't used by some other insertelement, turn it
11073       // (and any insertelements it points to), into one big shuffle.
11074       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11075         std::vector<Constant*> Mask;
11076         Value *RHS = 0;
11077         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11078         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11079         // We now have a shuffle of LHS, RHS, Mask.
11080         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11081       }
11082     }
11083   }
11084
11085   return 0;
11086 }
11087
11088
11089 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11090   Value *LHS = SVI.getOperand(0);
11091   Value *RHS = SVI.getOperand(1);
11092   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11093
11094   bool MadeChange = false;
11095   
11096   // Undefined shuffle mask -> undefined value.
11097   if (isa<UndefValue>(SVI.getOperand(2)))
11098     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11099   
11100   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11101   // the undef, change them to undefs.
11102   if (isa<UndefValue>(SVI.getOperand(1))) {
11103     // Scan to see if there are any references to the RHS.  If so, replace them
11104     // with undef element refs and set MadeChange to true.
11105     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11106       if (Mask[i] >= e && Mask[i] != 2*e) {
11107         Mask[i] = 2*e;
11108         MadeChange = true;
11109       }
11110     }
11111     
11112     if (MadeChange) {
11113       // Remap any references to RHS to use LHS.
11114       std::vector<Constant*> Elts;
11115       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11116         if (Mask[i] == 2*e)
11117           Elts.push_back(UndefValue::get(Type::Int32Ty));
11118         else
11119           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11120       }
11121       SVI.setOperand(2, ConstantVector::get(Elts));
11122     }
11123   }
11124   
11125   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11126   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11127   if (LHS == RHS || isa<UndefValue>(LHS)) {
11128     if (isa<UndefValue>(LHS) && LHS == RHS) {
11129       // shuffle(undef,undef,mask) -> undef.
11130       return ReplaceInstUsesWith(SVI, LHS);
11131     }
11132     
11133     // Remap any references to RHS to use LHS.
11134     std::vector<Constant*> Elts;
11135     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11136       if (Mask[i] >= 2*e)
11137         Elts.push_back(UndefValue::get(Type::Int32Ty));
11138       else {
11139         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11140             (Mask[i] <  e && isa<UndefValue>(LHS)))
11141           Mask[i] = 2*e;     // Turn into undef.
11142         else
11143           Mask[i] &= (e-1);  // Force to LHS.
11144         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11145       }
11146     }
11147     SVI.setOperand(0, SVI.getOperand(1));
11148     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11149     SVI.setOperand(2, ConstantVector::get(Elts));
11150     LHS = SVI.getOperand(0);
11151     RHS = SVI.getOperand(1);
11152     MadeChange = true;
11153   }
11154   
11155   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11156   bool isLHSID = true, isRHSID = true;
11157     
11158   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11159     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11160     // Is this an identity shuffle of the LHS value?
11161     isLHSID &= (Mask[i] == i);
11162       
11163     // Is this an identity shuffle of the RHS value?
11164     isRHSID &= (Mask[i]-e == i);
11165   }
11166
11167   // Eliminate identity shuffles.
11168   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11169   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11170   
11171   // If the LHS is a shufflevector itself, see if we can combine it with this
11172   // one without producing an unusual shuffle.  Here we are really conservative:
11173   // we are absolutely afraid of producing a shuffle mask not in the input
11174   // program, because the code gen may not be smart enough to turn a merged
11175   // shuffle into two specific shuffles: it may produce worse code.  As such,
11176   // we only merge two shuffles if the result is one of the two input shuffle
11177   // masks.  In this case, merging the shuffles just removes one instruction,
11178   // which we know is safe.  This is good for things like turning:
11179   // (splat(splat)) -> splat.
11180   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11181     if (isa<UndefValue>(RHS)) {
11182       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11183
11184       std::vector<unsigned> NewMask;
11185       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11186         if (Mask[i] >= 2*e)
11187           NewMask.push_back(2*e);
11188         else
11189           NewMask.push_back(LHSMask[Mask[i]]);
11190       
11191       // If the result mask is equal to the src shuffle or this shuffle mask, do
11192       // the replacement.
11193       if (NewMask == LHSMask || NewMask == Mask) {
11194         std::vector<Constant*> Elts;
11195         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11196           if (NewMask[i] >= e*2) {
11197             Elts.push_back(UndefValue::get(Type::Int32Ty));
11198           } else {
11199             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11200           }
11201         }
11202         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11203                                      LHSSVI->getOperand(1),
11204                                      ConstantVector::get(Elts));
11205       }
11206     }
11207   }
11208
11209   return MadeChange ? &SVI : 0;
11210 }
11211
11212
11213
11214
11215 /// TryToSinkInstruction - Try to move the specified instruction from its
11216 /// current block into the beginning of DestBlock, which can only happen if it's
11217 /// safe to move the instruction past all of the instructions between it and the
11218 /// end of its block.
11219 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11220   assert(I->hasOneUse() && "Invariants didn't hold!");
11221
11222   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11223   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
11224
11225   // Do not sink alloca instructions out of the entry block.
11226   if (isa<AllocaInst>(I) && I->getParent() ==
11227         &DestBlock->getParent()->getEntryBlock())
11228     return false;
11229
11230   // We can only sink load instructions if there is nothing between the load and
11231   // the end of block that could change the value.
11232   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
11233     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
11234          Scan != E; ++Scan)
11235       if (Scan->mayWriteToMemory())
11236         return false;
11237   }
11238
11239   BasicBlock::iterator InsertPos = DestBlock->begin();
11240   while (isa<PHINode>(InsertPos)) ++InsertPos;
11241
11242   I->moveBefore(InsertPos);
11243   ++NumSunkInst;
11244   return true;
11245 }
11246
11247
11248 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11249 /// all reachable code to the worklist.
11250 ///
11251 /// This has a couple of tricks to make the code faster and more powerful.  In
11252 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11253 /// them to the worklist (this significantly speeds up instcombine on code where
11254 /// many instructions are dead or constant).  Additionally, if we find a branch
11255 /// whose condition is a known constant, we only visit the reachable successors.
11256 ///
11257 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11258                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11259                                        InstCombiner &IC,
11260                                        const TargetData *TD) {
11261   std::vector<BasicBlock*> Worklist;
11262   Worklist.push_back(BB);
11263
11264   while (!Worklist.empty()) {
11265     BB = Worklist.back();
11266     Worklist.pop_back();
11267     
11268     // We have now visited this block!  If we've already been here, ignore it.
11269     if (!Visited.insert(BB)) continue;
11270     
11271     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11272       Instruction *Inst = BBI++;
11273       
11274       // DCE instruction if trivially dead.
11275       if (isInstructionTriviallyDead(Inst)) {
11276         ++NumDeadInst;
11277         DOUT << "IC: DCE: " << *Inst;
11278         Inst->eraseFromParent();
11279         continue;
11280       }
11281       
11282       // ConstantProp instruction if trivially constant.
11283       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11284         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11285         Inst->replaceAllUsesWith(C);
11286         ++NumConstProp;
11287         Inst->eraseFromParent();
11288         continue;
11289       }
11290      
11291       IC.AddToWorkList(Inst);
11292     }
11293
11294     // Recursively visit successors.  If this is a branch or switch on a
11295     // constant, only visit the reachable successor.
11296     TerminatorInst *TI = BB->getTerminator();
11297     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11298       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11299         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11300         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11301         Worklist.push_back(ReachableBB);
11302         continue;
11303       }
11304     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11305       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11306         // See if this is an explicit destination.
11307         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11308           if (SI->getCaseValue(i) == Cond) {
11309             BasicBlock *ReachableBB = SI->getSuccessor(i);
11310             Worklist.push_back(ReachableBB);
11311             continue;
11312           }
11313         
11314         // Otherwise it is the default destination.
11315         Worklist.push_back(SI->getSuccessor(0));
11316         continue;
11317       }
11318     }
11319     
11320     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11321       Worklist.push_back(TI->getSuccessor(i));
11322   }
11323 }
11324
11325 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11326   bool Changed = false;
11327   TD = &getAnalysis<TargetData>();
11328   
11329   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11330              << F.getNameStr() << "\n");
11331
11332   {
11333     // Do a depth-first traversal of the function, populate the worklist with
11334     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11335     // track of which blocks we visit.
11336     SmallPtrSet<BasicBlock*, 64> Visited;
11337     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11338
11339     // Do a quick scan over the function.  If we find any blocks that are
11340     // unreachable, remove any instructions inside of them.  This prevents
11341     // the instcombine code from having to deal with some bad special cases.
11342     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11343       if (!Visited.count(BB)) {
11344         Instruction *Term = BB->getTerminator();
11345         while (Term != BB->begin()) {   // Remove instrs bottom-up
11346           BasicBlock::iterator I = Term; --I;
11347
11348           DOUT << "IC: DCE: " << *I;
11349           ++NumDeadInst;
11350
11351           if (!I->use_empty())
11352             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11353           I->eraseFromParent();
11354         }
11355       }
11356   }
11357
11358   while (!Worklist.empty()) {
11359     Instruction *I = RemoveOneFromWorkList();
11360     if (I == 0) continue;  // skip null values.
11361
11362     // Check to see if we can DCE the instruction.
11363     if (isInstructionTriviallyDead(I)) {
11364       // Add operands to the worklist.
11365       if (I->getNumOperands() < 4)
11366         AddUsesToWorkList(*I);
11367       ++NumDeadInst;
11368
11369       DOUT << "IC: DCE: " << *I;
11370
11371       I->eraseFromParent();
11372       RemoveFromWorkList(I);
11373       continue;
11374     }
11375
11376     // Instruction isn't dead, see if we can constant propagate it.
11377     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11378       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11379
11380       // Add operands to the worklist.
11381       AddUsesToWorkList(*I);
11382       ReplaceInstUsesWith(*I, C);
11383
11384       ++NumConstProp;
11385       I->eraseFromParent();
11386       RemoveFromWorkList(I);
11387       continue;
11388     }
11389
11390     // See if we can trivially sink this instruction to a successor basic block.
11391     // FIXME: Remove GetResultInst test when first class support for aggregates is
11392     // implemented.
11393     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11394       BasicBlock *BB = I->getParent();
11395       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11396       if (UserParent != BB) {
11397         bool UserIsSuccessor = false;
11398         // See if the user is one of our successors.
11399         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11400           if (*SI == UserParent) {
11401             UserIsSuccessor = true;
11402             break;
11403           }
11404
11405         // If the user is one of our immediate successors, and if that successor
11406         // only has us as a predecessors (we'd have to split the critical edge
11407         // otherwise), we can keep going.
11408         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11409             next(pred_begin(UserParent)) == pred_end(UserParent))
11410           // Okay, the CFG is simple enough, try to sink this instruction.
11411           Changed |= TryToSinkInstruction(I, UserParent);
11412       }
11413     }
11414
11415     // Now that we have an instruction, try combining it to simplify it...
11416 #ifndef NDEBUG
11417     std::string OrigI;
11418 #endif
11419     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11420     if (Instruction *Result = visit(*I)) {
11421       ++NumCombined;
11422       // Should we replace the old instruction with a new one?
11423       if (Result != I) {
11424         DOUT << "IC: Old = " << *I
11425              << "    New = " << *Result;
11426
11427         // Everything uses the new instruction now.
11428         I->replaceAllUsesWith(Result);
11429
11430         // Push the new instruction and any users onto the worklist.
11431         AddToWorkList(Result);
11432         AddUsersToWorkList(*Result);
11433
11434         // Move the name to the new instruction first.
11435         Result->takeName(I);
11436
11437         // Insert the new instruction into the basic block...
11438         BasicBlock *InstParent = I->getParent();
11439         BasicBlock::iterator InsertPos = I;
11440
11441         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11442           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11443             ++InsertPos;
11444
11445         InstParent->getInstList().insert(InsertPos, Result);
11446
11447         // Make sure that we reprocess all operands now that we reduced their
11448         // use counts.
11449         AddUsesToWorkList(*I);
11450
11451         // Instructions can end up on the worklist more than once.  Make sure
11452         // we do not process an instruction that has been deleted.
11453         RemoveFromWorkList(I);
11454
11455         // Erase the old instruction.
11456         InstParent->getInstList().erase(I);
11457       } else {
11458 #ifndef NDEBUG
11459         DOUT << "IC: Mod = " << OrigI
11460              << "    New = " << *I;
11461 #endif
11462
11463         // If the instruction was modified, it's possible that it is now dead.
11464         // if so, remove it.
11465         if (isInstructionTriviallyDead(I)) {
11466           // Make sure we process all operands now that we are reducing their
11467           // use counts.
11468           AddUsesToWorkList(*I);
11469
11470           // Instructions may end up in the worklist more than once.  Erase all
11471           // occurrences of this instruction.
11472           RemoveFromWorkList(I);
11473           I->eraseFromParent();
11474         } else {
11475           AddToWorkList(I);
11476           AddUsersToWorkList(*I);
11477         }
11478       }
11479       Changed = true;
11480     }
11481   }
11482
11483   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11484     
11485   // Do an explicit clear, this shrinks the map if needed.
11486   WorklistMap.clear();
11487   return Changed;
11488 }
11489
11490
11491 bool InstCombiner::runOnFunction(Function &F) {
11492   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11493   
11494   bool EverMadeChange = false;
11495
11496   // Iterate while there is work to do.
11497   unsigned Iteration = 0;
11498   while (DoOneIteration(F, Iteration++)) 
11499     EverMadeChange = true;
11500   return EverMadeChange;
11501 }
11502
11503 FunctionPass *llvm::createInstructionCombiningPass() {
11504   return new InstCombiner();
11505 }
11506