20204154d0e8006fad405f6b006833fd94570a77
[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
12 // algebraic 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 *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
189                                       Constant *RHSC);
190     Instruction *visitFCmpInst(FCmpInst &I);
191     Instruction *visitICmpInst(ICmpInst &I);
192     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
193     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
194                                                 Instruction *LHS,
195                                                 ConstantInt *RHS);
196     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197                                 ConstantInt *DivRHS);
198
199     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200                              ICmpInst::Predicate Cond, Instruction &I);
201     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
202                                      BinaryOperator &I);
203     Instruction *commonCastTransforms(CastInst &CI);
204     Instruction *commonIntCastTransforms(CastInst &CI);
205     Instruction *commonPointerCastTransforms(CastInst &CI);
206     Instruction *visitTrunc(TruncInst &CI);
207     Instruction *visitZExt(ZExtInst &CI);
208     Instruction *visitSExt(SExtInst &CI);
209     Instruction *visitFPTrunc(FPTruncInst &CI);
210     Instruction *visitFPExt(CastInst &CI);
211     Instruction *visitFPToUI(FPToUIInst &FI);
212     Instruction *visitFPToSI(FPToSIInst &FI);
213     Instruction *visitUIToFP(CastInst &CI);
214     Instruction *visitSIToFP(CastInst &CI);
215     Instruction *visitPtrToInt(CastInst &CI);
216     Instruction *visitIntToPtr(IntToPtrInst &CI);
217     Instruction *visitBitCast(BitCastInst &CI);
218     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
219                                 Instruction *FI);
220     Instruction *visitSelectInst(SelectInst &CI);
221     Instruction *visitCallInst(CallInst &CI);
222     Instruction *visitInvokeInst(InvokeInst &II);
223     Instruction *visitPHINode(PHINode &PN);
224     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
225     Instruction *visitAllocationInst(AllocationInst &AI);
226     Instruction *visitFreeInst(FreeInst &FI);
227     Instruction *visitLoadInst(LoadInst &LI);
228     Instruction *visitStoreInst(StoreInst &SI);
229     Instruction *visitBranchInst(BranchInst &BI);
230     Instruction *visitSwitchInst(SwitchInst &SI);
231     Instruction *visitInsertElementInst(InsertElementInst &IE);
232     Instruction *visitExtractElementInst(ExtractElementInst &EI);
233     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
234
235     // visitInstruction - Specify what to return for unhandled instructions...
236     Instruction *visitInstruction(Instruction &I) { return 0; }
237
238   private:
239     Instruction *visitCallSite(CallSite CS);
240     bool transformConstExprCastCall(CallSite CS);
241     Instruction *transformCallThroughTrampoline(CallSite CS);
242     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243                                    bool DoXform = true);
244     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
245
246   public:
247     // InsertNewInstBefore - insert an instruction New before instruction Old
248     // in the program.  Add the new instruction to the worklist.
249     //
250     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
251       assert(New && New->getParent() == 0 &&
252              "New instruction already inserted into a basic block!");
253       BasicBlock *BB = Old.getParent();
254       BB->getInstList().insert(&Old, New);  // Insert inst
255       AddToWorkList(New);
256       return New;
257     }
258
259     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260     /// This also adds the cast to the worklist.  Finally, this returns the
261     /// cast.
262     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
263                             Instruction &Pos) {
264       if (V->getType() == Ty) return V;
265
266       if (Constant *CV = dyn_cast<Constant>(V))
267         return ConstantExpr::getCast(opc, CV, Ty);
268       
269       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
270       AddToWorkList(C);
271       return C;
272     }
273         
274     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
276     }
277
278
279     // ReplaceInstUsesWith - This method is to be used when an instruction is
280     // found to be dead, replacable with another preexisting expression.  Here
281     // we add all uses of I to the worklist, replace all uses of I with the new
282     // value, then return I, so that the inst combiner will know that I was
283     // modified.
284     //
285     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
286       AddUsersToWorkList(I);         // Add all modified instrs to worklist
287       if (&I != V) {
288         I.replaceAllUsesWith(V);
289         return &I;
290       } else {
291         // If we are replacing the instruction with itself, this must be in a
292         // segment of unreachable code, so just clobber the instruction.
293         I.replaceAllUsesWith(UndefValue::get(I.getType()));
294         return &I;
295       }
296     }
297
298     // UpdateValueUsesWith - This method is to be used when an value is
299     // found to be replacable with another preexisting expression or was
300     // updated.  Here we add all uses of I to the worklist, replace all uses of
301     // I with the new value (unless the instruction was just updated), then
302     // return true, so that the inst combiner will know that I was modified.
303     //
304     bool UpdateValueUsesWith(Value *Old, Value *New) {
305       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
306       if (Old != New)
307         Old->replaceAllUsesWith(New);
308       if (Instruction *I = dyn_cast<Instruction>(Old))
309         AddToWorkList(I);
310       if (Instruction *I = dyn_cast<Instruction>(New))
311         AddToWorkList(I);
312       return true;
313     }
314     
315     // EraseInstFromFunction - When dealing with an instruction that has side
316     // effects or produces a void value, we can't rely on DCE to delete the
317     // instruction.  Instead, visit methods should return the value returned by
318     // this function.
319     Instruction *EraseInstFromFunction(Instruction &I) {
320       assert(I.use_empty() && "Cannot erase instruction that is used!");
321       AddUsesToWorkList(I);
322       RemoveFromWorkList(&I);
323       I.eraseFromParent();
324       return 0;  // Don't do anything with FI
325     }
326
327   private:
328     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
330     /// casts that are known to not do anything...
331     ///
332     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333                                    Value *V, const Type *DestTy,
334                                    Instruction *InsertBefore);
335
336     /// SimplifyCommutative - This performs a few simplifications for 
337     /// commutative operators.
338     bool SimplifyCommutative(BinaryOperator &I);
339
340     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341     /// most-complex to least-complex order.
342     bool SimplifyCompare(CmpInst &I);
343
344     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345     /// on the demanded bits.
346     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
347                               APInt& KnownZero, APInt& KnownOne,
348                               unsigned Depth = 0);
349
350     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351                                       uint64_t &UndefElts, unsigned Depth = 0);
352       
353     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354     // PHI node as operand #0, see if we can fold the instruction into the PHI
355     // (which is only possible if all operands to the PHI are constants).
356     Instruction *FoldOpIntoPhi(Instruction &I);
357
358     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359     // operator and they all are only used by the PHI, PHI together their
360     // inputs, and do the operation once, to the result of the PHI.
361     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
362     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
363     
364     
365     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
367     
368     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
369                               bool isSub, Instruction &I);
370     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
371                                  bool isSigned, bool Inside, Instruction &IB);
372     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
373     Instruction *MatchBSwap(BinaryOperator &I);
374     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
375     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
376     Instruction *SimplifyMemSet(MemSetInst *MI);
377
378
379     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
380
381     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
382                            APInt& KnownOne, unsigned Depth = 0) const;
383     bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
384     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
385     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
386                                     unsigned CastOpc,
387                                     int &NumCastsRemoved);
388     unsigned GetOrEnforceKnownAlignment(Value *V,
389                                         unsigned PrefAlign = 0);
390   };
391 }
392
393 char InstCombiner::ID = 0;
394 static RegisterPass<InstCombiner>
395 X("instcombine", "Combine redundant instructions");
396
397 // getComplexity:  Assign a complexity or rank value to LLVM Values...
398 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
399 static unsigned getComplexity(Value *V) {
400   if (isa<Instruction>(V)) {
401     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
402       return 3;
403     return 4;
404   }
405   if (isa<Argument>(V)) return 3;
406   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
407 }
408
409 // isOnlyUse - Return true if this instruction will be deleted if we stop using
410 // it.
411 static bool isOnlyUse(Value *V) {
412   return V->hasOneUse() || isa<Constant>(V);
413 }
414
415 // getPromotedType - Return the specified type promoted as it would be to pass
416 // though a va_arg area...
417 static const Type *getPromotedType(const Type *Ty) {
418   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419     if (ITy->getBitWidth() < 32)
420       return Type::Int32Ty;
421   }
422   return Ty;
423 }
424
425 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
426 /// expression bitcast,  return the operand value, otherwise return null.
427 static Value *getBitCastOperand(Value *V) {
428   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
429     return I->getOperand(0);
430   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
431     if (CE->getOpcode() == Instruction::BitCast)
432       return CE->getOperand(0);
433   return 0;
434 }
435
436 /// This function is a wrapper around CastInst::isEliminableCastPair. It
437 /// simply extracts arguments and returns what that function returns.
438 static Instruction::CastOps 
439 isEliminableCastPair(
440   const CastInst *CI, ///< The first cast instruction
441   unsigned opcode,       ///< The opcode of the second cast instruction
442   const Type *DstTy,     ///< The target type for the second cast instruction
443   TargetData *TD         ///< The target data for pointer size
444 ) {
445   
446   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
447   const Type *MidTy = CI->getType();                  // B from above
448
449   // Get the opcodes of the two Cast instructions
450   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
452
453   return Instruction::CastOps(
454       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455                                      DstTy, TD->getIntPtrType()));
456 }
457
458 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459 /// in any code being generated.  It does not require codegen if V is simple
460 /// enough or if the cast can be folded into other casts.
461 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
462                               const Type *Ty, TargetData *TD) {
463   if (V->getType() == Ty || isa<Constant>(V)) return false;
464   
465   // If this is another cast that can be eliminated, it isn't codegen either.
466   if (const CastInst *CI = dyn_cast<CastInst>(V))
467     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
468       return false;
469   return true;
470 }
471
472 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
474 /// casts that are known to not do anything...
475 ///
476 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477                                              Value *V, const Type *DestTy,
478                                              Instruction *InsertBefore) {
479   if (V->getType() == DestTy) return V;
480   if (Constant *C = dyn_cast<Constant>(V))
481     return ConstantExpr::getCast(opcode, C, DestTy);
482   
483   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
484 }
485
486 // SimplifyCommutative - This performs a few simplifications for commutative
487 // operators:
488 //
489 //  1. Order operands such that they are listed from right (least complex) to
490 //     left (most complex).  This puts constants before unary operators before
491 //     binary operators.
492 //
493 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
495 //
496 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
497   bool Changed = false;
498   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499     Changed = !I.swapOperands();
500
501   if (!I.isAssociative()) return Changed;
502   Instruction::BinaryOps Opcode = I.getOpcode();
503   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505       if (isa<Constant>(I.getOperand(1))) {
506         Constant *Folded = ConstantExpr::get(I.getOpcode(),
507                                              cast<Constant>(I.getOperand(1)),
508                                              cast<Constant>(Op->getOperand(1)));
509         I.setOperand(0, Op->getOperand(0));
510         I.setOperand(1, Folded);
511         return true;
512       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514             isOnlyUse(Op) && isOnlyUse(Op1)) {
515           Constant *C1 = cast<Constant>(Op->getOperand(1));
516           Constant *C2 = cast<Constant>(Op1->getOperand(1));
517
518           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
519           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
520           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
521                                                     Op1->getOperand(0),
522                                                     Op1->getName(), &I);
523           AddToWorkList(New);
524           I.setOperand(0, New);
525           I.setOperand(1, Folded);
526           return true;
527         }
528     }
529   return Changed;
530 }
531
532 /// SimplifyCompare - For a CmpInst this function just orders the operands
533 /// so that theyare listed from right (least complex) to left (most complex).
534 /// This puts constants before unary operators before binary operators.
535 bool InstCombiner::SimplifyCompare(CmpInst &I) {
536   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
537     return false;
538   I.swapOperands();
539   // Compare instructions are not associative so there's nothing else we can do.
540   return true;
541 }
542
543 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544 // if the LHS is a constant zero (which is the 'negate' form).
545 //
546 static inline Value *dyn_castNegVal(Value *V) {
547   if (BinaryOperator::isNeg(V))
548     return BinaryOperator::getNegArgument(V);
549
550   // Constants can be considered to be negated values if they can be folded.
551   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552     return ConstantExpr::getNeg(C);
553
554   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
555     if (C->getType()->getElementType()->isInteger())
556       return ConstantExpr::getNeg(C);
557
558   return 0;
559 }
560
561 static inline Value *dyn_castNotVal(Value *V) {
562   if (BinaryOperator::isNot(V))
563     return BinaryOperator::getNotArgument(V);
564
565   // Constants can be considered to be not'ed values...
566   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
567     return ConstantInt::get(~C->getValue());
568   return 0;
569 }
570
571 // dyn_castFoldableMul - If this value is a multiply that can be folded into
572 // other computations (because it has a constant operand), return the
573 // non-constant operand of the multiply, and set CST to point to the multiplier.
574 // Otherwise, return null.
575 //
576 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
577   if (V->hasOneUse() && V->getType()->isInteger())
578     if (Instruction *I = dyn_cast<Instruction>(V)) {
579       if (I->getOpcode() == Instruction::Mul)
580         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
581           return I->getOperand(0);
582       if (I->getOpcode() == Instruction::Shl)
583         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
584           // The multiplier is really 1 << CST.
585           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
586           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
587           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
588           return I->getOperand(0);
589         }
590     }
591   return 0;
592 }
593
594 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
595 /// expression, return it.
596 static User *dyn_castGetElementPtr(Value *V) {
597   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
598   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
599     if (CE->getOpcode() == Instruction::GetElementPtr)
600       return cast<User>(V);
601   return false;
602 }
603
604 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
605 /// opcode value. Otherwise return UserOp1.
606 static unsigned getOpcode(Value *V) {
607   if (Instruction *I = dyn_cast<Instruction>(V))
608     return I->getOpcode();
609   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
610     return CE->getOpcode();
611   // Use UserOp1 to mean there's no opcode.
612   return Instruction::UserOp1;
613 }
614
615 /// AddOne - Add one to a ConstantInt
616 static ConstantInt *AddOne(ConstantInt *C) {
617   APInt Val(C->getValue());
618   return ConstantInt::get(++Val);
619 }
620 /// SubOne - Subtract one from a ConstantInt
621 static ConstantInt *SubOne(ConstantInt *C) {
622   APInt Val(C->getValue());
623   return ConstantInt::get(--Val);
624 }
625 /// Add - Add two ConstantInts together
626 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
627   return ConstantInt::get(C1->getValue() + C2->getValue());
628 }
629 /// And - Bitwise AND two ConstantInts together
630 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
631   return ConstantInt::get(C1->getValue() & C2->getValue());
632 }
633 /// Subtract - Subtract one ConstantInt from another
634 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
635   return ConstantInt::get(C1->getValue() - C2->getValue());
636 }
637 /// Multiply - Multiply two ConstantInts together
638 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
639   return ConstantInt::get(C1->getValue() * C2->getValue());
640 }
641 /// MultiplyOverflows - True if the multiply can not be expressed in an int
642 /// this size.
643 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
644   uint32_t W = C1->getBitWidth();
645   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
646   if (sign) {
647     LHSExt.sext(W * 2);
648     RHSExt.sext(W * 2);
649   } else {
650     LHSExt.zext(W * 2);
651     RHSExt.zext(W * 2);
652   }
653
654   APInt MulExt = LHSExt * RHSExt;
655
656   if (sign) {
657     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
658     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
659     return MulExt.slt(Min) || MulExt.sgt(Max);
660   } else 
661     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
662 }
663
664 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
665 /// known to be either zero or one and return them in the KnownZero/KnownOne
666 /// bit sets.  This code only analyzes bits in Mask, in order to short-circuit
667 /// processing.
668 /// NOTE: we cannot consider 'undef' to be "IsZero" here.  The problem is that
669 /// we cannot optimize based on the assumption that it is zero without changing
670 /// it to be an explicit zero.  If we don't change it to zero, other code could
671 /// optimized based on the contradictory assumption that it is non-zero.
672 /// Because instcombine aggressively folds operations with undef args anyway,
673 /// this won't lose us code quality.
674 void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
675                                      APInt& KnownZero, APInt& KnownOne,
676                                      unsigned Depth) const {
677   assert(V && "No Value?");
678   assert(Depth <= 6 && "Limit Search Depth");
679   uint32_t BitWidth = Mask.getBitWidth();
680   assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
681          "Not integer or pointer type!");
682   assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
683          (!isa<IntegerType>(V->getType()) ||
684           V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
685          KnownZero.getBitWidth() == BitWidth && 
686          KnownOne.getBitWidth() == BitWidth &&
687          "V, Mask, KnownOne and KnownZero should have same BitWidth");
688
689   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
690     // We know all of the bits for a constant!
691     KnownOne = CI->getValue() & Mask;
692     KnownZero = ~KnownOne & Mask;
693     return;
694   }
695   // Null is all-zeros.
696   if (isa<ConstantPointerNull>(V)) {
697     KnownOne.clear();
698     KnownZero = Mask;
699     return;
700   }
701   // The address of an aligned GlobalValue has trailing zeros.
702   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
703     unsigned Align = GV->getAlignment();
704     if (Align == 0 && TD && GV->getType()->getElementType()->isSized()) 
705       Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
706     if (Align > 0)
707       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
708                                               CountTrailingZeros_32(Align));
709     else
710       KnownZero.clear();
711     KnownOne.clear();
712     return;
713   }
714
715   KnownZero.clear(); KnownOne.clear();   // Start out not knowing anything.
716
717   if (Depth == 6 || Mask == 0)
718     return;  // Limit search depth.
719
720   User *I = dyn_cast<User>(V);
721   if (!I) return;
722
723   APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
724   switch (getOpcode(I)) {
725   default: break;
726   case Instruction::And: {
727     // If either the LHS or the RHS are Zero, the result is zero.
728     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
729     APInt Mask2(Mask & ~KnownZero);
730     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
731     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
732     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
733     
734     // Output known-1 bits are only known if set in both the LHS & RHS.
735     KnownOne &= KnownOne2;
736     // Output known-0 are known to be clear if zero in either the LHS | RHS.
737     KnownZero |= KnownZero2;
738     return;
739   }
740   case Instruction::Or: {
741     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
742     APInt Mask2(Mask & ~KnownOne);
743     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
744     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
745     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
746     
747     // Output known-0 bits are only known if clear in both the LHS & RHS.
748     KnownZero &= KnownZero2;
749     // Output known-1 are known to be set if set in either the LHS | RHS.
750     KnownOne |= KnownOne2;
751     return;
752   }
753   case Instruction::Xor: {
754     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
755     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
756     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
757     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
758     
759     // Output known-0 bits are known if clear or set in both the LHS & RHS.
760     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
761     // Output known-1 are known to be set if set in only one of the LHS, RHS.
762     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
763     KnownZero = KnownZeroOut;
764     return;
765   }
766   case Instruction::Mul: {
767     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
768     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
769     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
770     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
771     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
772     
773     // If low bits are zero in either operand, output low known-0 bits.
774     // Also compute a conserative estimate for high known-0 bits.
775     // More trickiness is possible, but this is sufficient for the
776     // interesting case of alignment computation.
777     KnownOne.clear();
778     unsigned TrailZ = KnownZero.countTrailingOnes() +
779                       KnownZero2.countTrailingOnes();
780     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
781                                KnownZero2.countLeadingOnes(),
782                                BitWidth) - BitWidth;
783
784     TrailZ = std::min(TrailZ, BitWidth);
785     LeadZ = std::min(LeadZ, BitWidth);
786     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
787                 APInt::getHighBitsSet(BitWidth, LeadZ);
788     KnownZero &= Mask;
789     return;
790   }
791   case Instruction::UDiv: {
792     // For the purposes of computing leading zeros we can conservatively
793     // treat a udiv as a logical right shift by the power of 2 known to
794     // be less than the denominator.
795     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
796     ComputeMaskedBits(I->getOperand(0),
797                       AllOnes, KnownZero2, KnownOne2, Depth+1);
798     unsigned LeadZ = KnownZero2.countLeadingOnes();
799
800     KnownOne2.clear();
801     KnownZero2.clear();
802     ComputeMaskedBits(I->getOperand(1),
803                       AllOnes, KnownZero2, KnownOne2, Depth+1);
804     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
805     if (RHSUnknownLeadingOnes != BitWidth)
806       LeadZ = std::min(BitWidth,
807                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
808
809     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
810     return;
811   }
812   case Instruction::Select:
813     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
814     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
815     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
816     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
817
818     // Only known if known in both the LHS and RHS.
819     KnownOne &= KnownOne2;
820     KnownZero &= KnownZero2;
821     return;
822   case Instruction::FPTrunc:
823   case Instruction::FPExt:
824   case Instruction::FPToUI:
825   case Instruction::FPToSI:
826   case Instruction::SIToFP:
827   case Instruction::UIToFP:
828     return; // Can't work with floating point.
829   case Instruction::PtrToInt:
830   case Instruction::IntToPtr:
831     // We can't handle these if we don't know the pointer size.
832     if (!TD) return;
833     // FALL THROUGH and handle them the same as zext/trunc.
834   case Instruction::ZExt:
835   case Instruction::Trunc: {
836     // Note that we handle pointer operands here because of inttoptr/ptrtoint
837     // which fall through here.
838     const Type *SrcTy = I->getOperand(0)->getType();
839     uint32_t SrcBitWidth = TD ?
840       TD->getTypeSizeInBits(SrcTy) :
841       SrcTy->getPrimitiveSizeInBits();
842     APInt MaskIn(Mask);
843     MaskIn.zextOrTrunc(SrcBitWidth);
844     KnownZero.zextOrTrunc(SrcBitWidth);
845     KnownOne.zextOrTrunc(SrcBitWidth);
846     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
847     KnownZero.zextOrTrunc(BitWidth);
848     KnownOne.zextOrTrunc(BitWidth);
849     // Any top bits are known to be zero.
850     if (BitWidth > SrcBitWidth)
851       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
852     return;
853   }
854   case Instruction::BitCast: {
855     const Type *SrcTy = I->getOperand(0)->getType();
856     if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
857       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
858       return;
859     }
860     break;
861   }
862   case Instruction::SExt: {
863     // Compute the bits in the result that are not present in the input.
864     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
865     uint32_t SrcBitWidth = SrcTy->getBitWidth();
866       
867     APInt MaskIn(Mask); 
868     MaskIn.trunc(SrcBitWidth);
869     KnownZero.trunc(SrcBitWidth);
870     KnownOne.trunc(SrcBitWidth);
871     ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
872     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
873     KnownZero.zext(BitWidth);
874     KnownOne.zext(BitWidth);
875
876     // If the sign bit of the input is known set or clear, then we know the
877     // top bits of the result.
878     if (KnownZero[SrcBitWidth-1])             // Input sign bit known zero
879       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
880     else if (KnownOne[SrcBitWidth-1])           // Input sign bit known set
881       KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
882     return;
883   }
884   case Instruction::Shl:
885     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
886     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
887       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
888       APInt Mask2(Mask.lshr(ShiftAmt));
889       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
890       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
891       KnownZero <<= ShiftAmt;
892       KnownOne  <<= ShiftAmt;
893       KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
894       return;
895     }
896     break;
897   case Instruction::LShr:
898     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
899     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
900       // Compute the new bits that are at the top now.
901       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
902       
903       // Unsigned shift right.
904       APInt Mask2(Mask.shl(ShiftAmt));
905       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
906       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
907       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
908       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
909       // high bits known zero.
910       KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
911       return;
912     }
913     break;
914   case Instruction::AShr:
915     // (ashr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
916     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
917       // Compute the new bits that are at the top now.
918       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
919       
920       // Signed shift right.
921       APInt Mask2(Mask.shl(ShiftAmt));
922       ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
923       assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
924       KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
925       KnownOne  = APIntOps::lshr(KnownOne, ShiftAmt);
926         
927       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
928       if (KnownZero[BitWidth-ShiftAmt-1])    // New bits are known zero.
929         KnownZero |= HighBits;
930       else if (KnownOne[BitWidth-ShiftAmt-1])  // New bits are known one.
931         KnownOne |= HighBits;
932       return;
933     }
934     break;
935   case Instruction::Sub: {
936     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
937       // We know that the top bits of C-X are clear if X contains less bits
938       // than C (i.e. no wrap-around can happen).  For example, 20-X is
939       // positive if we can prove that X is >= 0 and < 16.
940       if (!CLHS->getValue().isNegative()) {
941         unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
942         // NLZ can't be BitWidth with no sign bit
943         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
944         ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
945                           Depth+1);
946     
947         // If all of the MaskV bits are known to be zero, then we know the
948         // output top bits are zero, because we now know that the output is
949         // from [0-C].
950         if ((KnownZero2 & MaskV) == MaskV) {
951           unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
952           // Top bits known zero.
953           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
954         }
955       }        
956     }
957   }
958   // fall through
959   case Instruction::Add: {
960     // Output known-0 bits are known if clear or set in both the low clear bits
961     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
962     // low 3 bits clear.
963     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
964     ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
965     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
966     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
967
968     ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
969     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
970     KnownZeroOut = std::min(KnownZeroOut, 
971                             KnownZero2.countTrailingOnes());
972
973     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
974     return;
975   }
976   case Instruction::SRem:
977     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
978       APInt RA = Rem->getValue();
979       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
980         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
981         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
982         ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
983
984         // The sign of a remainder is equal to the sign of the first
985         // operand (zero being positive).
986         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
987           KnownZero2 |= ~LowBits;
988         else if (KnownOne2[BitWidth-1])
989           KnownOne2 |= ~LowBits;
990
991         KnownZero |= KnownZero2 & Mask;
992         KnownOne |= KnownOne2 & Mask;
993
994         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
995       }
996     }
997     break;
998   case Instruction::URem: {
999     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1000       APInt RA = Rem->getValue();
1001       if (RA.isPowerOf2()) {
1002         APInt LowBits = (RA - 1);
1003         APInt Mask2 = LowBits & Mask;
1004         KnownZero |= ~LowBits & Mask;
1005         ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1006         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1007         break;
1008       }
1009     }
1010
1011     // Since the result is less than or equal to either operand, any leading
1012     // zero bits in either operand must also exist in the result.
1013     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1014     ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1015                       Depth+1);
1016     ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1017                       Depth+1);
1018
1019     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1020                                 KnownZero2.countLeadingOnes());
1021     KnownOne.clear();
1022     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1023     break;
1024   }
1025
1026   case Instruction::Alloca:
1027   case Instruction::Malloc: {
1028     AllocationInst *AI = cast<AllocationInst>(V);
1029     unsigned Align = AI->getAlignment();
1030     if (Align == 0 && TD) {
1031       if (isa<AllocaInst>(AI))
1032         Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1033       else if (isa<MallocInst>(AI)) {
1034         // Malloc returns maximally aligned memory.
1035         Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1036         Align =
1037           std::max(Align,
1038                    (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1039         Align =
1040           std::max(Align,
1041                    (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1042       }
1043     }
1044     
1045     if (Align > 0)
1046       KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1047                                               CountTrailingZeros_32(Align));
1048     break;
1049   }
1050   case Instruction::GetElementPtr: {
1051     // Analyze all of the subscripts of this getelementptr instruction
1052     // to determine if we can prove known low zero bits.
1053     APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1054     APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1055     ComputeMaskedBits(I->getOperand(0), LocalMask,
1056                       LocalKnownZero, LocalKnownOne, Depth+1);
1057     unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1058
1059     gep_type_iterator GTI = gep_type_begin(I);
1060     for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1061       Value *Index = I->getOperand(i);
1062       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1063         // Handle struct member offset arithmetic.
1064         if (!TD) return;
1065         const StructLayout *SL = TD->getStructLayout(STy);
1066         unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1067         uint64_t Offset = SL->getElementOffset(Idx);
1068         TrailZ = std::min(TrailZ,
1069                           CountTrailingZeros_64(Offset));
1070       } else {
1071         // Handle array index arithmetic.
1072         const Type *IndexedTy = GTI.getIndexedType();
1073         if (!IndexedTy->isSized()) return;
1074         unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1075         uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1076         LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1077         LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1078         ComputeMaskedBits(Index, LocalMask,
1079                           LocalKnownZero, LocalKnownOne, Depth+1);
1080         TrailZ = std::min(TrailZ,
1081                           CountTrailingZeros_64(TypeSize) +
1082                             LocalKnownZero.countTrailingOnes());
1083       }
1084     }
1085     
1086     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1087     break;
1088   }
1089   case Instruction::PHI: {
1090     PHINode *P = cast<PHINode>(I);
1091     // Handle the case of a simple two-predecessor recurrence PHI.
1092     // There's a lot more that could theoretically be done here, but
1093     // this is sufficient to catch some interesting cases.
1094     if (P->getNumIncomingValues() == 2) {
1095       for (unsigned i = 0; i != 2; ++i) {
1096         Value *L = P->getIncomingValue(i);
1097         Value *R = P->getIncomingValue(!i);
1098         User *LU = dyn_cast<User>(L);
1099         if (!LU)
1100           continue;
1101         unsigned Opcode = getOpcode(LU);
1102         // Check for operations that have the property that if
1103         // both their operands have low zero bits, the result
1104         // will have low zero bits.
1105         if (Opcode == Instruction::Add ||
1106             Opcode == Instruction::Sub ||
1107             Opcode == Instruction::And ||
1108             Opcode == Instruction::Or ||
1109             Opcode == Instruction::Mul) {
1110           Value *LL = LU->getOperand(0);
1111           Value *LR = LU->getOperand(1);
1112           // Find a recurrence.
1113           if (LL == I)
1114             L = LR;
1115           else if (LR == I)
1116             L = LL;
1117           else
1118             break;
1119           // Ok, we have a PHI of the form L op= R. Check for low
1120           // zero bits.
1121           APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1122           ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1123           Mask2 = APInt::getLowBitsSet(BitWidth,
1124                                        KnownZero2.countTrailingOnes());
1125           KnownOne2.clear();
1126           KnownZero2.clear();
1127           ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1128           KnownZero = Mask &
1129                       APInt::getLowBitsSet(BitWidth,
1130                                            KnownZero2.countTrailingOnes());
1131           break;
1132         }
1133       }
1134     }
1135     break;
1136   }
1137   case Instruction::Call:
1138     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1139       switch (II->getIntrinsicID()) {
1140       default: break;
1141       case Intrinsic::ctpop:
1142       case Intrinsic::ctlz:
1143       case Intrinsic::cttz: {
1144         unsigned LowBits = Log2_32(BitWidth)+1;
1145         KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1146         break;
1147       }
1148       }
1149     }
1150     break;
1151   }
1152 }
1153
1154 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1155 /// this predicate to simplify operations downstream.  Mask is known to be zero
1156 /// for bits that V cannot have.
1157 bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1158                                      unsigned Depth) {
1159   APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1160   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1161   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1162   return (KnownZero & Mask) == Mask;
1163 }
1164
1165 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
1166 /// specified instruction is a constant integer.  If so, check to see if there
1167 /// are any bits set in the constant that are not demanded.  If so, shrink the
1168 /// constant and return true.
1169 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
1170                                    APInt Demanded) {
1171   assert(I && "No instruction?");
1172   assert(OpNo < I->getNumOperands() && "Operand index too large");
1173
1174   // If the operand is not a constant integer, nothing to do.
1175   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1176   if (!OpC) return false;
1177
1178   // If there are no bits set that aren't demanded, nothing to do.
1179   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1180   if ((~Demanded & OpC->getValue()) == 0)
1181     return false;
1182
1183   // This instruction is producing bits that are not demanded. Shrink the RHS.
1184   Demanded &= OpC->getValue();
1185   I->setOperand(OpNo, ConstantInt::get(Demanded));
1186   return true;
1187 }
1188
1189 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
1190 // set of known zero and one bits, compute the maximum and minimum values that
1191 // could have the specified known zero and known one bits, returning them in
1192 // min/max.
1193 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1194                                                    const APInt& KnownZero,
1195                                                    const APInt& KnownOne,
1196                                                    APInt& Min, APInt& Max) {
1197   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1198   assert(KnownZero.getBitWidth() == BitWidth && 
1199          KnownOne.getBitWidth() == BitWidth &&
1200          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1201          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1202   APInt UnknownBits = ~(KnownZero|KnownOne);
1203
1204   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1205   // bit if it is unknown.
1206   Min = KnownOne;
1207   Max = KnownOne|UnknownBits;
1208   
1209   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1210     Min.set(BitWidth-1);
1211     Max.clear(BitWidth-1);
1212   }
1213 }
1214
1215 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1216 // a set of known zero and one bits, compute the maximum and minimum values that
1217 // could have the specified known zero and known one bits, returning them in
1218 // min/max.
1219 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1220                                                      const APInt &KnownZero,
1221                                                      const APInt &KnownOne,
1222                                                      APInt &Min, APInt &Max) {
1223   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
1224   assert(KnownZero.getBitWidth() == BitWidth && 
1225          KnownOne.getBitWidth() == BitWidth &&
1226          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1227          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1228   APInt UnknownBits = ~(KnownZero|KnownOne);
1229   
1230   // The minimum value is when the unknown bits are all zeros.
1231   Min = KnownOne;
1232   // The maximum value is when the unknown bits are all ones.
1233   Max = KnownOne|UnknownBits;
1234 }
1235
1236 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1237 /// value based on the demanded bits. When this function is called, it is known
1238 /// that only the bits set in DemandedMask of the result of V are ever used
1239 /// downstream. Consequently, depending on the mask and V, it may be possible
1240 /// to replace V with a constant or one of its operands. In such cases, this
1241 /// function does the replacement and returns true. In all other cases, it
1242 /// returns false after analyzing the expression and setting KnownOne and known
1243 /// to be one in the expression. KnownZero contains all the bits that are known
1244 /// to be zero in the expression. These are provided to potentially allow the
1245 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1246 /// the expression. KnownOne and KnownZero always follow the invariant that 
1247 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1248 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1249 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1250 /// and KnownOne must all be the same.
1251 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1252                                         APInt& KnownZero, APInt& KnownOne,
1253                                         unsigned Depth) {
1254   assert(V != 0 && "Null pointer of Value???");
1255   assert(Depth <= 6 && "Limit Search Depth");
1256   uint32_t BitWidth = DemandedMask.getBitWidth();
1257   const IntegerType *VTy = cast<IntegerType>(V->getType());
1258   assert(VTy->getBitWidth() == BitWidth && 
1259          KnownZero.getBitWidth() == BitWidth && 
1260          KnownOne.getBitWidth() == BitWidth &&
1261          "Value *V, DemandedMask, KnownZero and KnownOne \
1262           must have same BitWidth");
1263   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1264     // We know all of the bits for a constant!
1265     KnownOne = CI->getValue() & DemandedMask;
1266     KnownZero = ~KnownOne & DemandedMask;
1267     return false;
1268   }
1269   
1270   KnownZero.clear(); 
1271   KnownOne.clear();
1272   if (!V->hasOneUse()) {    // Other users may use these bits.
1273     if (Depth != 0) {       // Not at the root.
1274       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1275       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1276       return false;
1277     }
1278     // If this is the root being simplified, allow it to have multiple uses,
1279     // just set the DemandedMask to all bits.
1280     DemandedMask = APInt::getAllOnesValue(BitWidth);
1281   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
1282     if (V != UndefValue::get(VTy))
1283       return UpdateValueUsesWith(V, UndefValue::get(VTy));
1284     return false;
1285   } else if (Depth == 6) {        // Limit search depth.
1286     return false;
1287   }
1288   
1289   Instruction *I = dyn_cast<Instruction>(V);
1290   if (!I) return false;        // Only analyze instructions.
1291
1292   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1293   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1294   switch (I->getOpcode()) {
1295   default:
1296     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1297     break;
1298   case Instruction::And:
1299     // If either the LHS or the RHS are Zero, the result is zero.
1300     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1301                              RHSKnownZero, RHSKnownOne, Depth+1))
1302       return true;
1303     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1304            "Bits known to be one AND zero?"); 
1305
1306     // If something is known zero on the RHS, the bits aren't demanded on the
1307     // LHS.
1308     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1309                              LHSKnownZero, LHSKnownOne, Depth+1))
1310       return true;
1311     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1312            "Bits known to be one AND zero?"); 
1313
1314     // If all of the demanded bits are known 1 on one side, return the other.
1315     // These bits cannot contribute to the result of the 'and'.
1316     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
1317         (DemandedMask & ~LHSKnownZero))
1318       return UpdateValueUsesWith(I, I->getOperand(0));
1319     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
1320         (DemandedMask & ~RHSKnownZero))
1321       return UpdateValueUsesWith(I, I->getOperand(1));
1322     
1323     // If all of the demanded bits in the inputs are known zeros, return zero.
1324     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1325       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1326       
1327     // If the RHS is a constant, see if we can simplify it.
1328     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1329       return UpdateValueUsesWith(I, I);
1330       
1331     // Output known-1 bits are only known if set in both the LHS & RHS.
1332     RHSKnownOne &= LHSKnownOne;
1333     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1334     RHSKnownZero |= LHSKnownZero;
1335     break;
1336   case Instruction::Or:
1337     // If either the LHS or the RHS are One, the result is One.
1338     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1339                              RHSKnownZero, RHSKnownOne, Depth+1))
1340       return true;
1341     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1342            "Bits known to be one AND zero?"); 
1343     // If something is known one on the RHS, the bits aren't demanded on the
1344     // LHS.
1345     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
1346                              LHSKnownZero, LHSKnownOne, Depth+1))
1347       return true;
1348     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1349            "Bits known to be one AND zero?"); 
1350     
1351     // If all of the demanded bits are known zero on one side, return the other.
1352     // These bits cannot contribute to the result of the 'or'.
1353     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
1354         (DemandedMask & ~LHSKnownOne))
1355       return UpdateValueUsesWith(I, I->getOperand(0));
1356     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
1357         (DemandedMask & ~RHSKnownOne))
1358       return UpdateValueUsesWith(I, I->getOperand(1));
1359
1360     // If all of the potentially set bits on one side are known to be set on
1361     // the other side, just use the 'other' side.
1362     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
1363         (DemandedMask & (~RHSKnownZero)))
1364       return UpdateValueUsesWith(I, I->getOperand(0));
1365     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
1366         (DemandedMask & (~LHSKnownZero)))
1367       return UpdateValueUsesWith(I, I->getOperand(1));
1368         
1369     // If the RHS is a constant, see if we can simplify it.
1370     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1371       return UpdateValueUsesWith(I, I);
1372           
1373     // Output known-0 bits are only known if clear in both the LHS & RHS.
1374     RHSKnownZero &= LHSKnownZero;
1375     // Output known-1 are known to be set if set in either the LHS | RHS.
1376     RHSKnownOne |= LHSKnownOne;
1377     break;
1378   case Instruction::Xor: {
1379     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1380                              RHSKnownZero, RHSKnownOne, Depth+1))
1381       return true;
1382     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1383            "Bits known to be one AND zero?"); 
1384     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1385                              LHSKnownZero, LHSKnownOne, Depth+1))
1386       return true;
1387     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1388            "Bits known to be one AND zero?"); 
1389     
1390     // If all of the demanded bits are known zero on one side, return the other.
1391     // These bits cannot contribute to the result of the 'xor'.
1392     if ((DemandedMask & RHSKnownZero) == DemandedMask)
1393       return UpdateValueUsesWith(I, I->getOperand(0));
1394     if ((DemandedMask & LHSKnownZero) == DemandedMask)
1395       return UpdateValueUsesWith(I, I->getOperand(1));
1396     
1397     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1398     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
1399                          (RHSKnownOne & LHSKnownOne);
1400     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1401     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
1402                         (RHSKnownOne & LHSKnownZero);
1403     
1404     // If all of the demanded bits are known to be zero on one side or the
1405     // other, turn this into an *inclusive* or.
1406     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1407     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1408       Instruction *Or =
1409         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1410                                  I->getName());
1411       InsertNewInstBefore(Or, *I);
1412       return UpdateValueUsesWith(I, Or);
1413     }
1414     
1415     // If all of the demanded bits on one side are known, and all of the set
1416     // bits on that side are also known to be set on the other side, turn this
1417     // into an AND, as we know the bits will be cleared.
1418     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1419     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
1420       // all known
1421       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1422         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1423         Instruction *And = 
1424           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1425         InsertNewInstBefore(And, *I);
1426         return UpdateValueUsesWith(I, And);
1427       }
1428     }
1429     
1430     // If the RHS is a constant, see if we can simplify it.
1431     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1432     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1433       return UpdateValueUsesWith(I, I);
1434     
1435     RHSKnownZero = KnownZeroOut;
1436     RHSKnownOne  = KnownOneOut;
1437     break;
1438   }
1439   case Instruction::Select:
1440     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1441                              RHSKnownZero, RHSKnownOne, Depth+1))
1442       return true;
1443     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1444                              LHSKnownZero, LHSKnownOne, Depth+1))
1445       return true;
1446     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1447            "Bits known to be one AND zero?"); 
1448     assert((LHSKnownZero & LHSKnownOne) == 0 && 
1449            "Bits known to be one AND zero?"); 
1450     
1451     // If the operands are constants, see if we can simplify them.
1452     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1453       return UpdateValueUsesWith(I, I);
1454     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1455       return UpdateValueUsesWith(I, I);
1456     
1457     // Only known if known in both the LHS and RHS.
1458     RHSKnownOne &= LHSKnownOne;
1459     RHSKnownZero &= LHSKnownZero;
1460     break;
1461   case Instruction::Trunc: {
1462     uint32_t truncBf = 
1463       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1464     DemandedMask.zext(truncBf);
1465     RHSKnownZero.zext(truncBf);
1466     RHSKnownOne.zext(truncBf);
1467     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
1468                              RHSKnownZero, RHSKnownOne, Depth+1))
1469       return true;
1470     DemandedMask.trunc(BitWidth);
1471     RHSKnownZero.trunc(BitWidth);
1472     RHSKnownOne.trunc(BitWidth);
1473     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1474            "Bits known to be one AND zero?"); 
1475     break;
1476   }
1477   case Instruction::BitCast:
1478     if (!I->getOperand(0)->getType()->isInteger())
1479       return false;
1480       
1481     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1482                              RHSKnownZero, RHSKnownOne, Depth+1))
1483       return true;
1484     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1485            "Bits known to be one AND zero?"); 
1486     break;
1487   case Instruction::ZExt: {
1488     // Compute the bits in the result that are not present in the input.
1489     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1490     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1491     
1492     DemandedMask.trunc(SrcBitWidth);
1493     RHSKnownZero.trunc(SrcBitWidth);
1494     RHSKnownOne.trunc(SrcBitWidth);
1495     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1496                              RHSKnownZero, RHSKnownOne, Depth+1))
1497       return true;
1498     DemandedMask.zext(BitWidth);
1499     RHSKnownZero.zext(BitWidth);
1500     RHSKnownOne.zext(BitWidth);
1501     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1502            "Bits known to be one AND zero?"); 
1503     // The top bits are known to be zero.
1504     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1505     break;
1506   }
1507   case Instruction::SExt: {
1508     // Compute the bits in the result that are not present in the input.
1509     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1510     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1511     
1512     APInt InputDemandedBits = DemandedMask & 
1513                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1514
1515     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1516     // If any of the sign extended bits are demanded, we know that the sign
1517     // bit is demanded.
1518     if ((NewBits & DemandedMask) != 0)
1519       InputDemandedBits.set(SrcBitWidth-1);
1520       
1521     InputDemandedBits.trunc(SrcBitWidth);
1522     RHSKnownZero.trunc(SrcBitWidth);
1523     RHSKnownOne.trunc(SrcBitWidth);
1524     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1525                              RHSKnownZero, RHSKnownOne, Depth+1))
1526       return true;
1527     InputDemandedBits.zext(BitWidth);
1528     RHSKnownZero.zext(BitWidth);
1529     RHSKnownOne.zext(BitWidth);
1530     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1531            "Bits known to be one AND zero?"); 
1532       
1533     // If the sign bit of the input is known set or clear, then we know the
1534     // top bits of the result.
1535
1536     // If the input sign bit is known zero, or if the NewBits are not demanded
1537     // convert this into a zero extension.
1538     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1539     {
1540       // Convert to ZExt cast
1541       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1542       return UpdateValueUsesWith(I, NewCast);
1543     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1544       RHSKnownOne |= NewBits;
1545     }
1546     break;
1547   }
1548   case Instruction::Add: {
1549     // Figure out what the input bits are.  If the top bits of the and result
1550     // are not demanded, then the add doesn't demand them from its input
1551     // either.
1552     uint32_t NLZ = DemandedMask.countLeadingZeros();
1553       
1554     // If there is a constant on the RHS, there are a variety of xformations
1555     // we can do.
1556     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1557       // If null, this should be simplified elsewhere.  Some of the xforms here
1558       // won't work if the RHS is zero.
1559       if (RHS->isZero())
1560         break;
1561       
1562       // If the top bit of the output is demanded, demand everything from the
1563       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1564       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1565
1566       // Find information about known zero/one bits in the input.
1567       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1568                                LHSKnownZero, LHSKnownOne, Depth+1))
1569         return true;
1570
1571       // If the RHS of the add has bits set that can't affect the input, reduce
1572       // the constant.
1573       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1574         return UpdateValueUsesWith(I, I);
1575       
1576       // Avoid excess work.
1577       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1578         break;
1579       
1580       // Turn it into OR if input bits are zero.
1581       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1582         Instruction *Or =
1583           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1584                                    I->getName());
1585         InsertNewInstBefore(Or, *I);
1586         return UpdateValueUsesWith(I, Or);
1587       }
1588       
1589       // We can say something about the output known-zero and known-one bits,
1590       // depending on potential carries from the input constant and the
1591       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1592       // bits set and the RHS constant is 0x01001, then we know we have a known
1593       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1594       
1595       // To compute this, we first compute the potential carry bits.  These are
1596       // the bits which may be modified.  I'm not aware of a better way to do
1597       // this scan.
1598       const APInt& RHSVal = RHS->getValue();
1599       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1600       
1601       // Now that we know which bits have carries, compute the known-1/0 sets.
1602       
1603       // Bits are known one if they are known zero in one operand and one in the
1604       // other, and there is no input carry.
1605       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1606                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1607       
1608       // Bits are known zero if they are known zero in both operands and there
1609       // is no input carry.
1610       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1611     } else {
1612       // If the high-bits of this ADD are not demanded, then it does not demand
1613       // the high bits of its LHS or RHS.
1614       if (DemandedMask[BitWidth-1] == 0) {
1615         // Right fill the mask of bits for this ADD to demand the most
1616         // significant bit and all those below it.
1617         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1618         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1619                                  LHSKnownZero, LHSKnownOne, Depth+1))
1620           return true;
1621         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1622                                  LHSKnownZero, LHSKnownOne, Depth+1))
1623           return true;
1624       }
1625     }
1626     break;
1627   }
1628   case Instruction::Sub:
1629     // If the high-bits of this SUB are not demanded, then it does not demand
1630     // the high bits of its LHS or RHS.
1631     if (DemandedMask[BitWidth-1] == 0) {
1632       // Right fill the mask of bits for this SUB to demand the most
1633       // significant bit and all those below it.
1634       uint32_t NLZ = DemandedMask.countLeadingZeros();
1635       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1636       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1637                                LHSKnownZero, LHSKnownOne, Depth+1))
1638         return true;
1639       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1640                                LHSKnownZero, LHSKnownOne, Depth+1))
1641         return true;
1642     }
1643     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1644     // the known zeros and ones.
1645     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1646     break;
1647   case Instruction::Shl:
1648     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1649       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1650       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1651       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1652                                RHSKnownZero, RHSKnownOne, Depth+1))
1653         return true;
1654       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1655              "Bits known to be one AND zero?"); 
1656       RHSKnownZero <<= ShiftAmt;
1657       RHSKnownOne  <<= ShiftAmt;
1658       // low bits known zero.
1659       if (ShiftAmt)
1660         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1661     }
1662     break;
1663   case Instruction::LShr:
1664     // For a logical shift right
1665     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1666       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1667       
1668       // Unsigned shift right.
1669       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1670       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1671                                RHSKnownZero, RHSKnownOne, Depth+1))
1672         return true;
1673       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1674              "Bits known to be one AND zero?"); 
1675       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1676       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1677       if (ShiftAmt) {
1678         // Compute the new bits that are at the top now.
1679         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1680         RHSKnownZero |= HighBits;  // high bits known zero.
1681       }
1682     }
1683     break;
1684   case Instruction::AShr:
1685     // If this is an arithmetic shift right and only the low-bit is set, we can
1686     // always convert this into a logical shr, even if the shift amount is
1687     // variable.  The low bit of the shift cannot be an input sign bit unless
1688     // the shift amount is >= the size of the datatype, which is undefined.
1689     if (DemandedMask == 1) {
1690       // Perform the logical shift right.
1691       Value *NewVal = BinaryOperator::CreateLShr(
1692                         I->getOperand(0), I->getOperand(1), I->getName());
1693       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1694       return UpdateValueUsesWith(I, NewVal);
1695     }    
1696
1697     // If the sign bit is the only bit demanded by this ashr, then there is no
1698     // need to do it, the shift doesn't change the high bit.
1699     if (DemandedMask.isSignBit())
1700       return UpdateValueUsesWith(I, I->getOperand(0));
1701     
1702     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1703       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1704       
1705       // Signed shift right.
1706       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1707       // If any of the "high bits" are demanded, we should set the sign bit as
1708       // demanded.
1709       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1710         DemandedMaskIn.set(BitWidth-1);
1711       if (SimplifyDemandedBits(I->getOperand(0),
1712                                DemandedMaskIn,
1713                                RHSKnownZero, RHSKnownOne, Depth+1))
1714         return true;
1715       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1716              "Bits known to be one AND zero?"); 
1717       // Compute the new bits that are at the top now.
1718       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1719       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1720       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1721         
1722       // Handle the sign bits.
1723       APInt SignBit(APInt::getSignBit(BitWidth));
1724       // Adjust to where it is now in the mask.
1725       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1726         
1727       // If the input sign bit is known to be zero, or if none of the top bits
1728       // are demanded, turn this into an unsigned shift right.
1729       if (RHSKnownZero[BitWidth-ShiftAmt-1] || 
1730           (HighBits & ~DemandedMask) == HighBits) {
1731         // Perform the logical shift right.
1732         Value *NewVal = BinaryOperator::CreateLShr(
1733                           I->getOperand(0), SA, I->getName());
1734         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1735         return UpdateValueUsesWith(I, NewVal);
1736       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1737         RHSKnownOne |= HighBits;
1738       }
1739     }
1740     break;
1741   case Instruction::SRem:
1742     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1743       APInt RA = Rem->getValue();
1744       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1745         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1746         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1747         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1748                                  LHSKnownZero, LHSKnownOne, Depth+1))
1749           return true;
1750
1751         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1752           LHSKnownZero |= ~LowBits;
1753         else if (LHSKnownOne[BitWidth-1])
1754           LHSKnownOne |= ~LowBits;
1755
1756         KnownZero |= LHSKnownZero & DemandedMask;
1757         KnownOne |= LHSKnownOne & DemandedMask;
1758
1759         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1760       }
1761     }
1762     break;
1763   case Instruction::URem: {
1764     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1765       APInt RA = Rem->getValue();
1766       if (RA.isPowerOf2()) {
1767         APInt LowBits = (RA - 1);
1768         APInt Mask2 = LowBits & DemandedMask;
1769         KnownZero |= ~LowBits & DemandedMask;
1770         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1771                                  KnownZero, KnownOne, Depth+1))
1772           return true;
1773
1774         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1775         break;
1776       }
1777     }
1778
1779     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1780     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1781     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1782                              KnownZero2, KnownOne2, Depth+1))
1783       return true;
1784
1785     uint32_t Leaders = KnownZero2.countLeadingOnes();
1786     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1787                              KnownZero2, KnownOne2, Depth+1))
1788       return true;
1789
1790     Leaders = std::max(Leaders,
1791                        KnownZero2.countLeadingOnes());
1792     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1793     break;
1794   }
1795   }
1796   
1797   // If the client is only demanding bits that we know, return the known
1798   // constant.
1799   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1800     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1801   return false;
1802 }
1803
1804
1805 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1806 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1807 /// actually used by the caller.  This method analyzes which elements of the
1808 /// operand are undef and returns that information in UndefElts.
1809 ///
1810 /// If the information about demanded elements can be used to simplify the
1811 /// operation, the operation is simplified, then the resultant value is
1812 /// returned.  This returns null if no change was made.
1813 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1814                                                 uint64_t &UndefElts,
1815                                                 unsigned Depth) {
1816   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1817   assert(VWidth <= 64 && "Vector too wide to analyze!");
1818   uint64_t EltMask = ~0ULL >> (64-VWidth);
1819   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1820          "Invalid DemandedElts!");
1821
1822   if (isa<UndefValue>(V)) {
1823     // If the entire vector is undefined, just return this info.
1824     UndefElts = EltMask;
1825     return 0;
1826   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1827     UndefElts = EltMask;
1828     return UndefValue::get(V->getType());
1829   }
1830   
1831   UndefElts = 0;
1832   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1833     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1834     Constant *Undef = UndefValue::get(EltTy);
1835
1836     std::vector<Constant*> Elts;
1837     for (unsigned i = 0; i != VWidth; ++i)
1838       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1839         Elts.push_back(Undef);
1840         UndefElts |= (1ULL << i);
1841       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1842         Elts.push_back(Undef);
1843         UndefElts |= (1ULL << i);
1844       } else {                               // Otherwise, defined.
1845         Elts.push_back(CP->getOperand(i));
1846       }
1847         
1848     // If we changed the constant, return it.
1849     Constant *NewCP = ConstantVector::get(Elts);
1850     return NewCP != CP ? NewCP : 0;
1851   } else if (isa<ConstantAggregateZero>(V)) {
1852     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1853     // set to undef.
1854     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1855     Constant *Zero = Constant::getNullValue(EltTy);
1856     Constant *Undef = UndefValue::get(EltTy);
1857     std::vector<Constant*> Elts;
1858     for (unsigned i = 0; i != VWidth; ++i)
1859       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1860     UndefElts = DemandedElts ^ EltMask;
1861     return ConstantVector::get(Elts);
1862   }
1863   
1864   if (!V->hasOneUse()) {    // Other users may use these bits.
1865     if (Depth != 0) {       // Not at the root.
1866       // TODO: Just compute the UndefElts information recursively.
1867       return false;
1868     }
1869     return false;
1870   } else if (Depth == 10) {        // Limit search depth.
1871     return false;
1872   }
1873   
1874   Instruction *I = dyn_cast<Instruction>(V);
1875   if (!I) return false;        // Only analyze instructions.
1876   
1877   bool MadeChange = false;
1878   uint64_t UndefElts2;
1879   Value *TmpV;
1880   switch (I->getOpcode()) {
1881   default: break;
1882     
1883   case Instruction::InsertElement: {
1884     // If this is a variable index, we don't know which element it overwrites.
1885     // demand exactly the same input as we produce.
1886     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1887     if (Idx == 0) {
1888       // Note that we can't propagate undef elt info, because we don't know
1889       // which elt is getting updated.
1890       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1891                                         UndefElts2, Depth+1);
1892       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1893       break;
1894     }
1895     
1896     // If this is inserting an element that isn't demanded, remove this
1897     // insertelement.
1898     unsigned IdxNo = Idx->getZExtValue();
1899     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1900       return AddSoonDeadInstToWorklist(*I, 0);
1901     
1902     // Otherwise, the element inserted overwrites whatever was there, so the
1903     // input demanded set is simpler than the output set.
1904     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1905                                       DemandedElts & ~(1ULL << IdxNo),
1906                                       UndefElts, Depth+1);
1907     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1908
1909     // The inserted element is defined.
1910     UndefElts |= 1ULL << IdxNo;
1911     break;
1912   }
1913   case Instruction::BitCast: {
1914     // Vector->vector casts only.
1915     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1916     if (!VTy) break;
1917     unsigned InVWidth = VTy->getNumElements();
1918     uint64_t InputDemandedElts = 0;
1919     unsigned Ratio;
1920
1921     if (VWidth == InVWidth) {
1922       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1923       // elements as are demanded of us.
1924       Ratio = 1;
1925       InputDemandedElts = DemandedElts;
1926     } else if (VWidth > InVWidth) {
1927       // Untested so far.
1928       break;
1929       
1930       // If there are more elements in the result than there are in the source,
1931       // then an input element is live if any of the corresponding output
1932       // elements are live.
1933       Ratio = VWidth/InVWidth;
1934       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1935         if (DemandedElts & (1ULL << OutIdx))
1936           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1937       }
1938     } else {
1939       // Untested so far.
1940       break;
1941       
1942       // If there are more elements in the source than there are in the result,
1943       // then an input element is live if the corresponding output element is
1944       // live.
1945       Ratio = InVWidth/VWidth;
1946       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1947         if (DemandedElts & (1ULL << InIdx/Ratio))
1948           InputDemandedElts |= 1ULL << InIdx;
1949     }
1950     
1951     // div/rem demand all inputs, because they don't want divide by zero.
1952     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1953                                       UndefElts2, Depth+1);
1954     if (TmpV) {
1955       I->setOperand(0, TmpV);
1956       MadeChange = true;
1957     }
1958     
1959     UndefElts = UndefElts2;
1960     if (VWidth > InVWidth) {
1961       assert(0 && "Unimp");
1962       // If there are more elements in the result than there are in the source,
1963       // then an output element is undef if the corresponding input element is
1964       // undef.
1965       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1966         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1967           UndefElts |= 1ULL << OutIdx;
1968     } else if (VWidth < InVWidth) {
1969       assert(0 && "Unimp");
1970       // If there are more elements in the source than there are in the result,
1971       // then a result element is undef if all of the corresponding input
1972       // elements are undef.
1973       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1974       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1975         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1976           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1977     }
1978     break;
1979   }
1980   case Instruction::And:
1981   case Instruction::Or:
1982   case Instruction::Xor:
1983   case Instruction::Add:
1984   case Instruction::Sub:
1985   case Instruction::Mul:
1986     // div/rem demand all inputs, because they don't want divide by zero.
1987     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1988                                       UndefElts, Depth+1);
1989     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1990     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1991                                       UndefElts2, Depth+1);
1992     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1993       
1994     // Output elements are undefined if both are undefined.  Consider things
1995     // like undef&0.  The result is known zero, not undef.
1996     UndefElts &= UndefElts2;
1997     break;
1998     
1999   case Instruction::Call: {
2000     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
2001     if (!II) break;
2002     switch (II->getIntrinsicID()) {
2003     default: break;
2004       
2005     // Binary vector operations that work column-wise.  A dest element is a
2006     // function of the corresponding input elements from the two inputs.
2007     case Intrinsic::x86_sse_sub_ss:
2008     case Intrinsic::x86_sse_mul_ss:
2009     case Intrinsic::x86_sse_min_ss:
2010     case Intrinsic::x86_sse_max_ss:
2011     case Intrinsic::x86_sse2_sub_sd:
2012     case Intrinsic::x86_sse2_mul_sd:
2013     case Intrinsic::x86_sse2_min_sd:
2014     case Intrinsic::x86_sse2_max_sd:
2015       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2016                                         UndefElts, Depth+1);
2017       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2018       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2019                                         UndefElts2, Depth+1);
2020       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2021
2022       // If only the low elt is demanded and this is a scalarizable intrinsic,
2023       // scalarize it now.
2024       if (DemandedElts == 1) {
2025         switch (II->getIntrinsicID()) {
2026         default: break;
2027         case Intrinsic::x86_sse_sub_ss:
2028         case Intrinsic::x86_sse_mul_ss:
2029         case Intrinsic::x86_sse2_sub_sd:
2030         case Intrinsic::x86_sse2_mul_sd:
2031           // TODO: Lower MIN/MAX/ABS/etc
2032           Value *LHS = II->getOperand(1);
2033           Value *RHS = II->getOperand(2);
2034           // Extract the element as scalars.
2035           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2036           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2037           
2038           switch (II->getIntrinsicID()) {
2039           default: assert(0 && "Case stmts out of sync!");
2040           case Intrinsic::x86_sse_sub_ss:
2041           case Intrinsic::x86_sse2_sub_sd:
2042             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
2043                                                         II->getName()), *II);
2044             break;
2045           case Intrinsic::x86_sse_mul_ss:
2046           case Intrinsic::x86_sse2_mul_sd:
2047             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
2048                                                          II->getName()), *II);
2049             break;
2050           }
2051           
2052           Instruction *New =
2053             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2054                                       II->getName());
2055           InsertNewInstBefore(New, *II);
2056           AddSoonDeadInstToWorklist(*II, 0);
2057           return New;
2058         }            
2059       }
2060         
2061       // Output elements are undefined if both are undefined.  Consider things
2062       // like undef&0.  The result is known zero, not undef.
2063       UndefElts &= UndefElts2;
2064       break;
2065     }
2066     break;
2067   }
2068   }
2069   return MadeChange ? I : 0;
2070 }
2071
2072 /// ComputeNumSignBits - Return the number of times the sign bit of the
2073 /// register is replicated into the other bits.  We know that at least 1 bit
2074 /// is always equal to the sign bit (itself), but other cases can give us
2075 /// information.  For example, immediately after an "ashr X, 2", we know that
2076 /// the top 3 bits are all equal to each other, so we return 3.
2077 ///
2078 unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2079   const IntegerType *Ty = cast<IntegerType>(V->getType());
2080   unsigned TyBits = Ty->getBitWidth();
2081   unsigned Tmp, Tmp2;
2082   unsigned FirstAnswer = 1;
2083
2084   if (Depth == 6)
2085     return 1;  // Limit search depth.
2086
2087   User *U = dyn_cast<User>(V);
2088   switch (getOpcode(V)) {
2089   default: break;
2090   case Instruction::SExt:
2091     Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2092     return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2093     
2094   case Instruction::AShr:
2095     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2096     // ashr X, C   -> adds C sign bits.
2097     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2098       Tmp += C->getZExtValue();
2099       if (Tmp > TyBits) Tmp = TyBits;
2100     }
2101     return Tmp;
2102   case Instruction::Shl:
2103     if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2104       // shl destroys sign bits.
2105       Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2106       if (C->getZExtValue() >= TyBits ||      // Bad shift.
2107           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
2108       return Tmp - C->getZExtValue();
2109     }
2110     break;
2111   case Instruction::And:
2112   case Instruction::Or:
2113   case Instruction::Xor:    // NOT is handled here.
2114     // Logical binary ops preserve the number of sign bits at the worst.
2115     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2116     if (Tmp != 1) {
2117       Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2118       FirstAnswer = std::min(Tmp, Tmp2);
2119       // We computed what we know about the sign bits as our first
2120       // answer. Now proceed to the generic code that uses
2121       // ComputeMaskedBits, and pick whichever answer is better.
2122     }
2123     break;
2124
2125   case Instruction::Select:
2126     Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
2127     if (Tmp == 1) return 1;  // Early out.
2128     Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
2129     return std::min(Tmp, Tmp2);
2130     
2131   case Instruction::Add:
2132     // Add can have at most one carry bit.  Thus we know that the output
2133     // is, at worst, one more bit than the inputs.
2134     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2135     if (Tmp == 1) return 1;  // Early out.
2136       
2137     // Special case decrementing a value (ADD X, -1):
2138     if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2139       if (CRHS->isAllOnesValue()) {
2140         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2141         APInt Mask = APInt::getAllOnesValue(TyBits);
2142         ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2143         
2144         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2145         // sign bits set.
2146         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2147           return TyBits;
2148         
2149         // If we are subtracting one from a positive number, there is no carry
2150         // out of the result.
2151         if (KnownZero.isNegative())
2152           return Tmp;
2153       }
2154       
2155     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2156     if (Tmp2 == 1) return 1;
2157       return std::min(Tmp, Tmp2)-1;
2158     break;
2159     
2160   case Instruction::Sub:
2161     Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2162     if (Tmp2 == 1) return 1;
2163       
2164     // Handle NEG.
2165     if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2166       if (CLHS->isNullValue()) {
2167         APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2168         APInt Mask = APInt::getAllOnesValue(TyBits);
2169         ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2170         // If the input is known to be 0 or 1, the output is 0/-1, which is all
2171         // sign bits set.
2172         if ((KnownZero | APInt(TyBits, 1)) == Mask)
2173           return TyBits;
2174         
2175         // If the input is known to be positive (the sign bit is known clear),
2176         // the output of the NEG has the same number of sign bits as the input.
2177         if (KnownZero.isNegative())
2178           return Tmp2;
2179         
2180         // Otherwise, we treat this like a SUB.
2181       }
2182     
2183     // Sub can have at most one carry bit.  Thus we know that the output
2184     // is, at worst, one more bit than the inputs.
2185     Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2186     if (Tmp == 1) return 1;  // Early out.
2187       return std::min(Tmp, Tmp2)-1;
2188     break;
2189   case Instruction::Trunc:
2190     // FIXME: it's tricky to do anything useful for this, but it is an important
2191     // case for targets like X86.
2192     break;
2193   }
2194   
2195   // Finally, if we can prove that the top bits of the result are 0's or 1's,
2196   // use this information.
2197   APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2198   APInt Mask = APInt::getAllOnesValue(TyBits);
2199   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2200   
2201   if (KnownZero.isNegative()) {        // sign bit is 0
2202     Mask = KnownZero;
2203   } else if (KnownOne.isNegative()) {  // sign bit is 1;
2204     Mask = KnownOne;
2205   } else {
2206     // Nothing known.
2207     return FirstAnswer;
2208   }
2209   
2210   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2211   // the number of identical bits in the top of the input value.
2212   Mask = ~Mask;
2213   Mask <<= Mask.getBitWidth()-TyBits;
2214   // Return # leading zeros.  We use 'min' here in case Val was zero before
2215   // shifting.  We don't want to return '64' as for an i32 "0".
2216   return std::max(FirstAnswer, std::min(TyBits, Mask.countLeadingZeros()));
2217 }
2218
2219
2220 /// AssociativeOpt - Perform an optimization on an associative operator.  This
2221 /// function is designed to check a chain of associative operators for a
2222 /// potential to apply a certain optimization.  Since the optimization may be
2223 /// applicable if the expression was reassociated, this checks the chain, then
2224 /// reassociates the expression as necessary to expose the optimization
2225 /// opportunity.  This makes use of a special Functor, which must define
2226 /// 'shouldApply' and 'apply' methods.
2227 ///
2228 template<typename Functor>
2229 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2230   unsigned Opcode = Root.getOpcode();
2231   Value *LHS = Root.getOperand(0);
2232
2233   // Quick check, see if the immediate LHS matches...
2234   if (F.shouldApply(LHS))
2235     return F.apply(Root);
2236
2237   // Otherwise, if the LHS is not of the same opcode as the root, return.
2238   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2239   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2240     // Should we apply this transform to the RHS?
2241     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2242
2243     // If not to the RHS, check to see if we should apply to the LHS...
2244     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2245       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
2246       ShouldApply = true;
2247     }
2248
2249     // If the functor wants to apply the optimization to the RHS of LHSI,
2250     // reassociate the expression from ((? op A) op B) to (? op (A op B))
2251     if (ShouldApply) {
2252       BasicBlock *BB = Root.getParent();
2253
2254       // Now all of the instructions are in the current basic block, go ahead
2255       // and perform the reassociation.
2256       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2257
2258       // First move the selected RHS to the LHS of the root...
2259       Root.setOperand(0, LHSI->getOperand(1));
2260
2261       // Make what used to be the LHS of the root be the user of the root...
2262       Value *ExtraOperand = TmpLHSI->getOperand(1);
2263       if (&Root == TmpLHSI) {
2264         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2265         return 0;
2266       }
2267       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
2268       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
2269       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2270       BasicBlock::iterator ARI = &Root; ++ARI;
2271       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
2272       ARI = Root;
2273
2274       // Now propagate the ExtraOperand down the chain of instructions until we
2275       // get to LHSI.
2276       while (TmpLHSI != LHSI) {
2277         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2278         // Move the instruction to immediately before the chain we are
2279         // constructing to avoid breaking dominance properties.
2280         NextLHSI->getParent()->getInstList().remove(NextLHSI);
2281         BB->getInstList().insert(ARI, NextLHSI);
2282         ARI = NextLHSI;
2283
2284         Value *NextOp = NextLHSI->getOperand(1);
2285         NextLHSI->setOperand(1, ExtraOperand);
2286         TmpLHSI = NextLHSI;
2287         ExtraOperand = NextOp;
2288       }
2289
2290       // Now that the instructions are reassociated, have the functor perform
2291       // the transformation...
2292       return F.apply(Root);
2293     }
2294
2295     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2296   }
2297   return 0;
2298 }
2299
2300 namespace {
2301
2302 // AddRHS - Implements: X + X --> X << 1
2303 struct AddRHS {
2304   Value *RHS;
2305   AddRHS(Value *rhs) : RHS(rhs) {}
2306   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2307   Instruction *apply(BinaryOperator &Add) const {
2308     return BinaryOperator::CreateShl(Add.getOperand(0),
2309                                      ConstantInt::get(Add.getType(), 1));
2310   }
2311 };
2312
2313 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2314 //                 iff C1&C2 == 0
2315 struct AddMaskingAnd {
2316   Constant *C2;
2317   AddMaskingAnd(Constant *c) : C2(c) {}
2318   bool shouldApply(Value *LHS) const {
2319     ConstantInt *C1;
2320     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2321            ConstantExpr::getAnd(C1, C2)->isNullValue();
2322   }
2323   Instruction *apply(BinaryOperator &Add) const {
2324     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2325   }
2326 };
2327
2328 }
2329
2330 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2331                                              InstCombiner *IC) {
2332   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2333     if (Constant *SOC = dyn_cast<Constant>(SO))
2334       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2335
2336     return IC->InsertNewInstBefore(CastInst::Create(
2337           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2338   }
2339
2340   // Figure out if the constant is the left or the right argument.
2341   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2342   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2343
2344   if (Constant *SOC = dyn_cast<Constant>(SO)) {
2345     if (ConstIsRHS)
2346       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2347     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2348   }
2349
2350   Value *Op0 = SO, *Op1 = ConstOperand;
2351   if (!ConstIsRHS)
2352     std::swap(Op0, Op1);
2353   Instruction *New;
2354   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2355     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2356   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2357     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
2358                           SO->getName()+".cmp");
2359   else {
2360     assert(0 && "Unknown binary instruction type!");
2361     abort();
2362   }
2363   return IC->InsertNewInstBefore(New, I);
2364 }
2365
2366 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2367 // constant as the other operand, try to fold the binary operator into the
2368 // select arguments.  This also works for Cast instructions, which obviously do
2369 // not have a second operand.
2370 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2371                                      InstCombiner *IC) {
2372   // Don't modify shared select instructions
2373   if (!SI->hasOneUse()) return 0;
2374   Value *TV = SI->getOperand(1);
2375   Value *FV = SI->getOperand(2);
2376
2377   if (isa<Constant>(TV) || isa<Constant>(FV)) {
2378     // Bool selects with constant operands can be folded to logical ops.
2379     if (SI->getType() == Type::Int1Ty) return 0;
2380
2381     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2382     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2383
2384     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2385                               SelectFalseVal);
2386   }
2387   return 0;
2388 }
2389
2390
2391 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2392 /// node as operand #0, see if we can fold the instruction into the PHI (which
2393 /// is only possible if all operands to the PHI are constants).
2394 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2395   PHINode *PN = cast<PHINode>(I.getOperand(0));
2396   unsigned NumPHIValues = PN->getNumIncomingValues();
2397   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2398
2399   // Check to see if all of the operands of the PHI are constants.  If there is
2400   // one non-constant value, remember the BB it is.  If there is more than one
2401   // or if *it* is a PHI, bail out.
2402   BasicBlock *NonConstBB = 0;
2403   for (unsigned i = 0; i != NumPHIValues; ++i)
2404     if (!isa<Constant>(PN->getIncomingValue(i))) {
2405       if (NonConstBB) return 0;  // More than one non-const value.
2406       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
2407       NonConstBB = PN->getIncomingBlock(i);
2408       
2409       // If the incoming non-constant value is in I's block, we have an infinite
2410       // loop.
2411       if (NonConstBB == I.getParent())
2412         return 0;
2413     }
2414   
2415   // If there is exactly one non-constant value, we can insert a copy of the
2416   // operation in that block.  However, if this is a critical edge, we would be
2417   // inserting the computation one some other paths (e.g. inside a loop).  Only
2418   // do this if the pred block is unconditionally branching into the phi block.
2419   if (NonConstBB) {
2420     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2421     if (!BI || !BI->isUnconditional()) return 0;
2422   }
2423
2424   // Okay, we can do the transformation: create the new PHI node.
2425   PHINode *NewPN = PHINode::Create(I.getType(), "");
2426   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2427   InsertNewInstBefore(NewPN, *PN);
2428   NewPN->takeName(PN);
2429
2430   // Next, add all of the operands to the PHI.
2431   if (I.getNumOperands() == 2) {
2432     Constant *C = cast<Constant>(I.getOperand(1));
2433     for (unsigned i = 0; i != NumPHIValues; ++i) {
2434       Value *InV = 0;
2435       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2436         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2437           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2438         else
2439           InV = ConstantExpr::get(I.getOpcode(), InC, C);
2440       } else {
2441         assert(PN->getIncomingBlock(i) == NonConstBB);
2442         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
2443           InV = BinaryOperator::Create(BO->getOpcode(),
2444                                        PN->getIncomingValue(i), C, "phitmp",
2445                                        NonConstBB->getTerminator());
2446         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2447           InV = CmpInst::Create(CI->getOpcode(), 
2448                                 CI->getPredicate(),
2449                                 PN->getIncomingValue(i), C, "phitmp",
2450                                 NonConstBB->getTerminator());
2451         else
2452           assert(0 && "Unknown binop!");
2453         
2454         AddToWorkList(cast<Instruction>(InV));
2455       }
2456       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2457     }
2458   } else { 
2459     CastInst *CI = cast<CastInst>(&I);
2460     const Type *RetTy = CI->getType();
2461     for (unsigned i = 0; i != NumPHIValues; ++i) {
2462       Value *InV;
2463       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2464         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2465       } else {
2466         assert(PN->getIncomingBlock(i) == NonConstBB);
2467         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
2468                                I.getType(), "phitmp", 
2469                                NonConstBB->getTerminator());
2470         AddToWorkList(cast<Instruction>(InV));
2471       }
2472       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2473     }
2474   }
2475   return ReplaceInstUsesWith(I, NewPN);
2476 }
2477
2478
2479 /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
2480 /// value is never equal to -0.0.
2481 ///
2482 /// Note that this function will need to be revisited when we support nondefault
2483 /// rounding modes!
2484 ///
2485 static bool CannotBeNegativeZero(const Value *V) {
2486   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2487     return !CFP->getValueAPF().isNegZero();
2488
2489   if (const Instruction *I = dyn_cast<Instruction>(V)) {
2490     // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2491     if (I->getOpcode() == Instruction::Add &&
2492         isa<ConstantFP>(I->getOperand(1)) && 
2493         cast<ConstantFP>(I->getOperand(1))->isNullValue())
2494       return true;
2495     
2496     // sitofp and uitofp turn into +0.0 for zero.
2497     if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2498       return true;
2499     
2500     if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2501       if (II->getIntrinsicID() == Intrinsic::sqrt)
2502         return CannotBeNegativeZero(II->getOperand(1));
2503     
2504     if (const CallInst *CI = dyn_cast<CallInst>(I))
2505       if (const Function *F = CI->getCalledFunction()) {
2506         if (F->isDeclaration()) {
2507           switch (F->getNameLen()) {
2508           case 3:  // abs(x) != -0.0
2509             if (!strcmp(F->getNameStart(), "abs")) return true;
2510             break;
2511           case 4:  // abs[lf](x) != -0.0
2512             if (!strcmp(F->getNameStart(), "absf")) return true;
2513             if (!strcmp(F->getNameStart(), "absl")) return true;
2514             break;
2515           }
2516         }
2517       }
2518   }
2519   
2520   return false;
2521 }
2522
2523 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2524 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
2525 /// This basically requires proving that the add in the original type would not
2526 /// overflow to change the sign bit or have a carry out.
2527 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2528   // There are different heuristics we can use for this.  Here are some simple
2529   // ones.
2530   
2531   // Add has the property that adding any two 2's complement numbers can only 
2532   // have one carry bit which can change a sign.  As such, if LHS and RHS each
2533   // have at least two sign bits, we know that the addition of the two values will
2534   // sign extend fine.
2535   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2536     return true;
2537   
2538   
2539   // If one of the operands only has one non-zero bit, and if the other operand
2540   // has a known-zero bit in a more significant place than it (not including the
2541   // sign bit) the ripple may go up to and fill the zero, but won't change the
2542   // sign.  For example, (X & ~4) + 1.
2543   
2544   // TODO: Implement.
2545   
2546   return false;
2547 }
2548
2549
2550 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2551   bool Changed = SimplifyCommutative(I);
2552   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2553
2554   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2555     // X + undef -> undef
2556     if (isa<UndefValue>(RHS))
2557       return ReplaceInstUsesWith(I, RHS);
2558
2559     // X + 0 --> X
2560     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2561       if (RHSC->isNullValue())
2562         return ReplaceInstUsesWith(I, LHS);
2563     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2564       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2565                               (I.getType())->getValueAPF()))
2566         return ReplaceInstUsesWith(I, LHS);
2567     }
2568
2569     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2570       // X + (signbit) --> X ^ signbit
2571       const APInt& Val = CI->getValue();
2572       uint32_t BitWidth = Val.getBitWidth();
2573       if (Val == APInt::getSignBit(BitWidth))
2574         return BinaryOperator::CreateXor(LHS, RHS);
2575       
2576       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
2577       // (X & 254)+1 -> (X&254)|1
2578       if (!isa<VectorType>(I.getType())) {
2579         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2580         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2581                                  KnownZero, KnownOne))
2582           return &I;
2583       }
2584     }
2585
2586     if (isa<PHINode>(LHS))
2587       if (Instruction *NV = FoldOpIntoPhi(I))
2588         return NV;
2589     
2590     ConstantInt *XorRHS = 0;
2591     Value *XorLHS = 0;
2592     if (isa<ConstantInt>(RHSC) &&
2593         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2594       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2595       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2596       
2597       uint32_t Size = TySizeBits / 2;
2598       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2599       APInt CFF80Val(-C0080Val);
2600       do {
2601         if (TySizeBits > Size) {
2602           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2603           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2604           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2605               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2606             // This is a sign extend if the top bits are known zero.
2607             if (!MaskedValueIsZero(XorLHS, 
2608                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2609               Size = 0;  // Not a sign ext, but can't be any others either.
2610             break;
2611           }
2612         }
2613         Size >>= 1;
2614         C0080Val = APIntOps::lshr(C0080Val, Size);
2615         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2616       } while (Size >= 1);
2617       
2618       // FIXME: This shouldn't be necessary. When the backends can handle types
2619       // with funny bit widths then this switch statement should be removed. It
2620       // is just here to get the size of the "middle" type back up to something
2621       // that the back ends can handle.
2622       const Type *MiddleType = 0;
2623       switch (Size) {
2624         default: break;
2625         case 32: MiddleType = Type::Int32Ty; break;
2626         case 16: MiddleType = Type::Int16Ty; break;
2627         case  8: MiddleType = Type::Int8Ty; break;
2628       }
2629       if (MiddleType) {
2630         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2631         InsertNewInstBefore(NewTrunc, I);
2632         return new SExtInst(NewTrunc, I.getType(), I.getName());
2633       }
2634     }
2635   }
2636
2637   // X + X --> X << 1
2638   if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2639     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2640
2641     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2642       if (RHSI->getOpcode() == Instruction::Sub)
2643         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2644           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2645     }
2646     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2647       if (LHSI->getOpcode() == Instruction::Sub)
2648         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2649           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2650     }
2651   }
2652
2653   // -A + B  -->  B - A
2654   // -A + -B  -->  -(A + B)
2655   if (Value *LHSV = dyn_castNegVal(LHS)) {
2656     if (LHS->getType()->isIntOrIntVector()) {
2657       if (Value *RHSV = dyn_castNegVal(RHS)) {
2658         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2659         InsertNewInstBefore(NewAdd, I);
2660         return BinaryOperator::CreateNeg(NewAdd);
2661       }
2662     }
2663     
2664     return BinaryOperator::CreateSub(RHS, LHSV);
2665   }
2666
2667   // A + -B  -->  A - B
2668   if (!isa<Constant>(RHS))
2669     if (Value *V = dyn_castNegVal(RHS))
2670       return BinaryOperator::CreateSub(LHS, V);
2671
2672
2673   ConstantInt *C2;
2674   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2675     if (X == RHS)   // X*C + X --> X * (C+1)
2676       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2677
2678     // X*C1 + X*C2 --> X * (C1+C2)
2679     ConstantInt *C1;
2680     if (X == dyn_castFoldableMul(RHS, C1))
2681       return BinaryOperator::CreateMul(X, Add(C1, C2));
2682   }
2683
2684   // X + X*C --> X * (C+1)
2685   if (dyn_castFoldableMul(RHS, C2) == LHS)
2686     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2687
2688   // X + ~X --> -1   since   ~X = -X-1
2689   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2690     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2691   
2692
2693   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2694   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2695     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2696       return R;
2697   
2698   // A+B --> A|B iff A and B have no bits set in common.
2699   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2700     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2701     APInt LHSKnownOne(IT->getBitWidth(), 0);
2702     APInt LHSKnownZero(IT->getBitWidth(), 0);
2703     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2704     if (LHSKnownZero != 0) {
2705       APInt RHSKnownOne(IT->getBitWidth(), 0);
2706       APInt RHSKnownZero(IT->getBitWidth(), 0);
2707       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2708       
2709       // No bits in common -> bitwise or.
2710       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2711         return BinaryOperator::CreateOr(LHS, RHS);
2712     }
2713   }
2714
2715   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2716   if (I.getType()->isIntOrIntVector()) {
2717     Value *W, *X, *Y, *Z;
2718     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2719         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2720       if (W != Y) {
2721         if (W == Z) {
2722           std::swap(Y, Z);
2723         } else if (Y == X) {
2724           std::swap(W, X);
2725         } else if (X == Z) {
2726           std::swap(Y, Z);
2727           std::swap(W, X);
2728         }
2729       }
2730
2731       if (W == Y) {
2732         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2733                                                             LHS->getName()), I);
2734         return BinaryOperator::CreateMul(W, NewAdd);
2735       }
2736     }
2737   }
2738
2739   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2740     Value *X = 0;
2741     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2742       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2743
2744     // (X & FF00) + xx00  -> (X+xx00) & FF00
2745     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2746       Constant *Anded = And(CRHS, C2);
2747       if (Anded == CRHS) {
2748         // See if all bits from the first bit set in the Add RHS up are included
2749         // in the mask.  First, get the rightmost bit.
2750         const APInt& AddRHSV = CRHS->getValue();
2751
2752         // Form a mask of all bits from the lowest bit added through the top.
2753         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2754
2755         // See if the and mask includes all of these bits.
2756         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2757
2758         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2759           // Okay, the xform is safe.  Insert the new add pronto.
2760           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2761                                                             LHS->getName()), I);
2762           return BinaryOperator::CreateAnd(NewAdd, C2);
2763         }
2764       }
2765     }
2766
2767     // Try to fold constant add into select arguments.
2768     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2769       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2770         return R;
2771   }
2772
2773   // add (cast *A to intptrtype) B -> 
2774   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2775   {
2776     CastInst *CI = dyn_cast<CastInst>(LHS);
2777     Value *Other = RHS;
2778     if (!CI) {
2779       CI = dyn_cast<CastInst>(RHS);
2780       Other = LHS;
2781     }
2782     if (CI && CI->getType()->isSized() && 
2783         (CI->getType()->getPrimitiveSizeInBits() == 
2784          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2785         && isa<PointerType>(CI->getOperand(0)->getType())) {
2786       unsigned AS =
2787         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2788       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2789                                       PointerType::get(Type::Int8Ty, AS), I);
2790       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2791       return new PtrToIntInst(I2, CI->getType());
2792     }
2793   }
2794   
2795   // add (select X 0 (sub n A)) A  -->  select X A n
2796   {
2797     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2798     Value *Other = RHS;
2799     if (!SI) {
2800       SI = dyn_cast<SelectInst>(RHS);
2801       Other = LHS;
2802     }
2803     if (SI && SI->hasOneUse()) {
2804       Value *TV = SI->getTrueValue();
2805       Value *FV = SI->getFalseValue();
2806       Value *A, *N;
2807
2808       // Can we fold the add into the argument of the select?
2809       // We check both true and false select arguments for a matching subtract.
2810       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2811           A == Other)  // Fold the add into the true select value.
2812         return SelectInst::Create(SI->getCondition(), N, A);
2813       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2814           A == Other)  // Fold the add into the false select value.
2815         return SelectInst::Create(SI->getCondition(), A, N);
2816     }
2817   }
2818   
2819   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2820   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2821     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2822       return ReplaceInstUsesWith(I, LHS);
2823
2824   // Check for (add (sext x), y), see if we can merge this into an
2825   // integer add followed by a sext.
2826   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2827     // (add (sext x), cst) --> (sext (add x, cst'))
2828     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2829       Constant *CI = 
2830         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2831       if (LHSConv->hasOneUse() &&
2832           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2833           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2834         // Insert the new, smaller add.
2835         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2836                                                         CI, "addconv");
2837         InsertNewInstBefore(NewAdd, I);
2838         return new SExtInst(NewAdd, I.getType());
2839       }
2840     }
2841     
2842     // (add (sext x), (sext y)) --> (sext (add int x, y))
2843     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2844       // Only do this if x/y have the same type, if at last one of them has a
2845       // single use (so we don't increase the number of sexts), and if the
2846       // integer add will not overflow.
2847       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2848           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2849           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2850                                    RHSConv->getOperand(0))) {
2851         // Insert the new integer add.
2852         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2853                                                         RHSConv->getOperand(0),
2854                                                         "addconv");
2855         InsertNewInstBefore(NewAdd, I);
2856         return new SExtInst(NewAdd, I.getType());
2857       }
2858     }
2859   }
2860   
2861   // Check for (add double (sitofp x), y), see if we can merge this into an
2862   // integer add followed by a promotion.
2863   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2864     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2865     // ... if the constant fits in the integer value.  This is useful for things
2866     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2867     // requires a constant pool load, and generally allows the add to be better
2868     // instcombined.
2869     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2870       Constant *CI = 
2871       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2872       if (LHSConv->hasOneUse() &&
2873           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2874           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2875         // Insert the new integer add.
2876         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2877                                                         CI, "addconv");
2878         InsertNewInstBefore(NewAdd, I);
2879         return new SIToFPInst(NewAdd, I.getType());
2880       }
2881     }
2882     
2883     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2884     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2885       // Only do this if x/y have the same type, if at last one of them has a
2886       // single use (so we don't increase the number of int->fp conversions),
2887       // and if the integer add will not overflow.
2888       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2889           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2890           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2891                                    RHSConv->getOperand(0))) {
2892         // Insert the new integer add.
2893         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2894                                                         RHSConv->getOperand(0),
2895                                                         "addconv");
2896         InsertNewInstBefore(NewAdd, I);
2897         return new SIToFPInst(NewAdd, I.getType());
2898       }
2899     }
2900   }
2901   
2902   return Changed ? &I : 0;
2903 }
2904
2905 // isSignBit - Return true if the value represented by the constant only has the
2906 // highest order bit set.
2907 static bool isSignBit(ConstantInt *CI) {
2908   uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2909   return CI->getValue() == APInt::getSignBit(NumBits);
2910 }
2911
2912 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2913   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2914
2915   if (Op0 == Op1)         // sub X, X  -> 0
2916     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2917
2918   // If this is a 'B = x-(-A)', change to B = x+A...
2919   if (Value *V = dyn_castNegVal(Op1))
2920     return BinaryOperator::CreateAdd(Op0, V);
2921
2922   if (isa<UndefValue>(Op0))
2923     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2924   if (isa<UndefValue>(Op1))
2925     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2926
2927   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2928     // Replace (-1 - A) with (~A)...
2929     if (C->isAllOnesValue())
2930       return BinaryOperator::CreateNot(Op1);
2931
2932     // C - ~X == X + (1+C)
2933     Value *X = 0;
2934     if (match(Op1, m_Not(m_Value(X))))
2935       return BinaryOperator::CreateAdd(X, AddOne(C));
2936
2937     // -(X >>u 31) -> (X >>s 31)
2938     // -(X >>s 31) -> (X >>u 31)
2939     if (C->isZero()) {
2940       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2941         if (SI->getOpcode() == Instruction::LShr) {
2942           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2943             // Check to see if we are shifting out everything but the sign bit.
2944             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2945                 SI->getType()->getPrimitiveSizeInBits()-1) {
2946               // Ok, the transformation is safe.  Insert AShr.
2947               return BinaryOperator::Create(Instruction::AShr, 
2948                                           SI->getOperand(0), CU, SI->getName());
2949             }
2950           }
2951         }
2952         else if (SI->getOpcode() == Instruction::AShr) {
2953           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2954             // Check to see if we are shifting out everything but the sign bit.
2955             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2956                 SI->getType()->getPrimitiveSizeInBits()-1) {
2957               // Ok, the transformation is safe.  Insert LShr. 
2958               return BinaryOperator::CreateLShr(
2959                                           SI->getOperand(0), CU, SI->getName());
2960             }
2961           }
2962         }
2963       }
2964     }
2965
2966     // Try to fold constant sub into select arguments.
2967     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2968       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2969         return R;
2970
2971     if (isa<PHINode>(Op0))
2972       if (Instruction *NV = FoldOpIntoPhi(I))
2973         return NV;
2974   }
2975
2976   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2977     if (Op1I->getOpcode() == Instruction::Add &&
2978         !Op0->getType()->isFPOrFPVector()) {
2979       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2980         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2981       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2982         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2983       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2984         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2985           // C1-(X+C2) --> (C1-C2)-X
2986           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2987                                            Op1I->getOperand(0));
2988       }
2989     }
2990
2991     if (Op1I->hasOneUse()) {
2992       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2993       // is not used by anyone else...
2994       //
2995       if (Op1I->getOpcode() == Instruction::Sub &&
2996           !Op1I->getType()->isFPOrFPVector()) {
2997         // Swap the two operands of the subexpr...
2998         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2999         Op1I->setOperand(0, IIOp1);
3000         Op1I->setOperand(1, IIOp0);
3001
3002         // Create the new top level add instruction...
3003         return BinaryOperator::CreateAdd(Op0, Op1);
3004       }
3005
3006       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3007       //
3008       if (Op1I->getOpcode() == Instruction::And &&
3009           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3010         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3011
3012         Value *NewNot =
3013           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3014         return BinaryOperator::CreateAnd(Op0, NewNot);
3015       }
3016
3017       // 0 - (X sdiv C)  -> (X sdiv -C)
3018       if (Op1I->getOpcode() == Instruction::SDiv)
3019         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3020           if (CSI->isZero())
3021             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
3022               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
3023                                                ConstantExpr::getNeg(DivRHS));
3024
3025       // X - X*C --> X * (1-C)
3026       ConstantInt *C2 = 0;
3027       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
3028         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
3029         return BinaryOperator::CreateMul(Op0, CP1);
3030       }
3031
3032       // X - ((X / Y) * Y) --> X % Y
3033       if (Op1I->getOpcode() == Instruction::Mul)
3034         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3035           if (Op0 == I->getOperand(0) &&
3036               Op1I->getOperand(1) == I->getOperand(1)) {
3037             if (I->getOpcode() == Instruction::SDiv)
3038               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
3039             if (I->getOpcode() == Instruction::UDiv)
3040               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
3041           }
3042     }
3043   }
3044
3045   if (!Op0->getType()->isFPOrFPVector())
3046     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3047       if (Op0I->getOpcode() == Instruction::Add) {
3048         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
3049           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3050         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
3051           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3052       } else if (Op0I->getOpcode() == Instruction::Sub) {
3053         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
3054           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
3055       }
3056     }
3057
3058   ConstantInt *C1;
3059   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
3060     if (X == Op1)  // X*C - X --> X * (C-1)
3061       return BinaryOperator::CreateMul(Op1, SubOne(C1));
3062
3063     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
3064     if (X == dyn_castFoldableMul(Op1, C2))
3065       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
3066   }
3067   return 0;
3068 }
3069
3070 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3071 /// comparison only checks the sign bit.  If it only checks the sign bit, set
3072 /// TrueIfSigned if the result of the comparison is true when the input value is
3073 /// signed.
3074 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3075                            bool &TrueIfSigned) {
3076   switch (pred) {
3077   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
3078     TrueIfSigned = true;
3079     return RHS->isZero();
3080   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
3081     TrueIfSigned = true;
3082     return RHS->isAllOnesValue();
3083   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
3084     TrueIfSigned = false;
3085     return RHS->isAllOnesValue();
3086   case ICmpInst::ICMP_UGT:
3087     // True if LHS u> RHS and RHS == high-bit-mask - 1
3088     TrueIfSigned = true;
3089     return RHS->getValue() ==
3090       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3091   case ICmpInst::ICMP_UGE: 
3092     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3093     TrueIfSigned = true;
3094     return RHS->getValue() == 
3095       APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
3096   default:
3097     return false;
3098   }
3099 }
3100
3101 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3102   bool Changed = SimplifyCommutative(I);
3103   Value *Op0 = I.getOperand(0);
3104
3105   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
3106     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3107
3108   // Simplify mul instructions with a constant RHS...
3109   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3110     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3111
3112       // ((X << C1)*C2) == (X * (C2 << C1))
3113       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3114         if (SI->getOpcode() == Instruction::Shl)
3115           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3116             return BinaryOperator::CreateMul(SI->getOperand(0),
3117                                              ConstantExpr::getShl(CI, ShOp));
3118
3119       if (CI->isZero())
3120         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
3121       if (CI->equalsInt(1))                  // X * 1  == X
3122         return ReplaceInstUsesWith(I, Op0);
3123       if (CI->isAllOnesValue())              // X * -1 == 0 - X
3124         return BinaryOperator::CreateNeg(Op0, I.getName());
3125
3126       const APInt& Val = cast<ConstantInt>(CI)->getValue();
3127       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
3128         return BinaryOperator::CreateShl(Op0,
3129                  ConstantInt::get(Op0->getType(), Val.logBase2()));
3130       }
3131     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
3132       if (Op1F->isNullValue())
3133         return ReplaceInstUsesWith(I, Op1);
3134
3135       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
3136       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3137       // We need a better interface for long double here.
3138       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3139         if (Op1F->isExactlyValue(1.0))
3140           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
3141     }
3142     
3143     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3144       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3145           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
3146         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3147         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
3148                                                      Op1, "tmp");
3149         InsertNewInstBefore(Add, I);
3150         Value *C1C2 = ConstantExpr::getMul(Op1, 
3151                                            cast<Constant>(Op0I->getOperand(1)));
3152         return BinaryOperator::CreateAdd(Add, C1C2);
3153         
3154       }
3155
3156     // Try to fold constant mul into select arguments.
3157     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3158       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3159         return R;
3160
3161     if (isa<PHINode>(Op0))
3162       if (Instruction *NV = FoldOpIntoPhi(I))
3163         return NV;
3164   }
3165
3166   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
3167     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3168       return BinaryOperator::CreateMul(Op0v, Op1v);
3169
3170   // If one of the operands of the multiply is a cast from a boolean value, then
3171   // we know the bool is either zero or one, so this is a 'masking' multiply.
3172   // See if we can simplify things based on how the boolean was originally
3173   // formed.
3174   CastInst *BoolCast = 0;
3175   if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3176     if (CI->getOperand(0)->getType() == Type::Int1Ty)
3177       BoolCast = CI;
3178   if (!BoolCast)
3179     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3180       if (CI->getOperand(0)->getType() == Type::Int1Ty)
3181         BoolCast = CI;
3182   if (BoolCast) {
3183     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3184       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3185       const Type *SCOpTy = SCIOp0->getType();
3186       bool TIS = false;
3187       
3188       // If the icmp is true iff the sign bit of X is set, then convert this
3189       // multiply into a shift/and combination.
3190       if (isa<ConstantInt>(SCIOp1) &&
3191           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3192           TIS) {
3193         // Shift the X value right to turn it into "all signbits".
3194         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3195                                           SCOpTy->getPrimitiveSizeInBits()-1);
3196         Value *V =
3197           InsertNewInstBefore(
3198             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
3199                                             BoolCast->getOperand(0)->getName()+
3200                                             ".mask"), I);
3201
3202         // If the multiply type is not the same as the source type, sign extend
3203         // or truncate to the multiply type.
3204         if (I.getType() != V->getType()) {
3205           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3206           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
3207           Instruction::CastOps opcode = 
3208             (SrcBits == DstBits ? Instruction::BitCast : 
3209              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3210           V = InsertCastBefore(opcode, V, I.getType(), I);
3211         }
3212
3213         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3214         return BinaryOperator::CreateAnd(V, OtherOp);
3215       }
3216     }
3217   }
3218
3219   return Changed ? &I : 0;
3220 }
3221
3222 /// This function implements the transforms on div instructions that work
3223 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3224 /// used by the visitors to those instructions.
3225 /// @brief Transforms common to all three div instructions
3226 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3227   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3228
3229   // undef / X -> 0        for integer.
3230   // undef / X -> undef    for FP (the undef could be a snan).
3231   if (isa<UndefValue>(Op0)) {
3232     if (Op0->getType()->isFPOrFPVector())
3233       return ReplaceInstUsesWith(I, Op0);
3234     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3235   }
3236
3237   // X / undef -> undef
3238   if (isa<UndefValue>(Op1))
3239     return ReplaceInstUsesWith(I, Op1);
3240
3241   // Handle cases involving: [su]div X, (select Cond, Y, Z)
3242   // This does not apply for fdiv.
3243   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3244     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
3245     // the same basic block, then we replace the select with Y, and the
3246     // condition of the select with false (if the cond value is in the same BB).
3247     // If the select has uses other than the div, this allows them to be
3248     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3249     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
3250       if (ST->isNullValue()) {
3251         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3252         if (CondI && CondI->getParent() == I.getParent())
3253           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3254         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3255           I.setOperand(1, SI->getOperand(2));
3256         else
3257           UpdateValueUsesWith(SI, SI->getOperand(2));
3258         return &I;
3259       }
3260
3261     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3262     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
3263       if (ST->isNullValue()) {
3264         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3265         if (CondI && CondI->getParent() == I.getParent())
3266           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3267         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3268           I.setOperand(1, SI->getOperand(1));
3269         else
3270           UpdateValueUsesWith(SI, SI->getOperand(1));
3271         return &I;
3272       }
3273   }
3274
3275   return 0;
3276 }
3277
3278 /// This function implements the transforms common to both integer division
3279 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3280 /// division instructions.
3281 /// @brief Common integer divide transforms
3282 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3283   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3284
3285   // (sdiv X, X) --> 1     (udiv X, X) --> 1
3286   if (Op0 == Op1) {
3287     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3288       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
3289       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3290       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3291     }
3292
3293     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
3294     return ReplaceInstUsesWith(I, CI);
3295   }
3296   
3297   if (Instruction *Common = commonDivTransforms(I))
3298     return Common;
3299
3300   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3301     // div X, 1 == X
3302     if (RHS->equalsInt(1))
3303       return ReplaceInstUsesWith(I, Op0);
3304
3305     // (X / C1) / C2  -> X / (C1*C2)
3306     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3307       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3308         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3309           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3310             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3311           else 
3312             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3313                                           Multiply(RHS, LHSRHS));
3314         }
3315
3316     if (!RHS->isZero()) { // avoid X udiv 0
3317       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3318         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3319           return R;
3320       if (isa<PHINode>(Op0))
3321         if (Instruction *NV = FoldOpIntoPhi(I))
3322           return NV;
3323     }
3324   }
3325
3326   // 0 / X == 0, we don't need to preserve faults!
3327   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3328     if (LHS->equalsInt(0))
3329       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3330
3331   return 0;
3332 }
3333
3334 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3335   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3336
3337   // Handle the integer div common cases
3338   if (Instruction *Common = commonIDivTransforms(I))
3339     return Common;
3340
3341   // X udiv C^2 -> X >> C
3342   // Check to see if this is an unsigned division with an exact power of 2,
3343   // if so, convert to a right shift.
3344   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3345     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
3346       return BinaryOperator::CreateLShr(Op0, 
3347                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3348   }
3349
3350   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
3351   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3352     if (RHSI->getOpcode() == Instruction::Shl &&
3353         isa<ConstantInt>(RHSI->getOperand(0))) {
3354       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3355       if (C1.isPowerOf2()) {
3356         Value *N = RHSI->getOperand(1);
3357         const Type *NTy = N->getType();
3358         if (uint32_t C2 = C1.logBase2()) {
3359           Constant *C2V = ConstantInt::get(NTy, C2);
3360           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3361         }
3362         return BinaryOperator::CreateLShr(Op0, N);
3363       }
3364     }
3365   }
3366   
3367   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3368   // where C1&C2 are powers of two.
3369   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
3370     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3371       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
3372         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3373         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3374           // Compute the shift amounts
3375           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3376           // Construct the "on true" case of the select
3377           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3378           Instruction *TSI = BinaryOperator::CreateLShr(
3379                                                  Op0, TC, SI->getName()+".t");
3380           TSI = InsertNewInstBefore(TSI, I);
3381   
3382           // Construct the "on false" case of the select
3383           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
3384           Instruction *FSI = BinaryOperator::CreateLShr(
3385                                                  Op0, FC, SI->getName()+".f");
3386           FSI = InsertNewInstBefore(FSI, I);
3387
3388           // construct the select instruction and return it.
3389           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3390         }
3391       }
3392   return 0;
3393 }
3394
3395 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3396   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3397
3398   // Handle the integer div common cases
3399   if (Instruction *Common = commonIDivTransforms(I))
3400     return Common;
3401
3402   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3403     // sdiv X, -1 == -X
3404     if (RHS->isAllOnesValue())
3405       return BinaryOperator::CreateNeg(Op0);
3406
3407     // -X/C -> X/-C
3408     if (Value *LHSNeg = dyn_castNegVal(Op0))
3409       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3410   }
3411
3412   // If the sign bits of both operands are zero (i.e. we can prove they are
3413   // unsigned inputs), turn this into a udiv.
3414   if (I.getType()->isInteger()) {
3415     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3416     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3417       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3418       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3419     }
3420   }      
3421   
3422   return 0;
3423 }
3424
3425 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3426   return commonDivTransforms(I);
3427 }
3428
3429 /// This function implements the transforms on rem instructions that work
3430 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
3431 /// is used by the visitors to those instructions.
3432 /// @brief Transforms common to all three rem instructions
3433 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3434   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3435
3436   // 0 % X == 0 for integer, we don't need to preserve faults!
3437   if (Constant *LHS = dyn_cast<Constant>(Op0))
3438     if (LHS->isNullValue())
3439       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3440
3441   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
3442     if (I.getType()->isFPOrFPVector())
3443       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
3444     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3445   }
3446   if (isa<UndefValue>(Op1))
3447     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
3448
3449   // Handle cases involving: rem X, (select Cond, Y, Z)
3450   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3451     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
3452     // the same basic block, then we replace the select with Y, and the
3453     // condition of the select with false (if the cond value is in the same
3454     // BB).  If the select has uses other than the div, this allows them to be
3455     // simplified also.
3456     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3457       if (ST->isNullValue()) {
3458         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3459         if (CondI && CondI->getParent() == I.getParent())
3460           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3461         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3462           I.setOperand(1, SI->getOperand(2));
3463         else
3464           UpdateValueUsesWith(SI, SI->getOperand(2));
3465         return &I;
3466       }
3467     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3468     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3469       if (ST->isNullValue()) {
3470         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3471         if (CondI && CondI->getParent() == I.getParent())
3472           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3473         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3474           I.setOperand(1, SI->getOperand(1));
3475         else
3476           UpdateValueUsesWith(SI, SI->getOperand(1));
3477         return &I;
3478       }
3479   }
3480
3481   return 0;
3482 }
3483
3484 /// This function implements the transforms common to both integer remainder
3485 /// instructions (urem and srem). It is called by the visitors to those integer
3486 /// remainder instructions.
3487 /// @brief Common integer remainder transforms
3488 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3489   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3490
3491   if (Instruction *common = commonRemTransforms(I))
3492     return common;
3493
3494   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3495     // X % 0 == undef, we don't need to preserve faults!
3496     if (RHS->equalsInt(0))
3497       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3498     
3499     if (RHS->equalsInt(1))  // X % 1 == 0
3500       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3501
3502     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3503       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3504         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3505           return R;
3506       } else if (isa<PHINode>(Op0I)) {
3507         if (Instruction *NV = FoldOpIntoPhi(I))
3508           return NV;
3509       }
3510
3511       // See if we can fold away this rem instruction.
3512       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3513       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3514       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3515                                KnownZero, KnownOne))
3516         return &I;
3517     }
3518   }
3519
3520   return 0;
3521 }
3522
3523 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3524   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3525
3526   if (Instruction *common = commonIRemTransforms(I))
3527     return common;
3528   
3529   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3530     // X urem C^2 -> X and C
3531     // Check to see if this is an unsigned remainder with an exact power of 2,
3532     // if so, convert to a bitwise and.
3533     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3534       if (C->getValue().isPowerOf2())
3535         return BinaryOperator::CreateAnd(Op0, SubOne(C));
3536   }
3537
3538   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3539     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
3540     if (RHSI->getOpcode() == Instruction::Shl &&
3541         isa<ConstantInt>(RHSI->getOperand(0))) {
3542       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3543         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3544         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3545                                                                    "tmp"), I);
3546         return BinaryOperator::CreateAnd(Op0, Add);
3547       }
3548     }
3549   }
3550
3551   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3552   // where C1&C2 are powers of two.
3553   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3554     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3555       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3556         // STO == 0 and SFO == 0 handled above.
3557         if ((STO->getValue().isPowerOf2()) && 
3558             (SFO->getValue().isPowerOf2())) {
3559           Value *TrueAnd = InsertNewInstBefore(
3560             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3561           Value *FalseAnd = InsertNewInstBefore(
3562             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3563           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3564         }
3565       }
3566   }
3567   
3568   return 0;
3569 }
3570
3571 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3572   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3573
3574   // Handle the integer rem common cases
3575   if (Instruction *common = commonIRemTransforms(I))
3576     return common;
3577   
3578   if (Value *RHSNeg = dyn_castNegVal(Op1))
3579     if (!isa<ConstantInt>(RHSNeg) || 
3580         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3581       // X % -Y -> X % Y
3582       AddUsesToWorkList(I);
3583       I.setOperand(1, RHSNeg);
3584       return &I;
3585     }
3586  
3587   // If the sign bits of both operands are zero (i.e. we can prove they are
3588   // unsigned inputs), turn this into a urem.
3589   if (I.getType()->isInteger()) {
3590     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3591     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3592       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3593       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3594     }
3595   }
3596
3597   return 0;
3598 }
3599
3600 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3601   return commonRemTransforms(I);
3602 }
3603
3604 // isMaxValueMinusOne - return true if this is Max-1
3605 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3606   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3607   if (!isSigned)
3608     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3609   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3610 }
3611
3612 // isMinValuePlusOne - return true if this is Min+1
3613 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3614   if (!isSigned)
3615     return C->getValue() == 1; // unsigned
3616     
3617   // Calculate 1111111111000000000000
3618   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3619   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3620 }
3621
3622 // isOneBitSet - Return true if there is exactly one bit set in the specified
3623 // constant.
3624 static bool isOneBitSet(const ConstantInt *CI) {
3625   return CI->getValue().isPowerOf2();
3626 }
3627
3628 // isHighOnes - Return true if the constant is of the form 1+0+.
3629 // This is the same as lowones(~X).
3630 static bool isHighOnes(const ConstantInt *CI) {
3631   return (~CI->getValue() + 1).isPowerOf2();
3632 }
3633
3634 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3635 /// are carefully arranged to allow folding of expressions such as:
3636 ///
3637 ///      (A < B) | (A > B) --> (A != B)
3638 ///
3639 /// Note that this is only valid if the first and second predicates have the
3640 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3641 ///
3642 /// Three bits are used to represent the condition, as follows:
3643 ///   0  A > B
3644 ///   1  A == B
3645 ///   2  A < B
3646 ///
3647 /// <=>  Value  Definition
3648 /// 000     0   Always false
3649 /// 001     1   A >  B
3650 /// 010     2   A == B
3651 /// 011     3   A >= B
3652 /// 100     4   A <  B
3653 /// 101     5   A != B
3654 /// 110     6   A <= B
3655 /// 111     7   Always true
3656 ///  
3657 static unsigned getICmpCode(const ICmpInst *ICI) {
3658   switch (ICI->getPredicate()) {
3659     // False -> 0
3660   case ICmpInst::ICMP_UGT: return 1;  // 001
3661   case ICmpInst::ICMP_SGT: return 1;  // 001
3662   case ICmpInst::ICMP_EQ:  return 2;  // 010
3663   case ICmpInst::ICMP_UGE: return 3;  // 011
3664   case ICmpInst::ICMP_SGE: return 3;  // 011
3665   case ICmpInst::ICMP_ULT: return 4;  // 100
3666   case ICmpInst::ICMP_SLT: return 4;  // 100
3667   case ICmpInst::ICMP_NE:  return 5;  // 101
3668   case ICmpInst::ICMP_ULE: return 6;  // 110
3669   case ICmpInst::ICMP_SLE: return 6;  // 110
3670     // True -> 7
3671   default:
3672     assert(0 && "Invalid ICmp predicate!");
3673     return 0;
3674   }
3675 }
3676
3677 /// getICmpValue - This is the complement of getICmpCode, which turns an
3678 /// opcode and two operands into either a constant true or false, or a brand 
3679 /// new ICmp instruction. The sign is passed in to determine which kind
3680 /// of predicate to use in new icmp instructions.
3681 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3682   switch (code) {
3683   default: assert(0 && "Illegal ICmp code!");
3684   case  0: return ConstantInt::getFalse();
3685   case  1: 
3686     if (sign)
3687       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3688     else
3689       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3690   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3691   case  3: 
3692     if (sign)
3693       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3694     else
3695       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3696   case  4: 
3697     if (sign)
3698       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3699     else
3700       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3701   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3702   case  6: 
3703     if (sign)
3704       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3705     else
3706       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3707   case  7: return ConstantInt::getTrue();
3708   }
3709 }
3710
3711 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3712   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3713     (ICmpInst::isSignedPredicate(p1) && 
3714      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3715     (ICmpInst::isSignedPredicate(p2) && 
3716      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3717 }
3718
3719 namespace { 
3720 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3721 struct FoldICmpLogical {
3722   InstCombiner &IC;
3723   Value *LHS, *RHS;
3724   ICmpInst::Predicate pred;
3725   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3726     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3727       pred(ICI->getPredicate()) {}
3728   bool shouldApply(Value *V) const {
3729     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3730       if (PredicatesFoldable(pred, ICI->getPredicate()))
3731         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3732                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3733     return false;
3734   }
3735   Instruction *apply(Instruction &Log) const {
3736     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3737     if (ICI->getOperand(0) != LHS) {
3738       assert(ICI->getOperand(1) == LHS);
3739       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3740     }
3741
3742     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3743     unsigned LHSCode = getICmpCode(ICI);
3744     unsigned RHSCode = getICmpCode(RHSICI);
3745     unsigned Code;
3746     switch (Log.getOpcode()) {
3747     case Instruction::And: Code = LHSCode & RHSCode; break;
3748     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3749     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3750     default: assert(0 && "Illegal logical opcode!"); return 0;
3751     }
3752
3753     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3754                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3755       
3756     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3757     if (Instruction *I = dyn_cast<Instruction>(RV))
3758       return I;
3759     // Otherwise, it's a constant boolean value...
3760     return IC.ReplaceInstUsesWith(Log, RV);
3761   }
3762 };
3763 } // end anonymous namespace
3764
3765 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3766 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3767 // guaranteed to be a binary operator.
3768 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3769                                     ConstantInt *OpRHS,
3770                                     ConstantInt *AndRHS,
3771                                     BinaryOperator &TheAnd) {
3772   Value *X = Op->getOperand(0);
3773   Constant *Together = 0;
3774   if (!Op->isShift())
3775     Together = And(AndRHS, OpRHS);
3776
3777   switch (Op->getOpcode()) {
3778   case Instruction::Xor:
3779     if (Op->hasOneUse()) {
3780       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3781       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3782       InsertNewInstBefore(And, TheAnd);
3783       And->takeName(Op);
3784       return BinaryOperator::CreateXor(And, Together);
3785     }
3786     break;
3787   case Instruction::Or:
3788     if (Together == AndRHS) // (X | C) & C --> C
3789       return ReplaceInstUsesWith(TheAnd, AndRHS);
3790
3791     if (Op->hasOneUse() && Together != OpRHS) {
3792       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3793       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3794       InsertNewInstBefore(Or, TheAnd);
3795       Or->takeName(Op);
3796       return BinaryOperator::CreateAnd(Or, AndRHS);
3797     }
3798     break;
3799   case Instruction::Add:
3800     if (Op->hasOneUse()) {
3801       // Adding a one to a single bit bit-field should be turned into an XOR
3802       // of the bit.  First thing to check is to see if this AND is with a
3803       // single bit constant.
3804       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3805
3806       // If there is only one bit set...
3807       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3808         // Ok, at this point, we know that we are masking the result of the
3809         // ADD down to exactly one bit.  If the constant we are adding has
3810         // no bits set below this bit, then we can eliminate the ADD.
3811         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3812
3813         // Check to see if any bits below the one bit set in AndRHSV are set.
3814         if ((AddRHS & (AndRHSV-1)) == 0) {
3815           // If not, the only thing that can effect the output of the AND is
3816           // the bit specified by AndRHSV.  If that bit is set, the effect of
3817           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3818           // no effect.
3819           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3820             TheAnd.setOperand(0, X);
3821             return &TheAnd;
3822           } else {
3823             // Pull the XOR out of the AND.
3824             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3825             InsertNewInstBefore(NewAnd, TheAnd);
3826             NewAnd->takeName(Op);
3827             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3828           }
3829         }
3830       }
3831     }
3832     break;
3833
3834   case Instruction::Shl: {
3835     // We know that the AND will not produce any of the bits shifted in, so if
3836     // the anded constant includes them, clear them now!
3837     //
3838     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3839     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3840     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3841     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3842
3843     if (CI->getValue() == ShlMask) { 
3844     // Masking out bits that the shift already masks
3845       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3846     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3847       TheAnd.setOperand(1, CI);
3848       return &TheAnd;
3849     }
3850     break;
3851   }
3852   case Instruction::LShr:
3853   {
3854     // We know that the AND will not produce any of the bits shifted in, so if
3855     // the anded constant includes them, clear them now!  This only applies to
3856     // unsigned shifts, because a signed shr may bring in set bits!
3857     //
3858     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3859     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3860     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3861     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3862
3863     if (CI->getValue() == ShrMask) {   
3864     // Masking out bits that the shift already masks.
3865       return ReplaceInstUsesWith(TheAnd, Op);
3866     } else if (CI != AndRHS) {
3867       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3868       return &TheAnd;
3869     }
3870     break;
3871   }
3872   case Instruction::AShr:
3873     // Signed shr.
3874     // See if this is shifting in some sign extension, then masking it out
3875     // with an and.
3876     if (Op->hasOneUse()) {
3877       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3878       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3879       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3880       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3881       if (C == AndRHS) {          // Masking out bits shifted in.
3882         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3883         // Make the argument unsigned.
3884         Value *ShVal = Op->getOperand(0);
3885         ShVal = InsertNewInstBefore(
3886             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3887                                    Op->getName()), TheAnd);
3888         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3889       }
3890     }
3891     break;
3892   }
3893   return 0;
3894 }
3895
3896
3897 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3898 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3899 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3900 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3901 /// insert new instructions.
3902 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3903                                            bool isSigned, bool Inside, 
3904                                            Instruction &IB) {
3905   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3906             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3907          "Lo is not <= Hi in range emission code!");
3908     
3909   if (Inside) {
3910     if (Lo == Hi)  // Trivially false.
3911       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3912
3913     // V >= Min && V < Hi --> V < Hi
3914     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3915       ICmpInst::Predicate pred = (isSigned ? 
3916         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3917       return new ICmpInst(pred, V, Hi);
3918     }
3919
3920     // Emit V-Lo <u Hi-Lo
3921     Constant *NegLo = ConstantExpr::getNeg(Lo);
3922     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3923     InsertNewInstBefore(Add, IB);
3924     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3925     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3926   }
3927
3928   if (Lo == Hi)  // Trivially true.
3929     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3930
3931   // V < Min || V >= Hi -> V > Hi-1
3932   Hi = SubOne(cast<ConstantInt>(Hi));
3933   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3934     ICmpInst::Predicate pred = (isSigned ? 
3935         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3936     return new ICmpInst(pred, V, Hi);
3937   }
3938
3939   // Emit V-Lo >u Hi-1-Lo
3940   // Note that Hi has already had one subtracted from it, above.
3941   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3942   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3943   InsertNewInstBefore(Add, IB);
3944   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3945   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3946 }
3947
3948 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3949 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3950 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3951 // not, since all 1s are not contiguous.
3952 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3953   const APInt& V = Val->getValue();
3954   uint32_t BitWidth = Val->getType()->getBitWidth();
3955   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3956
3957   // look for the first zero bit after the run of ones
3958   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3959   // look for the first non-zero bit
3960   ME = V.getActiveBits(); 
3961   return true;
3962 }
3963
3964 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3965 /// where isSub determines whether the operator is a sub.  If we can fold one of
3966 /// the following xforms:
3967 /// 
3968 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3969 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3970 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3971 ///
3972 /// return (A +/- B).
3973 ///
3974 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3975                                         ConstantInt *Mask, bool isSub,
3976                                         Instruction &I) {
3977   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3978   if (!LHSI || LHSI->getNumOperands() != 2 ||
3979       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3980
3981   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3982
3983   switch (LHSI->getOpcode()) {
3984   default: return 0;
3985   case Instruction::And:
3986     if (And(N, Mask) == Mask) {
3987       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3988       if ((Mask->getValue().countLeadingZeros() + 
3989            Mask->getValue().countPopulation()) == 
3990           Mask->getValue().getBitWidth())
3991         break;
3992
3993       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3994       // part, we don't need any explicit masks to take them out of A.  If that
3995       // is all N is, ignore it.
3996       uint32_t MB = 0, ME = 0;
3997       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3998         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3999         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4000         if (MaskedValueIsZero(RHS, Mask))
4001           break;
4002       }
4003     }
4004     return 0;
4005   case Instruction::Or:
4006   case Instruction::Xor:
4007     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4008     if ((Mask->getValue().countLeadingZeros() + 
4009          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4010         && And(N, Mask)->isZero())
4011       break;
4012     return 0;
4013   }
4014   
4015   Instruction *New;
4016   if (isSub)
4017     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
4018   else
4019     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
4020   return InsertNewInstBefore(New, I);
4021 }
4022
4023 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4024   bool Changed = SimplifyCommutative(I);
4025   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4026
4027   if (isa<UndefValue>(Op1))                         // X & undef -> 0
4028     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4029
4030   // and X, X = X
4031   if (Op0 == Op1)
4032     return ReplaceInstUsesWith(I, Op1);
4033
4034   // See if we can simplify any instructions used by the instruction whose sole 
4035   // purpose is to compute bits we don't care about.
4036   if (!isa<VectorType>(I.getType())) {
4037     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4038     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4039     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4040                              KnownZero, KnownOne))
4041       return &I;
4042   } else {
4043     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4044       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
4045         return ReplaceInstUsesWith(I, I.getOperand(0));
4046     } else if (isa<ConstantAggregateZero>(Op1)) {
4047       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
4048     }
4049   }
4050   
4051   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4052     const APInt& AndRHSMask = AndRHS->getValue();
4053     APInt NotAndRHS(~AndRHSMask);
4054
4055     // Optimize a variety of ((val OP C1) & C2) combinations...
4056     if (isa<BinaryOperator>(Op0)) {
4057       Instruction *Op0I = cast<Instruction>(Op0);
4058       Value *Op0LHS = Op0I->getOperand(0);
4059       Value *Op0RHS = Op0I->getOperand(1);
4060       switch (Op0I->getOpcode()) {
4061       case Instruction::Xor:
4062       case Instruction::Or:
4063         // If the mask is only needed on one incoming arm, push it up.
4064         if (Op0I->hasOneUse()) {
4065           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066             // Not masking anything out for the LHS, move to RHS.
4067             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4068                                                    Op0RHS->getName()+".masked");
4069             InsertNewInstBefore(NewRHS, I);
4070             return BinaryOperator::Create(
4071                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4072           }
4073           if (!isa<Constant>(Op0RHS) &&
4074               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4075             // Not masking anything out for the RHS, move to LHS.
4076             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4077                                                    Op0LHS->getName()+".masked");
4078             InsertNewInstBefore(NewLHS, I);
4079             return BinaryOperator::Create(
4080                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4081           }
4082         }
4083
4084         break;
4085       case Instruction::Add:
4086         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4087         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4089         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4090           return BinaryOperator::CreateAnd(V, AndRHS);
4091         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4092           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
4093         break;
4094
4095       case Instruction::Sub:
4096         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4097         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4099         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4100           return BinaryOperator::CreateAnd(V, AndRHS);
4101         break;
4102       }
4103
4104       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4105         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4106           return Res;
4107     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4108       // If this is an integer truncation or change from signed-to-unsigned, and
4109       // if the source is an and/or with immediate, transform it.  This
4110       // frequently occurs for bitfield accesses.
4111       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4112         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4113             CastOp->getNumOperands() == 2)
4114           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4115             if (CastOp->getOpcode() == Instruction::And) {
4116               // Change: and (cast (and X, C1) to T), C2
4117               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
4118               // This will fold the two constants together, which may allow 
4119               // other simplifications.
4120               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4121                 CastOp->getOperand(0), I.getType(), 
4122                 CastOp->getName()+".shrunk");
4123               NewCast = InsertNewInstBefore(NewCast, I);
4124               // trunc_or_bitcast(C1)&C2
4125               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4126               C3 = ConstantExpr::getAnd(C3, AndRHS);
4127               return BinaryOperator::CreateAnd(NewCast, C3);
4128             } else if (CastOp->getOpcode() == Instruction::Or) {
4129               // Change: and (cast (or X, C1) to T), C2
4130               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4131               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4132               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
4133                 return ReplaceInstUsesWith(I, AndRHS);
4134             }
4135           }
4136       }
4137     }
4138
4139     // Try to fold constant and into select arguments.
4140     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4141       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4142         return R;
4143     if (isa<PHINode>(Op0))
4144       if (Instruction *NV = FoldOpIntoPhi(I))
4145         return NV;
4146   }
4147
4148   Value *Op0NotVal = dyn_castNotVal(Op0);
4149   Value *Op1NotVal = dyn_castNotVal(Op1);
4150
4151   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
4152     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4153
4154   // (~A & ~B) == (~(A | B)) - De Morgan's Law
4155   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4156     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4157                                                I.getName()+".demorgan");
4158     InsertNewInstBefore(Or, I);
4159     return BinaryOperator::CreateNot(Or);
4160   }
4161   
4162   {
4163     Value *A = 0, *B = 0, *C = 0, *D = 0;
4164     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4165       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
4166         return ReplaceInstUsesWith(I, Op1);
4167     
4168       // (A|B) & ~(A&B) -> A^B
4169       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4170         if ((A == C && B == D) || (A == D && B == C))
4171           return BinaryOperator::CreateXor(A, B);
4172       }
4173     }
4174     
4175     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4176       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
4177         return ReplaceInstUsesWith(I, Op0);
4178
4179       // ~(A&B) & (A|B) -> A^B
4180       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4181         if ((A == C && B == D) || (A == D && B == C))
4182           return BinaryOperator::CreateXor(A, B);
4183       }
4184     }
4185     
4186     if (Op0->hasOneUse() &&
4187         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4188       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
4189         I.swapOperands();     // Simplify below
4190         std::swap(Op0, Op1);
4191       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
4192         cast<BinaryOperator>(Op0)->swapOperands();
4193         I.swapOperands();     // Simplify below
4194         std::swap(Op0, Op1);
4195       }
4196     }
4197     if (Op1->hasOneUse() &&
4198         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4199       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
4200         cast<BinaryOperator>(Op1)->swapOperands();
4201         std::swap(A, B);
4202       }
4203       if (A == Op0) {                                // A&(A^B) -> A & ~B
4204         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4205         InsertNewInstBefore(NotB, I);
4206         return BinaryOperator::CreateAnd(A, NotB);
4207       }
4208     }
4209   }
4210   
4211   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4212     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4213     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4214       return R;
4215
4216     Value *LHSVal, *RHSVal;
4217     ConstantInt *LHSCst, *RHSCst;
4218     ICmpInst::Predicate LHSCC, RHSCC;
4219     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
4222             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4223             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4226             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227             
4228             // Don't try to fold ICMP_SLT + ICMP_ULT.
4229             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4230              ICmpInst::isSignedPredicate(LHSCC) == 
4231                  ICmpInst::isSignedPredicate(RHSCC))) {
4232           // Ensure that the larger constant is on the RHS.
4233           ICmpInst::Predicate GT;
4234           if (ICmpInst::isSignedPredicate(LHSCC) ||
4235               (ICmpInst::isEquality(LHSCC) && 
4236                ICmpInst::isSignedPredicate(RHSCC)))
4237             GT = ICmpInst::ICMP_SGT;
4238           else
4239             GT = ICmpInst::ICMP_UGT;
4240           
4241           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4242           ICmpInst *LHS = cast<ICmpInst>(Op0);
4243           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4244             std::swap(LHS, RHS);
4245             std::swap(LHSCst, RHSCst);
4246             std::swap(LHSCC, RHSCC);
4247           }
4248
4249           // At this point, we know we have have two icmp instructions
4250           // comparing a value against two constants and and'ing the result
4251           // together.  Because of the above check, we know that we only have
4252           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
4253           // (from the FoldICmpLogical check above), that the two constants 
4254           // are not equal and that the larger constant is on the RHS
4255           assert(LHSCst != RHSCst && "Compares not folded above?");
4256
4257           switch (LHSCC) {
4258           default: assert(0 && "Unknown integer condition code!");
4259           case ICmpInst::ICMP_EQ:
4260             switch (RHSCC) {
4261             default: assert(0 && "Unknown integer condition code!");
4262             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
4263             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
4264             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
4265               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4266             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
4267             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
4268             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
4269               return ReplaceInstUsesWith(I, LHS);
4270             }
4271           case ICmpInst::ICMP_NE:
4272             switch (RHSCC) {
4273             default: assert(0 && "Unknown integer condition code!");
4274             case ICmpInst::ICMP_ULT:
4275               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4276                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4277               break;                        // (X != 13 & X u< 15) -> no change
4278             case ICmpInst::ICMP_SLT:
4279               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4280                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4281               break;                        // (X != 13 & X s< 15) -> no change
4282             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
4283             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
4284             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
4285               return ReplaceInstUsesWith(I, RHS);
4286             case ICmpInst::ICMP_NE:
4287               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4288                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4289                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4290                                                       LHSVal->getName()+".off");
4291                 InsertNewInstBefore(Add, I);
4292                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4293                                     ConstantInt::get(Add->getType(), 1));
4294               }
4295               break;                        // (X != 13 & X != 15) -> no change
4296             }
4297             break;
4298           case ICmpInst::ICMP_ULT:
4299             switch (RHSCC) {
4300             default: assert(0 && "Unknown integer condition code!");
4301             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
4302             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
4303               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4304             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
4305               break;
4306             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
4307             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
4308               return ReplaceInstUsesWith(I, LHS);
4309             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
4310               break;
4311             }
4312             break;
4313           case ICmpInst::ICMP_SLT:
4314             switch (RHSCC) {
4315             default: assert(0 && "Unknown integer condition code!");
4316             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
4317             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
4318               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4319             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
4320               break;
4321             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
4322             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
4323               return ReplaceInstUsesWith(I, LHS);
4324             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
4325               break;
4326             }
4327             break;
4328           case ICmpInst::ICMP_UGT:
4329             switch (RHSCC) {
4330             default: assert(0 && "Unknown integer condition code!");
4331             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
4332               return ReplaceInstUsesWith(I, LHS);
4333             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
4334               return ReplaceInstUsesWith(I, RHS);
4335             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
4336               break;
4337             case ICmpInst::ICMP_NE:
4338               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4339                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4340               break;                        // (X u> 13 & X != 15) -> no change
4341             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
4342               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
4343                                      true, I);
4344             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
4345               break;
4346             }
4347             break;
4348           case ICmpInst::ICMP_SGT:
4349             switch (RHSCC) {
4350             default: assert(0 && "Unknown integer condition code!");
4351             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
4352             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
4353               return ReplaceInstUsesWith(I, RHS);
4354             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
4355               break;
4356             case ICmpInst::ICMP_NE:
4357               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4358                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4359               break;                        // (X s> 13 & X != 15) -> no change
4360             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
4361               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
4362                                      true, I);
4363             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
4364               break;
4365             }
4366             break;
4367           }
4368         }
4369   }
4370
4371   // fold (and (cast A), (cast B)) -> (cast (and A, B))
4372   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4373     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4374       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4375         const Type *SrcTy = Op0C->getOperand(0)->getType();
4376         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4377             // Only do this if the casts both really cause code to be generated.
4378             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4379                               I.getType(), TD) &&
4380             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4381                               I.getType(), TD)) {
4382           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4383                                                          Op1C->getOperand(0),
4384                                                          I.getName());
4385           InsertNewInstBefore(NewOp, I);
4386           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4387         }
4388       }
4389     
4390   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
4391   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4392     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4393       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4394           SI0->getOperand(1) == SI1->getOperand(1) &&
4395           (SI0->hasOneUse() || SI1->hasOneUse())) {
4396         Instruction *NewOp =
4397           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4398                                                         SI1->getOperand(0),
4399                                                         SI0->getName()), I);
4400         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4401                                       SI1->getOperand(1));
4402       }
4403   }
4404
4405   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
4406   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4407     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4408       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4409           RHS->getPredicate() == FCmpInst::FCMP_ORD)
4410         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4411           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4412             // If either of the constants are nans, then the whole thing returns
4413             // false.
4414             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4415               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4416             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4417                                 RHS->getOperand(0));
4418           }
4419     }
4420   }
4421       
4422   return Changed ? &I : 0;
4423 }
4424
4425 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4426 /// in the result.  If it does, and if the specified byte hasn't been filled in
4427 /// yet, fill it in and return false.
4428 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4429   Instruction *I = dyn_cast<Instruction>(V);
4430   if (I == 0) return true;
4431
4432   // If this is an or instruction, it is an inner node of the bswap.
4433   if (I->getOpcode() == Instruction::Or)
4434     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4435            CollectBSwapParts(I->getOperand(1), ByteValues);
4436   
4437   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4438   // If this is a shift by a constant int, and it is "24", then its operand
4439   // defines a byte.  We only handle unsigned types here.
4440   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4441     // Not shifting the entire input by N-1 bytes?
4442     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4443         8*(ByteValues.size()-1))
4444       return true;
4445     
4446     unsigned DestNo;
4447     if (I->getOpcode() == Instruction::Shl) {
4448       // X << 24 defines the top byte with the lowest of the input bytes.
4449       DestNo = ByteValues.size()-1;
4450     } else {
4451       // X >>u 24 defines the low byte with the highest of the input bytes.
4452       DestNo = 0;
4453     }
4454     
4455     // If the destination byte value is already defined, the values are or'd
4456     // together, which isn't a bswap (unless it's an or of the same bits).
4457     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4458       return true;
4459     ByteValues[DestNo] = I->getOperand(0);
4460     return false;
4461   }
4462   
4463   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
4464   // don't have this.
4465   Value *Shift = 0, *ShiftLHS = 0;
4466   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4467   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4468       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4469     return true;
4470   Instruction *SI = cast<Instruction>(Shift);
4471
4472   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4473   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4474       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4475     return true;
4476   
4477   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4478   unsigned DestByte;
4479   if (AndAmt->getValue().getActiveBits() > 64)
4480     return true;
4481   uint64_t AndAmtVal = AndAmt->getZExtValue();
4482   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4483     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4484       break;
4485   // Unknown mask for bswap.
4486   if (DestByte == ByteValues.size()) return true;
4487   
4488   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4489   unsigned SrcByte;
4490   if (SI->getOpcode() == Instruction::Shl)
4491     SrcByte = DestByte - ShiftBytes;
4492   else
4493     SrcByte = DestByte + ShiftBytes;
4494   
4495   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4496   if (SrcByte != ByteValues.size()-DestByte-1)
4497     return true;
4498   
4499   // If the destination byte value is already defined, the values are or'd
4500   // together, which isn't a bswap (unless it's an or of the same bits).
4501   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4502     return true;
4503   ByteValues[DestByte] = SI->getOperand(0);
4504   return false;
4505 }
4506
4507 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4508 /// If so, insert the new bswap intrinsic and return it.
4509 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4510   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4511   if (!ITy || ITy->getBitWidth() % 16) 
4512     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
4513   
4514   /// ByteValues - For each byte of the result, we keep track of which value
4515   /// defines each byte.
4516   SmallVector<Value*, 8> ByteValues;
4517   ByteValues.resize(ITy->getBitWidth()/8);
4518     
4519   // Try to find all the pieces corresponding to the bswap.
4520   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4521       CollectBSwapParts(I.getOperand(1), ByteValues))
4522     return 0;
4523   
4524   // Check to see if all of the bytes come from the same value.
4525   Value *V = ByteValues[0];
4526   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
4527   
4528   // Check to make sure that all of the bytes come from the same value.
4529   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4530     if (ByteValues[i] != V)
4531       return 0;
4532   const Type *Tys[] = { ITy };
4533   Module *M = I.getParent()->getParent()->getParent();
4534   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4535   return CallInst::Create(F, V);
4536 }
4537
4538
4539 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4540   bool Changed = SimplifyCommutative(I);
4541   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4542
4543   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4544     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4545
4546   // or X, X = X
4547   if (Op0 == Op1)
4548     return ReplaceInstUsesWith(I, Op0);
4549
4550   // See if we can simplify any instructions used by the instruction whose sole 
4551   // purpose is to compute bits we don't care about.
4552   if (!isa<VectorType>(I.getType())) {
4553     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4554     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4555     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4556                              KnownZero, KnownOne))
4557       return &I;
4558   } else if (isa<ConstantAggregateZero>(Op1)) {
4559     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4560   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4561     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4562       return ReplaceInstUsesWith(I, I.getOperand(1));
4563   }
4564     
4565
4566   
4567   // or X, -1 == -1
4568   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4569     ConstantInt *C1 = 0; Value *X = 0;
4570     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4571     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4572       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4573       InsertNewInstBefore(Or, I);
4574       Or->takeName(Op0);
4575       return BinaryOperator::CreateAnd(Or, 
4576                ConstantInt::get(RHS->getValue() | C1->getValue()));
4577     }
4578
4579     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4580     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4581       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4582       InsertNewInstBefore(Or, I);
4583       Or->takeName(Op0);
4584       return BinaryOperator::CreateXor(Or,
4585                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4586     }
4587
4588     // Try to fold constant and into select arguments.
4589     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4590       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4591         return R;
4592     if (isa<PHINode>(Op0))
4593       if (Instruction *NV = FoldOpIntoPhi(I))
4594         return NV;
4595   }
4596
4597   Value *A = 0, *B = 0;
4598   ConstantInt *C1 = 0, *C2 = 0;
4599
4600   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4601     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4602       return ReplaceInstUsesWith(I, Op1);
4603   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4604     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4605       return ReplaceInstUsesWith(I, Op0);
4606
4607   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4608   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4609   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4610       match(Op1, m_Or(m_Value(), m_Value())) ||
4611       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4612        match(Op1, m_Shift(m_Value(), m_Value())))) {
4613     if (Instruction *BSwap = MatchBSwap(I))
4614       return BSwap;
4615   }
4616   
4617   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4618   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4619       MaskedValueIsZero(Op1, C1->getValue())) {
4620     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4621     InsertNewInstBefore(NOr, I);
4622     NOr->takeName(Op0);
4623     return BinaryOperator::CreateXor(NOr, C1);
4624   }
4625
4626   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4627   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4628       MaskedValueIsZero(Op0, C1->getValue())) {
4629     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4630     InsertNewInstBefore(NOr, I);
4631     NOr->takeName(Op0);
4632     return BinaryOperator::CreateXor(NOr, C1);
4633   }
4634
4635   // (A & C)|(B & D)
4636   Value *C = 0, *D = 0;
4637   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4638       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4639     Value *V1 = 0, *V2 = 0, *V3 = 0;
4640     C1 = dyn_cast<ConstantInt>(C);
4641     C2 = dyn_cast<ConstantInt>(D);
4642     if (C1 && C2) {  // (A & C1)|(B & C2)
4643       // If we have: ((V + N) & C1) | (V & C2)
4644       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4645       // replace with V+N.
4646       if (C1->getValue() == ~C2->getValue()) {
4647         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4648             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4649           // Add commutes, try both ways.
4650           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4651             return ReplaceInstUsesWith(I, A);
4652           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4653             return ReplaceInstUsesWith(I, A);
4654         }
4655         // Or commutes, try both ways.
4656         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4657             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4658           // Add commutes, try both ways.
4659           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4660             return ReplaceInstUsesWith(I, B);
4661           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4662             return ReplaceInstUsesWith(I, B);
4663         }
4664       }
4665       V1 = 0; V2 = 0; V3 = 0;
4666     }
4667     
4668     // Check to see if we have any common things being and'ed.  If so, find the
4669     // terms for V1 & (V2|V3).
4670     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4671       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4672         V1 = A, V2 = C, V3 = D;
4673       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4674         V1 = A, V2 = B, V3 = C;
4675       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4676         V1 = C, V2 = A, V3 = D;
4677       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4678         V1 = C, V2 = A, V3 = B;
4679       
4680       if (V1) {
4681         Value *Or =
4682           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4683         return BinaryOperator::CreateAnd(V1, Or);
4684       }
4685     }
4686   }
4687   
4688   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4689   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4690     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4691       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4692           SI0->getOperand(1) == SI1->getOperand(1) &&
4693           (SI0->hasOneUse() || SI1->hasOneUse())) {
4694         Instruction *NewOp =
4695         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4696                                                      SI1->getOperand(0),
4697                                                      SI0->getName()), I);
4698         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4699                                       SI1->getOperand(1));
4700       }
4701   }
4702
4703   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4704     if (A == Op1)   // ~A | A == -1
4705       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4706   } else {
4707     A = 0;
4708   }
4709   // Note, A is still live here!
4710   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4711     if (Op0 == B)
4712       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4713
4714     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4715     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4716       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4717                                               I.getName()+".demorgan"), I);
4718       return BinaryOperator::CreateNot(And);
4719     }
4720   }
4721
4722   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4723   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4724     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4725       return R;
4726
4727     Value *LHSVal, *RHSVal;
4728     ConstantInt *LHSCst, *RHSCst;
4729     ICmpInst::Predicate LHSCC, RHSCC;
4730     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4731       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4732         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4733             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4734             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4735             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4736             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4737             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4738             // We can't fold (ugt x, C) | (sgt x, C2).
4739             PredicatesFoldable(LHSCC, RHSCC)) {
4740           // Ensure that the larger constant is on the RHS.
4741           ICmpInst *LHS = cast<ICmpInst>(Op0);
4742           bool NeedsSwap;
4743           if (ICmpInst::isSignedPredicate(LHSCC))
4744             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4745           else
4746             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4747             
4748           if (NeedsSwap) {
4749             std::swap(LHS, RHS);
4750             std::swap(LHSCst, RHSCst);
4751             std::swap(LHSCC, RHSCC);
4752           }
4753
4754           // At this point, we know we have have two icmp instructions
4755           // comparing a value against two constants and or'ing the result
4756           // together.  Because of the above check, we know that we only have
4757           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4758           // FoldICmpLogical check above), that the two constants are not
4759           // equal.
4760           assert(LHSCst != RHSCst && "Compares not folded above?");
4761
4762           switch (LHSCC) {
4763           default: assert(0 && "Unknown integer condition code!");
4764           case ICmpInst::ICMP_EQ:
4765             switch (RHSCC) {
4766             default: assert(0 && "Unknown integer condition code!");
4767             case ICmpInst::ICMP_EQ:
4768               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4769                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4770                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4771                                                       LHSVal->getName()+".off");
4772                 InsertNewInstBefore(Add, I);
4773                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4774                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4775               }
4776               break;                         // (X == 13 | X == 15) -> no change
4777             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4778             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4779               break;
4780             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4781             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4782             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4783               return ReplaceInstUsesWith(I, RHS);
4784             }
4785             break;
4786           case ICmpInst::ICMP_NE:
4787             switch (RHSCC) {
4788             default: assert(0 && "Unknown integer condition code!");
4789             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4790             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4791             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4792               return ReplaceInstUsesWith(I, LHS);
4793             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4794             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4795             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4796               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4797             }
4798             break;
4799           case ICmpInst::ICMP_ULT:
4800             switch (RHSCC) {
4801             default: assert(0 && "Unknown integer condition code!");
4802             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4803               break;
4804             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4805               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4806               // this can cause overflow.
4807               if (RHSCst->isMaxValue(false))
4808                 return ReplaceInstUsesWith(I, LHS);
4809               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4810                                      false, I);
4811             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4812               break;
4813             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4814             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4815               return ReplaceInstUsesWith(I, RHS);
4816             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4817               break;
4818             }
4819             break;
4820           case ICmpInst::ICMP_SLT:
4821             switch (RHSCC) {
4822             default: assert(0 && "Unknown integer condition code!");
4823             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4824               break;
4825             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4826               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4827               // this can cause overflow.
4828               if (RHSCst->isMaxValue(true))
4829                 return ReplaceInstUsesWith(I, LHS);
4830               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4831                                      false, I);
4832             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4833               break;
4834             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4835             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4836               return ReplaceInstUsesWith(I, RHS);
4837             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4838               break;
4839             }
4840             break;
4841           case ICmpInst::ICMP_UGT:
4842             switch (RHSCC) {
4843             default: assert(0 && "Unknown integer condition code!");
4844             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4845             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4846               return ReplaceInstUsesWith(I, LHS);
4847             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4848               break;
4849             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4850             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4851               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4852             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4853               break;
4854             }
4855             break;
4856           case ICmpInst::ICMP_SGT:
4857             switch (RHSCC) {
4858             default: assert(0 && "Unknown integer condition code!");
4859             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4860             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4861               return ReplaceInstUsesWith(I, LHS);
4862             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4863               break;
4864             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4865             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4866               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4867             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4868               break;
4869             }
4870             break;
4871           }
4872         }
4873   }
4874     
4875   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4876   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4877     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4878       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4879         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4880             !isa<ICmpInst>(Op1C->getOperand(0))) {
4881           const Type *SrcTy = Op0C->getOperand(0)->getType();
4882           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4883               // Only do this if the casts both really cause code to be
4884               // generated.
4885               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4886                                 I.getType(), TD) &&
4887               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4888                                 I.getType(), TD)) {
4889             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4890                                                           Op1C->getOperand(0),
4891                                                           I.getName());
4892             InsertNewInstBefore(NewOp, I);
4893             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4894           }
4895         }
4896       }
4897   }
4898   
4899     
4900   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4901   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4902     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4903       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4904           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4905           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4906         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4907           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4908             // If either of the constants are nans, then the whole thing returns
4909             // true.
4910             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4911               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4912             
4913             // Otherwise, no need to compare the two constants, compare the
4914             // rest.
4915             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4916                                 RHS->getOperand(0));
4917           }
4918     }
4919   }
4920
4921   return Changed ? &I : 0;
4922 }
4923
4924 namespace {
4925
4926 // XorSelf - Implements: X ^ X --> 0
4927 struct XorSelf {
4928   Value *RHS;
4929   XorSelf(Value *rhs) : RHS(rhs) {}
4930   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4931   Instruction *apply(BinaryOperator &Xor) const {
4932     return &Xor;
4933   }
4934 };
4935
4936 }
4937
4938 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4939   bool Changed = SimplifyCommutative(I);
4940   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4941
4942   if (isa<UndefValue>(Op1)) {
4943     if (isa<UndefValue>(Op0))
4944       // Handle undef ^ undef -> 0 special case. This is a common
4945       // idiom (misuse).
4946       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4947     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4948   }
4949
4950   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4951   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4952     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4953     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4954   }
4955   
4956   // See if we can simplify any instructions used by the instruction whose sole 
4957   // purpose is to compute bits we don't care about.
4958   if (!isa<VectorType>(I.getType())) {
4959     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4960     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4961     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4962                              KnownZero, KnownOne))
4963       return &I;
4964   } else if (isa<ConstantAggregateZero>(Op1)) {
4965     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4966   }
4967
4968   // Is this a ~ operation?
4969   if (Value *NotOp = dyn_castNotVal(&I)) {
4970     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4971     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4972     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4973       if (Op0I->getOpcode() == Instruction::And || 
4974           Op0I->getOpcode() == Instruction::Or) {
4975         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4976         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4977           Instruction *NotY =
4978             BinaryOperator::CreateNot(Op0I->getOperand(1),
4979                                       Op0I->getOperand(1)->getName()+".not");
4980           InsertNewInstBefore(NotY, I);
4981           if (Op0I->getOpcode() == Instruction::And)
4982             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4983           else
4984             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4985         }
4986       }
4987     }
4988   }
4989   
4990   
4991   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4992     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4993     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4994       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4995         return new ICmpInst(ICI->getInversePredicate(),
4996                             ICI->getOperand(0), ICI->getOperand(1));
4997
4998       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4999         return new FCmpInst(FCI->getInversePredicate(),
5000                             FCI->getOperand(0), FCI->getOperand(1));
5001     }
5002
5003     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5004       // ~(c-X) == X-c-1 == X+(-c-1)
5005       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5006         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5007           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5008           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5009                                               ConstantInt::get(I.getType(), 1));
5010           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5011         }
5012           
5013       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5014         if (Op0I->getOpcode() == Instruction::Add) {
5015           // ~(X-c) --> (-c-1)-X
5016           if (RHS->isAllOnesValue()) {
5017             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5018             return BinaryOperator::CreateSub(
5019                            ConstantExpr::getSub(NegOp0CI,
5020                                              ConstantInt::get(I.getType(), 1)),
5021                                           Op0I->getOperand(0));
5022           } else if (RHS->getValue().isSignBit()) {
5023             // (X + C) ^ signbit -> (X + C + signbit)
5024             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5025             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5026
5027           }
5028         } else if (Op0I->getOpcode() == Instruction::Or) {
5029           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5030           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5031             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5032             // Anything in both C1 and C2 is known to be zero, remove it from
5033             // NewRHS.
5034             Constant *CommonBits = And(Op0CI, RHS);
5035             NewRHS = ConstantExpr::getAnd(NewRHS, 
5036                                           ConstantExpr::getNot(CommonBits));
5037             AddToWorkList(Op0I);
5038             I.setOperand(0, Op0I->getOperand(0));
5039             I.setOperand(1, NewRHS);
5040             return &I;
5041           }
5042         }
5043       }
5044     }
5045
5046     // Try to fold constant and into select arguments.
5047     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5048       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5049         return R;
5050     if (isa<PHINode>(Op0))
5051       if (Instruction *NV = FoldOpIntoPhi(I))
5052         return NV;
5053   }
5054
5055   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
5056     if (X == Op1)
5057       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5058
5059   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
5060     if (X == Op0)
5061       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5062
5063   
5064   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5065   if (Op1I) {
5066     Value *A, *B;
5067     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5068       if (A == Op0) {              // B^(B|A) == (A|B)^B
5069         Op1I->swapOperands();
5070         I.swapOperands();
5071         std::swap(Op0, Op1);
5072       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
5073         I.swapOperands();     // Simplified below.
5074         std::swap(Op0, Op1);
5075       }
5076     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5077       if (Op0 == A)                                          // A^(A^B) == B
5078         return ReplaceInstUsesWith(I, B);
5079       else if (Op0 == B)                                     // A^(B^A) == B
5080         return ReplaceInstUsesWith(I, A);
5081     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5082       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
5083         Op1I->swapOperands();
5084         std::swap(A, B);
5085       }
5086       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
5087         I.swapOperands();     // Simplified below.
5088         std::swap(Op0, Op1);
5089       }
5090     }
5091   }
5092   
5093   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5094   if (Op0I) {
5095     Value *A, *B;
5096     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5097       if (A == Op1)                                  // (B|A)^B == (A|B)^B
5098         std::swap(A, B);
5099       if (B == Op1) {                                // (A|B)^B == A & ~B
5100         Instruction *NotB =
5101           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5102         return BinaryOperator::CreateAnd(A, NotB);
5103       }
5104     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5105       if (Op1 == A)                                          // (A^B)^A == B
5106         return ReplaceInstUsesWith(I, B);
5107       else if (Op1 == B)                                     // (B^A)^A == B
5108         return ReplaceInstUsesWith(I, A);
5109     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5110       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
5111         std::swap(A, B);
5112       if (B == Op1 &&                                      // (B&A)^A == ~B & A
5113           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
5114         Instruction *N =
5115           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5116         return BinaryOperator::CreateAnd(N, Op1);
5117       }
5118     }
5119   }
5120   
5121   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
5122   if (Op0I && Op1I && Op0I->isShift() && 
5123       Op0I->getOpcode() == Op1I->getOpcode() && 
5124       Op0I->getOperand(1) == Op1I->getOperand(1) &&
5125       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5126     Instruction *NewOp =
5127       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5128                                                     Op1I->getOperand(0),
5129                                                     Op0I->getName()), I);
5130     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
5131                                   Op1I->getOperand(1));
5132   }
5133     
5134   if (Op0I && Op1I) {
5135     Value *A, *B, *C, *D;
5136     // (A & B)^(A | B) -> A ^ B
5137     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5138         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5139       if ((A == C && B == D) || (A == D && B == C)) 
5140         return BinaryOperator::CreateXor(A, B);
5141     }
5142     // (A | B)^(A & B) -> A ^ B
5143     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5144         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5145       if ((A == C && B == D) || (A == D && B == C)) 
5146         return BinaryOperator::CreateXor(A, B);
5147     }
5148     
5149     // (A & B)^(C & D)
5150     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5151         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5152         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5153       // (X & Y)^(X & Y) -> (Y^Z) & X
5154       Value *X = 0, *Y = 0, *Z = 0;
5155       if (A == C)
5156         X = A, Y = B, Z = D;
5157       else if (A == D)
5158         X = A, Y = B, Z = C;
5159       else if (B == C)
5160         X = B, Y = A, Z = D;
5161       else if (B == D)
5162         X = B, Y = A, Z = C;
5163       
5164       if (X) {
5165         Instruction *NewOp =
5166         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5167         return BinaryOperator::CreateAnd(NewOp, X);
5168       }
5169     }
5170   }
5171     
5172   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5173   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5174     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5175       return R;
5176
5177   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5178   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5179     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5180       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5181         const Type *SrcTy = Op0C->getOperand(0)->getType();
5182         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5183             // Only do this if the casts both really cause code to be generated.
5184             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
5185                               I.getType(), TD) &&
5186             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
5187                               I.getType(), TD)) {
5188           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5189                                                          Op1C->getOperand(0),
5190                                                          I.getName());
5191           InsertNewInstBefore(NewOp, I);
5192           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5193         }
5194       }
5195   }
5196   return Changed ? &I : 0;
5197 }
5198
5199 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5200 /// overflowed for this type.
5201 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5202                             ConstantInt *In2, bool IsSigned = false) {
5203   Result = cast<ConstantInt>(Add(In1, In2));
5204
5205   if (IsSigned)
5206     if (In2->getValue().isNegative())
5207       return Result->getValue().sgt(In1->getValue());
5208     else
5209       return Result->getValue().slt(In1->getValue());
5210   else
5211     return Result->getValue().ult(In1->getValue());
5212 }
5213
5214 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5215 /// code necessary to compute the offset from the base pointer (without adding
5216 /// in the base pointer).  Return the result as a signed integer of intptr size.
5217 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5218   TargetData &TD = IC.getTargetData();
5219   gep_type_iterator GTI = gep_type_begin(GEP);
5220   const Type *IntPtrTy = TD.getIntPtrType();
5221   Value *Result = Constant::getNullValue(IntPtrTy);
5222
5223   // Build a mask for high order bits.
5224   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5225   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5226
5227   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5228     Value *Op = GEP->getOperand(i);
5229     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5230     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5231       if (OpC->isZero()) continue;
5232       
5233       // Handle a struct index, which adds its field offset to the pointer.
5234       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5235         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5236         
5237         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5238           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5239         else
5240           Result = IC.InsertNewInstBefore(
5241                    BinaryOperator::CreateAdd(Result,
5242                                              ConstantInt::get(IntPtrTy, Size),
5243                                              GEP->getName()+".offs"), I);
5244         continue;
5245       }
5246       
5247       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5248       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5249       Scale = ConstantExpr::getMul(OC, Scale);
5250       if (Constant *RC = dyn_cast<Constant>(Result))
5251         Result = ConstantExpr::getAdd(RC, Scale);
5252       else {
5253         // Emit an add instruction.
5254         Result = IC.InsertNewInstBefore(
5255            BinaryOperator::CreateAdd(Result, Scale,
5256                                      GEP->getName()+".offs"), I);
5257       }
5258       continue;
5259     }
5260     // Convert to correct type.
5261     if (Op->getType() != IntPtrTy) {
5262       if (Constant *OpC = dyn_cast<Constant>(Op))
5263         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5264       else
5265         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5266                                                  Op->getName()+".c"), I);
5267     }
5268     if (Size != 1) {
5269       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5270       if (Constant *OpC = dyn_cast<Constant>(Op))
5271         Op = ConstantExpr::getMul(OpC, Scale);
5272       else    // We'll let instcombine(mul) convert this to a shl if possible.
5273         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5274                                                   GEP->getName()+".idx"), I);
5275     }
5276
5277     // Emit an add instruction.
5278     if (isa<Constant>(Op) && isa<Constant>(Result))
5279       Result = ConstantExpr::getAdd(cast<Constant>(Op),
5280                                     cast<Constant>(Result));
5281     else
5282       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5283                                                   GEP->getName()+".offs"), I);
5284   }
5285   return Result;
5286 }
5287
5288
5289 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5290 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
5291 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
5292 /// complex, and scales are involved.  The above expression would also be legal
5293 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
5294 /// later form is less amenable to optimization though, and we are allowed to
5295 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5296 ///
5297 /// If we can't emit an optimized form for this expression, this returns null.
5298 /// 
5299 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5300                                           InstCombiner &IC) {
5301   TargetData &TD = IC.getTargetData();
5302   gep_type_iterator GTI = gep_type_begin(GEP);
5303
5304   // Check to see if this gep only has a single variable index.  If so, and if
5305   // any constant indices are a multiple of its scale, then we can compute this
5306   // in terms of the scale of the variable index.  For example, if the GEP
5307   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5308   // because the expression will cross zero at the same point.
5309   unsigned i, e = GEP->getNumOperands();
5310   int64_t Offset = 0;
5311   for (i = 1; i != e; ++i, ++GTI) {
5312     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5313       // Compute the aggregate offset of constant indices.
5314       if (CI->isZero()) continue;
5315
5316       // Handle a struct index, which adds its field offset to the pointer.
5317       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5318         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5319       } else {
5320         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5321         Offset += Size*CI->getSExtValue();
5322       }
5323     } else {
5324       // Found our variable index.
5325       break;
5326     }
5327   }
5328   
5329   // If there are no variable indices, we must have a constant offset, just
5330   // evaluate it the general way.
5331   if (i == e) return 0;
5332   
5333   Value *VariableIdx = GEP->getOperand(i);
5334   // Determine the scale factor of the variable element.  For example, this is
5335   // 4 if the variable index is into an array of i32.
5336   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5337   
5338   // Verify that there are no other variable indices.  If so, emit the hard way.
5339   for (++i, ++GTI; i != e; ++i, ++GTI) {
5340     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5341     if (!CI) return 0;
5342    
5343     // Compute the aggregate offset of constant indices.
5344     if (CI->isZero()) continue;
5345     
5346     // Handle a struct index, which adds its field offset to the pointer.
5347     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5348       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5349     } else {
5350       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5351       Offset += Size*CI->getSExtValue();
5352     }
5353   }
5354   
5355   // Okay, we know we have a single variable index, which must be a
5356   // pointer/array/vector index.  If there is no offset, life is simple, return
5357   // the index.
5358   unsigned IntPtrWidth = TD.getPointerSizeInBits();
5359   if (Offset == 0) {
5360     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
5361     // we don't need to bother extending: the extension won't affect where the
5362     // computation crosses zero.
5363     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5364       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5365                                   VariableIdx->getNameStart(), &I);
5366     return VariableIdx;
5367   }
5368   
5369   // Otherwise, there is an index.  The computation we will do will be modulo
5370   // the pointer size, so get it.
5371   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5372   
5373   Offset &= PtrSizeMask;
5374   VariableScale &= PtrSizeMask;
5375
5376   // To do this transformation, any constant index must be a multiple of the
5377   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
5378   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
5379   // multiple of the variable scale.
5380   int64_t NewOffs = Offset / (int64_t)VariableScale;
5381   if (Offset != NewOffs*(int64_t)VariableScale)
5382     return 0;
5383
5384   // Okay, we can do this evaluation.  Start by converting the index to intptr.
5385   const Type *IntPtrTy = TD.getIntPtrType();
5386   if (VariableIdx->getType() != IntPtrTy)
5387     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5388                                               true /*SExt*/, 
5389                                               VariableIdx->getNameStart(), &I);
5390   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5391   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5392 }
5393
5394
5395 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5396 /// else.  At this point we know that the GEP is on the LHS of the comparison.
5397 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5398                                        ICmpInst::Predicate Cond,
5399                                        Instruction &I) {
5400   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5401
5402   // Look through bitcasts.
5403   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5404     RHS = BCI->getOperand(0);
5405
5406   Value *PtrBase = GEPLHS->getOperand(0);
5407   if (PtrBase == RHS) {
5408     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
5409     // This transformation (ignoring the base and scales) is valid because we
5410     // know pointers can't overflow.  See if we can output an optimized form.
5411     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5412     
5413     // If not, synthesize the offset the hard way.
5414     if (Offset == 0)
5415       Offset = EmitGEPOffset(GEPLHS, I, *this);
5416     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5417                         Constant::getNullValue(Offset->getType()));
5418   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5419     // If the base pointers are different, but the indices are the same, just
5420     // compare the base pointer.
5421     if (PtrBase != GEPRHS->getOperand(0)) {
5422       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5423       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5424                         GEPRHS->getOperand(0)->getType();
5425       if (IndicesTheSame)
5426         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5427           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5428             IndicesTheSame = false;
5429             break;
5430           }
5431
5432       // If all indices are the same, just compare the base pointers.
5433       if (IndicesTheSame)
5434         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
5435                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5436
5437       // Otherwise, the base pointers are different and the indices are
5438       // different, bail out.
5439       return 0;
5440     }
5441
5442     // If one of the GEPs has all zero indices, recurse.
5443     bool AllZeros = true;
5444     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5445       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5446           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5447         AllZeros = false;
5448         break;
5449       }
5450     if (AllZeros)
5451       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5452                           ICmpInst::getSwappedPredicate(Cond), I);
5453
5454     // If the other GEP has all zero indices, recurse.
5455     AllZeros = true;
5456     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5457       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5458           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5459         AllZeros = false;
5460         break;
5461       }
5462     if (AllZeros)
5463       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5464
5465     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5466       // If the GEPs only differ by one index, compare it.
5467       unsigned NumDifferences = 0;  // Keep track of # differences.
5468       unsigned DiffOperand = 0;     // The operand that differs.
5469       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5470         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5471           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5472                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5473             // Irreconcilable differences.
5474             NumDifferences = 2;
5475             break;
5476           } else {
5477             if (NumDifferences++) break;
5478             DiffOperand = i;
5479           }
5480         }
5481
5482       if (NumDifferences == 0)   // SAME GEP?
5483         return ReplaceInstUsesWith(I, // No comparison is needed here.
5484                                    ConstantInt::get(Type::Int1Ty,
5485                                              ICmpInst::isTrueWhenEqual(Cond)));
5486
5487       else if (NumDifferences == 1) {
5488         Value *LHSV = GEPLHS->getOperand(DiffOperand);
5489         Value *RHSV = GEPRHS->getOperand(DiffOperand);
5490         // Make sure we do a signed comparison here.
5491         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5492       }
5493     }
5494
5495     // Only lower this if the icmp is the only user of the GEP or if we expect
5496     // the result to fold to a constant!
5497     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5498         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5499       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5500       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5501       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5502       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5503     }
5504   }
5505   return 0;
5506 }
5507
5508 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5509 ///
5510 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5511                                                 Instruction *LHSI,
5512                                                 Constant *RHSC) {
5513   if (!isa<ConstantFP>(RHSC)) return 0;
5514   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5515   
5516   // Get the width of the mantissa.  We don't want to hack on conversions that
5517   // might lose information from the integer, e.g. "i64 -> float"
5518   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5519   if (MantissaWidth == -1) return 0;  // Unknown.
5520   
5521   // Check to see that the input is converted from an integer type that is small
5522   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5523   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5524   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5525   
5526   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5527   if (isa<UIToFPInst>(LHSI))
5528     ++InputSize;
5529   
5530   // If the conversion would lose info, don't hack on this.
5531   if ((int)InputSize > MantissaWidth)
5532     return 0;
5533   
5534   // Otherwise, we can potentially simplify the comparison.  We know that it
5535   // will always come through as an integer value and we know the constant is
5536   // not a NAN (it would have been previously simplified).
5537   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5538   
5539   ICmpInst::Predicate Pred;
5540   switch (I.getPredicate()) {
5541   default: assert(0 && "Unexpected predicate!");
5542   case FCmpInst::FCMP_UEQ:
5543   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5544   case FCmpInst::FCMP_UGT:
5545   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5546   case FCmpInst::FCMP_UGE:
5547   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5548   case FCmpInst::FCMP_ULT:
5549   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5550   case FCmpInst::FCMP_ULE:
5551   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5552   case FCmpInst::FCMP_UNE:
5553   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5554   case FCmpInst::FCMP_ORD:
5555     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5556   case FCmpInst::FCMP_UNO:
5557     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5558   }
5559   
5560   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5561   
5562   // Now we know that the APFloat is a normal number, zero or inf.
5563   
5564   // See if the FP constant is too large for the integer.  For example,
5565   // comparing an i8 to 300.0.
5566   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5567   
5568   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5569   // and large values. 
5570   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5571   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5572                         APFloat::rmNearestTiesToEven);
5573   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5574     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5575         Pred == ICmpInst::ICMP_SLE)
5576       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5577     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5578   }
5579   
5580   // See if the RHS value is < SignedMin.
5581   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5582   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5583                         APFloat::rmNearestTiesToEven);
5584   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5585     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5586         Pred == ICmpInst::ICMP_SGE)
5587       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5588     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5589   }
5590
5591   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5592   // it may still be fractional.  See if it is fractional by casting the FP
5593   // value to the integer value and back, checking for equality.  Don't do this
5594   // for zero, because -0.0 is not fractional.
5595   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5596   if (!RHS.isZero() &&
5597       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5598     // If we had a comparison against a fractional value, we have to adjust
5599     // the compare predicate and sometimes the value.  RHSC is rounded towards
5600     // zero at this point.
5601     switch (Pred) {
5602     default: assert(0 && "Unexpected integer comparison!");
5603     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5604       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5605     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5606       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5607     case ICmpInst::ICMP_SLE:
5608       // (float)int <= 4.4   --> int <= 4
5609       // (float)int <= -4.4  --> int < -4
5610       if (RHS.isNegative())
5611         Pred = ICmpInst::ICMP_SLT;
5612       break;
5613     case ICmpInst::ICMP_SLT:
5614       // (float)int < -4.4   --> int < -4
5615       // (float)int < 4.4    --> int <= 4
5616       if (!RHS.isNegative())
5617         Pred = ICmpInst::ICMP_SLE;
5618       break;
5619     case ICmpInst::ICMP_SGT:
5620       // (float)int > 4.4    --> int > 4
5621       // (float)int > -4.4   --> int >= -4
5622       if (RHS.isNegative())
5623         Pred = ICmpInst::ICMP_SGE;
5624       break;
5625     case ICmpInst::ICMP_SGE:
5626       // (float)int >= -4.4   --> int >= -4
5627       // (float)int >= 4.4    --> int > 4
5628       if (!RHS.isNegative())
5629         Pred = ICmpInst::ICMP_SGT;
5630       break;
5631     }
5632   }
5633
5634   // Lower this FP comparison into an appropriate integer version of the
5635   // comparison.
5636   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5637 }
5638
5639 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5640   bool Changed = SimplifyCompare(I);
5641   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5642
5643   // Fold trivial predicates.
5644   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5645     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5646   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5647     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5648   
5649   // Simplify 'fcmp pred X, X'
5650   if (Op0 == Op1) {
5651     switch (I.getPredicate()) {
5652     default: assert(0 && "Unknown predicate!");
5653     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5654     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5655     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5656       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5657     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5658     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5659     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5660       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5661       
5662     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5663     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5664     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5665     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5666       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5667       I.setPredicate(FCmpInst::FCMP_UNO);
5668       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5669       return &I;
5670       
5671     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5672     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5673     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5674     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5675       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5676       I.setPredicate(FCmpInst::FCMP_ORD);
5677       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5678       return &I;
5679     }
5680   }
5681     
5682   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5683     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5684
5685   // Handle fcmp with constant RHS
5686   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5687     // If the constant is a nan, see if we can fold the comparison based on it.
5688     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5689       if (CFP->getValueAPF().isNaN()) {
5690         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5691           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5692         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5693                "Comparison must be either ordered or unordered!");
5694         // True if unordered.
5695         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5696       }
5697     }
5698     
5699     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5700       switch (LHSI->getOpcode()) {
5701       case Instruction::PHI:
5702         if (Instruction *NV = FoldOpIntoPhi(I))
5703           return NV;
5704         break;
5705       case Instruction::SIToFP:
5706       case Instruction::UIToFP:
5707         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5708           return NV;
5709         break;
5710       case Instruction::Select:
5711         // If either operand of the select is a constant, we can fold the
5712         // comparison into the select arms, which will cause one to be
5713         // constant folded and the select turned into a bitwise or.
5714         Value *Op1 = 0, *Op2 = 0;
5715         if (LHSI->hasOneUse()) {
5716           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5717             // Fold the known value into the constant operand.
5718             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5719             // Insert a new FCmp of the other select operand.
5720             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5721                                                       LHSI->getOperand(2), RHSC,
5722                                                       I.getName()), I);
5723           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5724             // Fold the known value into the constant operand.
5725             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5726             // Insert a new FCmp of the other select operand.
5727             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5728                                                       LHSI->getOperand(1), RHSC,
5729                                                       I.getName()), I);
5730           }
5731         }
5732
5733         if (Op1)
5734           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5735         break;
5736       }
5737   }
5738
5739   return Changed ? &I : 0;
5740 }
5741
5742 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5743   bool Changed = SimplifyCompare(I);
5744   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5745   const Type *Ty = Op0->getType();
5746
5747   // icmp X, X
5748   if (Op0 == Op1)
5749     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5750                                                    I.isTrueWhenEqual()));
5751
5752   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5753     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5754   
5755   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5756   // addresses never equal each other!  We already know that Op0 != Op1.
5757   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5758        isa<ConstantPointerNull>(Op0)) &&
5759       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5760        isa<ConstantPointerNull>(Op1)))
5761     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5762                                                    !I.isTrueWhenEqual()));
5763
5764   // icmp's with boolean values can always be turned into bitwise operations
5765   if (Ty == Type::Int1Ty) {
5766     switch (I.getPredicate()) {
5767     default: assert(0 && "Invalid icmp instruction!");
5768     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5769       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5770       InsertNewInstBefore(Xor, I);
5771       return BinaryOperator::CreateNot(Xor);
5772     }
5773     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5774       return BinaryOperator::CreateXor(Op0, Op1);
5775
5776     case ICmpInst::ICMP_UGT:
5777     case ICmpInst::ICMP_SGT:
5778       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5779       // FALL THROUGH
5780     case ICmpInst::ICMP_ULT:
5781     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5782       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5783       InsertNewInstBefore(Not, I);
5784       return BinaryOperator::CreateAnd(Not, Op1);
5785     }
5786     case ICmpInst::ICMP_UGE:
5787     case ICmpInst::ICMP_SGE:
5788       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5789       // FALL THROUGH
5790     case ICmpInst::ICMP_ULE:
5791     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5792       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5793       InsertNewInstBefore(Not, I);
5794       return BinaryOperator::CreateOr(Not, Op1);
5795     }
5796     }
5797   }
5798
5799   // See if we are doing a comparison between a constant and an instruction that
5800   // can be folded into the comparison.
5801   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5802       Value *A, *B;
5803     
5804     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5805     if (I.isEquality() && CI->isNullValue() &&
5806         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5807       // (icmp cond A B) if cond is equality
5808       return new ICmpInst(I.getPredicate(), A, B);
5809     }
5810     
5811     switch (I.getPredicate()) {
5812     default: break;
5813     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5814       if (CI->isMinValue(false))
5815         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5816       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5817         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5818       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5819         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5820       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5821       if (CI->isMinValue(true))
5822         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5823                             ConstantInt::getAllOnesValue(Op0->getType()));
5824           
5825       break;
5826
5827     case ICmpInst::ICMP_SLT:
5828       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5829         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5830       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5831         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5832       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5833         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5834       break;
5835
5836     case ICmpInst::ICMP_UGT:
5837       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5838         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5839       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5840         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5841       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5842         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5843         
5844       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5845       if (CI->isMaxValue(true))
5846         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5847                             ConstantInt::getNullValue(Op0->getType()));
5848       break;
5849
5850     case ICmpInst::ICMP_SGT:
5851       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5852         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5853       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5854         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5855       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5856         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5857       break;
5858
5859     case ICmpInst::ICMP_ULE:
5860       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5861         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5862       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5863         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5864       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5865         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5866       break;
5867
5868     case ICmpInst::ICMP_SLE:
5869       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5870         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5871       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5872         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5873       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5874         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5875       break;
5876
5877     case ICmpInst::ICMP_UGE:
5878       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5879         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5880       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5881         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5882       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5883         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5884       break;
5885
5886     case ICmpInst::ICMP_SGE:
5887       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5888         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5889       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5890         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5891       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5892         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5893       break;
5894     }
5895
5896     // If we still have a icmp le or icmp ge instruction, turn it into the
5897     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5898     // already been handled above, this requires little checking.
5899     //
5900     switch (I.getPredicate()) {
5901     default: break;
5902     case ICmpInst::ICMP_ULE: 
5903       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5904     case ICmpInst::ICMP_SLE:
5905       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5906     case ICmpInst::ICMP_UGE:
5907       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5908     case ICmpInst::ICMP_SGE:
5909       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5910     }
5911     
5912     // See if we can fold the comparison based on bits known to be zero or one
5913     // in the input.  If this comparison is a normal comparison, it demands all
5914     // bits, if it is a sign bit comparison, it only demands the sign bit.
5915     
5916     bool UnusedBit;
5917     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5918     
5919     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5920     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5921     if (SimplifyDemandedBits(Op0, 
5922                              isSignBit ? APInt::getSignBit(BitWidth)
5923                                        : APInt::getAllOnesValue(BitWidth),
5924                              KnownZero, KnownOne, 0))
5925       return &I;
5926         
5927     // Given the known and unknown bits, compute a range that the LHS could be
5928     // in.
5929     if ((KnownOne | KnownZero) != 0) {
5930       // Compute the Min, Max and RHS values based on the known bits. For the
5931       // EQ and NE we use unsigned values.
5932       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5933       const APInt& RHSVal = CI->getValue();
5934       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5935         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5936                                                Max);
5937       } else {
5938         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5939                                                  Max);
5940       }
5941       switch (I.getPredicate()) {  // LE/GE have been folded already.
5942       default: assert(0 && "Unknown icmp opcode!");
5943       case ICmpInst::ICMP_EQ:
5944         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5945           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5946         break;
5947       case ICmpInst::ICMP_NE:
5948         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5949           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5950         break;
5951       case ICmpInst::ICMP_ULT:
5952         if (Max.ult(RHSVal))
5953           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5954         if (Min.uge(RHSVal))
5955           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5956         break;
5957       case ICmpInst::ICMP_UGT:
5958         if (Min.ugt(RHSVal))
5959           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5960         if (Max.ule(RHSVal))
5961           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5962         break;
5963       case ICmpInst::ICMP_SLT:
5964         if (Max.slt(RHSVal))
5965           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5966         if (Min.sgt(RHSVal))
5967           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5968         break;
5969       case ICmpInst::ICMP_SGT: 
5970         if (Min.sgt(RHSVal))
5971           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5972         if (Max.sle(RHSVal))
5973           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5974         break;
5975       }
5976     }
5977           
5978     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5979     // instruction, see if that instruction also has constants so that the 
5980     // instruction can be folded into the icmp 
5981     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5982       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5983         return Res;
5984   }
5985
5986   // Handle icmp with constant (but not simple integer constant) RHS
5987   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5988     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5989       switch (LHSI->getOpcode()) {
5990       case Instruction::GetElementPtr:
5991         if (RHSC->isNullValue()) {
5992           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5993           bool isAllZeros = true;
5994           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5995             if (!isa<Constant>(LHSI->getOperand(i)) ||
5996                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5997               isAllZeros = false;
5998               break;
5999             }
6000           if (isAllZeros)
6001             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6002                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
6003         }
6004         break;
6005
6006       case Instruction::PHI:
6007         if (Instruction *NV = FoldOpIntoPhi(I))
6008           return NV;
6009         break;
6010       case Instruction::Select: {
6011         // If either operand of the select is a constant, we can fold the
6012         // comparison into the select arms, which will cause one to be
6013         // constant folded and the select turned into a bitwise or.
6014         Value *Op1 = 0, *Op2 = 0;
6015         if (LHSI->hasOneUse()) {
6016           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6017             // Fold the known value into the constant operand.
6018             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6019             // Insert a new ICmp of the other select operand.
6020             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6021                                                    LHSI->getOperand(2), RHSC,
6022                                                    I.getName()), I);
6023           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6024             // Fold the known value into the constant operand.
6025             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6026             // Insert a new ICmp of the other select operand.
6027             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6028                                                    LHSI->getOperand(1), RHSC,
6029                                                    I.getName()), I);
6030           }
6031         }
6032
6033         if (Op1)
6034           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6035         break;
6036       }
6037       case Instruction::Malloc:
6038         // If we have (malloc != null), and if the malloc has a single use, we
6039         // can assume it is successful and remove the malloc.
6040         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6041           AddToWorkList(LHSI);
6042           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6043                                                          !I.isTrueWhenEqual()));
6044         }
6045         break;
6046       }
6047   }
6048
6049   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6050   if (User *GEP = dyn_castGetElementPtr(Op0))
6051     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6052       return NI;
6053   if (User *GEP = dyn_castGetElementPtr(Op1))
6054     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6055                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6056       return NI;
6057
6058   // Test to see if the operands of the icmp are casted versions of other
6059   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
6060   // now.
6061   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6062     if (isa<PointerType>(Op0->getType()) && 
6063         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
6064       // We keep moving the cast from the left operand over to the right
6065       // operand, where it can often be eliminated completely.
6066       Op0 = CI->getOperand(0);
6067
6068       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6069       // so eliminate it as well.
6070       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6071         Op1 = CI2->getOperand(0);
6072
6073       // If Op1 is a constant, we can fold the cast into the constant.
6074       if (Op0->getType() != Op1->getType()) {
6075         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6076           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6077         } else {
6078           // Otherwise, cast the RHS right before the icmp
6079           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6080         }
6081       }
6082       return new ICmpInst(I.getPredicate(), Op0, Op1);
6083     }
6084   }
6085   
6086   if (isa<CastInst>(Op0)) {
6087     // Handle the special case of: icmp (cast bool to X), <cst>
6088     // This comes up when you have code like
6089     //   int X = A < B;
6090     //   if (X) ...
6091     // For generality, we handle any zero-extension of any operand comparison
6092     // with a constant or another cast from the same type.
6093     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6094       if (Instruction *R = visitICmpInstWithCastAndCast(I))
6095         return R;
6096   }
6097   
6098   // ~x < ~y --> y < x
6099   { Value *A, *B;
6100     if (match(Op0, m_Not(m_Value(A))) &&
6101         match(Op1, m_Not(m_Value(B))))
6102       return new ICmpInst(I.getPredicate(), B, A);
6103   }
6104   
6105   if (I.isEquality()) {
6106     Value *A, *B, *C, *D;
6107     
6108     // -x == -y --> x == y
6109     if (match(Op0, m_Neg(m_Value(A))) &&
6110         match(Op1, m_Neg(m_Value(B))))
6111       return new ICmpInst(I.getPredicate(), A, B);
6112     
6113     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6114       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
6115         Value *OtherVal = A == Op1 ? B : A;
6116         return new ICmpInst(I.getPredicate(), OtherVal,
6117                             Constant::getNullValue(A->getType()));
6118       }
6119
6120       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6121         // A^c1 == C^c2 --> A == C^(c1^c2)
6122         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6123           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6124             if (Op1->hasOneUse()) {
6125               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6126               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6127               return new ICmpInst(I.getPredicate(), A,
6128                                   InsertNewInstBefore(Xor, I));
6129             }
6130         
6131         // A^B == A^D -> B == D
6132         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6133         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6134         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6135         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6136       }
6137     }
6138     
6139     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6140         (A == Op0 || B == Op0)) {
6141       // A == (A^B)  ->  B == 0
6142       Value *OtherVal = A == Op0 ? B : A;
6143       return new ICmpInst(I.getPredicate(), OtherVal,
6144                           Constant::getNullValue(A->getType()));
6145     }
6146     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6147       // (A-B) == A  ->  B == 0
6148       return new ICmpInst(I.getPredicate(), B,
6149                           Constant::getNullValue(B->getType()));
6150     }
6151     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6152       // A == (A-B)  ->  B == 0
6153       return new ICmpInst(I.getPredicate(), B,
6154                           Constant::getNullValue(B->getType()));
6155     }
6156     
6157     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6158     if (Op0->hasOneUse() && Op1->hasOneUse() &&
6159         match(Op0, m_And(m_Value(A), m_Value(B))) && 
6160         match(Op1, m_And(m_Value(C), m_Value(D)))) {
6161       Value *X = 0, *Y = 0, *Z = 0;
6162       
6163       if (A == C) {
6164         X = B; Y = D; Z = A;
6165       } else if (A == D) {
6166         X = B; Y = C; Z = A;
6167       } else if (B == C) {
6168         X = A; Y = D; Z = B;
6169       } else if (B == D) {
6170         X = A; Y = C; Z = B;
6171       }
6172       
6173       if (X) {   // Build (X^Y) & Z
6174         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6175         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6176         I.setOperand(0, Op1);
6177         I.setOperand(1, Constant::getNullValue(Op1->getType()));
6178         return &I;
6179       }
6180     }
6181   }
6182   return Changed ? &I : 0;
6183 }
6184
6185
6186 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6187 /// and CmpRHS are both known to be integer constants.
6188 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6189                                           ConstantInt *DivRHS) {
6190   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6191   const APInt &CmpRHSV = CmpRHS->getValue();
6192   
6193   // FIXME: If the operand types don't match the type of the divide 
6194   // then don't attempt this transform. The code below doesn't have the
6195   // logic to deal with a signed divide and an unsigned compare (and
6196   // vice versa). This is because (x /s C1) <s C2  produces different 
6197   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6198   // (x /u C1) <u C2.  Simply casting the operands and result won't 
6199   // work. :(  The if statement below tests that condition and bails 
6200   // if it finds it. 
6201   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6202   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6203     return 0;
6204   if (DivRHS->isZero())
6205     return 0; // The ProdOV computation fails on divide by zero.
6206
6207   // Compute Prod = CI * DivRHS. We are essentially solving an equation
6208   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
6209   // C2 (CI). By solving for X we can turn this into a range check 
6210   // instead of computing a divide. 
6211   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6212
6213   // Determine if the product overflows by seeing if the product is
6214   // not equal to the divide. Make sure we do the same kind of divide
6215   // as in the LHS instruction that we're folding. 
6216   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6217                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6218
6219   // Get the ICmp opcode
6220   ICmpInst::Predicate Pred = ICI.getPredicate();
6221
6222   // Figure out the interval that is being checked.  For example, a comparison
6223   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
6224   // Compute this interval based on the constants involved and the signedness of
6225   // the compare/divide.  This computes a half-open interval, keeping track of
6226   // whether either value in the interval overflows.  After analysis each
6227   // overflow variable is set to 0 if it's corresponding bound variable is valid
6228   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6229   int LoOverflow = 0, HiOverflow = 0;
6230   ConstantInt *LoBound = 0, *HiBound = 0;
6231   
6232   
6233   if (!DivIsSigned) {  // udiv
6234     // e.g. X/5 op 3  --> [15, 20)
6235     LoBound = Prod;
6236     HiOverflow = LoOverflow = ProdOV;
6237     if (!HiOverflow)
6238       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6239   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6240     if (CmpRHSV == 0) {       // (X / pos) op 0
6241       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
6242       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6243       HiBound = DivRHS;
6244     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
6245       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
6246       HiOverflow = LoOverflow = ProdOV;
6247       if (!HiOverflow)
6248         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6249     } else {                       // (X / pos) op neg
6250       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
6251       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6252       LoOverflow = AddWithOverflow(LoBound, Prod,
6253                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
6254       HiBound = AddOne(Prod);
6255       HiOverflow = ProdOV ? -1 : 0;
6256     }
6257   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6258     if (CmpRHSV == 0) {       // (X / neg) op 0
6259       // e.g. X/-5 op 0  --> [-4, 5)
6260       LoBound = AddOne(DivRHS);
6261       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6262       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
6263         HiOverflow = 1;            // [INTMIN+1, overflow)
6264         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
6265       }
6266     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
6267       // e.g. X/-5 op 3  --> [-19, -14)
6268       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6269       if (!LoOverflow)
6270         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6271       HiBound = AddOne(Prod);
6272     } else {                       // (X / neg) op neg
6273       // e.g. X/-5 op -3  --> [15, 20)
6274       LoBound = Prod;
6275       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6276       HiBound = Subtract(Prod, DivRHS);
6277     }
6278     
6279     // Dividing by a negative swaps the condition.  LT <-> GT
6280     Pred = ICmpInst::getSwappedPredicate(Pred);
6281   }
6282
6283   Value *X = DivI->getOperand(0);
6284   switch (Pred) {
6285   default: assert(0 && "Unhandled icmp opcode!");
6286   case ICmpInst::ICMP_EQ:
6287     if (LoOverflow && HiOverflow)
6288       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6289     else if (HiOverflow)
6290       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6291                           ICmpInst::ICMP_UGE, X, LoBound);
6292     else if (LoOverflow)
6293       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6294                           ICmpInst::ICMP_ULT, X, HiBound);
6295     else
6296       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6297   case ICmpInst::ICMP_NE:
6298     if (LoOverflow && HiOverflow)
6299       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6300     else if (HiOverflow)
6301       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
6302                           ICmpInst::ICMP_ULT, X, LoBound);
6303     else if (LoOverflow)
6304       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
6305                           ICmpInst::ICMP_UGE, X, HiBound);
6306     else
6307       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6308   case ICmpInst::ICMP_ULT:
6309   case ICmpInst::ICMP_SLT:
6310     if (LoOverflow == +1)   // Low bound is greater than input range.
6311       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6312     if (LoOverflow == -1)   // Low bound is less than input range.
6313       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6314     return new ICmpInst(Pred, X, LoBound);
6315   case ICmpInst::ICMP_UGT:
6316   case ICmpInst::ICMP_SGT:
6317     if (HiOverflow == +1)       // High bound greater than input range.
6318       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6319     else if (HiOverflow == -1)  // High bound less than input range.
6320       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6321     if (Pred == ICmpInst::ICMP_UGT)
6322       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6323     else
6324       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6325   }
6326 }
6327
6328
6329 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6330 ///
6331 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6332                                                           Instruction *LHSI,
6333                                                           ConstantInt *RHS) {
6334   const APInt &RHSV = RHS->getValue();
6335   
6336   switch (LHSI->getOpcode()) {
6337   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
6338     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6339       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6340       // fold the xor.
6341       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6342           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6343         Value *CompareVal = LHSI->getOperand(0);
6344         
6345         // If the sign bit of the XorCST is not set, there is no change to
6346         // the operation, just stop using the Xor.
6347         if (!XorCST->getValue().isNegative()) {
6348           ICI.setOperand(0, CompareVal);
6349           AddToWorkList(LHSI);
6350           return &ICI;
6351         }
6352         
6353         // Was the old condition true if the operand is positive?
6354         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6355         
6356         // If so, the new one isn't.
6357         isTrueIfPositive ^= true;
6358         
6359         if (isTrueIfPositive)
6360           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6361         else
6362           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6363       }
6364     }
6365     break;
6366   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
6367     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6368         LHSI->getOperand(0)->hasOneUse()) {
6369       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6370       
6371       // If the LHS is an AND of a truncating cast, we can widen the
6372       // and/compare to be the input width without changing the value
6373       // produced, eliminating a cast.
6374       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6375         // We can do this transformation if either the AND constant does not
6376         // have its sign bit set or if it is an equality comparison. 
6377         // Extending a relational comparison when we're checking the sign
6378         // bit would not work.
6379         if (Cast->hasOneUse() &&
6380             (ICI.isEquality() ||
6381              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6382           uint32_t BitWidth = 
6383             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6384           APInt NewCST = AndCST->getValue();
6385           NewCST.zext(BitWidth);
6386           APInt NewCI = RHSV;
6387           NewCI.zext(BitWidth);
6388           Instruction *NewAnd = 
6389             BinaryOperator::CreateAnd(Cast->getOperand(0),
6390                                       ConstantInt::get(NewCST),LHSI->getName());
6391           InsertNewInstBefore(NewAnd, ICI);
6392           return new ICmpInst(ICI.getPredicate(), NewAnd,
6393                               ConstantInt::get(NewCI));
6394         }
6395       }
6396       
6397       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6398       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
6399       // happens a LOT in code produced by the C front-end, for bitfield
6400       // access.
6401       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6402       if (Shift && !Shift->isShift())
6403         Shift = 0;
6404       
6405       ConstantInt *ShAmt;
6406       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6407       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
6408       const Type *AndTy = AndCST->getType();          // Type of the and.
6409       
6410       // We can fold this as long as we can't shift unknown bits
6411       // into the mask.  This can only happen with signed shift
6412       // rights, as they sign-extend.
6413       if (ShAmt) {
6414         bool CanFold = Shift->isLogicalShift();
6415         if (!CanFold) {
6416           // To test for the bad case of the signed shr, see if any
6417           // of the bits shifted in could be tested after the mask.
6418           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6419           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6420           
6421           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6422           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
6423                AndCST->getValue()) == 0)
6424             CanFold = true;
6425         }
6426         
6427         if (CanFold) {
6428           Constant *NewCst;
6429           if (Shift->getOpcode() == Instruction::Shl)
6430             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6431           else
6432             NewCst = ConstantExpr::getShl(RHS, ShAmt);
6433           
6434           // Check to see if we are shifting out any of the bits being
6435           // compared.
6436           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6437             // If we shifted bits out, the fold is not going to work out.
6438             // As a special case, check to see if this means that the
6439             // result is always true or false now.
6440             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6441               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6442             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6443               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6444           } else {
6445             ICI.setOperand(1, NewCst);
6446             Constant *NewAndCST;
6447             if (Shift->getOpcode() == Instruction::Shl)
6448               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6449             else
6450               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6451             LHSI->setOperand(1, NewAndCST);
6452             LHSI->setOperand(0, Shift->getOperand(0));
6453             AddToWorkList(Shift); // Shift is dead.
6454             AddUsesToWorkList(ICI);
6455             return &ICI;
6456           }
6457         }
6458       }
6459       
6460       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
6461       // preferable because it allows the C<<Y expression to be hoisted out
6462       // of a loop if Y is invariant and X is not.
6463       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6464           ICI.isEquality() && !Shift->isArithmeticShift() &&
6465           isa<Instruction>(Shift->getOperand(0))) {
6466         // Compute C << Y.
6467         Value *NS;
6468         if (Shift->getOpcode() == Instruction::LShr) {
6469           NS = BinaryOperator::CreateShl(AndCST, 
6470                                          Shift->getOperand(1), "tmp");
6471         } else {
6472           // Insert a logical shift.
6473           NS = BinaryOperator::CreateLShr(AndCST,
6474                                           Shift->getOperand(1), "tmp");
6475         }
6476         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6477         
6478         // Compute X & (C << Y).
6479         Instruction *NewAnd = 
6480           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6481         InsertNewInstBefore(NewAnd, ICI);
6482         
6483         ICI.setOperand(0, NewAnd);
6484         return &ICI;
6485       }
6486     }
6487     break;
6488     
6489   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6490     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6491     if (!ShAmt) break;
6492     
6493     uint32_t TypeBits = RHSV.getBitWidth();
6494     
6495     // Check that the shift amount is in range.  If not, don't perform
6496     // undefined shifts.  When the shift is visited it will be
6497     // simplified.
6498     if (ShAmt->uge(TypeBits))
6499       break;
6500     
6501     if (ICI.isEquality()) {
6502       // If we are comparing against bits always shifted out, the
6503       // comparison cannot succeed.
6504       Constant *Comp =
6505         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6506       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6507         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6508         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6509         return ReplaceInstUsesWith(ICI, Cst);
6510       }
6511       
6512       if (LHSI->hasOneUse()) {
6513         // Otherwise strength reduce the shift into an and.
6514         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6515         Constant *Mask =
6516           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6517         
6518         Instruction *AndI =
6519           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6520                                     Mask, LHSI->getName()+".mask");
6521         Value *And = InsertNewInstBefore(AndI, ICI);
6522         return new ICmpInst(ICI.getPredicate(), And,
6523                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6524       }
6525     }
6526     
6527     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6528     bool TrueIfSigned = false;
6529     if (LHSI->hasOneUse() &&
6530         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6531       // (X << 31) <s 0  --> (X&1) != 0
6532       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6533                                            (TypeBits-ShAmt->getZExtValue()-1));
6534       Instruction *AndI =
6535         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6536                                   Mask, LHSI->getName()+".mask");
6537       Value *And = InsertNewInstBefore(AndI, ICI);
6538       
6539       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6540                           And, Constant::getNullValue(And->getType()));
6541     }
6542     break;
6543   }
6544     
6545   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6546   case Instruction::AShr: {
6547     // Only handle equality comparisons of shift-by-constant.
6548     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6549     if (!ShAmt || !ICI.isEquality()) break;
6550
6551     // Check that the shift amount is in range.  If not, don't perform
6552     // undefined shifts.  When the shift is visited it will be
6553     // simplified.
6554     uint32_t TypeBits = RHSV.getBitWidth();
6555     if (ShAmt->uge(TypeBits))
6556       break;
6557     
6558     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6559       
6560     // If we are comparing against bits always shifted out, the
6561     // comparison cannot succeed.
6562     APInt Comp = RHSV << ShAmtVal;
6563     if (LHSI->getOpcode() == Instruction::LShr)
6564       Comp = Comp.lshr(ShAmtVal);
6565     else
6566       Comp = Comp.ashr(ShAmtVal);
6567     
6568     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6569       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6570       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6571       return ReplaceInstUsesWith(ICI, Cst);
6572     }
6573     
6574     // Otherwise, check to see if the bits shifted out are known to be zero.
6575     // If so, we can compare against the unshifted value:
6576     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6577     if (LHSI->hasOneUse() &&
6578         MaskedValueIsZero(LHSI->getOperand(0), 
6579                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6580       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6581                           ConstantExpr::getShl(RHS, ShAmt));
6582     }
6583       
6584     if (LHSI->hasOneUse()) {
6585       // Otherwise strength reduce the shift into an and.
6586       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6587       Constant *Mask = ConstantInt::get(Val);
6588       
6589       Instruction *AndI =
6590         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6591                                   Mask, LHSI->getName()+".mask");
6592       Value *And = InsertNewInstBefore(AndI, ICI);
6593       return new ICmpInst(ICI.getPredicate(), And,
6594                           ConstantExpr::getShl(RHS, ShAmt));
6595     }
6596     break;
6597   }
6598     
6599   case Instruction::SDiv:
6600   case Instruction::UDiv:
6601     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6602     // Fold this div into the comparison, producing a range check. 
6603     // Determine, based on the divide type, what the range is being 
6604     // checked.  If there is an overflow on the low or high side, remember 
6605     // it, otherwise compute the range [low, hi) bounding the new value.
6606     // See: InsertRangeTest above for the kinds of replacements possible.
6607     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6608       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6609                                           DivRHS))
6610         return R;
6611     break;
6612
6613   case Instruction::Add:
6614     // Fold: icmp pred (add, X, C1), C2
6615
6616     if (!ICI.isEquality()) {
6617       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6618       if (!LHSC) break;
6619       const APInt &LHSV = LHSC->getValue();
6620
6621       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6622                             .subtract(LHSV);
6623
6624       if (ICI.isSignedPredicate()) {
6625         if (CR.getLower().isSignBit()) {
6626           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6627                               ConstantInt::get(CR.getUpper()));
6628         } else if (CR.getUpper().isSignBit()) {
6629           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6630                               ConstantInt::get(CR.getLower()));
6631         }
6632       } else {
6633         if (CR.getLower().isMinValue()) {
6634           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6635                               ConstantInt::get(CR.getUpper()));
6636         } else if (CR.getUpper().isMinValue()) {
6637           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6638                               ConstantInt::get(CR.getLower()));
6639         }
6640       }
6641     }
6642     break;
6643   }
6644   
6645   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6646   if (ICI.isEquality()) {
6647     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6648     
6649     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6650     // the second operand is a constant, simplify a bit.
6651     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6652       switch (BO->getOpcode()) {
6653       case Instruction::SRem:
6654         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6655         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6656           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6657           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6658             Instruction *NewRem =
6659               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6660                                          BO->getName());
6661             InsertNewInstBefore(NewRem, ICI);
6662             return new ICmpInst(ICI.getPredicate(), NewRem, 
6663                                 Constant::getNullValue(BO->getType()));
6664           }
6665         }
6666         break;
6667       case Instruction::Add:
6668         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6669         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6670           if (BO->hasOneUse())
6671             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6672                                 Subtract(RHS, BOp1C));
6673         } else if (RHSV == 0) {
6674           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6675           // efficiently invertible, or if the add has just this one use.
6676           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6677           
6678           if (Value *NegVal = dyn_castNegVal(BOp1))
6679             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6680           else if (Value *NegVal = dyn_castNegVal(BOp0))
6681             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6682           else if (BO->hasOneUse()) {
6683             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6684             InsertNewInstBefore(Neg, ICI);
6685             Neg->takeName(BO);
6686             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6687           }
6688         }
6689         break;
6690       case Instruction::Xor:
6691         // For the xor case, we can xor two constants together, eliminating
6692         // the explicit xor.
6693         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6694           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6695                               ConstantExpr::getXor(RHS, BOC));
6696         
6697         // FALLTHROUGH
6698       case Instruction::Sub:
6699         // Replace (([sub|xor] A, B) != 0) with (A != B)
6700         if (RHSV == 0)
6701           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702                               BO->getOperand(1));
6703         break;
6704         
6705       case Instruction::Or:
6706         // If bits are being or'd in that are not present in the constant we
6707         // are comparing against, then the comparison could never succeed!
6708         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6709           Constant *NotCI = ConstantExpr::getNot(RHS);
6710           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6711             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6712                                                              isICMP_NE));
6713         }
6714         break;
6715         
6716       case Instruction::And:
6717         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6718           // If bits are being compared against that are and'd out, then the
6719           // comparison can never succeed!
6720           if ((RHSV & ~BOC->getValue()) != 0)
6721             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6722                                                              isICMP_NE));
6723           
6724           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6725           if (RHS == BOC && RHSV.isPowerOf2())
6726             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6727                                 ICmpInst::ICMP_NE, LHSI,
6728                                 Constant::getNullValue(RHS->getType()));
6729           
6730           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6731           if (isSignBit(BOC)) {
6732             Value *X = BO->getOperand(0);
6733             Constant *Zero = Constant::getNullValue(X->getType());
6734             ICmpInst::Predicate pred = isICMP_NE ? 
6735               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6736             return new ICmpInst(pred, X, Zero);
6737           }
6738           
6739           // ((X & ~7) == 0) --> X < 8
6740           if (RHSV == 0 && isHighOnes(BOC)) {
6741             Value *X = BO->getOperand(0);
6742             Constant *NegX = ConstantExpr::getNeg(BOC);
6743             ICmpInst::Predicate pred = isICMP_NE ? 
6744               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6745             return new ICmpInst(pred, X, NegX);
6746           }
6747         }
6748       default: break;
6749       }
6750     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6751       // Handle icmp {eq|ne} <intrinsic>, intcst.
6752       if (II->getIntrinsicID() == Intrinsic::bswap) {
6753         AddToWorkList(II);
6754         ICI.setOperand(0, II->getOperand(1));
6755         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6756         return &ICI;
6757       }
6758     }
6759   } else {  // Not a ICMP_EQ/ICMP_NE
6760             // If the LHS is a cast from an integral value of the same size, 
6761             // then since we know the RHS is a constant, try to simlify.
6762     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6763       Value *CastOp = Cast->getOperand(0);
6764       const Type *SrcTy = CastOp->getType();
6765       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6766       if (SrcTy->isInteger() && 
6767           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6768         // If this is an unsigned comparison, try to make the comparison use
6769         // smaller constant values.
6770         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6771           // X u< 128 => X s> -1
6772           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6773                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6774         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6775                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6776           // X u> 127 => X s< 0
6777           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6778                               Constant::getNullValue(SrcTy));
6779         }
6780       }
6781     }
6782   }
6783   return 0;
6784 }
6785
6786 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6787 /// We only handle extending casts so far.
6788 ///
6789 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6790   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6791   Value *LHSCIOp        = LHSCI->getOperand(0);
6792   const Type *SrcTy     = LHSCIOp->getType();
6793   const Type *DestTy    = LHSCI->getType();
6794   Value *RHSCIOp;
6795
6796   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6797   // integer type is the same size as the pointer type.
6798   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6799       getTargetData().getPointerSizeInBits() == 
6800          cast<IntegerType>(DestTy)->getBitWidth()) {
6801     Value *RHSOp = 0;
6802     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6803       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6804     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6805       RHSOp = RHSC->getOperand(0);
6806       // If the pointer types don't match, insert a bitcast.
6807       if (LHSCIOp->getType() != RHSOp->getType())
6808         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6809     }
6810
6811     if (RHSOp)
6812       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6813   }
6814   
6815   // The code below only handles extension cast instructions, so far.
6816   // Enforce this.
6817   if (LHSCI->getOpcode() != Instruction::ZExt &&
6818       LHSCI->getOpcode() != Instruction::SExt)
6819     return 0;
6820
6821   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6822   bool isSignedCmp = ICI.isSignedPredicate();
6823
6824   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6825     // Not an extension from the same type?
6826     RHSCIOp = CI->getOperand(0);
6827     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6828       return 0;
6829     
6830     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6831     // and the other is a zext), then we can't handle this.
6832     if (CI->getOpcode() != LHSCI->getOpcode())
6833       return 0;
6834
6835     // Deal with equality cases early.
6836     if (ICI.isEquality())
6837       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6838
6839     // A signed comparison of sign extended values simplifies into a
6840     // signed comparison.
6841     if (isSignedCmp && isSignedExt)
6842       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6843
6844     // The other three cases all fold into an unsigned comparison.
6845     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6846   }
6847
6848   // If we aren't dealing with a constant on the RHS, exit early
6849   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6850   if (!CI)
6851     return 0;
6852
6853   // Compute the constant that would happen if we truncated to SrcTy then
6854   // reextended to DestTy.
6855   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6856   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6857
6858   // If the re-extended constant didn't change...
6859   if (Res2 == CI) {
6860     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6861     // For example, we might have:
6862     //    %A = sext short %X to uint
6863     //    %B = icmp ugt uint %A, 1330
6864     // It is incorrect to transform this into 
6865     //    %B = icmp ugt short %X, 1330 
6866     // because %A may have negative value. 
6867     //
6868     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6869     // OR operation is EQ/NE.
6870     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6871       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6872     else
6873       return 0;
6874   }
6875
6876   // The re-extended constant changed so the constant cannot be represented 
6877   // in the shorter type. Consequently, we cannot emit a simple comparison.
6878
6879   // First, handle some easy cases. We know the result cannot be equal at this
6880   // point so handle the ICI.isEquality() cases
6881   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6882     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6883   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6884     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6885
6886   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6887   // should have been folded away previously and not enter in here.
6888   Value *Result;
6889   if (isSignedCmp) {
6890     // We're performing a signed comparison.
6891     if (cast<ConstantInt>(CI)->getValue().isNegative())
6892       Result = ConstantInt::getFalse();          // X < (small) --> false
6893     else
6894       Result = ConstantInt::getTrue();           // X < (large) --> true
6895   } else {
6896     // We're performing an unsigned comparison.
6897     if (isSignedExt) {
6898       // We're performing an unsigned comp with a sign extended value.
6899       // This is true if the input is >= 0. [aka >s -1]
6900       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6901       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6902                                    NegOne, ICI.getName()), ICI);
6903     } else {
6904       // Unsigned extend & unsigned compare -> always true.
6905       Result = ConstantInt::getTrue();
6906     }
6907   }
6908
6909   // Finally, return the value computed.
6910   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6911       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6912     return ReplaceInstUsesWith(ICI, Result);
6913   } else {
6914     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6915             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6916            "ICmp should be folded!");
6917     if (Constant *CI = dyn_cast<Constant>(Result))
6918       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6919     else
6920       return BinaryOperator::CreateNot(Result);
6921   }
6922 }
6923
6924 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6925   return commonShiftTransforms(I);
6926 }
6927
6928 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6929   return commonShiftTransforms(I);
6930 }
6931
6932 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6933   if (Instruction *R = commonShiftTransforms(I))
6934     return R;
6935   
6936   Value *Op0 = I.getOperand(0);
6937   
6938   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6939   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6940     if (CSI->isAllOnesValue())
6941       return ReplaceInstUsesWith(I, CSI);
6942   
6943   // See if we can turn a signed shr into an unsigned shr.
6944   if (MaskedValueIsZero(Op0, 
6945                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6946     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6947   
6948   return 0;
6949 }
6950
6951 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6952   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6953   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6954
6955   // shl X, 0 == X and shr X, 0 == X
6956   // shl 0, X == 0 and shr 0, X == 0
6957   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6958       Op0 == Constant::getNullValue(Op0->getType()))
6959     return ReplaceInstUsesWith(I, Op0);
6960   
6961   if (isa<UndefValue>(Op0)) {            
6962     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6963       return ReplaceInstUsesWith(I, Op0);
6964     else                                    // undef << X -> 0, undef >>u X -> 0
6965       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6966   }
6967   if (isa<UndefValue>(Op1)) {
6968     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6969       return ReplaceInstUsesWith(I, Op0);          
6970     else                                     // X << undef, X >>u undef -> 0
6971       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6972   }
6973
6974   // Try to fold constant and into select arguments.
6975   if (isa<Constant>(Op0))
6976     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6977       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6978         return R;
6979
6980   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6981     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6982       return Res;
6983   return 0;
6984 }
6985
6986 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6987                                                BinaryOperator &I) {
6988   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6989
6990   // See if we can simplify any instructions used by the instruction whose sole 
6991   // purpose is to compute bits we don't care about.
6992   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6993   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6994   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6995                            KnownZero, KnownOne))
6996     return &I;
6997   
6998   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6999   // of a signed value.
7000   //
7001   if (Op1->uge(TypeBits)) {
7002     if (I.getOpcode() != Instruction::AShr)
7003       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7004     else {
7005       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7006       return &I;
7007     }
7008   }
7009   
7010   // ((X*C1) << C2) == (X * (C1 << C2))
7011   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7012     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7013       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7014         return BinaryOperator::CreateMul(BO->getOperand(0),
7015                                          ConstantExpr::getShl(BOOp, Op1));
7016   
7017   // Try to fold constant and into select arguments.
7018   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7019     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7020       return R;
7021   if (isa<PHINode>(Op0))
7022     if (Instruction *NV = FoldOpIntoPhi(I))
7023       return NV;
7024   
7025   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7026   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7027     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7028     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7029     // place.  Don't try to do this transformation in this case.  Also, we
7030     // require that the input operand is a shift-by-constant so that we have
7031     // confidence that the shifts will get folded together.  We could do this
7032     // xform in more cases, but it is unlikely to be profitable.
7033     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
7034         isa<ConstantInt>(TrOp->getOperand(1))) {
7035       // Okay, we'll do this xform.  Make the shift of shift.
7036       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7037       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7038                                                 I.getName());
7039       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7040
7041       // For logical shifts, the truncation has the effect of making the high
7042       // part of the register be zeros.  Emulate this by inserting an AND to
7043       // clear the top bits as needed.  This 'and' will usually be zapped by
7044       // other xforms later if dead.
7045       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7046       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7047       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7048       
7049       // The mask we constructed says what the trunc would do if occurring
7050       // between the shifts.  We want to know the effect *after* the second
7051       // shift.  We know that it is a logical shift by a constant, so adjust the
7052       // mask as appropriate.
7053       if (I.getOpcode() == Instruction::Shl)
7054         MaskV <<= Op1->getZExtValue();
7055       else {
7056         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7057         MaskV = MaskV.lshr(Op1->getZExtValue());
7058       }
7059
7060       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7061                                                    TI->getName());
7062       InsertNewInstBefore(And, I); // shift1 & 0x00FF
7063
7064       // Return the value truncated to the interesting size.
7065       return new TruncInst(And, I.getType());
7066     }
7067   }
7068   
7069   if (Op0->hasOneUse()) {
7070     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7071       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7072       Value *V1, *V2;
7073       ConstantInt *CC;
7074       switch (Op0BO->getOpcode()) {
7075         default: break;
7076         case Instruction::Add:
7077         case Instruction::And:
7078         case Instruction::Or:
7079         case Instruction::Xor: {
7080           // These operators commute.
7081           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
7082           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7083               match(Op0BO->getOperand(1),
7084                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7085             Instruction *YS = BinaryOperator::CreateShl(
7086                                             Op0BO->getOperand(0), Op1,
7087                                             Op0BO->getName());
7088             InsertNewInstBefore(YS, I); // (Y << C)
7089             Instruction *X = 
7090               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7091                                      Op0BO->getOperand(1)->getName());
7092             InsertNewInstBefore(X, I);  // (X + (Y << C))
7093             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7094             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7095                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7096           }
7097           
7098           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
7099           Value *Op0BOOp1 = Op0BO->getOperand(1);
7100           if (isLeftShift && Op0BOOp1->hasOneUse() &&
7101               match(Op0BOOp1, 
7102                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
7103               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7104               V2 == Op1) {
7105             Instruction *YS = BinaryOperator::CreateShl(
7106                                                      Op0BO->getOperand(0), Op1,
7107                                                      Op0BO->getName());
7108             InsertNewInstBefore(YS, I); // (Y << C)
7109             Instruction *XM =
7110               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7111                                         V1->getName()+".mask");
7112             InsertNewInstBefore(XM, I); // X & (CC << C)
7113             
7114             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7115           }
7116         }
7117           
7118         // FALL THROUGH.
7119         case Instruction::Sub: {
7120           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
7121           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7122               match(Op0BO->getOperand(0),
7123                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7124             Instruction *YS = BinaryOperator::CreateShl(
7125                                                      Op0BO->getOperand(1), Op1,
7126                                                      Op0BO->getName());
7127             InsertNewInstBefore(YS, I); // (Y << C)
7128             Instruction *X =
7129               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7130                                      Op0BO->getOperand(0)->getName());
7131             InsertNewInstBefore(X, I);  // (X + (Y << C))
7132             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7133             return BinaryOperator::CreateAnd(X, ConstantInt::get(
7134                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7135           }
7136           
7137           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
7138           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7139               match(Op0BO->getOperand(0),
7140                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
7141                           m_ConstantInt(CC))) && V2 == Op1 &&
7142               cast<BinaryOperator>(Op0BO->getOperand(0))
7143                   ->getOperand(0)->hasOneUse()) {
7144             Instruction *YS = BinaryOperator::CreateShl(
7145                                                      Op0BO->getOperand(1), Op1,
7146                                                      Op0BO->getName());
7147             InsertNewInstBefore(YS, I); // (Y << C)
7148             Instruction *XM =
7149               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7150                                         V1->getName()+".mask");
7151             InsertNewInstBefore(XM, I); // X & (CC << C)
7152             
7153             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7154           }
7155           
7156           break;
7157         }
7158       }
7159       
7160       
7161       // If the operand is an bitwise operator with a constant RHS, and the
7162       // shift is the only use, we can pull it out of the shift.
7163       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7164         bool isValid = true;     // Valid only for And, Or, Xor
7165         bool highBitSet = false; // Transform if high bit of constant set?
7166         
7167         switch (Op0BO->getOpcode()) {
7168           default: isValid = false; break;   // Do not perform transform!
7169           case Instruction::Add:
7170             isValid = isLeftShift;
7171             break;
7172           case Instruction::Or:
7173           case Instruction::Xor:
7174             highBitSet = false;
7175             break;
7176           case Instruction::And:
7177             highBitSet = true;
7178             break;
7179         }
7180         
7181         // If this is a signed shift right, and the high bit is modified
7182         // by the logical operation, do not perform the transformation.
7183         // The highBitSet boolean indicates the value of the high bit of
7184         // the constant which would cause it to be modified for this
7185         // operation.
7186         //
7187         if (isValid && I.getOpcode() == Instruction::AShr)
7188           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7189         
7190         if (isValid) {
7191           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7192           
7193           Instruction *NewShift =
7194             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7195           InsertNewInstBefore(NewShift, I);
7196           NewShift->takeName(Op0BO);
7197           
7198           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7199                                         NewRHS);
7200         }
7201       }
7202     }
7203   }
7204   
7205   // Find out if this is a shift of a shift by a constant.
7206   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7207   if (ShiftOp && !ShiftOp->isShift())
7208     ShiftOp = 0;
7209   
7210   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7211     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7212     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7213     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7214     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7215     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
7216     Value *X = ShiftOp->getOperand(0);
7217     
7218     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
7219     if (AmtSum > TypeBits)
7220       AmtSum = TypeBits;
7221     
7222     const IntegerType *Ty = cast<IntegerType>(I.getType());
7223     
7224     // Check for (X << c1) << c2  and  (X >> c1) >> c2
7225     if (I.getOpcode() == ShiftOp->getOpcode()) {
7226       return BinaryOperator::Create(I.getOpcode(), X,
7227                                     ConstantInt::get(Ty, AmtSum));
7228     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7229                I.getOpcode() == Instruction::AShr) {
7230       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
7231       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7232     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7233                I.getOpcode() == Instruction::LShr) {
7234       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7235       Instruction *Shift =
7236         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7237       InsertNewInstBefore(Shift, I);
7238
7239       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7240       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7241     }
7242     
7243     // Okay, if we get here, one shift must be left, and the other shift must be
7244     // right.  See if the amounts are equal.
7245     if (ShiftAmt1 == ShiftAmt2) {
7246       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7247       if (I.getOpcode() == Instruction::Shl) {
7248         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7249         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7250       }
7251       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7252       if (I.getOpcode() == Instruction::LShr) {
7253         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7254         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7255       }
7256       // We can simplify ((X << C) >>s C) into a trunc + sext.
7257       // NOTE: we could do this for any C, but that would make 'unusual' integer
7258       // types.  For now, just stick to ones well-supported by the code
7259       // generators.
7260       const Type *SExtType = 0;
7261       switch (Ty->getBitWidth() - ShiftAmt1) {
7262       case 1  :
7263       case 8  :
7264       case 16 :
7265       case 32 :
7266       case 64 :
7267       case 128:
7268         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7269         break;
7270       default: break;
7271       }
7272       if (SExtType) {
7273         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7274         InsertNewInstBefore(NewTrunc, I);
7275         return new SExtInst(NewTrunc, Ty);
7276       }
7277       // Otherwise, we can't handle it yet.
7278     } else if (ShiftAmt1 < ShiftAmt2) {
7279       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7280       
7281       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7282       if (I.getOpcode() == Instruction::Shl) {
7283         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7284                ShiftOp->getOpcode() == Instruction::AShr);
7285         Instruction *Shift =
7286           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7287         InsertNewInstBefore(Shift, I);
7288         
7289         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7290         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7291       }
7292       
7293       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
7294       if (I.getOpcode() == Instruction::LShr) {
7295         assert(ShiftOp->getOpcode() == Instruction::Shl);
7296         Instruction *Shift =
7297           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7298         InsertNewInstBefore(Shift, I);
7299         
7300         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7301         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7302       }
7303       
7304       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7305     } else {
7306       assert(ShiftAmt2 < ShiftAmt1);
7307       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7308
7309       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7310       if (I.getOpcode() == Instruction::Shl) {
7311         assert(ShiftOp->getOpcode() == Instruction::LShr ||
7312                ShiftOp->getOpcode() == Instruction::AShr);
7313         Instruction *Shift =
7314           BinaryOperator::Create(ShiftOp->getOpcode(), X,
7315                                  ConstantInt::get(Ty, ShiftDiff));
7316         InsertNewInstBefore(Shift, I);
7317         
7318         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7319         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7320       }
7321       
7322       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
7323       if (I.getOpcode() == Instruction::LShr) {
7324         assert(ShiftOp->getOpcode() == Instruction::Shl);
7325         Instruction *Shift =
7326           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7327         InsertNewInstBefore(Shift, I);
7328         
7329         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7330         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7331       }
7332       
7333       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7334     }
7335   }
7336   return 0;
7337 }
7338
7339
7340 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7341 /// expression.  If so, decompose it, returning some value X, such that Val is
7342 /// X*Scale+Offset.
7343 ///
7344 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7345                                         int &Offset) {
7346   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7347   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7348     Offset = CI->getZExtValue();
7349     Scale  = 0;
7350     return ConstantInt::get(Type::Int32Ty, 0);
7351   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7352     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7353       if (I->getOpcode() == Instruction::Shl) {
7354         // This is a value scaled by '1 << the shift amt'.
7355         Scale = 1U << RHS->getZExtValue();
7356         Offset = 0;
7357         return I->getOperand(0);
7358       } else if (I->getOpcode() == Instruction::Mul) {
7359         // This value is scaled by 'RHS'.
7360         Scale = RHS->getZExtValue();
7361         Offset = 0;
7362         return I->getOperand(0);
7363       } else if (I->getOpcode() == Instruction::Add) {
7364         // We have X+C.  Check to see if we really have (X*C2)+C1, 
7365         // where C1 is divisible by C2.
7366         unsigned SubScale;
7367         Value *SubVal = 
7368           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7369         Offset += RHS->getZExtValue();
7370         Scale = SubScale;
7371         return SubVal;
7372       }
7373     }
7374   }
7375
7376   // Otherwise, we can't look past this.
7377   Scale = 1;
7378   Offset = 0;
7379   return Val;
7380 }
7381
7382
7383 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7384 /// try to eliminate the cast by moving the type information into the alloc.
7385 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7386                                                    AllocationInst &AI) {
7387   const PointerType *PTy = cast<PointerType>(CI.getType());
7388   
7389   // Remove any uses of AI that are dead.
7390   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7391   
7392   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7393     Instruction *User = cast<Instruction>(*UI++);
7394     if (isInstructionTriviallyDead(User)) {
7395       while (UI != E && *UI == User)
7396         ++UI; // If this instruction uses AI more than once, don't break UI.
7397       
7398       ++NumDeadInst;
7399       DOUT << "IC: DCE: " << *User;
7400       EraseInstFromFunction(*User);
7401     }
7402   }
7403   
7404   // Get the type really allocated and the type casted to.
7405   const Type *AllocElTy = AI.getAllocatedType();
7406   const Type *CastElTy = PTy->getElementType();
7407   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7408
7409   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7410   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7411   if (CastElTyAlign < AllocElTyAlign) return 0;
7412
7413   // If the allocation has multiple uses, only promote it if we are strictly
7414   // increasing the alignment of the resultant allocation.  If we keep it the
7415   // same, we open the door to infinite loops of various kinds.
7416   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7417
7418   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7419   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7420   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7421
7422   // See if we can satisfy the modulus by pulling a scale out of the array
7423   // size argument.
7424   unsigned ArraySizeScale;
7425   int ArrayOffset;
7426   Value *NumElements = // See if the array size is a decomposable linear expr.
7427     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7428  
7429   // If we can now satisfy the modulus, by using a non-1 scale, we really can
7430   // do the xform.
7431   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7432       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
7433
7434   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7435   Value *Amt = 0;
7436   if (Scale == 1) {
7437     Amt = NumElements;
7438   } else {
7439     // If the allocation size is constant, form a constant mul expression
7440     Amt = ConstantInt::get(Type::Int32Ty, Scale);
7441     if (isa<ConstantInt>(NumElements))
7442       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7443     // otherwise multiply the amount and the number of elements
7444     else if (Scale != 1) {
7445       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7446       Amt = InsertNewInstBefore(Tmp, AI);
7447     }
7448   }
7449   
7450   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7451     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7452     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7453     Amt = InsertNewInstBefore(Tmp, AI);
7454   }
7455   
7456   AllocationInst *New;
7457   if (isa<MallocInst>(AI))
7458     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7459   else
7460     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7461   InsertNewInstBefore(New, AI);
7462   New->takeName(&AI);
7463   
7464   // If the allocation has multiple uses, insert a cast and change all things
7465   // that used it to use the new cast.  This will also hack on CI, but it will
7466   // die soon.
7467   if (!AI.hasOneUse()) {
7468     AddUsesToWorkList(AI);
7469     // New is the allocation instruction, pointer typed. AI is the original
7470     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7471     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7472     InsertNewInstBefore(NewCast, AI);
7473     AI.replaceAllUsesWith(NewCast);
7474   }
7475   return ReplaceInstUsesWith(CI, New);
7476 }
7477
7478 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7479 /// and return it as type Ty without inserting any new casts and without
7480 /// changing the computed value.  This is used by code that tries to decide
7481 /// whether promoting or shrinking integer operations to wider or smaller types
7482 /// will allow us to eliminate a truncate or extend.
7483 ///
7484 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7485 /// extension operation if Ty is larger.
7486 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7487                                               unsigned CastOpc,
7488                                               int &NumCastsRemoved) {
7489   // We can always evaluate constants in another type.
7490   if (isa<ConstantInt>(V))
7491     return true;
7492   
7493   Instruction *I = dyn_cast<Instruction>(V);
7494   if (!I) return false;
7495   
7496   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7497   
7498   // If this is an extension or truncate, we can often eliminate it.
7499   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7500     // If this is a cast from the destination type, we can trivially eliminate
7501     // it, and this will remove a cast overall.
7502     if (I->getOperand(0)->getType() == Ty) {
7503       // If the first operand is itself a cast, and is eliminable, do not count
7504       // this as an eliminable cast.  We would prefer to eliminate those two
7505       // casts first.
7506       if (!isa<CastInst>(I->getOperand(0)))
7507         ++NumCastsRemoved;
7508       return true;
7509     }
7510   }
7511
7512   // We can't extend or shrink something that has multiple uses: doing so would
7513   // require duplicating the instruction in general, which isn't profitable.
7514   if (!I->hasOneUse()) return false;
7515
7516   switch (I->getOpcode()) {
7517   case Instruction::Add:
7518   case Instruction::Sub:
7519   case Instruction::And:
7520   case Instruction::Or:
7521   case Instruction::Xor:
7522     // These operators can all arbitrarily be extended or truncated.
7523     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7524                                       NumCastsRemoved) &&
7525            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7526                                       NumCastsRemoved);
7527
7528   case Instruction::Mul:
7529     // A multiply can be truncated by truncating its operands.
7530     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
7531            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7532                                       NumCastsRemoved) &&
7533            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7534                                       NumCastsRemoved);
7535
7536   case Instruction::Shl:
7537     // If we are truncating the result of this SHL, and if it's a shift of a
7538     // constant amount, we can always perform a SHL in a smaller type.
7539     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7540       uint32_t BitWidth = Ty->getBitWidth();
7541       if (BitWidth < OrigTy->getBitWidth() && 
7542           CI->getLimitedValue(BitWidth) < BitWidth)
7543         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7544                                           NumCastsRemoved);
7545     }
7546     break;
7547   case Instruction::LShr:
7548     // If this is a truncate of a logical shr, we can truncate it to a smaller
7549     // lshr iff we know that the bits we would otherwise be shifting in are
7550     // already zeros.
7551     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7552       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7553       uint32_t BitWidth = Ty->getBitWidth();
7554       if (BitWidth < OrigBitWidth &&
7555           MaskedValueIsZero(I->getOperand(0),
7556             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7557           CI->getLimitedValue(BitWidth) < BitWidth) {
7558         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7559                                           NumCastsRemoved);
7560       }
7561     }
7562     break;
7563   case Instruction::ZExt:
7564   case Instruction::SExt:
7565   case Instruction::Trunc:
7566     // If this is the same kind of case as our original (e.g. zext+zext), we
7567     // can safely replace it.  Note that replacing it does not reduce the number
7568     // of casts in the input.
7569     if (I->getOpcode() == CastOpc)
7570       return true;
7571     
7572     break;
7573   default:
7574     // TODO: Can handle more cases here.
7575     break;
7576   }
7577   
7578   return false;
7579 }
7580
7581 /// EvaluateInDifferentType - Given an expression that 
7582 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7583 /// evaluate the expression.
7584 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7585                                              bool isSigned) {
7586   if (Constant *C = dyn_cast<Constant>(V))
7587     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7588
7589   // Otherwise, it must be an instruction.
7590   Instruction *I = cast<Instruction>(V);
7591   Instruction *Res = 0;
7592   switch (I->getOpcode()) {
7593   case Instruction::Add:
7594   case Instruction::Sub:
7595   case Instruction::Mul:
7596   case Instruction::And:
7597   case Instruction::Or:
7598   case Instruction::Xor:
7599   case Instruction::AShr:
7600   case Instruction::LShr:
7601   case Instruction::Shl: {
7602     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7603     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7604     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7605                                  LHS, RHS, I->getName());
7606     break;
7607   }    
7608   case Instruction::Trunc:
7609   case Instruction::ZExt:
7610   case Instruction::SExt:
7611     // If the source type of the cast is the type we're trying for then we can
7612     // just return the source.  There's no need to insert it because it is not
7613     // new.
7614     if (I->getOperand(0)->getType() == Ty)
7615       return I->getOperand(0);
7616     
7617     // Otherwise, must be the same type of case, so just reinsert a new one.
7618     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7619                            Ty, I->getName());
7620     break;
7621   default: 
7622     // TODO: Can handle more cases here.
7623     assert(0 && "Unreachable!");
7624     break;
7625   }
7626   
7627   return InsertNewInstBefore(Res, *I);
7628 }
7629
7630 /// @brief Implement the transforms common to all CastInst visitors.
7631 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7632   Value *Src = CI.getOperand(0);
7633
7634   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7635   // eliminate it now.
7636   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7637     if (Instruction::CastOps opc = 
7638         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7639       // The first cast (CSrc) is eliminable so we need to fix up or replace
7640       // the second cast (CI). CSrc will then have a good chance of being dead.
7641       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7642     }
7643   }
7644
7645   // If we are casting a select then fold the cast into the select
7646   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7647     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7648       return NV;
7649
7650   // If we are casting a PHI then fold the cast into the PHI
7651   if (isa<PHINode>(Src))
7652     if (Instruction *NV = FoldOpIntoPhi(CI))
7653       return NV;
7654   
7655   return 0;
7656 }
7657
7658 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7659 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7660   Value *Src = CI.getOperand(0);
7661   
7662   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7663     // If casting the result of a getelementptr instruction with no offset, turn
7664     // this into a cast of the original pointer!
7665     if (GEP->hasAllZeroIndices()) {
7666       // Changing the cast operand is usually not a good idea but it is safe
7667       // here because the pointer operand is being replaced with another 
7668       // pointer operand so the opcode doesn't need to change.
7669       AddToWorkList(GEP);
7670       CI.setOperand(0, GEP->getOperand(0));
7671       return &CI;
7672     }
7673     
7674     // If the GEP has a single use, and the base pointer is a bitcast, and the
7675     // GEP computes a constant offset, see if we can convert these three
7676     // instructions into fewer.  This typically happens with unions and other
7677     // non-type-safe code.
7678     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7679       if (GEP->hasAllConstantIndices()) {
7680         // We are guaranteed to get a constant from EmitGEPOffset.
7681         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7682         int64_t Offset = OffsetV->getSExtValue();
7683         
7684         // Get the base pointer input of the bitcast, and the type it points to.
7685         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7686         const Type *GEPIdxTy =
7687           cast<PointerType>(OrigBase->getType())->getElementType();
7688         if (GEPIdxTy->isSized()) {
7689           SmallVector<Value*, 8> NewIndices;
7690           
7691           // Start with the index over the outer type.  Note that the type size
7692           // might be zero (even if the offset isn't zero) if the indexed type
7693           // is something like [0 x {int, int}]
7694           const Type *IntPtrTy = TD->getIntPtrType();
7695           int64_t FirstIdx = 0;
7696           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7697             FirstIdx = Offset/TySize;
7698             Offset %= TySize;
7699           
7700             // Handle silly modulus not returning values values [0..TySize).
7701             if (Offset < 0) {
7702               --FirstIdx;
7703               Offset += TySize;
7704               assert(Offset >= 0);
7705             }
7706             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7707           }
7708           
7709           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7710
7711           // Index into the types.  If we fail, set OrigBase to null.
7712           while (Offset) {
7713             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7714               const StructLayout *SL = TD->getStructLayout(STy);
7715               if (Offset < (int64_t)SL->getSizeInBytes()) {
7716                 unsigned Elt = SL->getElementContainingOffset(Offset);
7717                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7718               
7719                 Offset -= SL->getElementOffset(Elt);
7720                 GEPIdxTy = STy->getElementType(Elt);
7721               } else {
7722                 // Otherwise, we can't index into this, bail out.
7723                 Offset = 0;
7724                 OrigBase = 0;
7725               }
7726             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7727               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7728               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7729                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7730                 Offset %= EltSize;
7731               } else {
7732                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7733               }
7734               GEPIdxTy = STy->getElementType();
7735             } else {
7736               // Otherwise, we can't index into this, bail out.
7737               Offset = 0;
7738               OrigBase = 0;
7739             }
7740           }
7741           if (OrigBase) {
7742             // If we were able to index down into an element, create the GEP
7743             // and bitcast the result.  This eliminates one bitcast, potentially
7744             // two.
7745             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7746                                                           NewIndices.begin(),
7747                                                           NewIndices.end(), "");
7748             InsertNewInstBefore(NGEP, CI);
7749             NGEP->takeName(GEP);
7750             
7751             if (isa<BitCastInst>(CI))
7752               return new BitCastInst(NGEP, CI.getType());
7753             assert(isa<PtrToIntInst>(CI));
7754             return new PtrToIntInst(NGEP, CI.getType());
7755           }
7756         }
7757       }      
7758     }
7759   }
7760     
7761   return commonCastTransforms(CI);
7762 }
7763
7764
7765
7766 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7767 /// integer types. This function implements the common transforms for all those
7768 /// cases.
7769 /// @brief Implement the transforms common to CastInst with integer operands
7770 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7771   if (Instruction *Result = commonCastTransforms(CI))
7772     return Result;
7773
7774   Value *Src = CI.getOperand(0);
7775   const Type *SrcTy = Src->getType();
7776   const Type *DestTy = CI.getType();
7777   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7778   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7779
7780   // See if we can simplify any instructions used by the LHS whose sole 
7781   // purpose is to compute bits we don't care about.
7782   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7783   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7784                            KnownZero, KnownOne))
7785     return &CI;
7786
7787   // If the source isn't an instruction or has more than one use then we
7788   // can't do anything more. 
7789   Instruction *SrcI = dyn_cast<Instruction>(Src);
7790   if (!SrcI || !Src->hasOneUse())
7791     return 0;
7792
7793   // Attempt to propagate the cast into the instruction for int->int casts.
7794   int NumCastsRemoved = 0;
7795   if (!isa<BitCastInst>(CI) &&
7796       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7797                                  CI.getOpcode(), NumCastsRemoved)) {
7798     // If this cast is a truncate, evaluting in a different type always
7799     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7800     // we need to do an AND to maintain the clear top-part of the computation,
7801     // so we require that the input have eliminated at least one cast.  If this
7802     // is a sign extension, we insert two new casts (to do the extension) so we
7803     // require that two casts have been eliminated.
7804     bool DoXForm;
7805     switch (CI.getOpcode()) {
7806     default:
7807       // All the others use floating point so we shouldn't actually 
7808       // get here because of the check above.
7809       assert(0 && "Unknown cast type");
7810     case Instruction::Trunc:
7811       DoXForm = true;
7812       break;
7813     case Instruction::ZExt:
7814       DoXForm = NumCastsRemoved >= 1;
7815       break;
7816     case Instruction::SExt:
7817       DoXForm = NumCastsRemoved >= 2;
7818       break;
7819     }
7820     
7821     if (DoXForm) {
7822       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7823                                            CI.getOpcode() == Instruction::SExt);
7824       assert(Res->getType() == DestTy);
7825       switch (CI.getOpcode()) {
7826       default: assert(0 && "Unknown cast type!");
7827       case Instruction::Trunc:
7828       case Instruction::BitCast:
7829         // Just replace this cast with the result.
7830         return ReplaceInstUsesWith(CI, Res);
7831       case Instruction::ZExt: {
7832         // We need to emit an AND to clear the high bits.
7833         assert(SrcBitSize < DestBitSize && "Not a zext?");
7834         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7835                                                             SrcBitSize));
7836         return BinaryOperator::CreateAnd(Res, C);
7837       }
7838       case Instruction::SExt:
7839         // We need to emit a cast to truncate, then a cast to sext.
7840         return CastInst::Create(Instruction::SExt,
7841             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7842                              CI), DestTy);
7843       }
7844     }
7845   }
7846   
7847   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7848   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7849
7850   switch (SrcI->getOpcode()) {
7851   case Instruction::Add:
7852   case Instruction::Mul:
7853   case Instruction::And:
7854   case Instruction::Or:
7855   case Instruction::Xor:
7856     // If we are discarding information, rewrite.
7857     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7858       // Don't insert two casts if they cannot be eliminated.  We allow 
7859       // two casts to be inserted if the sizes are the same.  This could 
7860       // only be converting signedness, which is a noop.
7861       if (DestBitSize == SrcBitSize || 
7862           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7863           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7864         Instruction::CastOps opcode = CI.getOpcode();
7865         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7866         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7867         return BinaryOperator::Create(
7868             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7869       }
7870     }
7871
7872     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7873     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7874         SrcI->getOpcode() == Instruction::Xor &&
7875         Op1 == ConstantInt::getTrue() &&
7876         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7877       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7878       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7879     }
7880     break;
7881   case Instruction::SDiv:
7882   case Instruction::UDiv:
7883   case Instruction::SRem:
7884   case Instruction::URem:
7885     // If we are just changing the sign, rewrite.
7886     if (DestBitSize == SrcBitSize) {
7887       // Don't insert two casts if they cannot be eliminated.  We allow 
7888       // two casts to be inserted if the sizes are the same.  This could 
7889       // only be converting signedness, which is a noop.
7890       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7891           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7892         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7893                                               Op0, DestTy, SrcI);
7894         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7895                                               Op1, DestTy, SrcI);
7896         return BinaryOperator::Create(
7897           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7898       }
7899     }
7900     break;
7901
7902   case Instruction::Shl:
7903     // Allow changing the sign of the source operand.  Do not allow 
7904     // changing the size of the shift, UNLESS the shift amount is a 
7905     // constant.  We must not change variable sized shifts to a smaller 
7906     // size, because it is undefined to shift more bits out than exist 
7907     // in the value.
7908     if (DestBitSize == SrcBitSize ||
7909         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7910       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7911           Instruction::BitCast : Instruction::Trunc);
7912       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7913       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7914       return BinaryOperator::CreateShl(Op0c, Op1c);
7915     }
7916     break;
7917   case Instruction::AShr:
7918     // If this is a signed shr, and if all bits shifted in are about to be
7919     // truncated off, turn it into an unsigned shr to allow greater
7920     // simplifications.
7921     if (DestBitSize < SrcBitSize &&
7922         isa<ConstantInt>(Op1)) {
7923       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7924       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7925         // Insert the new logical shift right.
7926         return BinaryOperator::CreateLShr(Op0, Op1);
7927       }
7928     }
7929     break;
7930   }
7931   return 0;
7932 }
7933
7934 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7935   if (Instruction *Result = commonIntCastTransforms(CI))
7936     return Result;
7937   
7938   Value *Src = CI.getOperand(0);
7939   const Type *Ty = CI.getType();
7940   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7941   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7942   
7943   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7944     switch (SrcI->getOpcode()) {
7945     default: break;
7946     case Instruction::LShr:
7947       // We can shrink lshr to something smaller if we know the bits shifted in
7948       // are already zeros.
7949       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7950         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7951         
7952         // Get a mask for the bits shifting in.
7953         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7954         Value* SrcIOp0 = SrcI->getOperand(0);
7955         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7956           if (ShAmt >= DestBitWidth)        // All zeros.
7957             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7958
7959           // Okay, we can shrink this.  Truncate the input, then return a new
7960           // shift.
7961           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7962           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7963                                        Ty, CI);
7964           return BinaryOperator::CreateLShr(V1, V2);
7965         }
7966       } else {     // This is a variable shr.
7967         
7968         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7969         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7970         // loop-invariant and CSE'd.
7971         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7972           Value *One = ConstantInt::get(SrcI->getType(), 1);
7973
7974           Value *V = InsertNewInstBefore(
7975               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7976                                      "tmp"), CI);
7977           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7978                                                             SrcI->getOperand(0),
7979                                                             "tmp"), CI);
7980           Value *Zero = Constant::getNullValue(V->getType());
7981           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7982         }
7983       }
7984       break;
7985     }
7986   }
7987   
7988   return 0;
7989 }
7990
7991 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7992 /// in order to eliminate the icmp.
7993 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7994                                              bool DoXform) {
7995   // If we are just checking for a icmp eq of a single bit and zext'ing it
7996   // to an integer, then shift the bit to the appropriate place and then
7997   // cast to integer to avoid the comparison.
7998   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7999     const APInt &Op1CV = Op1C->getValue();
8000       
8001     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
8002     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
8003     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8004         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8005       if (!DoXform) return ICI;
8006
8007       Value *In = ICI->getOperand(0);
8008       Value *Sh = ConstantInt::get(In->getType(),
8009                                    In->getType()->getPrimitiveSizeInBits()-1);
8010       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8011                                                         In->getName()+".lobit"),
8012                                CI);
8013       if (In->getType() != CI.getType())
8014         In = CastInst::CreateIntegerCast(In, CI.getType(),
8015                                          false/*ZExt*/, "tmp", &CI);
8016
8017       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8018         Constant *One = ConstantInt::get(In->getType(), 1);
8019         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8020                                                          In->getName()+".not"),
8021                                  CI);
8022       }
8023
8024       return ReplaceInstUsesWith(CI, In);
8025     }
8026       
8027       
8028       
8029     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
8030     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8031     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
8032     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
8033     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
8034     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
8035     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
8036     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8037     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
8038         // This only works for EQ and NE
8039         ICI->isEquality()) {
8040       // If Op1C some other power of two, convert:
8041       uint32_t BitWidth = Op1C->getType()->getBitWidth();
8042       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8043       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8044       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8045         
8046       APInt KnownZeroMask(~KnownZero);
8047       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8048         if (!DoXform) return ICI;
8049
8050         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8051         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8052           // (X&4) == 2 --> false
8053           // (X&4) != 2 --> true
8054           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8055           Res = ConstantExpr::getZExt(Res, CI.getType());
8056           return ReplaceInstUsesWith(CI, Res);
8057         }
8058           
8059         uint32_t ShiftAmt = KnownZeroMask.logBase2();
8060         Value *In = ICI->getOperand(0);
8061         if (ShiftAmt) {
8062           // Perform a logical shr by shiftamt.
8063           // Insert the shift to put the result in the low bit.
8064           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8065                                   ConstantInt::get(In->getType(), ShiftAmt),
8066                                                    In->getName()+".lobit"), CI);
8067         }
8068           
8069         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8070           Constant *One = ConstantInt::get(In->getType(), 1);
8071           In = BinaryOperator::CreateXor(In, One, "tmp");
8072           InsertNewInstBefore(cast<Instruction>(In), CI);
8073         }
8074           
8075         if (CI.getType() == In->getType())
8076           return ReplaceInstUsesWith(CI, In);
8077         else
8078           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8079       }
8080     }
8081   }
8082
8083   return 0;
8084 }
8085
8086 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8087   // If one of the common conversion will work ..
8088   if (Instruction *Result = commonIntCastTransforms(CI))
8089     return Result;
8090
8091   Value *Src = CI.getOperand(0);
8092
8093   // If this is a cast of a cast
8094   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
8095     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8096     // types and if the sizes are just right we can convert this into a logical
8097     // 'and' which will be much cheaper than the pair of casts.
8098     if (isa<TruncInst>(CSrc)) {
8099       // Get the sizes of the types involved
8100       Value *A = CSrc->getOperand(0);
8101       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8102       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8103       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8104       // If we're actually extending zero bits and the trunc is a no-op
8105       if (MidSize < DstSize && SrcSize == DstSize) {
8106         // Replace both of the casts with an And of the type mask.
8107         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8108         Constant *AndConst = ConstantInt::get(AndValue);
8109         Instruction *And = 
8110           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8111         // Unfortunately, if the type changed, we need to cast it back.
8112         if (And->getType() != CI.getType()) {
8113           And->setName(CSrc->getName()+".mask");
8114           InsertNewInstBefore(And, CI);
8115           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8116         }
8117         return And;
8118       }
8119     }
8120   }
8121
8122   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8123     return transformZExtICmp(ICI, CI);
8124
8125   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8126   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8127     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8128     // of the (zext icmp) will be transformed.
8129     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8130     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8131     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8132         (transformZExtICmp(LHS, CI, false) ||
8133          transformZExtICmp(RHS, CI, false))) {
8134       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8135       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8136       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8137     }
8138   }
8139
8140   return 0;
8141 }
8142
8143 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8144   if (Instruction *I = commonIntCastTransforms(CI))
8145     return I;
8146   
8147   Value *Src = CI.getOperand(0);
8148   
8149   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
8150   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
8151   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8152     // If we are just checking for a icmp eq of a single bit and zext'ing it
8153     // to an integer, then shift the bit to the appropriate place and then
8154     // cast to integer to avoid the comparison.
8155     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8156       const APInt &Op1CV = Op1C->getValue();
8157       
8158       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
8159       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
8160       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8161           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8162         Value *In = ICI->getOperand(0);
8163         Value *Sh = ConstantInt::get(In->getType(),
8164                                      In->getType()->getPrimitiveSizeInBits()-1);
8165         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8166                                                         In->getName()+".lobit"),
8167                                  CI);
8168         if (In->getType() != CI.getType())
8169           In = CastInst::CreateIntegerCast(In, CI.getType(),
8170                                            true/*SExt*/, "tmp", &CI);
8171         
8172         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
8173           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8174                                      In->getName()+".not"), CI);
8175         
8176         return ReplaceInstUsesWith(CI, In);
8177       }
8178     }
8179   }
8180
8181   // See if the value being truncated is already sign extended.  If so, just
8182   // eliminate the trunc/sext pair.
8183   if (getOpcode(Src) == Instruction::Trunc) {
8184     Value *Op = cast<User>(Src)->getOperand(0);
8185     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
8186     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
8187     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8188     unsigned NumSignBits = ComputeNumSignBits(Op);
8189
8190     if (OpBits == DestBits) {
8191       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
8192       // bits, it is already ready.
8193       if (NumSignBits > DestBits-MidBits)
8194         return ReplaceInstUsesWith(CI, Op);
8195     } else if (OpBits < DestBits) {
8196       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
8197       // bits, just sext from i32.
8198       if (NumSignBits > OpBits-MidBits)
8199         return new SExtInst(Op, CI.getType(), "tmp");
8200     } else {
8201       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
8202       // bits, just truncate to i32.
8203       if (NumSignBits > OpBits-MidBits)
8204         return new TruncInst(Op, CI.getType(), "tmp");
8205     }
8206   }
8207       
8208   return 0;
8209 }
8210
8211 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8212 /// in the specified FP type without changing its value.
8213 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8214   APFloat F = CFP->getValueAPF();
8215   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
8216     return ConstantFP::get(F);
8217   return 0;
8218 }
8219
8220 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8221 /// through it until we get the source value.
8222 static Value *LookThroughFPExtensions(Value *V) {
8223   if (Instruction *I = dyn_cast<Instruction>(V))
8224     if (I->getOpcode() == Instruction::FPExt)
8225       return LookThroughFPExtensions(I->getOperand(0));
8226   
8227   // If this value is a constant, return the constant in the smallest FP type
8228   // that can accurately represent it.  This allows us to turn
8229   // (float)((double)X+2.0) into x+2.0f.
8230   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8231     if (CFP->getType() == Type::PPC_FP128Ty)
8232       return V;  // No constant folding of this.
8233     // See if the value can be truncated to float and then reextended.
8234     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8235       return V;
8236     if (CFP->getType() == Type::DoubleTy)
8237       return V;  // Won't shrink.
8238     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8239       return V;
8240     // Don't try to shrink to various long double types.
8241   }
8242   
8243   return V;
8244 }
8245
8246 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8247   if (Instruction *I = commonCastTransforms(CI))
8248     return I;
8249   
8250   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8251   // smaller than the destination type, we can eliminate the truncate by doing
8252   // the add as the smaller type.  This applies to add/sub/mul/div as well as
8253   // many builtins (sqrt, etc).
8254   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8255   if (OpI && OpI->hasOneUse()) {
8256     switch (OpI->getOpcode()) {
8257     default: break;
8258     case Instruction::Add:
8259     case Instruction::Sub:
8260     case Instruction::Mul:
8261     case Instruction::FDiv:
8262     case Instruction::FRem:
8263       const Type *SrcTy = OpI->getType();
8264       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8265       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8266       if (LHSTrunc->getType() != SrcTy && 
8267           RHSTrunc->getType() != SrcTy) {
8268         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8269         // If the source types were both smaller than the destination type of
8270         // the cast, do this xform.
8271         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8272             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8273           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8274                                       CI.getType(), CI);
8275           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8276                                       CI.getType(), CI);
8277           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8278         }
8279       }
8280       break;  
8281     }
8282   }
8283   return 0;
8284 }
8285
8286 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8287   return commonCastTransforms(CI);
8288 }
8289
8290 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8291   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
8292   // mantissa to accurately represent all values of X.  For example, do not
8293   // do this with i64->float->i64.
8294   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8295     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8296         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8297                     SrcI->getType()->getFPMantissaWidth())
8298       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8299
8300   return commonCastTransforms(FI);
8301 }
8302
8303 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8304   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
8305   // mantissa to accurately represent all values of X.  For example, do not
8306   // do this with i64->float->i64.
8307   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8308     if (SrcI->getOperand(0)->getType() == FI.getType() &&
8309         (int)FI.getType()->getPrimitiveSizeInBits() <= 
8310                     SrcI->getType()->getFPMantissaWidth())
8311       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8312   
8313   return commonCastTransforms(FI);
8314 }
8315
8316 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8317   return commonCastTransforms(CI);
8318 }
8319
8320 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8321   return commonCastTransforms(CI);
8322 }
8323
8324 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8325   return commonPointerCastTransforms(CI);
8326 }
8327
8328 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8329   if (Instruction *I = commonCastTransforms(CI))
8330     return I;
8331   
8332   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8333   if (!DestPointee->isSized()) return 0;
8334
8335   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8336   ConstantInt *Cst;
8337   Value *X;
8338   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8339                                     m_ConstantInt(Cst)))) {
8340     // If the source and destination operands have the same type, see if this
8341     // is a single-index GEP.
8342     if (X->getType() == CI.getType()) {
8343       // Get the size of the pointee type.
8344       uint64_t Size = TD->getABITypeSize(DestPointee);
8345
8346       // Convert the constant to intptr type.
8347       APInt Offset = Cst->getValue();
8348       Offset.sextOrTrunc(TD->getPointerSizeInBits());
8349
8350       // If Offset is evenly divisible by Size, we can do this xform.
8351       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8352         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8353         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8354       }
8355     }
8356     // TODO: Could handle other cases, e.g. where add is indexing into field of
8357     // struct etc.
8358   } else if (CI.getOperand(0)->hasOneUse() &&
8359              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8360     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8361     // "inttoptr+GEP" instead of "add+intptr".
8362     
8363     // Get the size of the pointee type.
8364     uint64_t Size = TD->getABITypeSize(DestPointee);
8365     
8366     // Convert the constant to intptr type.
8367     APInt Offset = Cst->getValue();
8368     Offset.sextOrTrunc(TD->getPointerSizeInBits());
8369     
8370     // If Offset is evenly divisible by Size, we can do this xform.
8371     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8372       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8373       
8374       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8375                                                             "tmp"), CI);
8376       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8377     }
8378   }
8379   return 0;
8380 }
8381
8382 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8383   // If the operands are integer typed then apply the integer transforms,
8384   // otherwise just apply the common ones.
8385   Value *Src = CI.getOperand(0);
8386   const Type *SrcTy = Src->getType();
8387   const Type *DestTy = CI.getType();
8388
8389   if (SrcTy->isInteger() && DestTy->isInteger()) {
8390     if (Instruction *Result = commonIntCastTransforms(CI))
8391       return Result;
8392   } else if (isa<PointerType>(SrcTy)) {
8393     if (Instruction *I = commonPointerCastTransforms(CI))
8394       return I;
8395   } else {
8396     if (Instruction *Result = commonCastTransforms(CI))
8397       return Result;
8398   }
8399
8400
8401   // Get rid of casts from one type to the same type. These are useless and can
8402   // be replaced by the operand.
8403   if (DestTy == Src->getType())
8404     return ReplaceInstUsesWith(CI, Src);
8405
8406   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8407     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8408     const Type *DstElTy = DstPTy->getElementType();
8409     const Type *SrcElTy = SrcPTy->getElementType();
8410     
8411     // If the address spaces don't match, don't eliminate the bitcast, which is
8412     // required for changing types.
8413     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8414       return 0;
8415     
8416     // If we are casting a malloc or alloca to a pointer to a type of the same
8417     // size, rewrite the allocation instruction to allocate the "right" type.
8418     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8419       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8420         return V;
8421     
8422     // If the source and destination are pointers, and this cast is equivalent
8423     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8424     // This can enhance SROA and other transforms that want type-safe pointers.
8425     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8426     unsigned NumZeros = 0;
8427     while (SrcElTy != DstElTy && 
8428            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8429            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8430       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8431       ++NumZeros;
8432     }
8433
8434     // If we found a path from the src to dest, create the getelementptr now.
8435     if (SrcElTy == DstElTy) {
8436       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8437       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8438                                        ((Instruction*) NULL));
8439     }
8440   }
8441
8442   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8443     if (SVI->hasOneUse()) {
8444       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8445       // a bitconvert to a vector with the same # elts.
8446       if (isa<VectorType>(DestTy) && 
8447           cast<VectorType>(DestTy)->getNumElements() == 
8448                 SVI->getType()->getNumElements()) {
8449         CastInst *Tmp;
8450         // If either of the operands is a cast from CI.getType(), then
8451         // evaluating the shuffle in the casted destination's type will allow
8452         // us to eliminate at least one cast.
8453         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8454              Tmp->getOperand(0)->getType() == DestTy) ||
8455             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8456              Tmp->getOperand(0)->getType() == DestTy)) {
8457           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8458                                                SVI->getOperand(0), DestTy, &CI);
8459           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8460                                                SVI->getOperand(1), DestTy, &CI);
8461           // Return a new shuffle vector.  Use the same element ID's, as we
8462           // know the vector types match #elts.
8463           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8464         }
8465       }
8466     }
8467   }
8468   return 0;
8469 }
8470
8471 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8472 ///   %C = or %A, %B
8473 ///   %D = select %cond, %C, %A
8474 /// into:
8475 ///   %C = select %cond, %B, 0
8476 ///   %D = or %A, %C
8477 ///
8478 /// Assuming that the specified instruction is an operand to the select, return
8479 /// a bitmask indicating which operands of this instruction are foldable if they
8480 /// equal the other incoming value of the select.
8481 ///
8482 static unsigned GetSelectFoldableOperands(Instruction *I) {
8483   switch (I->getOpcode()) {
8484   case Instruction::Add:
8485   case Instruction::Mul:
8486   case Instruction::And:
8487   case Instruction::Or:
8488   case Instruction::Xor:
8489     return 3;              // Can fold through either operand.
8490   case Instruction::Sub:   // Can only fold on the amount subtracted.
8491   case Instruction::Shl:   // Can only fold on the shift amount.
8492   case Instruction::LShr:
8493   case Instruction::AShr:
8494     return 1;
8495   default:
8496     return 0;              // Cannot fold
8497   }
8498 }
8499
8500 /// GetSelectFoldableConstant - For the same transformation as the previous
8501 /// function, return the identity constant that goes into the select.
8502 static Constant *GetSelectFoldableConstant(Instruction *I) {
8503   switch (I->getOpcode()) {
8504   default: assert(0 && "This cannot happen!"); abort();
8505   case Instruction::Add:
8506   case Instruction::Sub:
8507   case Instruction::Or:
8508   case Instruction::Xor:
8509   case Instruction::Shl:
8510   case Instruction::LShr:
8511   case Instruction::AShr:
8512     return Constant::getNullValue(I->getType());
8513   case Instruction::And:
8514     return Constant::getAllOnesValue(I->getType());
8515   case Instruction::Mul:
8516     return ConstantInt::get(I->getType(), 1);
8517   }
8518 }
8519
8520 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8521 /// have the same opcode and only one use each.  Try to simplify this.
8522 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8523                                           Instruction *FI) {
8524   if (TI->getNumOperands() == 1) {
8525     // If this is a non-volatile load or a cast from the same type,
8526     // merge.
8527     if (TI->isCast()) {
8528       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8529         return 0;
8530     } else {
8531       return 0;  // unknown unary op.
8532     }
8533
8534     // Fold this by inserting a select from the input values.
8535     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8536                                            FI->getOperand(0), SI.getName()+".v");
8537     InsertNewInstBefore(NewSI, SI);
8538     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8539                             TI->getType());
8540   }
8541
8542   // Only handle binary operators here.
8543   if (!isa<BinaryOperator>(TI))
8544     return 0;
8545
8546   // Figure out if the operations have any operands in common.
8547   Value *MatchOp, *OtherOpT, *OtherOpF;
8548   bool MatchIsOpZero;
8549   if (TI->getOperand(0) == FI->getOperand(0)) {
8550     MatchOp  = TI->getOperand(0);
8551     OtherOpT = TI->getOperand(1);
8552     OtherOpF = FI->getOperand(1);
8553     MatchIsOpZero = true;
8554   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8555     MatchOp  = TI->getOperand(1);
8556     OtherOpT = TI->getOperand(0);
8557     OtherOpF = FI->getOperand(0);
8558     MatchIsOpZero = false;
8559   } else if (!TI->isCommutative()) {
8560     return 0;
8561   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8562     MatchOp  = TI->getOperand(0);
8563     OtherOpT = TI->getOperand(1);
8564     OtherOpF = FI->getOperand(0);
8565     MatchIsOpZero = true;
8566   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8567     MatchOp  = TI->getOperand(1);
8568     OtherOpT = TI->getOperand(0);
8569     OtherOpF = FI->getOperand(1);
8570     MatchIsOpZero = true;
8571   } else {
8572     return 0;
8573   }
8574
8575   // If we reach here, they do have operations in common.
8576   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8577                                          OtherOpF, SI.getName()+".v");
8578   InsertNewInstBefore(NewSI, SI);
8579
8580   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8581     if (MatchIsOpZero)
8582       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8583     else
8584       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8585   }
8586   assert(0 && "Shouldn't get here");
8587   return 0;
8588 }
8589
8590 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8591   Value *CondVal = SI.getCondition();
8592   Value *TrueVal = SI.getTrueValue();
8593   Value *FalseVal = SI.getFalseValue();
8594
8595   // select true, X, Y  -> X
8596   // select false, X, Y -> Y
8597   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8598     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8599
8600   // select C, X, X -> X
8601   if (TrueVal == FalseVal)
8602     return ReplaceInstUsesWith(SI, TrueVal);
8603
8604   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8605     return ReplaceInstUsesWith(SI, FalseVal);
8606   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8607     return ReplaceInstUsesWith(SI, TrueVal);
8608   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8609     if (isa<Constant>(TrueVal))
8610       return ReplaceInstUsesWith(SI, TrueVal);
8611     else
8612       return ReplaceInstUsesWith(SI, FalseVal);
8613   }
8614
8615   if (SI.getType() == Type::Int1Ty) {
8616     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8617       if (C->getZExtValue()) {
8618         // Change: A = select B, true, C --> A = or B, C
8619         return BinaryOperator::CreateOr(CondVal, FalseVal);
8620       } else {
8621         // Change: A = select B, false, C --> A = and !B, C
8622         Value *NotCond =
8623           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8624                                              "not."+CondVal->getName()), SI);
8625         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8626       }
8627     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8628       if (C->getZExtValue() == false) {
8629         // Change: A = select B, C, false --> A = and B, C
8630         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8631       } else {
8632         // Change: A = select B, C, true --> A = or !B, C
8633         Value *NotCond =
8634           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8635                                              "not."+CondVal->getName()), SI);
8636         return BinaryOperator::CreateOr(NotCond, TrueVal);
8637       }
8638     }
8639     
8640     // select a, b, a  -> a&b
8641     // select a, a, b  -> a|b
8642     if (CondVal == TrueVal)
8643       return BinaryOperator::CreateOr(CondVal, FalseVal);
8644     else if (CondVal == FalseVal)
8645       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8646   }
8647
8648   // Selecting between two integer constants?
8649   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8650     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8651       // select C, 1, 0 -> zext C to int
8652       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8653         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8654       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8655         // select C, 0, 1 -> zext !C to int
8656         Value *NotCond =
8657           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8658                                                "not."+CondVal->getName()), SI);
8659         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8660       }
8661       
8662       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8663
8664       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8665
8666         // (x <s 0) ? -1 : 0 -> ashr x, 31
8667         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8668           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8669             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8670               // The comparison constant and the result are not neccessarily the
8671               // same width. Make an all-ones value by inserting a AShr.
8672               Value *X = IC->getOperand(0);
8673               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8674               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8675               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8676                                                         ShAmt, "ones");
8677               InsertNewInstBefore(SRA, SI);
8678               
8679               // Finally, convert to the type of the select RHS.  We figure out
8680               // if this requires a SExt, Trunc or BitCast based on the sizes.
8681               Instruction::CastOps opc = Instruction::BitCast;
8682               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8683               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8684               if (SRASize < SISize)
8685                 opc = Instruction::SExt;
8686               else if (SRASize > SISize)
8687                 opc = Instruction::Trunc;
8688               return CastInst::Create(opc, SRA, SI.getType());
8689             }
8690           }
8691
8692
8693         // If one of the constants is zero (we know they can't both be) and we
8694         // have an icmp instruction with zero, and we have an 'and' with the
8695         // non-constant value, eliminate this whole mess.  This corresponds to
8696         // cases like this: ((X & 27) ? 27 : 0)
8697         if (TrueValC->isZero() || FalseValC->isZero())
8698           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8699               cast<Constant>(IC->getOperand(1))->isNullValue())
8700             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8701               if (ICA->getOpcode() == Instruction::And &&
8702                   isa<ConstantInt>(ICA->getOperand(1)) &&
8703                   (ICA->getOperand(1) == TrueValC ||
8704                    ICA->getOperand(1) == FalseValC) &&
8705                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8706                 // Okay, now we know that everything is set up, we just don't
8707                 // know whether we have a icmp_ne or icmp_eq and whether the 
8708                 // true or false val is the zero.
8709                 bool ShouldNotVal = !TrueValC->isZero();
8710                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8711                 Value *V = ICA;
8712                 if (ShouldNotVal)
8713                   V = InsertNewInstBefore(BinaryOperator::Create(
8714                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8715                 return ReplaceInstUsesWith(SI, V);
8716               }
8717       }
8718     }
8719
8720   // See if we are selecting two values based on a comparison of the two values.
8721   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8722     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8723       // Transform (X == Y) ? X : Y  -> Y
8724       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8725         // This is not safe in general for floating point:  
8726         // consider X== -0, Y== +0.
8727         // It becomes safe if either operand is a nonzero constant.
8728         ConstantFP *CFPt, *CFPf;
8729         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8730               !CFPt->getValueAPF().isZero()) ||
8731             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8732              !CFPf->getValueAPF().isZero()))
8733         return ReplaceInstUsesWith(SI, FalseVal);
8734       }
8735       // Transform (X != Y) ? X : Y  -> X
8736       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8737         return ReplaceInstUsesWith(SI, TrueVal);
8738       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8739
8740     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8741       // Transform (X == Y) ? Y : X  -> X
8742       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8743         // This is not safe in general for floating point:  
8744         // consider X== -0, Y== +0.
8745         // It becomes safe if either operand is a nonzero constant.
8746         ConstantFP *CFPt, *CFPf;
8747         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8748               !CFPt->getValueAPF().isZero()) ||
8749             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8750              !CFPf->getValueAPF().isZero()))
8751           return ReplaceInstUsesWith(SI, FalseVal);
8752       }
8753       // Transform (X != Y) ? Y : X  -> Y
8754       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8755         return ReplaceInstUsesWith(SI, TrueVal);
8756       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8757     }
8758   }
8759
8760   // See if we are selecting two values based on a comparison of the two values.
8761   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8762     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8763       // Transform (X == Y) ? X : Y  -> Y
8764       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8765         return ReplaceInstUsesWith(SI, FalseVal);
8766       // Transform (X != Y) ? X : Y  -> X
8767       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8768         return ReplaceInstUsesWith(SI, TrueVal);
8769       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8770
8771     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8772       // Transform (X == Y) ? Y : X  -> X
8773       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8774         return ReplaceInstUsesWith(SI, FalseVal);
8775       // Transform (X != Y) ? Y : X  -> Y
8776       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8777         return ReplaceInstUsesWith(SI, TrueVal);
8778       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8779     }
8780   }
8781
8782   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8783     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8784       if (TI->hasOneUse() && FI->hasOneUse()) {
8785         Instruction *AddOp = 0, *SubOp = 0;
8786
8787         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8788         if (TI->getOpcode() == FI->getOpcode())
8789           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8790             return IV;
8791
8792         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8793         // even legal for FP.
8794         if (TI->getOpcode() == Instruction::Sub &&
8795             FI->getOpcode() == Instruction::Add) {
8796           AddOp = FI; SubOp = TI;
8797         } else if (FI->getOpcode() == Instruction::Sub &&
8798                    TI->getOpcode() == Instruction::Add) {
8799           AddOp = TI; SubOp = FI;
8800         }
8801
8802         if (AddOp) {
8803           Value *OtherAddOp = 0;
8804           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8805             OtherAddOp = AddOp->getOperand(1);
8806           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8807             OtherAddOp = AddOp->getOperand(0);
8808           }
8809
8810           if (OtherAddOp) {
8811             // So at this point we know we have (Y -> OtherAddOp):
8812             //        select C, (add X, Y), (sub X, Z)
8813             Value *NegVal;  // Compute -Z
8814             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8815               NegVal = ConstantExpr::getNeg(C);
8816             } else {
8817               NegVal = InsertNewInstBefore(
8818                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8819             }
8820
8821             Value *NewTrueOp = OtherAddOp;
8822             Value *NewFalseOp = NegVal;
8823             if (AddOp != TI)
8824               std::swap(NewTrueOp, NewFalseOp);
8825             Instruction *NewSel =
8826               SelectInst::Create(CondVal, NewTrueOp,
8827                                  NewFalseOp, SI.getName() + ".p");
8828
8829             NewSel = InsertNewInstBefore(NewSel, SI);
8830             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8831           }
8832         }
8833       }
8834
8835   // See if we can fold the select into one of our operands.
8836   if (SI.getType()->isInteger()) {
8837     // See the comment above GetSelectFoldableOperands for a description of the
8838     // transformation we are doing here.
8839     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8840       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8841           !isa<Constant>(FalseVal))
8842         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8843           unsigned OpToFold = 0;
8844           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8845             OpToFold = 1;
8846           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8847             OpToFold = 2;
8848           }
8849
8850           if (OpToFold) {
8851             Constant *C = GetSelectFoldableConstant(TVI);
8852             Instruction *NewSel =
8853               SelectInst::Create(SI.getCondition(),
8854                                  TVI->getOperand(2-OpToFold), C);
8855             InsertNewInstBefore(NewSel, SI);
8856             NewSel->takeName(TVI);
8857             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8858               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8859             else {
8860               assert(0 && "Unknown instruction!!");
8861             }
8862           }
8863         }
8864
8865     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8866       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8867           !isa<Constant>(TrueVal))
8868         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8869           unsigned OpToFold = 0;
8870           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8871             OpToFold = 1;
8872           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8873             OpToFold = 2;
8874           }
8875
8876           if (OpToFold) {
8877             Constant *C = GetSelectFoldableConstant(FVI);
8878             Instruction *NewSel =
8879               SelectInst::Create(SI.getCondition(), C,
8880                                  FVI->getOperand(2-OpToFold));
8881             InsertNewInstBefore(NewSel, SI);
8882             NewSel->takeName(FVI);
8883             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8884               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8885             else
8886               assert(0 && "Unknown instruction!!");
8887           }
8888         }
8889   }
8890
8891   if (BinaryOperator::isNot(CondVal)) {
8892     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8893     SI.setOperand(1, FalseVal);
8894     SI.setOperand(2, TrueVal);
8895     return &SI;
8896   }
8897
8898   return 0;
8899 }
8900
8901 /// EnforceKnownAlignment - If the specified pointer points to an object that
8902 /// we control, modify the object's alignment to PrefAlign. This isn't
8903 /// often possible though. If alignment is important, a more reliable approach
8904 /// is to simply align all global variables and allocation instructions to
8905 /// their preferred alignment from the beginning.
8906 ///
8907 static unsigned EnforceKnownAlignment(Value *V,
8908                                       unsigned Align, unsigned PrefAlign) {
8909
8910   User *U = dyn_cast<User>(V);
8911   if (!U) return Align;
8912
8913   switch (getOpcode(U)) {
8914   default: break;
8915   case Instruction::BitCast:
8916     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8917   case Instruction::GetElementPtr: {
8918     // If all indexes are zero, it is just the alignment of the base pointer.
8919     bool AllZeroOperands = true;
8920     for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8921       if (!isa<Constant>(U->getOperand(i)) ||
8922           !cast<Constant>(U->getOperand(i))->isNullValue()) {
8923         AllZeroOperands = false;
8924         break;
8925       }
8926
8927     if (AllZeroOperands) {
8928       // Treat this like a bitcast.
8929       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8930     }
8931     break;
8932   }
8933   }
8934
8935   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8936     // If there is a large requested alignment and we can, bump up the alignment
8937     // of the global.
8938     if (!GV->isDeclaration()) {
8939       GV->setAlignment(PrefAlign);
8940       Align = PrefAlign;
8941     }
8942   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8943     // If there is a requested alignment and if this is an alloca, round up.  We
8944     // don't do this for malloc, because some systems can't respect the request.
8945     if (isa<AllocaInst>(AI)) {
8946       AI->setAlignment(PrefAlign);
8947       Align = PrefAlign;
8948     }
8949   }
8950
8951   return Align;
8952 }
8953
8954 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8955 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8956 /// and it is more than the alignment of the ultimate object, see if we can
8957 /// increase the alignment of the ultimate object, making this check succeed.
8958 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8959                                                   unsigned PrefAlign) {
8960   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8961                       sizeof(PrefAlign) * CHAR_BIT;
8962   APInt Mask = APInt::getAllOnesValue(BitWidth);
8963   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8964   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8965   unsigned TrailZ = KnownZero.countTrailingOnes();
8966   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8967
8968   if (PrefAlign > Align)
8969     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8970   
8971     // We don't need to make any adjustment.
8972   return Align;
8973 }
8974
8975 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8976   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8977   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8978   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8979   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8980
8981   if (CopyAlign < MinAlign) {
8982     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8983     return MI;
8984   }
8985   
8986   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8987   // load/store.
8988   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8989   if (MemOpLength == 0) return 0;
8990   
8991   // Source and destination pointer types are always "i8*" for intrinsic.  See
8992   // if the size is something we can handle with a single primitive load/store.
8993   // A single load+store correctly handles overlapping memory in the memmove
8994   // case.
8995   unsigned Size = MemOpLength->getZExtValue();
8996   if (Size == 0) return MI;  // Delete this mem transfer.
8997   
8998   if (Size > 8 || (Size&(Size-1)))
8999     return 0;  // If not 1/2/4/8 bytes, exit.
9000   
9001   // Use an integer load+store unless we can find something better.
9002   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9003   
9004   // Memcpy forces the use of i8* for the source and destination.  That means
9005   // that if you're using memcpy to move one double around, you'll get a cast
9006   // from double* to i8*.  We'd much rather use a double load+store rather than
9007   // an i64 load+store, here because this improves the odds that the source or
9008   // dest address will be promotable.  See if we can find a better type than the
9009   // integer datatype.
9010   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9011     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9012     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9013       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
9014       // down through these levels if so.
9015       while (!SrcETy->isSingleValueType()) {
9016         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9017           if (STy->getNumElements() == 1)
9018             SrcETy = STy->getElementType(0);
9019           else
9020             break;
9021         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9022           if (ATy->getNumElements() == 1)
9023             SrcETy = ATy->getElementType();
9024           else
9025             break;
9026         } else
9027           break;
9028       }
9029       
9030       if (SrcETy->isSingleValueType())
9031         NewPtrTy = PointerType::getUnqual(SrcETy);
9032     }
9033   }
9034   
9035   
9036   // If the memcpy/memmove provides better alignment info than we can
9037   // infer, use it.
9038   SrcAlign = std::max(SrcAlign, CopyAlign);
9039   DstAlign = std::max(DstAlign, CopyAlign);
9040   
9041   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9042   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9043   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9044   InsertNewInstBefore(L, *MI);
9045   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9046
9047   // Set the size of the copy to 0, it will be deleted on the next iteration.
9048   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9049   return MI;
9050 }
9051
9052 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9053   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9054   if (MI->getAlignment()->getZExtValue() < Alignment) {
9055     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9056     return MI;
9057   }
9058   
9059   // Extract the length and alignment and fill if they are constant.
9060   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9061   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9062   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9063     return 0;
9064   uint64_t Len = LenC->getZExtValue();
9065   Alignment = MI->getAlignment()->getZExtValue();
9066   
9067   // If the length is zero, this is a no-op
9068   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9069   
9070   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9071   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9072     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
9073     
9074     Value *Dest = MI->getDest();
9075     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9076
9077     // Alignment 0 is identity for alignment 1 for memset, but not store.
9078     if (Alignment == 0) Alignment = 1;
9079     
9080     // Extract the fill value and store.
9081     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9082     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9083                                       Alignment), *MI);
9084     
9085     // Set the size of the copy to 0, it will be deleted on the next iteration.
9086     MI->setLength(Constant::getNullValue(LenC->getType()));
9087     return MI;
9088   }
9089
9090   return 0;
9091 }
9092
9093
9094 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
9095 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
9096 /// the heavy lifting.
9097 ///
9098 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9099   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9100   if (!II) return visitCallSite(&CI);
9101   
9102   // Intrinsics cannot occur in an invoke, so handle them here instead of in
9103   // visitCallSite.
9104   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9105     bool Changed = false;
9106
9107     // memmove/cpy/set of zero bytes is a noop.
9108     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9109       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9110
9111       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9112         if (CI->getZExtValue() == 1) {
9113           // Replace the instruction with just byte operations.  We would
9114           // transform other cases to loads/stores, but we don't know if
9115           // alignment is sufficient.
9116         }
9117     }
9118
9119     // If we have a memmove and the source operation is a constant global,
9120     // then the source and dest pointers can't alias, so we can change this
9121     // into a call to memcpy.
9122     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9123       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9124         if (GVSrc->isConstant()) {
9125           Module *M = CI.getParent()->getParent()->getParent();
9126           Intrinsic::ID MemCpyID;
9127           if (CI.getOperand(3)->getType() == Type::Int32Ty)
9128             MemCpyID = Intrinsic::memcpy_i32;
9129           else
9130             MemCpyID = Intrinsic::memcpy_i64;
9131           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
9132           Changed = true;
9133         }
9134     }
9135
9136     // If we can determine a pointer alignment that is bigger than currently
9137     // set, update the alignment.
9138     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9139       if (Instruction *I = SimplifyMemTransfer(MI))
9140         return I;
9141     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9142       if (Instruction *I = SimplifyMemSet(MSI))
9143         return I;
9144     }
9145           
9146     if (Changed) return II;
9147   } else {
9148     switch (II->getIntrinsicID()) {
9149     default: break;
9150     case Intrinsic::ppc_altivec_lvx:
9151     case Intrinsic::ppc_altivec_lvxl:
9152     case Intrinsic::x86_sse_loadu_ps:
9153     case Intrinsic::x86_sse2_loadu_pd:
9154     case Intrinsic::x86_sse2_loadu_dq:
9155       // Turn PPC lvx     -> load if the pointer is known aligned.
9156       // Turn X86 loadups -> load if the pointer is known aligned.
9157       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9158         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9159                                          PointerType::getUnqual(II->getType()),
9160                                          CI);
9161         return new LoadInst(Ptr);
9162       }
9163       break;
9164     case Intrinsic::ppc_altivec_stvx:
9165     case Intrinsic::ppc_altivec_stvxl:
9166       // Turn stvx -> store if the pointer is known aligned.
9167       if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9168         const Type *OpPtrTy = 
9169           PointerType::getUnqual(II->getOperand(1)->getType());
9170         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9171         return new StoreInst(II->getOperand(1), Ptr);
9172       }
9173       break;
9174     case Intrinsic::x86_sse_storeu_ps:
9175     case Intrinsic::x86_sse2_storeu_pd:
9176     case Intrinsic::x86_sse2_storeu_dq:
9177     case Intrinsic::x86_sse2_storel_dq:
9178       // Turn X86 storeu -> store if the pointer is known aligned.
9179       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9180         const Type *OpPtrTy = 
9181           PointerType::getUnqual(II->getOperand(2)->getType());
9182         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9183         return new StoreInst(II->getOperand(2), Ptr);
9184       }
9185       break;
9186       
9187     case Intrinsic::x86_sse_cvttss2si: {
9188       // These intrinsics only demands the 0th element of its input vector.  If
9189       // we can simplify the input based on that, do so now.
9190       uint64_t UndefElts;
9191       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
9192                                                 UndefElts)) {
9193         II->setOperand(1, V);
9194         return II;
9195       }
9196       break;
9197     }
9198       
9199     case Intrinsic::ppc_altivec_vperm:
9200       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9201       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9202         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9203         
9204         // Check that all of the elements are integer constants or undefs.
9205         bool AllEltsOk = true;
9206         for (unsigned i = 0; i != 16; ++i) {
9207           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
9208               !isa<UndefValue>(Mask->getOperand(i))) {
9209             AllEltsOk = false;
9210             break;
9211           }
9212         }
9213         
9214         if (AllEltsOk) {
9215           // Cast the input vectors to byte vectors.
9216           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9217           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9218           Value *Result = UndefValue::get(Op0->getType());
9219           
9220           // Only extract each element once.
9221           Value *ExtractedElts[32];
9222           memset(ExtractedElts, 0, sizeof(ExtractedElts));
9223           
9224           for (unsigned i = 0; i != 16; ++i) {
9225             if (isa<UndefValue>(Mask->getOperand(i)))
9226               continue;
9227             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9228             Idx &= 31;  // Match the hardware behavior.
9229             
9230             if (ExtractedElts[Idx] == 0) {
9231               Instruction *Elt = 
9232                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9233               InsertNewInstBefore(Elt, CI);
9234               ExtractedElts[Idx] = Elt;
9235             }
9236           
9237             // Insert this value into the result vector.
9238             Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9239                                                i, "tmp");
9240             InsertNewInstBefore(cast<Instruction>(Result), CI);
9241           }
9242           return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9243         }
9244       }
9245       break;
9246
9247     case Intrinsic::stackrestore: {
9248       // If the save is right next to the restore, remove the restore.  This can
9249       // happen when variable allocas are DCE'd.
9250       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9251         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9252           BasicBlock::iterator BI = SS;
9253           if (&*++BI == II)
9254             return EraseInstFromFunction(CI);
9255         }
9256       }
9257       
9258       // Scan down this block to see if there is another stack restore in the
9259       // same block without an intervening call/alloca.
9260       BasicBlock::iterator BI = II;
9261       TerminatorInst *TI = II->getParent()->getTerminator();
9262       bool CannotRemove = false;
9263       for (++BI; &*BI != TI; ++BI) {
9264         if (isa<AllocaInst>(BI)) {
9265           CannotRemove = true;
9266           break;
9267         }
9268         if (isa<CallInst>(BI)) {
9269           if (!isa<IntrinsicInst>(BI)) {
9270             CannotRemove = true;
9271             break;
9272           }
9273           // If there is a stackrestore below this one, remove this one.
9274           return EraseInstFromFunction(CI);
9275         }
9276       }
9277       
9278       // If the stack restore is in a return/unwind block and if there are no
9279       // allocas or calls between the restore and the return, nuke the restore.
9280       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9281         return EraseInstFromFunction(CI);
9282       break;
9283     }
9284     }
9285   }
9286
9287   return visitCallSite(II);
9288 }
9289
9290 // InvokeInst simplification
9291 //
9292 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9293   return visitCallSite(&II);
9294 }
9295
9296 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
9297 /// passed through the varargs area, we can eliminate the use of the cast.
9298 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9299                                          const CastInst * const CI,
9300                                          const TargetData * const TD,
9301                                          const int ix) {
9302   if (!CI->isLosslessCast())
9303     return false;
9304
9305   // The size of ByVal arguments is derived from the type, so we
9306   // can't change to a type with a different size.  If the size were
9307   // passed explicitly we could avoid this check.
9308   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9309     return true;
9310
9311   const Type* SrcTy = 
9312             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9313   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9314   if (!SrcTy->isSized() || !DstTy->isSized())
9315     return false;
9316   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9317     return false;
9318   return true;
9319 }
9320
9321 // visitCallSite - Improvements for call and invoke instructions.
9322 //
9323 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9324   bool Changed = false;
9325
9326   // If the callee is a constexpr cast of a function, attempt to move the cast
9327   // to the arguments of the call/invoke.
9328   if (transformConstExprCastCall(CS)) return 0;
9329
9330   Value *Callee = CS.getCalledValue();
9331
9332   if (Function *CalleeF = dyn_cast<Function>(Callee))
9333     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9334       Instruction *OldCall = CS.getInstruction();
9335       // If the call and callee calling conventions don't match, this call must
9336       // be unreachable, as the call is undefined.
9337       new StoreInst(ConstantInt::getTrue(),
9338                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9339                                     OldCall);
9340       if (!OldCall->use_empty())
9341         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9342       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9343         return EraseInstFromFunction(*OldCall);
9344       return 0;
9345     }
9346
9347   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9348     // This instruction is not reachable, just remove it.  We insert a store to
9349     // undef so that we know that this code is not reachable, despite the fact
9350     // that we can't modify the CFG here.
9351     new StoreInst(ConstantInt::getTrue(),
9352                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9353                   CS.getInstruction());
9354
9355     if (!CS.getInstruction()->use_empty())
9356       CS.getInstruction()->
9357         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9358
9359     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9360       // Don't break the CFG, insert a dummy cond branch.
9361       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9362                          ConstantInt::getTrue(), II);
9363     }
9364     return EraseInstFromFunction(*CS.getInstruction());
9365   }
9366
9367   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9368     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9369       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9370         return transformCallThroughTrampoline(CS);
9371
9372   const PointerType *PTy = cast<PointerType>(Callee->getType());
9373   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9374   if (FTy->isVarArg()) {
9375     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9376     // See if we can optimize any arguments passed through the varargs area of
9377     // the call.
9378     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9379            E = CS.arg_end(); I != E; ++I, ++ix) {
9380       CastInst *CI = dyn_cast<CastInst>(*I);
9381       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9382         *I = CI->getOperand(0);
9383         Changed = true;
9384       }
9385     }
9386   }
9387
9388   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9389     // Inline asm calls cannot throw - mark them 'nounwind'.
9390     CS.setDoesNotThrow();
9391     Changed = true;
9392   }
9393
9394   return Changed ? CS.getInstruction() : 0;
9395 }
9396
9397 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9398 // attempt to move the cast to the arguments of the call/invoke.
9399 //
9400 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9401   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9402   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9403   if (CE->getOpcode() != Instruction::BitCast || 
9404       !isa<Function>(CE->getOperand(0)))
9405     return false;
9406   Function *Callee = cast<Function>(CE->getOperand(0));
9407   Instruction *Caller = CS.getInstruction();
9408   const PAListPtr &CallerPAL = CS.getParamAttrs();
9409
9410   // Okay, this is a cast from a function to a different type.  Unless doing so
9411   // would cause a type conversion of one of our arguments, change this call to
9412   // be a direct call with arguments casted to the appropriate types.
9413   //
9414   const FunctionType *FT = Callee->getFunctionType();
9415   const Type *OldRetTy = Caller->getType();
9416
9417   if (isa<StructType>(FT->getReturnType()))
9418     return false; // TODO: Handle multiple return values.
9419
9420   // Check to see if we are changing the return type...
9421   if (OldRetTy != FT->getReturnType()) {
9422     if (Callee->isDeclaration() &&
9423         // Conversion is ok if changing from pointer to int of same size.
9424         !(isa<PointerType>(FT->getReturnType()) &&
9425           TD->getIntPtrType() == OldRetTy))
9426       return false;   // Cannot transform this return value.
9427
9428     if (!Caller->use_empty() &&
9429         // void -> non-void is handled specially
9430         FT->getReturnType() != Type::VoidTy &&
9431         !CastInst::isCastable(FT->getReturnType(), OldRetTy))
9432       return false;   // Cannot transform this return value.
9433
9434     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9435       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9436       if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9437         return false;   // Attribute not compatible with transformed value.
9438     }
9439
9440     // If the callsite is an invoke instruction, and the return value is used by
9441     // a PHI node in a successor, we cannot change the return type of the call
9442     // because there is no place to put the cast instruction (without breaking
9443     // the critical edge).  Bail out in this case.
9444     if (!Caller->use_empty())
9445       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9446         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9447              UI != E; ++UI)
9448           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9449             if (PN->getParent() == II->getNormalDest() ||
9450                 PN->getParent() == II->getUnwindDest())
9451               return false;
9452   }
9453
9454   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9455   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9456
9457   CallSite::arg_iterator AI = CS.arg_begin();
9458   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9459     const Type *ParamTy = FT->getParamType(i);
9460     const Type *ActTy = (*AI)->getType();
9461
9462     if (!CastInst::isCastable(ActTy, ParamTy))
9463       return false;   // Cannot transform this parameter value.
9464
9465     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9466       return false;   // Attribute not compatible with transformed value.
9467
9468     ConstantInt *c = dyn_cast<ConstantInt>(*AI);
9469     // Some conversions are safe even if we do not have a body.
9470     // Either we can cast directly, or we can upconvert the argument
9471     bool isConvertible = ActTy == ParamTy ||
9472       (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9473       (ParamTy->isInteger() && ActTy->isInteger() &&
9474        ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9475       (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9476        && c->getValue().isStrictlyPositive());
9477     if (Callee->isDeclaration() && !isConvertible) return false;
9478   }
9479
9480   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9481       Callee->isDeclaration())
9482     return false;   // Do not delete arguments unless we have a function body.
9483
9484   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9485       !CallerPAL.isEmpty())
9486     // In this case we have more arguments than the new function type, but we
9487     // won't be dropping them.  Check that these extra arguments have attributes
9488     // that are compatible with being a vararg call argument.
9489     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9490       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9491         break;
9492       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9493       if (PAttrs & ParamAttr::VarArgsIncompatible)
9494         return false;
9495     }
9496
9497   // Okay, we decided that this is a safe thing to do: go ahead and start
9498   // inserting cast instructions as necessary...
9499   std::vector<Value*> Args;
9500   Args.reserve(NumActualArgs);
9501   SmallVector<ParamAttrsWithIndex, 8> attrVec;
9502   attrVec.reserve(NumCommonArgs);
9503
9504   // Get any return attributes.
9505   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9506
9507   // If the return value is not being used, the type may not be compatible
9508   // with the existing attributes.  Wipe out any problematic attributes.
9509   RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
9510
9511   // Add the new return attributes.
9512   if (RAttrs)
9513     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9514
9515   AI = CS.arg_begin();
9516   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9517     const Type *ParamTy = FT->getParamType(i);
9518     if ((*AI)->getType() == ParamTy) {
9519       Args.push_back(*AI);
9520     } else {
9521       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9522           false, ParamTy, false);
9523       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9524       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9525     }
9526
9527     // Add any parameter attributes.
9528     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9529       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9530   }
9531
9532   // If the function takes more arguments than the call was taking, add them
9533   // now...
9534   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9535     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9536
9537   // If we are removing arguments to the function, emit an obnoxious warning...
9538   if (FT->getNumParams() < NumActualArgs) {
9539     if (!FT->isVarArg()) {
9540       cerr << "WARNING: While resolving call to function '"
9541            << Callee->getName() << "' arguments were dropped!\n";
9542     } else {
9543       // Add all of the arguments in their promoted form to the arg list...
9544       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9545         const Type *PTy = getPromotedType((*AI)->getType());
9546         if (PTy != (*AI)->getType()) {
9547           // Must promote to pass through va_arg area!
9548           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9549                                                                 PTy, false);
9550           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9551           InsertNewInstBefore(Cast, *Caller);
9552           Args.push_back(Cast);
9553         } else {
9554           Args.push_back(*AI);
9555         }
9556
9557         // Add any parameter attributes.
9558         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9559           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9560       }
9561     }
9562   }
9563
9564   if (FT->getReturnType() == Type::VoidTy)
9565     Caller->setName("");   // Void type should not have a name.
9566
9567   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9568
9569   Instruction *NC;
9570   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9571     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9572                             Args.begin(), Args.end(),
9573                             Caller->getName(), Caller);
9574     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9575     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9576   } else {
9577     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9578                           Caller->getName(), Caller);
9579     CallInst *CI = cast<CallInst>(Caller);
9580     if (CI->isTailCall())
9581       cast<CallInst>(NC)->setTailCall();
9582     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9583     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9584   }
9585
9586   // Insert a cast of the return type as necessary.
9587   Value *NV = NC;
9588   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9589     if (NV->getType() != Type::VoidTy) {
9590       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9591                                                             OldRetTy, false);
9592       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9593
9594       // If this is an invoke instruction, we should insert it after the first
9595       // non-phi, instruction in the normal successor block.
9596       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9597         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9598         InsertNewInstBefore(NC, *I);
9599       } else {
9600         // Otherwise, it's a call, just insert cast right after the call instr
9601         InsertNewInstBefore(NC, *Caller);
9602       }
9603       AddUsersToWorkList(*Caller);
9604     } else {
9605       NV = UndefValue::get(Caller->getType());
9606     }
9607   }
9608
9609   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9610     Caller->replaceAllUsesWith(NV);
9611   Caller->eraseFromParent();
9612   RemoveFromWorkList(Caller);
9613   return true;
9614 }
9615
9616 // transformCallThroughTrampoline - Turn a call to a function created by the
9617 // init_trampoline intrinsic into a direct call to the underlying function.
9618 //
9619 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9620   Value *Callee = CS.getCalledValue();
9621   const PointerType *PTy = cast<PointerType>(Callee->getType());
9622   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9623   const PAListPtr &Attrs = CS.getParamAttrs();
9624
9625   // If the call already has the 'nest' attribute somewhere then give up -
9626   // otherwise 'nest' would occur twice after splicing in the chain.
9627   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9628     return 0;
9629
9630   IntrinsicInst *Tramp =
9631     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9632
9633   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9634   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9635   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9636
9637   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9638   if (!NestAttrs.isEmpty()) {
9639     unsigned NestIdx = 1;
9640     const Type *NestTy = 0;
9641     ParameterAttributes NestAttr = ParamAttr::None;
9642
9643     // Look for a parameter marked with the 'nest' attribute.
9644     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9645          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9646       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9647         // Record the parameter type and any other attributes.
9648         NestTy = *I;
9649         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9650         break;
9651       }
9652
9653     if (NestTy) {
9654       Instruction *Caller = CS.getInstruction();
9655       std::vector<Value*> NewArgs;
9656       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9657
9658       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9659       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9660
9661       // Insert the nest argument into the call argument list, which may
9662       // mean appending it.  Likewise for attributes.
9663
9664       // Add any function result attributes.
9665       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9666         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9667
9668       {
9669         unsigned Idx = 1;
9670         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9671         do {
9672           if (Idx == NestIdx) {
9673             // Add the chain argument and attributes.
9674             Value *NestVal = Tramp->getOperand(3);
9675             if (NestVal->getType() != NestTy)
9676               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9677             NewArgs.push_back(NestVal);
9678             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9679           }
9680
9681           if (I == E)
9682             break;
9683
9684           // Add the original argument and attributes.
9685           NewArgs.push_back(*I);
9686           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9687             NewAttrs.push_back
9688               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9689
9690           ++Idx, ++I;
9691         } while (1);
9692       }
9693
9694       // The trampoline may have been bitcast to a bogus type (FTy).
9695       // Handle this by synthesizing a new function type, equal to FTy
9696       // with the chain parameter inserted.
9697
9698       std::vector<const Type*> NewTypes;
9699       NewTypes.reserve(FTy->getNumParams()+1);
9700
9701       // Insert the chain's type into the list of parameter types, which may
9702       // mean appending it.
9703       {
9704         unsigned Idx = 1;
9705         FunctionType::param_iterator I = FTy->param_begin(),
9706           E = FTy->param_end();
9707
9708         do {
9709           if (Idx == NestIdx)
9710             // Add the chain's type.
9711             NewTypes.push_back(NestTy);
9712
9713           if (I == E)
9714             break;
9715
9716           // Add the original type.
9717           NewTypes.push_back(*I);
9718
9719           ++Idx, ++I;
9720         } while (1);
9721       }
9722
9723       // Replace the trampoline call with a direct call.  Let the generic
9724       // code sort out any function type mismatches.
9725       FunctionType *NewFTy =
9726         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9727       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9728         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9729       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9730
9731       Instruction *NewCaller;
9732       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9733         NewCaller = InvokeInst::Create(NewCallee,
9734                                        II->getNormalDest(), II->getUnwindDest(),
9735                                        NewArgs.begin(), NewArgs.end(),
9736                                        Caller->getName(), Caller);
9737         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9738         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9739       } else {
9740         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9741                                      Caller->getName(), Caller);
9742         if (cast<CallInst>(Caller)->isTailCall())
9743           cast<CallInst>(NewCaller)->setTailCall();
9744         cast<CallInst>(NewCaller)->
9745           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9746         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9747       }
9748       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9749         Caller->replaceAllUsesWith(NewCaller);
9750       Caller->eraseFromParent();
9751       RemoveFromWorkList(Caller);
9752       return 0;
9753     }
9754   }
9755
9756   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9757   // parameter, there is no need to adjust the argument list.  Let the generic
9758   // code sort out any function type mismatches.
9759   Constant *NewCallee =
9760     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9761   CS.setCalledFunction(NewCallee);
9762   return CS.getInstruction();
9763 }
9764
9765 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9766 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9767 /// and a single binop.
9768 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9769   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9770   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9771          isa<CmpInst>(FirstInst));
9772   unsigned Opc = FirstInst->getOpcode();
9773   Value *LHSVal = FirstInst->getOperand(0);
9774   Value *RHSVal = FirstInst->getOperand(1);
9775     
9776   const Type *LHSType = LHSVal->getType();
9777   const Type *RHSType = RHSVal->getType();
9778   
9779   // Scan to see if all operands are the same opcode, all have one use, and all
9780   // kill their operands (i.e. the operands have one use).
9781   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9782     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9783     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9784         // Verify type of the LHS matches so we don't fold cmp's of different
9785         // types or GEP's with different index types.
9786         I->getOperand(0)->getType() != LHSType ||
9787         I->getOperand(1)->getType() != RHSType)
9788       return 0;
9789
9790     // If they are CmpInst instructions, check their predicates
9791     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9792       if (cast<CmpInst>(I)->getPredicate() !=
9793           cast<CmpInst>(FirstInst)->getPredicate())
9794         return 0;
9795     
9796     // Keep track of which operand needs a phi node.
9797     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9798     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9799   }
9800   
9801   // Otherwise, this is safe to transform, determine if it is profitable.
9802
9803   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9804   // Indexes are often folded into load/store instructions, so we don't want to
9805   // hide them behind a phi.
9806   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9807     return 0;
9808   
9809   Value *InLHS = FirstInst->getOperand(0);
9810   Value *InRHS = FirstInst->getOperand(1);
9811   PHINode *NewLHS = 0, *NewRHS = 0;
9812   if (LHSVal == 0) {
9813     NewLHS = PHINode::Create(LHSType,
9814                              FirstInst->getOperand(0)->getName() + ".pn");
9815     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9816     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9817     InsertNewInstBefore(NewLHS, PN);
9818     LHSVal = NewLHS;
9819   }
9820   
9821   if (RHSVal == 0) {
9822     NewRHS = PHINode::Create(RHSType,
9823                              FirstInst->getOperand(1)->getName() + ".pn");
9824     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9825     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9826     InsertNewInstBefore(NewRHS, PN);
9827     RHSVal = NewRHS;
9828   }
9829   
9830   // Add all operands to the new PHIs.
9831   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9832     if (NewLHS) {
9833       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9834       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9835     }
9836     if (NewRHS) {
9837       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9838       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9839     }
9840   }
9841     
9842   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9843     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9844   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9845     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9846                            RHSVal);
9847   else {
9848     assert(isa<GetElementPtrInst>(FirstInst));
9849     return GetElementPtrInst::Create(LHSVal, RHSVal);
9850   }
9851 }
9852
9853 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9854 /// of the block that defines it.  This means that it must be obvious the value
9855 /// of the load is not changed from the point of the load to the end of the
9856 /// block it is in.
9857 ///
9858 /// Finally, it is safe, but not profitable, to sink a load targetting a
9859 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9860 /// to a register.
9861 static bool isSafeToSinkLoad(LoadInst *L) {
9862   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9863   
9864   for (++BBI; BBI != E; ++BBI)
9865     if (BBI->mayWriteToMemory())
9866       return false;
9867   
9868   // Check for non-address taken alloca.  If not address-taken already, it isn't
9869   // profitable to do this xform.
9870   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9871     bool isAddressTaken = false;
9872     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9873          UI != E; ++UI) {
9874       if (isa<LoadInst>(UI)) continue;
9875       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9876         // If storing TO the alloca, then the address isn't taken.
9877         if (SI->getOperand(1) == AI) continue;
9878       }
9879       isAddressTaken = true;
9880       break;
9881     }
9882     
9883     if (!isAddressTaken)
9884       return false;
9885   }
9886   
9887   return true;
9888 }
9889
9890
9891 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9892 // operator and they all are only used by the PHI, PHI together their
9893 // inputs, and do the operation once, to the result of the PHI.
9894 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9895   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9896
9897   // Scan the instruction, looking for input operations that can be folded away.
9898   // If all input operands to the phi are the same instruction (e.g. a cast from
9899   // the same type or "+42") we can pull the operation through the PHI, reducing
9900   // code size and simplifying code.
9901   Constant *ConstantOp = 0;
9902   const Type *CastSrcTy = 0;
9903   bool isVolatile = false;
9904   if (isa<CastInst>(FirstInst)) {
9905     CastSrcTy = FirstInst->getOperand(0)->getType();
9906   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9907     // Can fold binop, compare or shift here if the RHS is a constant, 
9908     // otherwise call FoldPHIArgBinOpIntoPHI.
9909     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9910     if (ConstantOp == 0)
9911       return FoldPHIArgBinOpIntoPHI(PN);
9912   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9913     isVolatile = LI->isVolatile();
9914     // We can't sink the load if the loaded value could be modified between the
9915     // load and the PHI.
9916     if (LI->getParent() != PN.getIncomingBlock(0) ||
9917         !isSafeToSinkLoad(LI))
9918       return 0;
9919   } else if (isa<GetElementPtrInst>(FirstInst)) {
9920     if (FirstInst->getNumOperands() == 2)
9921       return FoldPHIArgBinOpIntoPHI(PN);
9922     // Can't handle general GEPs yet.
9923     return 0;
9924   } else {
9925     return 0;  // Cannot fold this operation.
9926   }
9927
9928   // Check to see if all arguments are the same operation.
9929   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9930     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9931     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9932     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9933       return 0;
9934     if (CastSrcTy) {
9935       if (I->getOperand(0)->getType() != CastSrcTy)
9936         return 0;  // Cast operation must match.
9937     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9938       // We can't sink the load if the loaded value could be modified between 
9939       // the load and the PHI.
9940       if (LI->isVolatile() != isVolatile ||
9941           LI->getParent() != PN.getIncomingBlock(i) ||
9942           !isSafeToSinkLoad(LI))
9943         return 0;
9944       
9945       // If the PHI is volatile and its block has multiple successors, sinking
9946       // it would remove a load of the volatile value from the path through the
9947       // other successor.
9948       if (isVolatile &&
9949           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9950         return 0;
9951
9952       
9953     } else if (I->getOperand(1) != ConstantOp) {
9954       return 0;
9955     }
9956   }
9957
9958   // Okay, they are all the same operation.  Create a new PHI node of the
9959   // correct type, and PHI together all of the LHS's of the instructions.
9960   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9961                                    PN.getName()+".in");
9962   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9963
9964   Value *InVal = FirstInst->getOperand(0);
9965   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9966
9967   // Add all operands to the new PHI.
9968   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9969     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9970     if (NewInVal != InVal)
9971       InVal = 0;
9972     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9973   }
9974
9975   Value *PhiVal;
9976   if (InVal) {
9977     // The new PHI unions all of the same values together.  This is really
9978     // common, so we handle it intelligently here for compile-time speed.
9979     PhiVal = InVal;
9980     delete NewPN;
9981   } else {
9982     InsertNewInstBefore(NewPN, PN);
9983     PhiVal = NewPN;
9984   }
9985
9986   // Insert and return the new operation.
9987   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9988     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9989   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9990     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9991   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9992     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9993                            PhiVal, ConstantOp);
9994   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9995   
9996   // If this was a volatile load that we are merging, make sure to loop through
9997   // and mark all the input loads as non-volatile.  If we don't do this, we will
9998   // insert a new volatile load and the old ones will not be deletable.
9999   if (isVolatile)
10000     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10001       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10002   
10003   return new LoadInst(PhiVal, "", isVolatile);
10004 }
10005
10006 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10007 /// that is dead.
10008 static bool DeadPHICycle(PHINode *PN,
10009                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10010   if (PN->use_empty()) return true;
10011   if (!PN->hasOneUse()) return false;
10012
10013   // Remember this node, and if we find the cycle, return.
10014   if (!PotentiallyDeadPHIs.insert(PN))
10015     return true;
10016   
10017   // Don't scan crazily complex things.
10018   if (PotentiallyDeadPHIs.size() == 16)
10019     return false;
10020
10021   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10022     return DeadPHICycle(PU, PotentiallyDeadPHIs);
10023
10024   return false;
10025 }
10026
10027 /// PHIsEqualValue - Return true if this phi node is always equal to
10028 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
10029 ///   z = some value; x = phi (y, z); y = phi (x, z)
10030 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
10031                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10032   // See if we already saw this PHI node.
10033   if (!ValueEqualPHIs.insert(PN))
10034     return true;
10035   
10036   // Don't scan crazily complex things.
10037   if (ValueEqualPHIs.size() == 16)
10038     return false;
10039  
10040   // Scan the operands to see if they are either phi nodes or are equal to
10041   // the value.
10042   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10043     Value *Op = PN->getIncomingValue(i);
10044     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10045       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10046         return false;
10047     } else if (Op != NonPhiInVal)
10048       return false;
10049   }
10050   
10051   return true;
10052 }
10053
10054
10055 // PHINode simplification
10056 //
10057 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10058   // If LCSSA is around, don't mess with Phi nodes
10059   if (MustPreserveLCSSA) return 0;
10060   
10061   if (Value *V = PN.hasConstantValue())
10062     return ReplaceInstUsesWith(PN, V);
10063
10064   // If all PHI operands are the same operation, pull them through the PHI,
10065   // reducing code size.
10066   if (isa<Instruction>(PN.getIncomingValue(0)) &&
10067       PN.getIncomingValue(0)->hasOneUse())
10068     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10069       return Result;
10070
10071   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
10072   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10073   // PHI)... break the cycle.
10074   if (PN.hasOneUse()) {
10075     Instruction *PHIUser = cast<Instruction>(PN.use_back());
10076     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10077       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10078       PotentiallyDeadPHIs.insert(&PN);
10079       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10080         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10081     }
10082    
10083     // If this phi has a single use, and if that use just computes a value for
10084     // the next iteration of a loop, delete the phi.  This occurs with unused
10085     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
10086     // common case here is good because the only other things that catch this
10087     // are induction variable analysis (sometimes) and ADCE, which is only run
10088     // late.
10089     if (PHIUser->hasOneUse() &&
10090         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10091         PHIUser->use_back() == &PN) {
10092       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10093     }
10094   }
10095
10096   // We sometimes end up with phi cycles that non-obviously end up being the
10097   // same value, for example:
10098   //   z = some value; x = phi (y, z); y = phi (x, z)
10099   // where the phi nodes don't necessarily need to be in the same block.  Do a
10100   // quick check to see if the PHI node only contains a single non-phi value, if
10101   // so, scan to see if the phi cycle is actually equal to that value.
10102   {
10103     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10104     // Scan for the first non-phi operand.
10105     while (InValNo != NumOperandVals && 
10106            isa<PHINode>(PN.getIncomingValue(InValNo)))
10107       ++InValNo;
10108
10109     if (InValNo != NumOperandVals) {
10110       Value *NonPhiInVal = PN.getOperand(InValNo);
10111       
10112       // Scan the rest of the operands to see if there are any conflicts, if so
10113       // there is no need to recursively scan other phis.
10114       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10115         Value *OpVal = PN.getIncomingValue(InValNo);
10116         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10117           break;
10118       }
10119       
10120       // If we scanned over all operands, then we have one unique value plus
10121       // phi values.  Scan PHI nodes to see if they all merge in each other or
10122       // the value.
10123       if (InValNo == NumOperandVals) {
10124         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10125         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10126           return ReplaceInstUsesWith(PN, NonPhiInVal);
10127       }
10128     }
10129   }
10130   return 0;
10131 }
10132
10133 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10134                                    Instruction *InsertPoint,
10135                                    InstCombiner *IC) {
10136   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10137   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10138   // We must cast correctly to the pointer type. Ensure that we
10139   // sign extend the integer value if it is smaller as this is
10140   // used for address computation.
10141   Instruction::CastOps opcode = 
10142      (VTySize < PtrSize ? Instruction::SExt :
10143       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10144   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10145 }
10146
10147
10148 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10149   Value *PtrOp = GEP.getOperand(0);
10150   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
10151   // If so, eliminate the noop.
10152   if (GEP.getNumOperands() == 1)
10153     return ReplaceInstUsesWith(GEP, PtrOp);
10154
10155   if (isa<UndefValue>(GEP.getOperand(0)))
10156     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10157
10158   bool HasZeroPointerIndex = false;
10159   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10160     HasZeroPointerIndex = C->isNullValue();
10161
10162   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10163     return ReplaceInstUsesWith(GEP, PtrOp);
10164
10165   // Eliminate unneeded casts for indices.
10166   bool MadeChange = false;
10167   
10168   gep_type_iterator GTI = gep_type_begin(GEP);
10169   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
10170     if (isa<SequentialType>(*GTI)) {
10171       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
10172         if (CI->getOpcode() == Instruction::ZExt ||
10173             CI->getOpcode() == Instruction::SExt) {
10174           const Type *SrcTy = CI->getOperand(0)->getType();
10175           // We can eliminate a cast from i32 to i64 iff the target 
10176           // is a 32-bit pointer target.
10177           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10178             MadeChange = true;
10179             GEP.setOperand(i, CI->getOperand(0));
10180           }
10181         }
10182       }
10183       // If we are using a wider index than needed for this platform, shrink it
10184       // to what we need.  If the incoming value needs a cast instruction,
10185       // insert it.  This explicit cast can make subsequent optimizations more
10186       // obvious.
10187       Value *Op = GEP.getOperand(i);
10188       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10189         if (Constant *C = dyn_cast<Constant>(Op)) {
10190           GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
10191           MadeChange = true;
10192         } else {
10193           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10194                                 GEP);
10195           GEP.setOperand(i, Op);
10196           MadeChange = true;
10197         }
10198       }
10199     }
10200   }
10201   if (MadeChange) return &GEP;
10202
10203   // If this GEP instruction doesn't move the pointer, and if the input operand
10204   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10205   // real input to the dest type.
10206   if (GEP.hasAllZeroIndices()) {
10207     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10208       // If the bitcast is of an allocation, and the allocation will be
10209       // converted to match the type of the cast, don't touch this.
10210       if (isa<AllocationInst>(BCI->getOperand(0))) {
10211         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10212         if (Instruction *I = visitBitCast(*BCI)) {
10213           if (I != BCI) {
10214             I->takeName(BCI);
10215             BCI->getParent()->getInstList().insert(BCI, I);
10216             ReplaceInstUsesWith(*BCI, I);
10217           }
10218           return &GEP;
10219         }
10220       }
10221       return new BitCastInst(BCI->getOperand(0), GEP.getType());
10222     }
10223   }
10224   
10225   // Combine Indices - If the source pointer to this getelementptr instruction
10226   // is a getelementptr instruction, combine the indices of the two
10227   // getelementptr instructions into a single instruction.
10228   //
10229   SmallVector<Value*, 8> SrcGEPOperands;
10230   if (User *Src = dyn_castGetElementPtr(PtrOp))
10231     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10232
10233   if (!SrcGEPOperands.empty()) {
10234     // Note that if our source is a gep chain itself that we wait for that
10235     // chain to be resolved before we perform this transformation.  This
10236     // avoids us creating a TON of code in some cases.
10237     //
10238     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10239         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10240       return 0;   // Wait until our source is folded to completion.
10241
10242     SmallVector<Value*, 8> Indices;
10243
10244     // Find out whether the last index in the source GEP is a sequential idx.
10245     bool EndsWithSequential = false;
10246     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10247            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10248       EndsWithSequential = !isa<StructType>(*I);
10249
10250     // Can we combine the two pointer arithmetics offsets?
10251     if (EndsWithSequential) {
10252       // Replace: gep (gep %P, long B), long A, ...
10253       // With:    T = long A+B; gep %P, T, ...
10254       //
10255       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10256       if (SO1 == Constant::getNullValue(SO1->getType())) {
10257         Sum = GO1;
10258       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10259         Sum = SO1;
10260       } else {
10261         // If they aren't the same type, convert both to an integer of the
10262         // target's pointer size.
10263         if (SO1->getType() != GO1->getType()) {
10264           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10265             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10266           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10267             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10268           } else {
10269             unsigned PS = TD->getPointerSizeInBits();
10270             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10271               // Convert GO1 to SO1's type.
10272               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10273
10274             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10275               // Convert SO1 to GO1's type.
10276               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10277             } else {
10278               const Type *PT = TD->getIntPtrType();
10279               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10280               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10281             }
10282           }
10283         }
10284         if (isa<Constant>(SO1) && isa<Constant>(GO1))
10285           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10286         else {
10287           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10288           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10289         }
10290       }
10291
10292       // Recycle the GEP we already have if possible.
10293       if (SrcGEPOperands.size() == 2) {
10294         GEP.setOperand(0, SrcGEPOperands[0]);
10295         GEP.setOperand(1, Sum);
10296         return &GEP;
10297       } else {
10298         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10299                        SrcGEPOperands.end()-1);
10300         Indices.push_back(Sum);
10301         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10302       }
10303     } else if (isa<Constant>(*GEP.idx_begin()) &&
10304                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10305                SrcGEPOperands.size() != 1) {
10306       // Otherwise we can do the fold if the first index of the GEP is a zero
10307       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10308                      SrcGEPOperands.end());
10309       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10310     }
10311
10312     if (!Indices.empty())
10313       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10314                                        Indices.end(), GEP.getName());
10315
10316   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10317     // GEP of global variable.  If all of the indices for this GEP are
10318     // constants, we can promote this to a constexpr instead of an instruction.
10319
10320     // Scan for nonconstants...
10321     SmallVector<Constant*, 8> Indices;
10322     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10323     for (; I != E && isa<Constant>(*I); ++I)
10324       Indices.push_back(cast<Constant>(*I));
10325
10326     if (I == E) {  // If they are all constants...
10327       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10328                                                     &Indices[0],Indices.size());
10329
10330       // Replace all uses of the GEP with the new constexpr...
10331       return ReplaceInstUsesWith(GEP, CE);
10332     }
10333   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10334     if (!isa<PointerType>(X->getType())) {
10335       // Not interesting.  Source pointer must be a cast from pointer.
10336     } else if (HasZeroPointerIndex) {
10337       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10338       // into     : GEP [10 x i8]* X, i32 0, ...
10339       //
10340       // This occurs when the program declares an array extern like "int X[];"
10341       //
10342       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10343       const PointerType *XTy = cast<PointerType>(X->getType());
10344       if (const ArrayType *XATy =
10345           dyn_cast<ArrayType>(XTy->getElementType()))
10346         if (const ArrayType *CATy =
10347             dyn_cast<ArrayType>(CPTy->getElementType()))
10348           if (CATy->getElementType() == XATy->getElementType()) {
10349             // At this point, we know that the cast source type is a pointer
10350             // to an array of the same type as the destination pointer
10351             // array.  Because the array type is never stepped over (there
10352             // is a leading zero) we can fold the cast into this GEP.
10353             GEP.setOperand(0, X);
10354             return &GEP;
10355           }
10356     } else if (GEP.getNumOperands() == 2) {
10357       // Transform things like:
10358       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10359       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10360       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10361       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10362       if (isa<ArrayType>(SrcElTy) &&
10363           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10364           TD->getABITypeSize(ResElTy)) {
10365         Value *Idx[2];
10366         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10367         Idx[1] = GEP.getOperand(1);
10368         Value *V = InsertNewInstBefore(
10369                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10370         // V and GEP are both pointer types --> BitCast
10371         return new BitCastInst(V, GEP.getType());
10372       }
10373       
10374       // Transform things like:
10375       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10376       //   (where tmp = 8*tmp2) into:
10377       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10378       
10379       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10380         uint64_t ArrayEltSize =
10381             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10382         
10383         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10384         // allow either a mul, shift, or constant here.
10385         Value *NewIdx = 0;
10386         ConstantInt *Scale = 0;
10387         if (ArrayEltSize == 1) {
10388           NewIdx = GEP.getOperand(1);
10389           Scale = ConstantInt::get(NewIdx->getType(), 1);
10390         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10391           NewIdx = ConstantInt::get(CI->getType(), 1);
10392           Scale = CI;
10393         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10394           if (Inst->getOpcode() == Instruction::Shl &&
10395               isa<ConstantInt>(Inst->getOperand(1))) {
10396             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10397             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10398             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10399             NewIdx = Inst->getOperand(0);
10400           } else if (Inst->getOpcode() == Instruction::Mul &&
10401                      isa<ConstantInt>(Inst->getOperand(1))) {
10402             Scale = cast<ConstantInt>(Inst->getOperand(1));
10403             NewIdx = Inst->getOperand(0);
10404           }
10405         }
10406         
10407         // If the index will be to exactly the right offset with the scale taken
10408         // out, perform the transformation. Note, we don't know whether Scale is
10409         // signed or not. We'll use unsigned version of division/modulo
10410         // operation after making sure Scale doesn't have the sign bit set.
10411         if (Scale && Scale->getSExtValue() >= 0LL &&
10412             Scale->getZExtValue() % ArrayEltSize == 0) {
10413           Scale = ConstantInt::get(Scale->getType(),
10414                                    Scale->getZExtValue() / ArrayEltSize);
10415           if (Scale->getZExtValue() != 1) {
10416             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10417                                                        false /*ZExt*/);
10418             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10419             NewIdx = InsertNewInstBefore(Sc, GEP);
10420           }
10421
10422           // Insert the new GEP instruction.
10423           Value *Idx[2];
10424           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10425           Idx[1] = NewIdx;
10426           Instruction *NewGEP =
10427             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10428           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10429           // The NewGEP must be pointer typed, so must the old one -> BitCast
10430           return new BitCastInst(NewGEP, GEP.getType());
10431         }
10432       }
10433     }
10434   }
10435
10436   return 0;
10437 }
10438
10439 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10440   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10441   if (AI.isArrayAllocation()) {  // Check C != 1
10442     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10443       const Type *NewTy = 
10444         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10445       AllocationInst *New = 0;
10446
10447       // Create and insert the replacement instruction...
10448       if (isa<MallocInst>(AI))
10449         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10450       else {
10451         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10452         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10453       }
10454
10455       InsertNewInstBefore(New, AI);
10456
10457       // Scan to the end of the allocation instructions, to skip over a block of
10458       // allocas if possible...
10459       //
10460       BasicBlock::iterator It = New;
10461       while (isa<AllocationInst>(*It)) ++It;
10462
10463       // Now that I is pointing to the first non-allocation-inst in the block,
10464       // insert our getelementptr instruction...
10465       //
10466       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10467       Value *Idx[2];
10468       Idx[0] = NullIdx;
10469       Idx[1] = NullIdx;
10470       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10471                                            New->getName()+".sub", It);
10472
10473       // Now make everything use the getelementptr instead of the original
10474       // allocation.
10475       return ReplaceInstUsesWith(AI, V);
10476     } else if (isa<UndefValue>(AI.getArraySize())) {
10477       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10478     }
10479   }
10480
10481   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10482   // Note that we only do this for alloca's, because malloc should allocate and
10483   // return a unique pointer, even for a zero byte allocation.
10484   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10485       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10486     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10487
10488   return 0;
10489 }
10490
10491 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10492   Value *Op = FI.getOperand(0);
10493
10494   // free undef -> unreachable.
10495   if (isa<UndefValue>(Op)) {
10496     // Insert a new store to null because we cannot modify the CFG here.
10497     new StoreInst(ConstantInt::getTrue(),
10498                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10499     return EraseInstFromFunction(FI);
10500   }
10501   
10502   // If we have 'free null' delete the instruction.  This can happen in stl code
10503   // when lots of inlining happens.
10504   if (isa<ConstantPointerNull>(Op))
10505     return EraseInstFromFunction(FI);
10506   
10507   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10508   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10509     FI.setOperand(0, CI->getOperand(0));
10510     return &FI;
10511   }
10512   
10513   // Change free (gep X, 0,0,0,0) into free(X)
10514   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10515     if (GEPI->hasAllZeroIndices()) {
10516       AddToWorkList(GEPI);
10517       FI.setOperand(0, GEPI->getOperand(0));
10518       return &FI;
10519     }
10520   }
10521   
10522   // Change free(malloc) into nothing, if the malloc has a single use.
10523   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10524     if (MI->hasOneUse()) {
10525       EraseInstFromFunction(FI);
10526       return EraseInstFromFunction(*MI);
10527     }
10528
10529   return 0;
10530 }
10531
10532
10533 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10534 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10535                                         const TargetData *TD) {
10536   User *CI = cast<User>(LI.getOperand(0));
10537   Value *CastOp = CI->getOperand(0);
10538
10539   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10540     // Instead of loading constant c string, use corresponding integer value
10541     // directly if string length is small enough.
10542     const std::string &Str = CE->getOperand(0)->getStringValue();
10543     if (!Str.empty()) {
10544       unsigned len = Str.length();
10545       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10546       unsigned numBits = Ty->getPrimitiveSizeInBits();
10547       // Replace LI with immediate integer store.
10548       if ((numBits >> 3) == len + 1) {
10549         APInt StrVal(numBits, 0);
10550         APInt SingleChar(numBits, 0);
10551         if (TD->isLittleEndian()) {
10552           for (signed i = len-1; i >= 0; i--) {
10553             SingleChar = (uint64_t) Str[i];
10554             StrVal = (StrVal << 8) | SingleChar;
10555           }
10556         } else {
10557           for (unsigned i = 0; i < len; i++) {
10558             SingleChar = (uint64_t) Str[i];
10559             StrVal = (StrVal << 8) | SingleChar;
10560           }
10561           // Append NULL at the end.
10562           SingleChar = 0;
10563           StrVal = (StrVal << 8) | SingleChar;
10564         }
10565         Value *NL = ConstantInt::get(StrVal);
10566         return IC.ReplaceInstUsesWith(LI, NL);
10567       }
10568     }
10569   }
10570
10571   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10572   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10573     const Type *SrcPTy = SrcTy->getElementType();
10574
10575     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10576          isa<VectorType>(DestPTy)) {
10577       // If the source is an array, the code below will not succeed.  Check to
10578       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10579       // constants.
10580       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10581         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10582           if (ASrcTy->getNumElements() != 0) {
10583             Value *Idxs[2];
10584             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10585             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10586             SrcTy = cast<PointerType>(CastOp->getType());
10587             SrcPTy = SrcTy->getElementType();
10588           }
10589
10590       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10591             isa<VectorType>(SrcPTy)) &&
10592           // Do not allow turning this into a load of an integer, which is then
10593           // casted to a pointer, this pessimizes pointer analysis a lot.
10594           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10595           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10596                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10597
10598         // Okay, we are casting from one integer or pointer type to another of
10599         // the same size.  Instead of casting the pointer before the load, cast
10600         // the result of the loaded value.
10601         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10602                                                              CI->getName(),
10603                                                          LI.isVolatile()),LI);
10604         // Now cast the result of the load.
10605         return new BitCastInst(NewLoad, LI.getType());
10606       }
10607     }
10608   }
10609   return 0;
10610 }
10611
10612 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10613 /// from this value cannot trap.  If it is not obviously safe to load from the
10614 /// specified pointer, we do a quick local scan of the basic block containing
10615 /// ScanFrom, to determine if the address is already accessed.
10616 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10617   // If it is an alloca it is always safe to load from.
10618   if (isa<AllocaInst>(V)) return true;
10619
10620   // If it is a global variable it is mostly safe to load from.
10621   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10622     // Don't try to evaluate aliases.  External weak GV can be null.
10623     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10624
10625   // Otherwise, be a little bit agressive by scanning the local block where we
10626   // want to check to see if the pointer is already being loaded or stored
10627   // from/to.  If so, the previous load or store would have already trapped,
10628   // so there is no harm doing an extra load (also, CSE will later eliminate
10629   // the load entirely).
10630   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10631
10632   while (BBI != E) {
10633     --BBI;
10634
10635     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10636       if (LI->getOperand(0) == V) return true;
10637     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10638       if (SI->getOperand(1) == V) return true;
10639
10640   }
10641   return false;
10642 }
10643
10644 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10645 /// until we find the underlying object a pointer is referring to or something
10646 /// we don't understand.  Note that the returned pointer may be offset from the
10647 /// input, because we ignore GEP indices.
10648 static Value *GetUnderlyingObject(Value *Ptr) {
10649   while (1) {
10650     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10651       if (CE->getOpcode() == Instruction::BitCast ||
10652           CE->getOpcode() == Instruction::GetElementPtr)
10653         Ptr = CE->getOperand(0);
10654       else
10655         return Ptr;
10656     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10657       Ptr = BCI->getOperand(0);
10658     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10659       Ptr = GEP->getOperand(0);
10660     } else {
10661       return Ptr;
10662     }
10663   }
10664 }
10665
10666 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10667   Value *Op = LI.getOperand(0);
10668
10669   // Attempt to improve the alignment.
10670   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10671   if (KnownAlign >
10672       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10673                                 LI.getAlignment()))
10674     LI.setAlignment(KnownAlign);
10675
10676   // load (cast X) --> cast (load X) iff safe
10677   if (isa<CastInst>(Op))
10678     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10679       return Res;
10680
10681   // None of the following transforms are legal for volatile loads.
10682   if (LI.isVolatile()) return 0;
10683   
10684   if (&LI.getParent()->front() != &LI) {
10685     BasicBlock::iterator BBI = &LI; --BBI;
10686     // If the instruction immediately before this is a store to the same
10687     // address, do a simple form of store->load forwarding.
10688     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10689       if (SI->getOperand(1) == LI.getOperand(0))
10690         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10691     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10692       if (LIB->getOperand(0) == LI.getOperand(0))
10693         return ReplaceInstUsesWith(LI, LIB);
10694   }
10695
10696   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10697     const Value *GEPI0 = GEPI->getOperand(0);
10698     // TODO: Consider a target hook for valid address spaces for this xform.
10699     if (isa<ConstantPointerNull>(GEPI0) &&
10700         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10701       // Insert a new store to null instruction before the load to indicate
10702       // that this code is not reachable.  We do this instead of inserting
10703       // an unreachable instruction directly because we cannot modify the
10704       // CFG.
10705       new StoreInst(UndefValue::get(LI.getType()),
10706                     Constant::getNullValue(Op->getType()), &LI);
10707       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10708     }
10709   } 
10710
10711   if (Constant *C = dyn_cast<Constant>(Op)) {
10712     // load null/undef -> undef
10713     // TODO: Consider a target hook for valid address spaces for this xform.
10714     if (isa<UndefValue>(C) || (C->isNullValue() && 
10715         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10716       // Insert a new store to null instruction before the load to indicate that
10717       // this code is not reachable.  We do this instead of inserting an
10718       // unreachable instruction directly because we cannot modify the CFG.
10719       new StoreInst(UndefValue::get(LI.getType()),
10720                     Constant::getNullValue(Op->getType()), &LI);
10721       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10722     }
10723
10724     // Instcombine load (constant global) into the value loaded.
10725     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10726       if (GV->isConstant() && !GV->isDeclaration())
10727         return ReplaceInstUsesWith(LI, GV->getInitializer());
10728
10729     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10730     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10731       if (CE->getOpcode() == Instruction::GetElementPtr) {
10732         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10733           if (GV->isConstant() && !GV->isDeclaration())
10734             if (Constant *V = 
10735                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10736               return ReplaceInstUsesWith(LI, V);
10737         if (CE->getOperand(0)->isNullValue()) {
10738           // Insert a new store to null instruction before the load to indicate
10739           // that this code is not reachable.  We do this instead of inserting
10740           // an unreachable instruction directly because we cannot modify the
10741           // CFG.
10742           new StoreInst(UndefValue::get(LI.getType()),
10743                         Constant::getNullValue(Op->getType()), &LI);
10744           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10745         }
10746
10747       } else if (CE->isCast()) {
10748         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10749           return Res;
10750       }
10751     }
10752   }
10753     
10754   // If this load comes from anywhere in a constant global, and if the global
10755   // is all undef or zero, we know what it loads.
10756   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10757     if (GV->isConstant() && GV->hasInitializer()) {
10758       if (GV->getInitializer()->isNullValue())
10759         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10760       else if (isa<UndefValue>(GV->getInitializer()))
10761         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10762     }
10763   }
10764
10765   if (Op->hasOneUse()) {
10766     // Change select and PHI nodes to select values instead of addresses: this
10767     // helps alias analysis out a lot, allows many others simplifications, and
10768     // exposes redundancy in the code.
10769     //
10770     // Note that we cannot do the transformation unless we know that the
10771     // introduced loads cannot trap!  Something like this is valid as long as
10772     // the condition is always false: load (select bool %C, int* null, int* %G),
10773     // but it would not be valid if we transformed it to load from null
10774     // unconditionally.
10775     //
10776     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10777       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10778       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10779           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10780         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10781                                      SI->getOperand(1)->getName()+".val"), LI);
10782         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10783                                      SI->getOperand(2)->getName()+".val"), LI);
10784         return SelectInst::Create(SI->getCondition(), V1, V2);
10785       }
10786
10787       // load (select (cond, null, P)) -> load P
10788       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10789         if (C->isNullValue()) {
10790           LI.setOperand(0, SI->getOperand(2));
10791           return &LI;
10792         }
10793
10794       // load (select (cond, P, null)) -> load P
10795       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10796         if (C->isNullValue()) {
10797           LI.setOperand(0, SI->getOperand(1));
10798           return &LI;
10799         }
10800     }
10801   }
10802   return 0;
10803 }
10804
10805 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10806 /// when possible.
10807 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10808   User *CI = cast<User>(SI.getOperand(1));
10809   Value *CastOp = CI->getOperand(0);
10810
10811   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10812   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10813     const Type *SrcPTy = SrcTy->getElementType();
10814
10815     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10816       // If the source is an array, the code below will not succeed.  Check to
10817       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10818       // constants.
10819       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10820         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10821           if (ASrcTy->getNumElements() != 0) {
10822             Value* Idxs[2];
10823             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10824             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10825             SrcTy = cast<PointerType>(CastOp->getType());
10826             SrcPTy = SrcTy->getElementType();
10827           }
10828
10829       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10830           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10831                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10832
10833         // Okay, we are casting from one integer or pointer type to another of
10834         // the same size.  Instead of casting the pointer before 
10835         // the store, cast the value to be stored.
10836         Value *NewCast;
10837         Value *SIOp0 = SI.getOperand(0);
10838         Instruction::CastOps opcode = Instruction::BitCast;
10839         const Type* CastSrcTy = SIOp0->getType();
10840         const Type* CastDstTy = SrcPTy;
10841         if (isa<PointerType>(CastDstTy)) {
10842           if (CastSrcTy->isInteger())
10843             opcode = Instruction::IntToPtr;
10844         } else if (isa<IntegerType>(CastDstTy)) {
10845           if (isa<PointerType>(SIOp0->getType()))
10846             opcode = Instruction::PtrToInt;
10847         }
10848         if (Constant *C = dyn_cast<Constant>(SIOp0))
10849           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10850         else
10851           NewCast = IC.InsertNewInstBefore(
10852             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10853             SI);
10854         return new StoreInst(NewCast, CastOp);
10855       }
10856     }
10857   }
10858   return 0;
10859 }
10860
10861 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10862   Value *Val = SI.getOperand(0);
10863   Value *Ptr = SI.getOperand(1);
10864
10865   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10866     EraseInstFromFunction(SI);
10867     ++NumCombined;
10868     return 0;
10869   }
10870   
10871   // If the RHS is an alloca with a single use, zapify the store, making the
10872   // alloca dead.
10873   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10874     if (isa<AllocaInst>(Ptr)) {
10875       EraseInstFromFunction(SI);
10876       ++NumCombined;
10877       return 0;
10878     }
10879     
10880     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10881       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10882           GEP->getOperand(0)->hasOneUse()) {
10883         EraseInstFromFunction(SI);
10884         ++NumCombined;
10885         return 0;
10886       }
10887   }
10888
10889   // Attempt to improve the alignment.
10890   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10891   if (KnownAlign >
10892       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10893                                 SI.getAlignment()))
10894     SI.setAlignment(KnownAlign);
10895
10896   // Do really simple DSE, to catch cases where there are several consequtive
10897   // stores to the same location, separated by a few arithmetic operations. This
10898   // situation often occurs with bitfield accesses.
10899   BasicBlock::iterator BBI = &SI;
10900   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10901        --ScanInsts) {
10902     --BBI;
10903     
10904     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10905       // Prev store isn't volatile, and stores to the same location?
10906       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10907         ++NumDeadStore;
10908         ++BBI;
10909         EraseInstFromFunction(*PrevSI);
10910         continue;
10911       }
10912       break;
10913     }
10914     
10915     // If this is a load, we have to stop.  However, if the loaded value is from
10916     // the pointer we're loading and is producing the pointer we're storing,
10917     // then *this* store is dead (X = load P; store X -> P).
10918     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10919       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10920         EraseInstFromFunction(SI);
10921         ++NumCombined;
10922         return 0;
10923       }
10924       // Otherwise, this is a load from some other location.  Stores before it
10925       // may not be dead.
10926       break;
10927     }
10928     
10929     // Don't skip over loads or things that can modify memory.
10930     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10931       break;
10932   }
10933   
10934   
10935   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10936
10937   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10938   if (isa<ConstantPointerNull>(Ptr)) {
10939     if (!isa<UndefValue>(Val)) {
10940       SI.setOperand(0, UndefValue::get(Val->getType()));
10941       if (Instruction *U = dyn_cast<Instruction>(Val))
10942         AddToWorkList(U);  // Dropped a use.
10943       ++NumCombined;
10944     }
10945     return 0;  // Do not modify these!
10946   }
10947
10948   // store undef, Ptr -> noop
10949   if (isa<UndefValue>(Val)) {
10950     EraseInstFromFunction(SI);
10951     ++NumCombined;
10952     return 0;
10953   }
10954
10955   // If the pointer destination is a cast, see if we can fold the cast into the
10956   // source instead.
10957   if (isa<CastInst>(Ptr))
10958     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10959       return Res;
10960   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10961     if (CE->isCast())
10962       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10963         return Res;
10964
10965   
10966   // If this store is the last instruction in the basic block, and if the block
10967   // ends with an unconditional branch, try to move it to the successor block.
10968   BBI = &SI; ++BBI;
10969   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10970     if (BI->isUnconditional())
10971       if (SimplifyStoreAtEndOfBlock(SI))
10972         return 0;  // xform done!
10973   
10974   return 0;
10975 }
10976
10977 /// SimplifyStoreAtEndOfBlock - Turn things like:
10978 ///   if () { *P = v1; } else { *P = v2 }
10979 /// into a phi node with a store in the successor.
10980 ///
10981 /// Simplify things like:
10982 ///   *P = v1; if () { *P = v2; }
10983 /// into a phi node with a store in the successor.
10984 ///
10985 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10986   BasicBlock *StoreBB = SI.getParent();
10987   
10988   // Check to see if the successor block has exactly two incoming edges.  If
10989   // so, see if the other predecessor contains a store to the same location.
10990   // if so, insert a PHI node (if needed) and move the stores down.
10991   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10992   
10993   // Determine whether Dest has exactly two predecessors and, if so, compute
10994   // the other predecessor.
10995   pred_iterator PI = pred_begin(DestBB);
10996   BasicBlock *OtherBB = 0;
10997   if (*PI != StoreBB)
10998     OtherBB = *PI;
10999   ++PI;
11000   if (PI == pred_end(DestBB))
11001     return false;
11002   
11003   if (*PI != StoreBB) {
11004     if (OtherBB)
11005       return false;
11006     OtherBB = *PI;
11007   }
11008   if (++PI != pred_end(DestBB))
11009     return false;
11010   
11011   
11012   // Verify that the other block ends in a branch and is not otherwise empty.
11013   BasicBlock::iterator BBI = OtherBB->getTerminator();
11014   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11015   if (!OtherBr || BBI == OtherBB->begin())
11016     return false;
11017   
11018   // If the other block ends in an unconditional branch, check for the 'if then
11019   // else' case.  there is an instruction before the branch.
11020   StoreInst *OtherStore = 0;
11021   if (OtherBr->isUnconditional()) {
11022     // If this isn't a store, or isn't a store to the same location, bail out.
11023     --BBI;
11024     OtherStore = dyn_cast<StoreInst>(BBI);
11025     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11026       return false;
11027   } else {
11028     // Otherwise, the other block ended with a conditional branch. If one of the
11029     // destinations is StoreBB, then we have the if/then case.
11030     if (OtherBr->getSuccessor(0) != StoreBB && 
11031         OtherBr->getSuccessor(1) != StoreBB)
11032       return false;
11033     
11034     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11035     // if/then triangle.  See if there is a store to the same ptr as SI that
11036     // lives in OtherBB.
11037     for (;; --BBI) {
11038       // Check to see if we find the matching store.
11039       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11040         if (OtherStore->getOperand(1) != SI.getOperand(1))
11041           return false;
11042         break;
11043       }
11044       // If we find something that may be using the stored value, or if we run
11045       // out of instructions, we can't do the xform.
11046       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11047           BBI == OtherBB->begin())
11048         return false;
11049     }
11050     
11051     // In order to eliminate the store in OtherBr, we have to
11052     // make sure nothing reads the stored value in StoreBB.
11053     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11054       // FIXME: This should really be AA driven.
11055       if (isa<LoadInst>(I) || I->mayWriteToMemory())
11056         return false;
11057     }
11058   }
11059   
11060   // Insert a PHI node now if we need it.
11061   Value *MergedVal = OtherStore->getOperand(0);
11062   if (MergedVal != SI.getOperand(0)) {
11063     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11064     PN->reserveOperandSpace(2);
11065     PN->addIncoming(SI.getOperand(0), SI.getParent());
11066     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11067     MergedVal = InsertNewInstBefore(PN, DestBB->front());
11068   }
11069   
11070   // Advance to a place where it is safe to insert the new store and
11071   // insert it.
11072   BBI = DestBB->getFirstNonPHI();
11073   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11074                                     OtherStore->isVolatile()), *BBI);
11075   
11076   // Nuke the old stores.
11077   EraseInstFromFunction(SI);
11078   EraseInstFromFunction(*OtherStore);
11079   ++NumCombined;
11080   return true;
11081 }
11082
11083
11084 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11085   // Change br (not X), label True, label False to: br X, label False, True
11086   Value *X = 0;
11087   BasicBlock *TrueDest;
11088   BasicBlock *FalseDest;
11089   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11090       !isa<Constant>(X)) {
11091     // Swap Destinations and condition...
11092     BI.setCondition(X);
11093     BI.setSuccessor(0, FalseDest);
11094     BI.setSuccessor(1, TrueDest);
11095     return &BI;
11096   }
11097
11098   // Cannonicalize fcmp_one -> fcmp_oeq
11099   FCmpInst::Predicate FPred; Value *Y;
11100   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
11101                              TrueDest, FalseDest)))
11102     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11103          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11104       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11105       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11106       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11107       NewSCC->takeName(I);
11108       // Swap Destinations and condition...
11109       BI.setCondition(NewSCC);
11110       BI.setSuccessor(0, FalseDest);
11111       BI.setSuccessor(1, TrueDest);
11112       RemoveFromWorkList(I);
11113       I->eraseFromParent();
11114       AddToWorkList(NewSCC);
11115       return &BI;
11116     }
11117
11118   // Cannonicalize icmp_ne -> icmp_eq
11119   ICmpInst::Predicate IPred;
11120   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11121                       TrueDest, FalseDest)))
11122     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
11123          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11124          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11125       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11126       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11127       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11128       NewSCC->takeName(I);
11129       // Swap Destinations and condition...
11130       BI.setCondition(NewSCC);
11131       BI.setSuccessor(0, FalseDest);
11132       BI.setSuccessor(1, TrueDest);
11133       RemoveFromWorkList(I);
11134       I->eraseFromParent();;
11135       AddToWorkList(NewSCC);
11136       return &BI;
11137     }
11138
11139   return 0;
11140 }
11141
11142 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11143   Value *Cond = SI.getCondition();
11144   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11145     if (I->getOpcode() == Instruction::Add)
11146       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11147         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11148         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11149           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11150                                                 AddRHS));
11151         SI.setOperand(0, I->getOperand(0));
11152         AddToWorkList(I);
11153         return &SI;
11154       }
11155   }
11156   return 0;
11157 }
11158
11159 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11160 /// is to leave as a vector operation.
11161 static bool CheapToScalarize(Value *V, bool isConstant) {
11162   if (isa<ConstantAggregateZero>(V)) 
11163     return true;
11164   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11165     if (isConstant) return true;
11166     // If all elts are the same, we can extract.
11167     Constant *Op0 = C->getOperand(0);
11168     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11169       if (C->getOperand(i) != Op0)
11170         return false;
11171     return true;
11172   }
11173   Instruction *I = dyn_cast<Instruction>(V);
11174   if (!I) return false;
11175   
11176   // Insert element gets simplified to the inserted element or is deleted if
11177   // this is constant idx extract element and its a constant idx insertelt.
11178   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11179       isa<ConstantInt>(I->getOperand(2)))
11180     return true;
11181   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11182     return true;
11183   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11184     if (BO->hasOneUse() &&
11185         (CheapToScalarize(BO->getOperand(0), isConstant) ||
11186          CheapToScalarize(BO->getOperand(1), isConstant)))
11187       return true;
11188   if (CmpInst *CI = dyn_cast<CmpInst>(I))
11189     if (CI->hasOneUse() &&
11190         (CheapToScalarize(CI->getOperand(0), isConstant) ||
11191          CheapToScalarize(CI->getOperand(1), isConstant)))
11192       return true;
11193   
11194   return false;
11195 }
11196
11197 /// Read and decode a shufflevector mask.
11198 ///
11199 /// It turns undef elements into values that are larger than the number of
11200 /// elements in the input.
11201 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11202   unsigned NElts = SVI->getType()->getNumElements();
11203   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11204     return std::vector<unsigned>(NElts, 0);
11205   if (isa<UndefValue>(SVI->getOperand(2)))
11206     return std::vector<unsigned>(NElts, 2*NElts);
11207
11208   std::vector<unsigned> Result;
11209   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11210   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11211     if (isa<UndefValue>(CP->getOperand(i)))
11212       Result.push_back(NElts*2);  // undef -> 8
11213     else
11214       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
11215   return Result;
11216 }
11217
11218 /// FindScalarElement - Given a vector and an element number, see if the scalar
11219 /// value is already around as a register, for example if it were inserted then
11220 /// extracted from the vector.
11221 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11222   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11223   const VectorType *PTy = cast<VectorType>(V->getType());
11224   unsigned Width = PTy->getNumElements();
11225   if (EltNo >= Width)  // Out of range access.
11226     return UndefValue::get(PTy->getElementType());
11227   
11228   if (isa<UndefValue>(V))
11229     return UndefValue::get(PTy->getElementType());
11230   else if (isa<ConstantAggregateZero>(V))
11231     return Constant::getNullValue(PTy->getElementType());
11232   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11233     return CP->getOperand(EltNo);
11234   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11235     // If this is an insert to a variable element, we don't know what it is.
11236     if (!isa<ConstantInt>(III->getOperand(2))) 
11237       return 0;
11238     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11239     
11240     // If this is an insert to the element we are looking for, return the
11241     // inserted value.
11242     if (EltNo == IIElt) 
11243       return III->getOperand(1);
11244     
11245     // Otherwise, the insertelement doesn't modify the value, recurse on its
11246     // vector input.
11247     return FindScalarElement(III->getOperand(0), EltNo);
11248   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11249     unsigned InEl = getShuffleMask(SVI)[EltNo];
11250     if (InEl < Width)
11251       return FindScalarElement(SVI->getOperand(0), InEl);
11252     else if (InEl < Width*2)
11253       return FindScalarElement(SVI->getOperand(1), InEl - Width);
11254     else
11255       return UndefValue::get(PTy->getElementType());
11256   }
11257   
11258   // Otherwise, we don't know.
11259   return 0;
11260 }
11261
11262 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11263
11264   // If vector val is undef, replace extract with scalar undef.
11265   if (isa<UndefValue>(EI.getOperand(0)))
11266     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11267
11268   // If vector val is constant 0, replace extract with scalar 0.
11269   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11270     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11271   
11272   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11273     // If vector val is constant with uniform operands, replace EI
11274     // with that operand
11275     Constant *op0 = C->getOperand(0);
11276     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11277       if (C->getOperand(i) != op0) {
11278         op0 = 0; 
11279         break;
11280       }
11281     if (op0)
11282       return ReplaceInstUsesWith(EI, op0);
11283   }
11284   
11285   // If extracting a specified index from the vector, see if we can recursively
11286   // find a previously computed scalar that was inserted into the vector.
11287   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11288     unsigned IndexVal = IdxC->getZExtValue();
11289     unsigned VectorWidth = 
11290       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11291       
11292     // If this is extracting an invalid index, turn this into undef, to avoid
11293     // crashing the code below.
11294     if (IndexVal >= VectorWidth)
11295       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11296     
11297     // This instruction only demands the single element from the input vector.
11298     // If the input vector has a single use, simplify it based on this use
11299     // property.
11300     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11301       uint64_t UndefElts;
11302       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11303                                                 1 << IndexVal,
11304                                                 UndefElts)) {
11305         EI.setOperand(0, V);
11306         return &EI;
11307       }
11308     }
11309     
11310     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11311       return ReplaceInstUsesWith(EI, Elt);
11312     
11313     // If the this extractelement is directly using a bitcast from a vector of
11314     // the same number of elements, see if we can find the source element from
11315     // it.  In this case, we will end up needing to bitcast the scalars.
11316     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11317       if (const VectorType *VT = 
11318               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11319         if (VT->getNumElements() == VectorWidth)
11320           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11321             return new BitCastInst(Elt, EI.getType());
11322     }
11323   }
11324   
11325   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11326     if (I->hasOneUse()) {
11327       // Push extractelement into predecessor operation if legal and
11328       // profitable to do so
11329       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11330         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11331         if (CheapToScalarize(BO, isConstantElt)) {
11332           ExtractElementInst *newEI0 = 
11333             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11334                                    EI.getName()+".lhs");
11335           ExtractElementInst *newEI1 =
11336             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11337                                    EI.getName()+".rhs");
11338           InsertNewInstBefore(newEI0, EI);
11339           InsertNewInstBefore(newEI1, EI);
11340           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11341         }
11342       } else if (isa<LoadInst>(I)) {
11343         unsigned AS = 
11344           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11345         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11346                                          PointerType::get(EI.getType(), AS),EI);
11347         GetElementPtrInst *GEP =
11348           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11349         InsertNewInstBefore(GEP, EI);
11350         return new LoadInst(GEP);
11351       }
11352     }
11353     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11354       // Extracting the inserted element?
11355       if (IE->getOperand(2) == EI.getOperand(1))
11356         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11357       // If the inserted and extracted elements are constants, they must not
11358       // be the same value, extract from the pre-inserted value instead.
11359       if (isa<Constant>(IE->getOperand(2)) &&
11360           isa<Constant>(EI.getOperand(1))) {
11361         AddUsesToWorkList(EI);
11362         EI.setOperand(0, IE->getOperand(0));
11363         return &EI;
11364       }
11365     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11366       // If this is extracting an element from a shufflevector, figure out where
11367       // it came from and extract from the appropriate input element instead.
11368       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11369         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11370         Value *Src;
11371         if (SrcIdx < SVI->getType()->getNumElements())
11372           Src = SVI->getOperand(0);
11373         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11374           SrcIdx -= SVI->getType()->getNumElements();
11375           Src = SVI->getOperand(1);
11376         } else {
11377           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11378         }
11379         return new ExtractElementInst(Src, SrcIdx);
11380       }
11381     }
11382   }
11383   return 0;
11384 }
11385
11386 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11387 /// elements from either LHS or RHS, return the shuffle mask and true. 
11388 /// Otherwise, return false.
11389 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11390                                          std::vector<Constant*> &Mask) {
11391   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11392          "Invalid CollectSingleShuffleElements");
11393   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11394
11395   if (isa<UndefValue>(V)) {
11396     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11397     return true;
11398   } else if (V == LHS) {
11399     for (unsigned i = 0; i != NumElts; ++i)
11400       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11401     return true;
11402   } else if (V == RHS) {
11403     for (unsigned i = 0; i != NumElts; ++i)
11404       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11405     return true;
11406   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11407     // If this is an insert of an extract from some other vector, include it.
11408     Value *VecOp    = IEI->getOperand(0);
11409     Value *ScalarOp = IEI->getOperand(1);
11410     Value *IdxOp    = IEI->getOperand(2);
11411     
11412     if (!isa<ConstantInt>(IdxOp))
11413       return false;
11414     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11415     
11416     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11417       // Okay, we can handle this if the vector we are insertinting into is
11418       // transitively ok.
11419       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11420         // If so, update the mask to reflect the inserted undef.
11421         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11422         return true;
11423       }      
11424     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11425       if (isa<ConstantInt>(EI->getOperand(1)) &&
11426           EI->getOperand(0)->getType() == V->getType()) {
11427         unsigned ExtractedIdx =
11428           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11429         
11430         // This must be extracting from either LHS or RHS.
11431         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11432           // Okay, we can handle this if the vector we are insertinting into is
11433           // transitively ok.
11434           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11435             // If so, update the mask to reflect the inserted value.
11436             if (EI->getOperand(0) == LHS) {
11437               Mask[InsertedIdx & (NumElts-1)] = 
11438                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11439             } else {
11440               assert(EI->getOperand(0) == RHS);
11441               Mask[InsertedIdx & (NumElts-1)] = 
11442                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11443               
11444             }
11445             return true;
11446           }
11447         }
11448       }
11449     }
11450   }
11451   // TODO: Handle shufflevector here!
11452   
11453   return false;
11454 }
11455
11456 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11457 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11458 /// that computes V and the LHS value of the shuffle.
11459 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11460                                      Value *&RHS) {
11461   assert(isa<VectorType>(V->getType()) && 
11462          (RHS == 0 || V->getType() == RHS->getType()) &&
11463          "Invalid shuffle!");
11464   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11465
11466   if (isa<UndefValue>(V)) {
11467     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11468     return V;
11469   } else if (isa<ConstantAggregateZero>(V)) {
11470     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11471     return V;
11472   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11473     // If this is an insert of an extract from some other vector, include it.
11474     Value *VecOp    = IEI->getOperand(0);
11475     Value *ScalarOp = IEI->getOperand(1);
11476     Value *IdxOp    = IEI->getOperand(2);
11477     
11478     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11479       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11480           EI->getOperand(0)->getType() == V->getType()) {
11481         unsigned ExtractedIdx =
11482           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11483         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11484         
11485         // Either the extracted from or inserted into vector must be RHSVec,
11486         // otherwise we'd end up with a shuffle of three inputs.
11487         if (EI->getOperand(0) == RHS || RHS == 0) {
11488           RHS = EI->getOperand(0);
11489           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11490           Mask[InsertedIdx & (NumElts-1)] = 
11491             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11492           return V;
11493         }
11494         
11495         if (VecOp == RHS) {
11496           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11497           // Everything but the extracted element is replaced with the RHS.
11498           for (unsigned i = 0; i != NumElts; ++i) {
11499             if (i != InsertedIdx)
11500               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11501           }
11502           return V;
11503         }
11504         
11505         // If this insertelement is a chain that comes from exactly these two
11506         // vectors, return the vector and the effective shuffle.
11507         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11508           return EI->getOperand(0);
11509         
11510       }
11511     }
11512   }
11513   // TODO: Handle shufflevector here!
11514   
11515   // Otherwise, can't do anything fancy.  Return an identity vector.
11516   for (unsigned i = 0; i != NumElts; ++i)
11517     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11518   return V;
11519 }
11520
11521 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11522   Value *VecOp    = IE.getOperand(0);
11523   Value *ScalarOp = IE.getOperand(1);
11524   Value *IdxOp    = IE.getOperand(2);
11525   
11526   // Inserting an undef or into an undefined place, remove this.
11527   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11528     ReplaceInstUsesWith(IE, VecOp);
11529   
11530   // If the inserted element was extracted from some other vector, and if the 
11531   // indexes are constant, try to turn this into a shufflevector operation.
11532   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11533     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11534         EI->getOperand(0)->getType() == IE.getType()) {
11535       unsigned NumVectorElts = IE.getType()->getNumElements();
11536       unsigned ExtractedIdx =
11537         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11538       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11539       
11540       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11541         return ReplaceInstUsesWith(IE, VecOp);
11542       
11543       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11544         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11545       
11546       // If we are extracting a value from a vector, then inserting it right
11547       // back into the same place, just use the input vector.
11548       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11549         return ReplaceInstUsesWith(IE, VecOp);      
11550       
11551       // We could theoretically do this for ANY input.  However, doing so could
11552       // turn chains of insertelement instructions into a chain of shufflevector
11553       // instructions, and right now we do not merge shufflevectors.  As such,
11554       // only do this in a situation where it is clear that there is benefit.
11555       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11556         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11557         // the values of VecOp, except then one read from EIOp0.
11558         // Build a new shuffle mask.
11559         std::vector<Constant*> Mask;
11560         if (isa<UndefValue>(VecOp))
11561           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11562         else {
11563           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11564           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11565                                                        NumVectorElts));
11566         } 
11567         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11568         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11569                                      ConstantVector::get(Mask));
11570       }
11571       
11572       // If this insertelement isn't used by some other insertelement, turn it
11573       // (and any insertelements it points to), into one big shuffle.
11574       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11575         std::vector<Constant*> Mask;
11576         Value *RHS = 0;
11577         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11578         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11579         // We now have a shuffle of LHS, RHS, Mask.
11580         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11581       }
11582     }
11583   }
11584
11585   return 0;
11586 }
11587
11588
11589 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11590   Value *LHS = SVI.getOperand(0);
11591   Value *RHS = SVI.getOperand(1);
11592   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11593
11594   bool MadeChange = false;
11595   
11596   // Undefined shuffle mask -> undefined value.
11597   if (isa<UndefValue>(SVI.getOperand(2)))
11598     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11599   
11600   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11601   // the undef, change them to undefs.
11602   if (isa<UndefValue>(SVI.getOperand(1))) {
11603     // Scan to see if there are any references to the RHS.  If so, replace them
11604     // with undef element refs and set MadeChange to true.
11605     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11606       if (Mask[i] >= e && Mask[i] != 2*e) {
11607         Mask[i] = 2*e;
11608         MadeChange = true;
11609       }
11610     }
11611     
11612     if (MadeChange) {
11613       // Remap any references to RHS to use LHS.
11614       std::vector<Constant*> Elts;
11615       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11616         if (Mask[i] == 2*e)
11617           Elts.push_back(UndefValue::get(Type::Int32Ty));
11618         else
11619           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11620       }
11621       SVI.setOperand(2, ConstantVector::get(Elts));
11622     }
11623   }
11624   
11625   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11626   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11627   if (LHS == RHS || isa<UndefValue>(LHS)) {
11628     if (isa<UndefValue>(LHS) && LHS == RHS) {
11629       // shuffle(undef,undef,mask) -> undef.
11630       return ReplaceInstUsesWith(SVI, LHS);
11631     }
11632     
11633     // Remap any references to RHS to use LHS.
11634     std::vector<Constant*> Elts;
11635     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11636       if (Mask[i] >= 2*e)
11637         Elts.push_back(UndefValue::get(Type::Int32Ty));
11638       else {
11639         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11640             (Mask[i] <  e && isa<UndefValue>(LHS)))
11641           Mask[i] = 2*e;     // Turn into undef.
11642         else
11643           Mask[i] &= (e-1);  // Force to LHS.
11644         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11645       }
11646     }
11647     SVI.setOperand(0, SVI.getOperand(1));
11648     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11649     SVI.setOperand(2, ConstantVector::get(Elts));
11650     LHS = SVI.getOperand(0);
11651     RHS = SVI.getOperand(1);
11652     MadeChange = true;
11653   }
11654   
11655   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11656   bool isLHSID = true, isRHSID = true;
11657     
11658   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11659     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11660     // Is this an identity shuffle of the LHS value?
11661     isLHSID &= (Mask[i] == i);
11662       
11663     // Is this an identity shuffle of the RHS value?
11664     isRHSID &= (Mask[i]-e == i);
11665   }
11666
11667   // Eliminate identity shuffles.
11668   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11669   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11670   
11671   // If the LHS is a shufflevector itself, see if we can combine it with this
11672   // one without producing an unusual shuffle.  Here we are really conservative:
11673   // we are absolutely afraid of producing a shuffle mask not in the input
11674   // program, because the code gen may not be smart enough to turn a merged
11675   // shuffle into two specific shuffles: it may produce worse code.  As such,
11676   // we only merge two shuffles if the result is one of the two input shuffle
11677   // masks.  In this case, merging the shuffles just removes one instruction,
11678   // which we know is safe.  This is good for things like turning:
11679   // (splat(splat)) -> splat.
11680   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11681     if (isa<UndefValue>(RHS)) {
11682       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11683
11684       std::vector<unsigned> NewMask;
11685       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11686         if (Mask[i] >= 2*e)
11687           NewMask.push_back(2*e);
11688         else
11689           NewMask.push_back(LHSMask[Mask[i]]);
11690       
11691       // If the result mask is equal to the src shuffle or this shuffle mask, do
11692       // the replacement.
11693       if (NewMask == LHSMask || NewMask == Mask) {
11694         std::vector<Constant*> Elts;
11695         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11696           if (NewMask[i] >= e*2) {
11697             Elts.push_back(UndefValue::get(Type::Int32Ty));
11698           } else {
11699             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11700           }
11701         }
11702         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11703                                      LHSSVI->getOperand(1),
11704                                      ConstantVector::get(Elts));
11705       }
11706     }
11707   }
11708
11709   return MadeChange ? &SVI : 0;
11710 }
11711
11712
11713
11714
11715 /// TryToSinkInstruction - Try to move the specified instruction from its
11716 /// current block into the beginning of DestBlock, which can only happen if it's
11717 /// safe to move the instruction past all of the instructions between it and the
11718 /// end of its block.
11719 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11720   assert(I->hasOneUse() && "Invariants didn't hold!");
11721
11722   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11723   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11724     return false;
11725
11726   // Do not sink alloca instructions out of the entry block.
11727   if (isa<AllocaInst>(I) && I->getParent() ==
11728         &DestBlock->getParent()->getEntryBlock())
11729     return false;
11730
11731   // We can only sink load instructions if there is nothing between the load and
11732   // the end of block that could change the value.
11733   if (I->mayReadFromMemory()) {
11734     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11735          Scan != E; ++Scan)
11736       if (Scan->mayWriteToMemory())
11737         return false;
11738   }
11739
11740   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11741
11742   I->moveBefore(InsertPos);
11743   ++NumSunkInst;
11744   return true;
11745 }
11746
11747
11748 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11749 /// all reachable code to the worklist.
11750 ///
11751 /// This has a couple of tricks to make the code faster and more powerful.  In
11752 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11753 /// them to the worklist (this significantly speeds up instcombine on code where
11754 /// many instructions are dead or constant).  Additionally, if we find a branch
11755 /// whose condition is a known constant, we only visit the reachable successors.
11756 ///
11757 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11758                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11759                                        InstCombiner &IC,
11760                                        const TargetData *TD) {
11761   std::vector<BasicBlock*> Worklist;
11762   Worklist.push_back(BB);
11763
11764   while (!Worklist.empty()) {
11765     BB = Worklist.back();
11766     Worklist.pop_back();
11767     
11768     // We have now visited this block!  If we've already been here, ignore it.
11769     if (!Visited.insert(BB)) continue;
11770     
11771     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11772       Instruction *Inst = BBI++;
11773       
11774       // DCE instruction if trivially dead.
11775       if (isInstructionTriviallyDead(Inst)) {
11776         ++NumDeadInst;
11777         DOUT << "IC: DCE: " << *Inst;
11778         Inst->eraseFromParent();
11779         continue;
11780       }
11781       
11782       // ConstantProp instruction if trivially constant.
11783       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11784         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11785         Inst->replaceAllUsesWith(C);
11786         ++NumConstProp;
11787         Inst->eraseFromParent();
11788         continue;
11789       }
11790      
11791       IC.AddToWorkList(Inst);
11792     }
11793
11794     // Recursively visit successors.  If this is a branch or switch on a
11795     // constant, only visit the reachable successor.
11796     TerminatorInst *TI = BB->getTerminator();
11797     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11798       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11799         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11800         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11801         Worklist.push_back(ReachableBB);
11802         continue;
11803       }
11804     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11805       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11806         // See if this is an explicit destination.
11807         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11808           if (SI->getCaseValue(i) == Cond) {
11809             BasicBlock *ReachableBB = SI->getSuccessor(i);
11810             Worklist.push_back(ReachableBB);
11811             continue;
11812           }
11813         
11814         // Otherwise it is the default destination.
11815         Worklist.push_back(SI->getSuccessor(0));
11816         continue;
11817       }
11818     }
11819     
11820     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11821       Worklist.push_back(TI->getSuccessor(i));
11822   }
11823 }
11824
11825 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11826   bool Changed = false;
11827   TD = &getAnalysis<TargetData>();
11828   
11829   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11830              << F.getNameStr() << "\n");
11831
11832   {
11833     // Do a depth-first traversal of the function, populate the worklist with
11834     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11835     // track of which blocks we visit.
11836     SmallPtrSet<BasicBlock*, 64> Visited;
11837     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11838
11839     // Do a quick scan over the function.  If we find any blocks that are
11840     // unreachable, remove any instructions inside of them.  This prevents
11841     // the instcombine code from having to deal with some bad special cases.
11842     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11843       if (!Visited.count(BB)) {
11844         Instruction *Term = BB->getTerminator();
11845         while (Term != BB->begin()) {   // Remove instrs bottom-up
11846           BasicBlock::iterator I = Term; --I;
11847
11848           DOUT << "IC: DCE: " << *I;
11849           ++NumDeadInst;
11850
11851           if (!I->use_empty())
11852             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11853           I->eraseFromParent();
11854         }
11855       }
11856   }
11857
11858   while (!Worklist.empty()) {
11859     Instruction *I = RemoveOneFromWorkList();
11860     if (I == 0) continue;  // skip null values.
11861
11862     // Check to see if we can DCE the instruction.
11863     if (isInstructionTriviallyDead(I)) {
11864       // Add operands to the worklist.
11865       if (I->getNumOperands() < 4)
11866         AddUsesToWorkList(*I);
11867       ++NumDeadInst;
11868
11869       DOUT << "IC: DCE: " << *I;
11870
11871       I->eraseFromParent();
11872       RemoveFromWorkList(I);
11873       continue;
11874     }
11875
11876     // Instruction isn't dead, see if we can constant propagate it.
11877     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11878       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11879
11880       // Add operands to the worklist.
11881       AddUsesToWorkList(*I);
11882       ReplaceInstUsesWith(*I, C);
11883
11884       ++NumConstProp;
11885       I->eraseFromParent();
11886       RemoveFromWorkList(I);
11887       continue;
11888     }
11889
11890     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11891       // See if we can constant fold its operands.
11892       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11893         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11894           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11895             i->set(NewC);
11896         }
11897       }
11898     }
11899
11900     // See if we can trivially sink this instruction to a successor basic block.
11901     // FIXME: Remove GetResultInst test when first class support for aggregates
11902     // is implemented.
11903     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11904       BasicBlock *BB = I->getParent();
11905       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11906       if (UserParent != BB) {
11907         bool UserIsSuccessor = false;
11908         // See if the user is one of our successors.
11909         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11910           if (*SI == UserParent) {
11911             UserIsSuccessor = true;
11912             break;
11913           }
11914
11915         // If the user is one of our immediate successors, and if that successor
11916         // only has us as a predecessors (we'd have to split the critical edge
11917         // otherwise), we can keep going.
11918         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11919             next(pred_begin(UserParent)) == pred_end(UserParent))
11920           // Okay, the CFG is simple enough, try to sink this instruction.
11921           Changed |= TryToSinkInstruction(I, UserParent);
11922       }
11923     }
11924
11925     // Now that we have an instruction, try combining it to simplify it...
11926 #ifndef NDEBUG
11927     std::string OrigI;
11928 #endif
11929     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11930     if (Instruction *Result = visit(*I)) {
11931       ++NumCombined;
11932       // Should we replace the old instruction with a new one?
11933       if (Result != I) {
11934         DOUT << "IC: Old = " << *I
11935              << "    New = " << *Result;
11936
11937         // Everything uses the new instruction now.
11938         I->replaceAllUsesWith(Result);
11939
11940         // Push the new instruction and any users onto the worklist.
11941         AddToWorkList(Result);
11942         AddUsersToWorkList(*Result);
11943
11944         // Move the name to the new instruction first.
11945         Result->takeName(I);
11946
11947         // Insert the new instruction into the basic block...
11948         BasicBlock *InstParent = I->getParent();
11949         BasicBlock::iterator InsertPos = I;
11950
11951         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11952           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11953             ++InsertPos;
11954
11955         InstParent->getInstList().insert(InsertPos, Result);
11956
11957         // Make sure that we reprocess all operands now that we reduced their
11958         // use counts.
11959         AddUsesToWorkList(*I);
11960
11961         // Instructions can end up on the worklist more than once.  Make sure
11962         // we do not process an instruction that has been deleted.
11963         RemoveFromWorkList(I);
11964
11965         // Erase the old instruction.
11966         InstParent->getInstList().erase(I);
11967       } else {
11968 #ifndef NDEBUG
11969         DOUT << "IC: Mod = " << OrigI
11970              << "    New = " << *I;
11971 #endif
11972
11973         // If the instruction was modified, it's possible that it is now dead.
11974         // if so, remove it.
11975         if (isInstructionTriviallyDead(I)) {
11976           // Make sure we process all operands now that we are reducing their
11977           // use counts.
11978           AddUsesToWorkList(*I);
11979
11980           // Instructions may end up in the worklist more than once.  Erase all
11981           // occurrences of this instruction.
11982           RemoveFromWorkList(I);
11983           I->eraseFromParent();
11984         } else {
11985           AddToWorkList(I);
11986           AddUsersToWorkList(*I);
11987         }
11988       }
11989       Changed = true;
11990     }
11991   }
11992
11993   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11994     
11995   // Do an explicit clear, this shrinks the map if needed.
11996   WorklistMap.clear();
11997   return Changed;
11998 }
11999
12000
12001 bool InstCombiner::runOnFunction(Function &F) {
12002   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12003   
12004   bool EverMadeChange = false;
12005
12006   // Iterate while there is work to do.
12007   unsigned Iteration = 0;
12008   while (DoOneIteration(F, Iteration++))
12009     EverMadeChange = true;
12010   return EverMadeChange;
12011 }
12012
12013 FunctionPass *llvm::createInstructionCombiningPass() {
12014   return new InstCombiner();
12015 }
12016