Use recently added getTruncateOrZeroExtend method to make the code shorter.
[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/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include <algorithm>
61 #include <climits>
62 #include <sstream>
63 using namespace llvm;
64 using namespace llvm::PatternMatch;
65
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72 namespace {
73   class VISIBILITY_HIDDEN InstCombiner
74     : public FunctionPass,
75       public InstVisitor<InstCombiner, Instruction*> {
76     // Worklist of all of the instructions that need to be simplified.
77     std::vector<Instruction*> Worklist;
78     DenseMap<Instruction*, unsigned> WorklistMap;
79     TargetData *TD;
80     bool MustPreserveLCSSA;
81   public:
82     static char ID; // Pass identification, replacement for typeid
83     InstCombiner() : FunctionPass((intptr_t)&ID) {}
84
85     /// AddToWorkList - Add the specified instruction to the worklist if it
86     /// isn't already in it.
87     void AddToWorkList(Instruction *I) {
88       if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
89         Worklist.push_back(I);
90     }
91     
92     // RemoveFromWorkList - remove I from the worklist if it exists.
93     void RemoveFromWorkList(Instruction *I) {
94       DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95       if (It == WorklistMap.end()) return; // Not in worklist.
96       
97       // Don't bother moving everything down, just null out the slot.
98       Worklist[It->second] = 0;
99       
100       WorklistMap.erase(It);
101     }
102     
103     Instruction *RemoveOneFromWorkList() {
104       Instruction *I = Worklist.back();
105       Worklist.pop_back();
106       WorklistMap.erase(I);
107       return I;
108     }
109
110     
111     /// AddUsersToWorkList - When an instruction is simplified, add all users of
112     /// the instruction to the work lists because they might get more simplified
113     /// now.
114     ///
115     void AddUsersToWorkList(Value &I) {
116       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117            UI != UE; ++UI)
118         AddToWorkList(cast<Instruction>(*UI));
119     }
120
121     /// AddUsesToWorkList - When an instruction is simplified, add operands to
122     /// the work lists because they might get more simplified now.
123     ///
124     void AddUsesToWorkList(Instruction &I) {
125       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126         if (Instruction *Op = dyn_cast<Instruction>(*i))
127           AddToWorkList(Op);
128     }
129     
130     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131     /// dead.  Add all of its operands to the worklist, turning them into
132     /// undef's to reduce the number of uses of those instructions.
133     ///
134     /// Return the specified operand before it is turned into an undef.
135     ///
136     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137       Value *R = I.getOperand(op);
138       
139       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140         if (Instruction *Op = dyn_cast<Instruction>(*i)) {
141           AddToWorkList(Op);
142           // Set the operand to undef to drop the use.
143           *i = UndefValue::get(Op->getType());
144         }
145       
146       return R;
147     }
148
149   public:
150     virtual bool runOnFunction(Function &F);
151     
152     bool DoOneIteration(Function &F, unsigned ItNum);
153
154     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155       AU.addRequired<TargetData>();
156       AU.addPreservedID(LCSSAID);
157       AU.setPreservesCFG();
158     }
159
160     TargetData &getTargetData() const { return *TD; }
161
162     // Visitation implementation - Implement instruction combining for different
163     // instruction types.  The semantics are as follows:
164     // Return Value:
165     //    null        - No change was made
166     //     I          - Change was made, I is still valid, I may be dead though
167     //   otherwise    - Change was made, replace I with returned instruction
168     //
169     Instruction *visitAdd(BinaryOperator &I);
170     Instruction *visitSub(BinaryOperator &I);
171     Instruction *visitMul(BinaryOperator &I);
172     Instruction *visitURem(BinaryOperator &I);
173     Instruction *visitSRem(BinaryOperator &I);
174     Instruction *visitFRem(BinaryOperator &I);
175     Instruction *commonRemTransforms(BinaryOperator &I);
176     Instruction *commonIRemTransforms(BinaryOperator &I);
177     Instruction *commonDivTransforms(BinaryOperator &I);
178     Instruction *commonIDivTransforms(BinaryOperator &I);
179     Instruction *visitUDiv(BinaryOperator &I);
180     Instruction *visitSDiv(BinaryOperator &I);
181     Instruction *visitFDiv(BinaryOperator &I);
182     Instruction *visitAnd(BinaryOperator &I);
183     Instruction *visitOr (BinaryOperator &I);
184     Instruction *visitXor(BinaryOperator &I);
185     Instruction *visitShl(BinaryOperator &I);
186     Instruction *visitAShr(BinaryOperator &I);
187     Instruction *visitLShr(BinaryOperator &I);
188     Instruction *commonShiftTransforms(BinaryOperator &I);
189     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190                                       Constant *RHSC);
191     Instruction *visitFCmpInst(FCmpInst &I);
192     Instruction *visitICmpInst(ICmpInst &I);
193     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
195                                                 Instruction *LHS,
196                                                 ConstantInt *RHS);
197     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198                                 ConstantInt *DivRHS);
199
200     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201                              ICmpInst::Predicate Cond, Instruction &I);
202     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203                                      BinaryOperator &I);
204     Instruction *commonCastTransforms(CastInst &CI);
205     Instruction *commonIntCastTransforms(CastInst &CI);
206     Instruction *commonPointerCastTransforms(CastInst &CI);
207     Instruction *visitTrunc(TruncInst &CI);
208     Instruction *visitZExt(ZExtInst &CI);
209     Instruction *visitSExt(SExtInst &CI);
210     Instruction *visitFPTrunc(FPTruncInst &CI);
211     Instruction *visitFPExt(CastInst &CI);
212     Instruction *visitFPToUI(FPToUIInst &FI);
213     Instruction *visitFPToSI(FPToSIInst &FI);
214     Instruction *visitUIToFP(CastInst &CI);
215     Instruction *visitSIToFP(CastInst &CI);
216     Instruction *visitPtrToInt(CastInst &CI);
217     Instruction *visitIntToPtr(IntToPtrInst &CI);
218     Instruction *visitBitCast(BitCastInst &CI);
219     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220                                 Instruction *FI);
221     Instruction *visitSelectInst(SelectInst &CI);
222     Instruction *visitCallInst(CallInst &CI);
223     Instruction *visitInvokeInst(InvokeInst &II);
224     Instruction *visitPHINode(PHINode &PN);
225     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226     Instruction *visitAllocationInst(AllocationInst &AI);
227     Instruction *visitFreeInst(FreeInst &FI);
228     Instruction *visitLoadInst(LoadInst &LI);
229     Instruction *visitStoreInst(StoreInst &SI);
230     Instruction *visitBranchInst(BranchInst &BI);
231     Instruction *visitSwitchInst(SwitchInst &SI);
232     Instruction *visitInsertElementInst(InsertElementInst &IE);
233     Instruction *visitExtractElementInst(ExtractElementInst &EI);
234     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235     Instruction *visitExtractValueInst(ExtractValueInst &EV);
236
237     // visitInstruction - Specify what to return for unhandled instructions...
238     Instruction *visitInstruction(Instruction &I) { return 0; }
239
240   private:
241     Instruction *visitCallSite(CallSite CS);
242     bool transformConstExprCastCall(CallSite CS);
243     Instruction *transformCallThroughTrampoline(CallSite CS);
244     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245                                    bool DoXform = true);
246     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
247
248   public:
249     // InsertNewInstBefore - insert an instruction New before instruction Old
250     // in the program.  Add the new instruction to the worklist.
251     //
252     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253       assert(New && New->getParent() == 0 &&
254              "New instruction already inserted into a basic block!");
255       BasicBlock *BB = Old.getParent();
256       BB->getInstList().insert(&Old, New);  // Insert inst
257       AddToWorkList(New);
258       return New;
259     }
260
261     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262     /// This also adds the cast to the worklist.  Finally, this returns the
263     /// cast.
264     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
265                             Instruction &Pos) {
266       if (V->getType() == Ty) return V;
267
268       if (Constant *CV = dyn_cast<Constant>(V))
269         return ConstantExpr::getCast(opc, CV, Ty);
270       
271       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
272       AddToWorkList(C);
273       return C;
274     }
275         
276     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
278     }
279
280
281     // ReplaceInstUsesWith - This method is to be used when an instruction is
282     // found to be dead, replacable with another preexisting expression.  Here
283     // we add all uses of I to the worklist, replace all uses of I with the new
284     // value, then return I, so that the inst combiner will know that I was
285     // modified.
286     //
287     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288       AddUsersToWorkList(I);         // Add all modified instrs to worklist
289       if (&I != V) {
290         I.replaceAllUsesWith(V);
291         return &I;
292       } else {
293         // If we are replacing the instruction with itself, this must be in a
294         // segment of unreachable code, so just clobber the instruction.
295         I.replaceAllUsesWith(UndefValue::get(I.getType()));
296         return &I;
297       }
298     }
299
300     // UpdateValueUsesWith - This method is to be used when an value is
301     // found to be replacable with another preexisting expression or was
302     // updated.  Here we add all uses of I to the worklist, replace all uses of
303     // I with the new value (unless the instruction was just updated), then
304     // return true, so that the inst combiner will know that I was modified.
305     //
306     bool UpdateValueUsesWith(Value *Old, Value *New) {
307       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
308       if (Old != New)
309         Old->replaceAllUsesWith(New);
310       if (Instruction *I = dyn_cast<Instruction>(Old))
311         AddToWorkList(I);
312       if (Instruction *I = dyn_cast<Instruction>(New))
313         AddToWorkList(I);
314       return true;
315     }
316     
317     // EraseInstFromFunction - When dealing with an instruction that has side
318     // effects or produces a void value, we can't rely on DCE to delete the
319     // instruction.  Instead, visit methods should return the value returned by
320     // this function.
321     Instruction *EraseInstFromFunction(Instruction &I) {
322       assert(I.use_empty() && "Cannot erase instruction that is used!");
323       AddUsesToWorkList(I);
324       RemoveFromWorkList(&I);
325       I.eraseFromParent();
326       return 0;  // Don't do anything with FI
327     }
328         
329     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330                            APInt &KnownOne, unsigned Depth = 0) const {
331       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332     }
333     
334     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
335                            unsigned Depth = 0) const {
336       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
337     }
338     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339       return llvm::ComputeNumSignBits(Op, TD, Depth);
340     }
341
342   private:
343     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
345     /// casts that are known to not do anything...
346     ///
347     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348                                    Value *V, const Type *DestTy,
349                                    Instruction *InsertBefore);
350
351     /// SimplifyCommutative - This performs a few simplifications for 
352     /// commutative operators.
353     bool SimplifyCommutative(BinaryOperator &I);
354
355     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356     /// most-complex to least-complex order.
357     bool SimplifyCompare(CmpInst &I);
358
359     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360     /// on the demanded bits.
361     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
362                               APInt& KnownZero, APInt& KnownOne,
363                               unsigned Depth = 0);
364
365     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366                                       uint64_t &UndefElts, unsigned Depth = 0);
367       
368     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369     // PHI node as operand #0, see if we can fold the instruction into the PHI
370     // (which is only possible if all operands to the PHI are constants).
371     Instruction *FoldOpIntoPhi(Instruction &I);
372
373     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374     // operator and they all are only used by the PHI, PHI together their
375     // inputs, and do the operation once, to the result of the PHI.
376     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
378     
379     
380     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
382     
383     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384                               bool isSub, Instruction &I);
385     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386                                  bool isSigned, bool Inside, Instruction &IB);
387     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388     Instruction *MatchBSwap(BinaryOperator &I);
389     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391     Instruction *SimplifyMemSet(MemSetInst *MI);
392
393
394     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
395
396     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
397                                     unsigned CastOpc,
398                                     int &NumCastsRemoved);
399     unsigned GetOrEnforceKnownAlignment(Value *V,
400                                         unsigned PrefAlign = 0);
401
402     // visitExtractValue helpers
403     Value *FindScalarValue(Value *V,
404                            const unsigned *idx_begin,
405                            const unsigned *idx_end,
406                            Instruction &InsertBefore);
407     Value *BuildSubAggregate(Value *From,
408                              const unsigned *idx_begin,
409                              const unsigned *idx_end,
410                              Instruction &InsertBefore);
411     Value *BuildSubAggregate(Value *From,
412                              Value* To,
413                              const Type *IndexedType,
414                              SmallVector<unsigned, 10> &Idxs,
415                              unsigned IdxSkip,
416                              Instruction &InsertBefore);
417   };
418 }
419
420 char InstCombiner::ID = 0;
421 static RegisterPass<InstCombiner>
422 X("instcombine", "Combine redundant instructions");
423
424 // getComplexity:  Assign a complexity or rank value to LLVM Values...
425 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
426 static unsigned getComplexity(Value *V) {
427   if (isa<Instruction>(V)) {
428     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
429       return 3;
430     return 4;
431   }
432   if (isa<Argument>(V)) return 3;
433   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
434 }
435
436 // isOnlyUse - Return true if this instruction will be deleted if we stop using
437 // it.
438 static bool isOnlyUse(Value *V) {
439   return V->hasOneUse() || isa<Constant>(V);
440 }
441
442 // getPromotedType - Return the specified type promoted as it would be to pass
443 // though a va_arg area...
444 static const Type *getPromotedType(const Type *Ty) {
445   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
446     if (ITy->getBitWidth() < 32)
447       return Type::Int32Ty;
448   }
449   return Ty;
450 }
451
452 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
453 /// expression bitcast,  return the operand value, otherwise return null.
454 static Value *getBitCastOperand(Value *V) {
455   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
456     return I->getOperand(0);
457   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
458     if (CE->getOpcode() == Instruction::BitCast)
459       return CE->getOperand(0);
460   return 0;
461 }
462
463 /// This function is a wrapper around CastInst::isEliminableCastPair. It
464 /// simply extracts arguments and returns what that function returns.
465 static Instruction::CastOps 
466 isEliminableCastPair(
467   const CastInst *CI, ///< The first cast instruction
468   unsigned opcode,       ///< The opcode of the second cast instruction
469   const Type *DstTy,     ///< The target type for the second cast instruction
470   TargetData *TD         ///< The target data for pointer size
471 ) {
472   
473   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
474   const Type *MidTy = CI->getType();                  // B from above
475
476   // Get the opcodes of the two Cast instructions
477   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
478   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
479
480   return Instruction::CastOps(
481       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
482                                      DstTy, TD->getIntPtrType()));
483 }
484
485 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
486 /// in any code being generated.  It does not require codegen if V is simple
487 /// enough or if the cast can be folded into other casts.
488 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
489                               const Type *Ty, TargetData *TD) {
490   if (V->getType() == Ty || isa<Constant>(V)) return false;
491   
492   // If this is another cast that can be eliminated, it isn't codegen either.
493   if (const CastInst *CI = dyn_cast<CastInst>(V))
494     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
495       return false;
496   return true;
497 }
498
499 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
500 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
501 /// casts that are known to not do anything...
502 ///
503 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
504                                              Value *V, const Type *DestTy,
505                                              Instruction *InsertBefore) {
506   if (V->getType() == DestTy) return V;
507   if (Constant *C = dyn_cast<Constant>(V))
508     return ConstantExpr::getCast(opcode, C, DestTy);
509   
510   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
511 }
512
513 // SimplifyCommutative - This performs a few simplifications for commutative
514 // operators:
515 //
516 //  1. Order operands such that they are listed from right (least complex) to
517 //     left (most complex).  This puts constants before unary operators before
518 //     binary operators.
519 //
520 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
521 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
522 //
523 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
524   bool Changed = false;
525   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
526     Changed = !I.swapOperands();
527
528   if (!I.isAssociative()) return Changed;
529   Instruction::BinaryOps Opcode = I.getOpcode();
530   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
531     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
532       if (isa<Constant>(I.getOperand(1))) {
533         Constant *Folded = ConstantExpr::get(I.getOpcode(),
534                                              cast<Constant>(I.getOperand(1)),
535                                              cast<Constant>(Op->getOperand(1)));
536         I.setOperand(0, Op->getOperand(0));
537         I.setOperand(1, Folded);
538         return true;
539       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
540         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
541             isOnlyUse(Op) && isOnlyUse(Op1)) {
542           Constant *C1 = cast<Constant>(Op->getOperand(1));
543           Constant *C2 = cast<Constant>(Op1->getOperand(1));
544
545           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
546           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
547           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
548                                                     Op1->getOperand(0),
549                                                     Op1->getName(), &I);
550           AddToWorkList(New);
551           I.setOperand(0, New);
552           I.setOperand(1, Folded);
553           return true;
554         }
555     }
556   return Changed;
557 }
558
559 /// SimplifyCompare - For a CmpInst this function just orders the operands
560 /// so that theyare listed from right (least complex) to left (most complex).
561 /// This puts constants before unary operators before binary operators.
562 bool InstCombiner::SimplifyCompare(CmpInst &I) {
563   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
564     return false;
565   I.swapOperands();
566   // Compare instructions are not associative so there's nothing else we can do.
567   return true;
568 }
569
570 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
571 // if the LHS is a constant zero (which is the 'negate' form).
572 //
573 static inline Value *dyn_castNegVal(Value *V) {
574   if (BinaryOperator::isNeg(V))
575     return BinaryOperator::getNegArgument(V);
576
577   // Constants can be considered to be negated values if they can be folded.
578   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579     return ConstantExpr::getNeg(C);
580
581   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
582     if (C->getType()->getElementType()->isInteger())
583       return ConstantExpr::getNeg(C);
584
585   return 0;
586 }
587
588 static inline Value *dyn_castNotVal(Value *V) {
589   if (BinaryOperator::isNot(V))
590     return BinaryOperator::getNotArgument(V);
591
592   // Constants can be considered to be not'ed values...
593   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
594     return ConstantInt::get(~C->getValue());
595   return 0;
596 }
597
598 // dyn_castFoldableMul - If this value is a multiply that can be folded into
599 // other computations (because it has a constant operand), return the
600 // non-constant operand of the multiply, and set CST to point to the multiplier.
601 // Otherwise, return null.
602 //
603 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
604   if (V->hasOneUse() && V->getType()->isInteger())
605     if (Instruction *I = dyn_cast<Instruction>(V)) {
606       if (I->getOpcode() == Instruction::Mul)
607         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
608           return I->getOperand(0);
609       if (I->getOpcode() == Instruction::Shl)
610         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
611           // The multiplier is really 1 << CST.
612           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
613           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
614           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
615           return I->getOperand(0);
616         }
617     }
618   return 0;
619 }
620
621 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
622 /// expression, return it.
623 static User *dyn_castGetElementPtr(Value *V) {
624   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
625   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
626     if (CE->getOpcode() == Instruction::GetElementPtr)
627       return cast<User>(V);
628   return false;
629 }
630
631 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
632 /// opcode value. Otherwise return UserOp1.
633 static unsigned getOpcode(const Value *V) {
634   if (const Instruction *I = dyn_cast<Instruction>(V))
635     return I->getOpcode();
636   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
637     return CE->getOpcode();
638   // Use UserOp1 to mean there's no opcode.
639   return Instruction::UserOp1;
640 }
641
642 /// AddOne - Add one to a ConstantInt
643 static ConstantInt *AddOne(ConstantInt *C) {
644   APInt Val(C->getValue());
645   return ConstantInt::get(++Val);
646 }
647 /// SubOne - Subtract one from a ConstantInt
648 static ConstantInt *SubOne(ConstantInt *C) {
649   APInt Val(C->getValue());
650   return ConstantInt::get(--Val);
651 }
652 /// Add - Add two ConstantInts together
653 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
654   return ConstantInt::get(C1->getValue() + C2->getValue());
655 }
656 /// And - Bitwise AND two ConstantInts together
657 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
658   return ConstantInt::get(C1->getValue() & C2->getValue());
659 }
660 /// Subtract - Subtract one ConstantInt from another
661 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
662   return ConstantInt::get(C1->getValue() - C2->getValue());
663 }
664 /// Multiply - Multiply two ConstantInts together
665 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
666   return ConstantInt::get(C1->getValue() * C2->getValue());
667 }
668 /// MultiplyOverflows - True if the multiply can not be expressed in an int
669 /// this size.
670 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
671   uint32_t W = C1->getBitWidth();
672   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
673   if (sign) {
674     LHSExt.sext(W * 2);
675     RHSExt.sext(W * 2);
676   } else {
677     LHSExt.zext(W * 2);
678     RHSExt.zext(W * 2);
679   }
680
681   APInt MulExt = LHSExt * RHSExt;
682
683   if (sign) {
684     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
685     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
686     return MulExt.slt(Min) || MulExt.sgt(Max);
687   } else 
688     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
689 }
690
691
692 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
693 /// specified instruction is a constant integer.  If so, check to see if there
694 /// are any bits set in the constant that are not demanded.  If so, shrink the
695 /// constant and return true.
696 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
697                                    APInt Demanded) {
698   assert(I && "No instruction?");
699   assert(OpNo < I->getNumOperands() && "Operand index too large");
700
701   // If the operand is not a constant integer, nothing to do.
702   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
703   if (!OpC) return false;
704
705   // If there are no bits set that aren't demanded, nothing to do.
706   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
707   if ((~Demanded & OpC->getValue()) == 0)
708     return false;
709
710   // This instruction is producing bits that are not demanded. Shrink the RHS.
711   Demanded &= OpC->getValue();
712   I->setOperand(OpNo, ConstantInt::get(Demanded));
713   return true;
714 }
715
716 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
717 // set of known zero and one bits, compute the maximum and minimum values that
718 // could have the specified known zero and known one bits, returning them in
719 // min/max.
720 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
721                                                    const APInt& KnownZero,
722                                                    const APInt& KnownOne,
723                                                    APInt& Min, APInt& Max) {
724   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
725   assert(KnownZero.getBitWidth() == BitWidth && 
726          KnownOne.getBitWidth() == BitWidth &&
727          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
728          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
729   APInt UnknownBits = ~(KnownZero|KnownOne);
730
731   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
732   // bit if it is unknown.
733   Min = KnownOne;
734   Max = KnownOne|UnknownBits;
735   
736   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
737     Min.set(BitWidth-1);
738     Max.clear(BitWidth-1);
739   }
740 }
741
742 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
743 // a set of known zero and one bits, compute the maximum and minimum values that
744 // could have the specified known zero and known one bits, returning them in
745 // min/max.
746 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
747                                                      const APInt &KnownZero,
748                                                      const APInt &KnownOne,
749                                                      APInt &Min, APInt &Max) {
750   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
751   assert(KnownZero.getBitWidth() == BitWidth && 
752          KnownOne.getBitWidth() == BitWidth &&
753          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
754          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
755   APInt UnknownBits = ~(KnownZero|KnownOne);
756   
757   // The minimum value is when the unknown bits are all zeros.
758   Min = KnownOne;
759   // The maximum value is when the unknown bits are all ones.
760   Max = KnownOne|UnknownBits;
761 }
762
763 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
764 /// value based on the demanded bits. When this function is called, it is known
765 /// that only the bits set in DemandedMask of the result of V are ever used
766 /// downstream. Consequently, depending on the mask and V, it may be possible
767 /// to replace V with a constant or one of its operands. In such cases, this
768 /// function does the replacement and returns true. In all other cases, it
769 /// returns false after analyzing the expression and setting KnownOne and known
770 /// to be one in the expression. KnownZero contains all the bits that are known
771 /// to be zero in the expression. These are provided to potentially allow the
772 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
773 /// the expression. KnownOne and KnownZero always follow the invariant that 
774 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
775 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
776 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
777 /// and KnownOne must all be the same.
778 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
779                                         APInt& KnownZero, APInt& KnownOne,
780                                         unsigned Depth) {
781   assert(V != 0 && "Null pointer of Value???");
782   assert(Depth <= 6 && "Limit Search Depth");
783   uint32_t BitWidth = DemandedMask.getBitWidth();
784   const IntegerType *VTy = cast<IntegerType>(V->getType());
785   assert(VTy->getBitWidth() == BitWidth && 
786          KnownZero.getBitWidth() == BitWidth && 
787          KnownOne.getBitWidth() == BitWidth &&
788          "Value *V, DemandedMask, KnownZero and KnownOne \
789           must have same BitWidth");
790   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
791     // We know all of the bits for a constant!
792     KnownOne = CI->getValue() & DemandedMask;
793     KnownZero = ~KnownOne & DemandedMask;
794     return false;
795   }
796   
797   KnownZero.clear(); 
798   KnownOne.clear();
799   if (!V->hasOneUse()) {    // Other users may use these bits.
800     if (Depth != 0) {       // Not at the root.
801       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
802       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
803       return false;
804     }
805     // If this is the root being simplified, allow it to have multiple uses,
806     // just set the DemandedMask to all bits.
807     DemandedMask = APInt::getAllOnesValue(BitWidth);
808   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
809     if (V != UndefValue::get(VTy))
810       return UpdateValueUsesWith(V, UndefValue::get(VTy));
811     return false;
812   } else if (Depth == 6) {        // Limit search depth.
813     return false;
814   }
815   
816   Instruction *I = dyn_cast<Instruction>(V);
817   if (!I) return false;        // Only analyze instructions.
818
819   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
820   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
821   switch (I->getOpcode()) {
822   default:
823     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
824     break;
825   case Instruction::And:
826     // If either the LHS or the RHS are Zero, the result is zero.
827     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
828                              RHSKnownZero, RHSKnownOne, Depth+1))
829       return true;
830     assert((RHSKnownZero & RHSKnownOne) == 0 && 
831            "Bits known to be one AND zero?"); 
832
833     // If something is known zero on the RHS, the bits aren't demanded on the
834     // LHS.
835     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
836                              LHSKnownZero, LHSKnownOne, Depth+1))
837       return true;
838     assert((LHSKnownZero & LHSKnownOne) == 0 && 
839            "Bits known to be one AND zero?"); 
840
841     // If all of the demanded bits are known 1 on one side, return the other.
842     // These bits cannot contribute to the result of the 'and'.
843     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
844         (DemandedMask & ~LHSKnownZero))
845       return UpdateValueUsesWith(I, I->getOperand(0));
846     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
847         (DemandedMask & ~RHSKnownZero))
848       return UpdateValueUsesWith(I, I->getOperand(1));
849     
850     // If all of the demanded bits in the inputs are known zeros, return zero.
851     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
852       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
853       
854     // If the RHS is a constant, see if we can simplify it.
855     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
856       return UpdateValueUsesWith(I, I);
857       
858     // Output known-1 bits are only known if set in both the LHS & RHS.
859     RHSKnownOne &= LHSKnownOne;
860     // Output known-0 are known to be clear if zero in either the LHS | RHS.
861     RHSKnownZero |= LHSKnownZero;
862     break;
863   case Instruction::Or:
864     // If either the LHS or the RHS are One, the result is One.
865     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
866                              RHSKnownZero, RHSKnownOne, Depth+1))
867       return true;
868     assert((RHSKnownZero & RHSKnownOne) == 0 && 
869            "Bits known to be one AND zero?"); 
870     // If something is known one on the RHS, the bits aren't demanded on the
871     // LHS.
872     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
873                              LHSKnownZero, LHSKnownOne, Depth+1))
874       return true;
875     assert((LHSKnownZero & LHSKnownOne) == 0 && 
876            "Bits known to be one AND zero?"); 
877     
878     // If all of the demanded bits are known zero on one side, return the other.
879     // These bits cannot contribute to the result of the 'or'.
880     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
881         (DemandedMask & ~LHSKnownOne))
882       return UpdateValueUsesWith(I, I->getOperand(0));
883     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
884         (DemandedMask & ~RHSKnownOne))
885       return UpdateValueUsesWith(I, I->getOperand(1));
886
887     // If all of the potentially set bits on one side are known to be set on
888     // the other side, just use the 'other' side.
889     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
890         (DemandedMask & (~RHSKnownZero)))
891       return UpdateValueUsesWith(I, I->getOperand(0));
892     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
893         (DemandedMask & (~LHSKnownZero)))
894       return UpdateValueUsesWith(I, I->getOperand(1));
895         
896     // If the RHS is a constant, see if we can simplify it.
897     if (ShrinkDemandedConstant(I, 1, DemandedMask))
898       return UpdateValueUsesWith(I, I);
899           
900     // Output known-0 bits are only known if clear in both the LHS & RHS.
901     RHSKnownZero &= LHSKnownZero;
902     // Output known-1 are known to be set if set in either the LHS | RHS.
903     RHSKnownOne |= LHSKnownOne;
904     break;
905   case Instruction::Xor: {
906     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
907                              RHSKnownZero, RHSKnownOne, Depth+1))
908       return true;
909     assert((RHSKnownZero & RHSKnownOne) == 0 && 
910            "Bits known to be one AND zero?"); 
911     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
912                              LHSKnownZero, LHSKnownOne, Depth+1))
913       return true;
914     assert((LHSKnownZero & LHSKnownOne) == 0 && 
915            "Bits known to be one AND zero?"); 
916     
917     // If all of the demanded bits are known zero on one side, return the other.
918     // These bits cannot contribute to the result of the 'xor'.
919     if ((DemandedMask & RHSKnownZero) == DemandedMask)
920       return UpdateValueUsesWith(I, I->getOperand(0));
921     if ((DemandedMask & LHSKnownZero) == DemandedMask)
922       return UpdateValueUsesWith(I, I->getOperand(1));
923     
924     // Output known-0 bits are known if clear or set in both the LHS & RHS.
925     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
926                          (RHSKnownOne & LHSKnownOne);
927     // Output known-1 are known to be set if set in only one of the LHS, RHS.
928     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
929                         (RHSKnownOne & LHSKnownZero);
930     
931     // If all of the demanded bits are known to be zero on one side or the
932     // other, turn this into an *inclusive* or.
933     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
934     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
935       Instruction *Or =
936         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
937                                  I->getName());
938       InsertNewInstBefore(Or, *I);
939       return UpdateValueUsesWith(I, Or);
940     }
941     
942     // If all of the demanded bits on one side are known, and all of the set
943     // bits on that side are also known to be set on the other side, turn this
944     // into an AND, as we know the bits will be cleared.
945     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
946     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
947       // all known
948       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
949         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
950         Instruction *And = 
951           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
952         InsertNewInstBefore(And, *I);
953         return UpdateValueUsesWith(I, And);
954       }
955     }
956     
957     // If the RHS is a constant, see if we can simplify it.
958     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
959     if (ShrinkDemandedConstant(I, 1, DemandedMask))
960       return UpdateValueUsesWith(I, I);
961     
962     RHSKnownZero = KnownZeroOut;
963     RHSKnownOne  = KnownOneOut;
964     break;
965   }
966   case Instruction::Select:
967     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
968                              RHSKnownZero, RHSKnownOne, Depth+1))
969       return true;
970     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
971                              LHSKnownZero, LHSKnownOne, Depth+1))
972       return true;
973     assert((RHSKnownZero & RHSKnownOne) == 0 && 
974            "Bits known to be one AND zero?"); 
975     assert((LHSKnownZero & LHSKnownOne) == 0 && 
976            "Bits known to be one AND zero?"); 
977     
978     // If the operands are constants, see if we can simplify them.
979     if (ShrinkDemandedConstant(I, 1, DemandedMask))
980       return UpdateValueUsesWith(I, I);
981     if (ShrinkDemandedConstant(I, 2, DemandedMask))
982       return UpdateValueUsesWith(I, I);
983     
984     // Only known if known in both the LHS and RHS.
985     RHSKnownOne &= LHSKnownOne;
986     RHSKnownZero &= LHSKnownZero;
987     break;
988   case Instruction::Trunc: {
989     uint32_t truncBf = 
990       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
991     DemandedMask.zext(truncBf);
992     RHSKnownZero.zext(truncBf);
993     RHSKnownOne.zext(truncBf);
994     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
995                              RHSKnownZero, RHSKnownOne, Depth+1))
996       return true;
997     DemandedMask.trunc(BitWidth);
998     RHSKnownZero.trunc(BitWidth);
999     RHSKnownOne.trunc(BitWidth);
1000     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1001            "Bits known to be one AND zero?"); 
1002     break;
1003   }
1004   case Instruction::BitCast:
1005     if (!I->getOperand(0)->getType()->isInteger())
1006       return false;
1007       
1008     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009                              RHSKnownZero, RHSKnownOne, Depth+1))
1010       return true;
1011     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1012            "Bits known to be one AND zero?"); 
1013     break;
1014   case Instruction::ZExt: {
1015     // Compute the bits in the result that are not present in the input.
1016     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1017     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1018     
1019     DemandedMask.trunc(SrcBitWidth);
1020     RHSKnownZero.trunc(SrcBitWidth);
1021     RHSKnownOne.trunc(SrcBitWidth);
1022     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1023                              RHSKnownZero, RHSKnownOne, Depth+1))
1024       return true;
1025     DemandedMask.zext(BitWidth);
1026     RHSKnownZero.zext(BitWidth);
1027     RHSKnownOne.zext(BitWidth);
1028     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1029            "Bits known to be one AND zero?"); 
1030     // The top bits are known to be zero.
1031     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1032     break;
1033   }
1034   case Instruction::SExt: {
1035     // Compute the bits in the result that are not present in the input.
1036     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1037     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1038     
1039     APInt InputDemandedBits = DemandedMask & 
1040                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1041
1042     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1043     // If any of the sign extended bits are demanded, we know that the sign
1044     // bit is demanded.
1045     if ((NewBits & DemandedMask) != 0)
1046       InputDemandedBits.set(SrcBitWidth-1);
1047       
1048     InputDemandedBits.trunc(SrcBitWidth);
1049     RHSKnownZero.trunc(SrcBitWidth);
1050     RHSKnownOne.trunc(SrcBitWidth);
1051     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1052                              RHSKnownZero, RHSKnownOne, Depth+1))
1053       return true;
1054     InputDemandedBits.zext(BitWidth);
1055     RHSKnownZero.zext(BitWidth);
1056     RHSKnownOne.zext(BitWidth);
1057     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1058            "Bits known to be one AND zero?"); 
1059       
1060     // If the sign bit of the input is known set or clear, then we know the
1061     // top bits of the result.
1062
1063     // If the input sign bit is known zero, or if the NewBits are not demanded
1064     // convert this into a zero extension.
1065     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1066     {
1067       // Convert to ZExt cast
1068       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1069       return UpdateValueUsesWith(I, NewCast);
1070     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1071       RHSKnownOne |= NewBits;
1072     }
1073     break;
1074   }
1075   case Instruction::Add: {
1076     // Figure out what the input bits are.  If the top bits of the and result
1077     // are not demanded, then the add doesn't demand them from its input
1078     // either.
1079     uint32_t NLZ = DemandedMask.countLeadingZeros();
1080       
1081     // If there is a constant on the RHS, there are a variety of xformations
1082     // we can do.
1083     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1084       // If null, this should be simplified elsewhere.  Some of the xforms here
1085       // won't work if the RHS is zero.
1086       if (RHS->isZero())
1087         break;
1088       
1089       // If the top bit of the output is demanded, demand everything from the
1090       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1091       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1092
1093       // Find information about known zero/one bits in the input.
1094       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1095                                LHSKnownZero, LHSKnownOne, Depth+1))
1096         return true;
1097
1098       // If the RHS of the add has bits set that can't affect the input, reduce
1099       // the constant.
1100       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1101         return UpdateValueUsesWith(I, I);
1102       
1103       // Avoid excess work.
1104       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1105         break;
1106       
1107       // Turn it into OR if input bits are zero.
1108       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1109         Instruction *Or =
1110           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1111                                    I->getName());
1112         InsertNewInstBefore(Or, *I);
1113         return UpdateValueUsesWith(I, Or);
1114       }
1115       
1116       // We can say something about the output known-zero and known-one bits,
1117       // depending on potential carries from the input constant and the
1118       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1119       // bits set and the RHS constant is 0x01001, then we know we have a known
1120       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1121       
1122       // To compute this, we first compute the potential carry bits.  These are
1123       // the bits which may be modified.  I'm not aware of a better way to do
1124       // this scan.
1125       const APInt& RHSVal = RHS->getValue();
1126       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1127       
1128       // Now that we know which bits have carries, compute the known-1/0 sets.
1129       
1130       // Bits are known one if they are known zero in one operand and one in the
1131       // other, and there is no input carry.
1132       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1133                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1134       
1135       // Bits are known zero if they are known zero in both operands and there
1136       // is no input carry.
1137       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1138     } else {
1139       // If the high-bits of this ADD are not demanded, then it does not demand
1140       // the high bits of its LHS or RHS.
1141       if (DemandedMask[BitWidth-1] == 0) {
1142         // Right fill the mask of bits for this ADD to demand the most
1143         // significant bit and all those below it.
1144         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1145         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1146                                  LHSKnownZero, LHSKnownOne, Depth+1))
1147           return true;
1148         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1149                                  LHSKnownZero, LHSKnownOne, Depth+1))
1150           return true;
1151       }
1152     }
1153     break;
1154   }
1155   case Instruction::Sub:
1156     // If the high-bits of this SUB are not demanded, then it does not demand
1157     // the high bits of its LHS or RHS.
1158     if (DemandedMask[BitWidth-1] == 0) {
1159       // Right fill the mask of bits for this SUB to demand the most
1160       // significant bit and all those below it.
1161       uint32_t NLZ = DemandedMask.countLeadingZeros();
1162       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1163       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1164                                LHSKnownZero, LHSKnownOne, Depth+1))
1165         return true;
1166       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1167                                LHSKnownZero, LHSKnownOne, Depth+1))
1168         return true;
1169     }
1170     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1171     // the known zeros and ones.
1172     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1173     break;
1174   case Instruction::Shl:
1175     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1176       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1177       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1178       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1179                                RHSKnownZero, RHSKnownOne, Depth+1))
1180         return true;
1181       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1182              "Bits known to be one AND zero?"); 
1183       RHSKnownZero <<= ShiftAmt;
1184       RHSKnownOne  <<= ShiftAmt;
1185       // low bits known zero.
1186       if (ShiftAmt)
1187         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1188     }
1189     break;
1190   case Instruction::LShr:
1191     // For a logical shift right
1192     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1193       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1194       
1195       // Unsigned shift right.
1196       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1197       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1198                                RHSKnownZero, RHSKnownOne, Depth+1))
1199         return true;
1200       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1201              "Bits known to be one AND zero?"); 
1202       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1203       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1204       if (ShiftAmt) {
1205         // Compute the new bits that are at the top now.
1206         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1207         RHSKnownZero |= HighBits;  // high bits known zero.
1208       }
1209     }
1210     break;
1211   case Instruction::AShr:
1212     // If this is an arithmetic shift right and only the low-bit is set, we can
1213     // always convert this into a logical shr, even if the shift amount is
1214     // variable.  The low bit of the shift cannot be an input sign bit unless
1215     // the shift amount is >= the size of the datatype, which is undefined.
1216     if (DemandedMask == 1) {
1217       // Perform the logical shift right.
1218       Value *NewVal = BinaryOperator::CreateLShr(
1219                         I->getOperand(0), I->getOperand(1), I->getName());
1220       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1221       return UpdateValueUsesWith(I, NewVal);
1222     }    
1223
1224     // If the sign bit is the only bit demanded by this ashr, then there is no
1225     // need to do it, the shift doesn't change the high bit.
1226     if (DemandedMask.isSignBit())
1227       return UpdateValueUsesWith(I, I->getOperand(0));
1228     
1229     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1230       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1231       
1232       // Signed shift right.
1233       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1234       // If any of the "high bits" are demanded, we should set the sign bit as
1235       // demanded.
1236       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1237         DemandedMaskIn.set(BitWidth-1);
1238       if (SimplifyDemandedBits(I->getOperand(0),
1239                                DemandedMaskIn,
1240                                RHSKnownZero, RHSKnownOne, Depth+1))
1241         return true;
1242       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1243              "Bits known to be one AND zero?"); 
1244       // Compute the new bits that are at the top now.
1245       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1246       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1247       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1248         
1249       // Handle the sign bits.
1250       APInt SignBit(APInt::getSignBit(BitWidth));
1251       // Adjust to where it is now in the mask.
1252       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1253         
1254       // If the input sign bit is known to be zero, or if none of the top bits
1255       // are demanded, turn this into an unsigned shift right.
1256       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1257           (HighBits & ~DemandedMask) == HighBits) {
1258         // Perform the logical shift right.
1259         Value *NewVal = BinaryOperator::CreateLShr(
1260                           I->getOperand(0), SA, I->getName());
1261         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1262         return UpdateValueUsesWith(I, NewVal);
1263       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1264         RHSKnownOne |= HighBits;
1265       }
1266     }
1267     break;
1268   case Instruction::SRem:
1269     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270       APInt RA = Rem->getValue();
1271       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1272         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1273         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1274         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1275                                  LHSKnownZero, LHSKnownOne, Depth+1))
1276           return true;
1277
1278         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1279           LHSKnownZero |= ~LowBits;
1280         else if (LHSKnownOne[BitWidth-1])
1281           LHSKnownOne |= ~LowBits;
1282
1283         KnownZero |= LHSKnownZero & DemandedMask;
1284         KnownOne |= LHSKnownOne & DemandedMask;
1285
1286         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1287       }
1288     }
1289     break;
1290   case Instruction::URem: {
1291     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1292       APInt RA = Rem->getValue();
1293       if (RA.isPowerOf2()) {
1294         APInt LowBits = (RA - 1);
1295         APInt Mask2 = LowBits & DemandedMask;
1296         KnownZero |= ~LowBits & DemandedMask;
1297         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1298                                  KnownZero, KnownOne, Depth+1))
1299           return true;
1300
1301         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1302         break;
1303       }
1304     }
1305
1306     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1307     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1308     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1309                              KnownZero2, KnownOne2, Depth+1))
1310       return true;
1311
1312     uint32_t Leaders = KnownZero2.countLeadingOnes();
1313     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1314                              KnownZero2, KnownOne2, Depth+1))
1315       return true;
1316
1317     Leaders = std::max(Leaders,
1318                        KnownZero2.countLeadingOnes());
1319     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1320     break;
1321   }
1322   }
1323   
1324   // If the client is only demanding bits that we know, return the known
1325   // constant.
1326   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1327     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1328   return false;
1329 }
1330
1331
1332 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1333 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1334 /// actually used by the caller.  This method analyzes which elements of the
1335 /// operand are undef and returns that information in UndefElts.
1336 ///
1337 /// If the information about demanded elements can be used to simplify the
1338 /// operation, the operation is simplified, then the resultant value is
1339 /// returned.  This returns null if no change was made.
1340 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1341                                                 uint64_t &UndefElts,
1342                                                 unsigned Depth) {
1343   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1344   assert(VWidth <= 64 && "Vector too wide to analyze!");
1345   uint64_t EltMask = ~0ULL >> (64-VWidth);
1346   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1347          "Invalid DemandedElts!");
1348
1349   if (isa<UndefValue>(V)) {
1350     // If the entire vector is undefined, just return this info.
1351     UndefElts = EltMask;
1352     return 0;
1353   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1354     UndefElts = EltMask;
1355     return UndefValue::get(V->getType());
1356   }
1357   
1358   UndefElts = 0;
1359   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1360     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1361     Constant *Undef = UndefValue::get(EltTy);
1362
1363     std::vector<Constant*> Elts;
1364     for (unsigned i = 0; i != VWidth; ++i)
1365       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1366         Elts.push_back(Undef);
1367         UndefElts |= (1ULL << i);
1368       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1369         Elts.push_back(Undef);
1370         UndefElts |= (1ULL << i);
1371       } else {                               // Otherwise, defined.
1372         Elts.push_back(CP->getOperand(i));
1373       }
1374         
1375     // If we changed the constant, return it.
1376     Constant *NewCP = ConstantVector::get(Elts);
1377     return NewCP != CP ? NewCP : 0;
1378   } else if (isa<ConstantAggregateZero>(V)) {
1379     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1380     // set to undef.
1381     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1382     Constant *Zero = Constant::getNullValue(EltTy);
1383     Constant *Undef = UndefValue::get(EltTy);
1384     std::vector<Constant*> Elts;
1385     for (unsigned i = 0; i != VWidth; ++i)
1386       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1387     UndefElts = DemandedElts ^ EltMask;
1388     return ConstantVector::get(Elts);
1389   }
1390   
1391   if (!V->hasOneUse()) {    // Other users may use these bits.
1392     if (Depth != 0) {       // Not at the root.
1393       // TODO: Just compute the UndefElts information recursively.
1394       return false;
1395     }
1396     return false;
1397   } else if (Depth == 10) {        // Limit search depth.
1398     return false;
1399   }
1400   
1401   Instruction *I = dyn_cast<Instruction>(V);
1402   if (!I) return false;        // Only analyze instructions.
1403   
1404   bool MadeChange = false;
1405   uint64_t UndefElts2;
1406   Value *TmpV;
1407   switch (I->getOpcode()) {
1408   default: break;
1409     
1410   case Instruction::InsertElement: {
1411     // If this is a variable index, we don't know which element it overwrites.
1412     // demand exactly the same input as we produce.
1413     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1414     if (Idx == 0) {
1415       // Note that we can't propagate undef elt info, because we don't know
1416       // which elt is getting updated.
1417       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1418                                         UndefElts2, Depth+1);
1419       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1420       break;
1421     }
1422     
1423     // If this is inserting an element that isn't demanded, remove this
1424     // insertelement.
1425     unsigned IdxNo = Idx->getZExtValue();
1426     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1427       return AddSoonDeadInstToWorklist(*I, 0);
1428     
1429     // Otherwise, the element inserted overwrites whatever was there, so the
1430     // input demanded set is simpler than the output set.
1431     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1432                                       DemandedElts & ~(1ULL << IdxNo),
1433                                       UndefElts, Depth+1);
1434     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1435
1436     // The inserted element is defined.
1437     UndefElts |= 1ULL << IdxNo;
1438     break;
1439   }
1440   case Instruction::BitCast: {
1441     // Vector->vector casts only.
1442     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1443     if (!VTy) break;
1444     unsigned InVWidth = VTy->getNumElements();
1445     uint64_t InputDemandedElts = 0;
1446     unsigned Ratio;
1447
1448     if (VWidth == InVWidth) {
1449       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1450       // elements as are demanded of us.
1451       Ratio = 1;
1452       InputDemandedElts = DemandedElts;
1453     } else if (VWidth > InVWidth) {
1454       // Untested so far.
1455       break;
1456       
1457       // If there are more elements in the result than there are in the source,
1458       // then an input element is live if any of the corresponding output
1459       // elements are live.
1460       Ratio = VWidth/InVWidth;
1461       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1462         if (DemandedElts & (1ULL << OutIdx))
1463           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1464       }
1465     } else {
1466       // Untested so far.
1467       break;
1468       
1469       // If there are more elements in the source than there are in the result,
1470       // then an input element is live if the corresponding output element is
1471       // live.
1472       Ratio = InVWidth/VWidth;
1473       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1474         if (DemandedElts & (1ULL << InIdx/Ratio))
1475           InputDemandedElts |= 1ULL << InIdx;
1476     }
1477     
1478     // div/rem demand all inputs, because they don't want divide by zero.
1479     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1480                                       UndefElts2, Depth+1);
1481     if (TmpV) {
1482       I->setOperand(0, TmpV);
1483       MadeChange = true;
1484     }
1485     
1486     UndefElts = UndefElts2;
1487     if (VWidth > InVWidth) {
1488       assert(0 && "Unimp");
1489       // If there are more elements in the result than there are in the source,
1490       // then an output element is undef if the corresponding input element is
1491       // undef.
1492       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1493         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1494           UndefElts |= 1ULL << OutIdx;
1495     } else if (VWidth < InVWidth) {
1496       assert(0 && "Unimp");
1497       // If there are more elements in the source than there are in the result,
1498       // then a result element is undef if all of the corresponding input
1499       // elements are undef.
1500       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1501       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1502         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1503           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1504     }
1505     break;
1506   }
1507   case Instruction::And:
1508   case Instruction::Or:
1509   case Instruction::Xor:
1510   case Instruction::Add:
1511   case Instruction::Sub:
1512   case Instruction::Mul:
1513     // div/rem demand all inputs, because they don't want divide by zero.
1514     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1515                                       UndefElts, Depth+1);
1516     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1517     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1518                                       UndefElts2, Depth+1);
1519     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1520       
1521     // Output elements are undefined if both are undefined.  Consider things
1522     // like undef&0.  The result is known zero, not undef.
1523     UndefElts &= UndefElts2;
1524     break;
1525     
1526   case Instruction::Call: {
1527     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1528     if (!II) break;
1529     switch (II->getIntrinsicID()) {
1530     default: break;
1531       
1532     // Binary vector operations that work column-wise.  A dest element is a
1533     // function of the corresponding input elements from the two inputs.
1534     case Intrinsic::x86_sse_sub_ss:
1535     case Intrinsic::x86_sse_mul_ss:
1536     case Intrinsic::x86_sse_min_ss:
1537     case Intrinsic::x86_sse_max_ss:
1538     case Intrinsic::x86_sse2_sub_sd:
1539     case Intrinsic::x86_sse2_mul_sd:
1540     case Intrinsic::x86_sse2_min_sd:
1541     case Intrinsic::x86_sse2_max_sd:
1542       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1543                                         UndefElts, Depth+1);
1544       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1545       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1546                                         UndefElts2, Depth+1);
1547       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1548
1549       // If only the low elt is demanded and this is a scalarizable intrinsic,
1550       // scalarize it now.
1551       if (DemandedElts == 1) {
1552         switch (II->getIntrinsicID()) {
1553         default: break;
1554         case Intrinsic::x86_sse_sub_ss:
1555         case Intrinsic::x86_sse_mul_ss:
1556         case Intrinsic::x86_sse2_sub_sd:
1557         case Intrinsic::x86_sse2_mul_sd:
1558           // TODO: Lower MIN/MAX/ABS/etc
1559           Value *LHS = II->getOperand(1);
1560           Value *RHS = II->getOperand(2);
1561           // Extract the element as scalars.
1562           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1563           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1564           
1565           switch (II->getIntrinsicID()) {
1566           default: assert(0 && "Case stmts out of sync!");
1567           case Intrinsic::x86_sse_sub_ss:
1568           case Intrinsic::x86_sse2_sub_sd:
1569             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1570                                                         II->getName()), *II);
1571             break;
1572           case Intrinsic::x86_sse_mul_ss:
1573           case Intrinsic::x86_sse2_mul_sd:
1574             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1575                                                          II->getName()), *II);
1576             break;
1577           }
1578           
1579           Instruction *New =
1580             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1581                                       II->getName());
1582           InsertNewInstBefore(New, *II);
1583           AddSoonDeadInstToWorklist(*II, 0);
1584           return New;
1585         }            
1586       }
1587         
1588       // Output elements are undefined if both are undefined.  Consider things
1589       // like undef&0.  The result is known zero, not undef.
1590       UndefElts &= UndefElts2;
1591       break;
1592     }
1593     break;
1594   }
1595   }
1596   return MadeChange ? I : 0;
1597 }
1598
1599
1600 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1601 /// function is designed to check a chain of associative operators for a
1602 /// potential to apply a certain optimization.  Since the optimization may be
1603 /// applicable if the expression was reassociated, this checks the chain, then
1604 /// reassociates the expression as necessary to expose the optimization
1605 /// opportunity.  This makes use of a special Functor, which must define
1606 /// 'shouldApply' and 'apply' methods.
1607 ///
1608 template<typename Functor>
1609 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1610   unsigned Opcode = Root.getOpcode();
1611   Value *LHS = Root.getOperand(0);
1612
1613   // Quick check, see if the immediate LHS matches...
1614   if (F.shouldApply(LHS))
1615     return F.apply(Root);
1616
1617   // Otherwise, if the LHS is not of the same opcode as the root, return.
1618   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1619   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1620     // Should we apply this transform to the RHS?
1621     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1622
1623     // If not to the RHS, check to see if we should apply to the LHS...
1624     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1625       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1626       ShouldApply = true;
1627     }
1628
1629     // If the functor wants to apply the optimization to the RHS of LHSI,
1630     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1631     if (ShouldApply) {
1632       BasicBlock *BB = Root.getParent();
1633
1634       // Now all of the instructions are in the current basic block, go ahead
1635       // and perform the reassociation.
1636       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1637
1638       // First move the selected RHS to the LHS of the root...
1639       Root.setOperand(0, LHSI->getOperand(1));
1640
1641       // Make what used to be the LHS of the root be the user of the root...
1642       Value *ExtraOperand = TmpLHSI->getOperand(1);
1643       if (&Root == TmpLHSI) {
1644         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1645         return 0;
1646       }
1647       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1648       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1649       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1650       BasicBlock::iterator ARI = &Root; ++ARI;
1651       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1652       ARI = Root;
1653
1654       // Now propagate the ExtraOperand down the chain of instructions until we
1655       // get to LHSI.
1656       while (TmpLHSI != LHSI) {
1657         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1658         // Move the instruction to immediately before the chain we are
1659         // constructing to avoid breaking dominance properties.
1660         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1661         BB->getInstList().insert(ARI, NextLHSI);
1662         ARI = NextLHSI;
1663
1664         Value *NextOp = NextLHSI->getOperand(1);
1665         NextLHSI->setOperand(1, ExtraOperand);
1666         TmpLHSI = NextLHSI;
1667         ExtraOperand = NextOp;
1668       }
1669
1670       // Now that the instructions are reassociated, have the functor perform
1671       // the transformation...
1672       return F.apply(Root);
1673     }
1674
1675     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1676   }
1677   return 0;
1678 }
1679
1680 namespace {
1681
1682 // AddRHS - Implements: X + X --> X << 1
1683 struct AddRHS {
1684   Value *RHS;
1685   AddRHS(Value *rhs) : RHS(rhs) {}
1686   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1687   Instruction *apply(BinaryOperator &Add) const {
1688     return BinaryOperator::CreateShl(Add.getOperand(0),
1689                                      ConstantInt::get(Add.getType(), 1));
1690   }
1691 };
1692
1693 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1694 //                 iff C1&C2 == 0
1695 struct AddMaskingAnd {
1696   Constant *C2;
1697   AddMaskingAnd(Constant *c) : C2(c) {}
1698   bool shouldApply(Value *LHS) const {
1699     ConstantInt *C1;
1700     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1701            ConstantExpr::getAnd(C1, C2)->isNullValue();
1702   }
1703   Instruction *apply(BinaryOperator &Add) const {
1704     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1705   }
1706 };
1707
1708 }
1709
1710 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1711                                              InstCombiner *IC) {
1712   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1713     if (Constant *SOC = dyn_cast<Constant>(SO))
1714       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1715
1716     return IC->InsertNewInstBefore(CastInst::Create(
1717           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1718   }
1719
1720   // Figure out if the constant is the left or the right argument.
1721   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1722   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1723
1724   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1725     if (ConstIsRHS)
1726       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1727     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1728   }
1729
1730   Value *Op0 = SO, *Op1 = ConstOperand;
1731   if (!ConstIsRHS)
1732     std::swap(Op0, Op1);
1733   Instruction *New;
1734   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1735     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1736   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1737     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1738                           SO->getName()+".cmp");
1739   else {
1740     assert(0 && "Unknown binary instruction type!");
1741     abort();
1742   }
1743   return IC->InsertNewInstBefore(New, I);
1744 }
1745
1746 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1747 // constant as the other operand, try to fold the binary operator into the
1748 // select arguments.  This also works for Cast instructions, which obviously do
1749 // not have a second operand.
1750 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1751                                      InstCombiner *IC) {
1752   // Don't modify shared select instructions
1753   if (!SI->hasOneUse()) return 0;
1754   Value *TV = SI->getOperand(1);
1755   Value *FV = SI->getOperand(2);
1756
1757   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1758     // Bool selects with constant operands can be folded to logical ops.
1759     if (SI->getType() == Type::Int1Ty) return 0;
1760
1761     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1762     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1763
1764     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1765                               SelectFalseVal);
1766   }
1767   return 0;
1768 }
1769
1770
1771 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1772 /// node as operand #0, see if we can fold the instruction into the PHI (which
1773 /// is only possible if all operands to the PHI are constants).
1774 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1775   PHINode *PN = cast<PHINode>(I.getOperand(0));
1776   unsigned NumPHIValues = PN->getNumIncomingValues();
1777   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1778
1779   // Check to see if all of the operands of the PHI are constants.  If there is
1780   // one non-constant value, remember the BB it is.  If there is more than one
1781   // or if *it* is a PHI, bail out.
1782   BasicBlock *NonConstBB = 0;
1783   for (unsigned i = 0; i != NumPHIValues; ++i)
1784     if (!isa<Constant>(PN->getIncomingValue(i))) {
1785       if (NonConstBB) return 0;  // More than one non-const value.
1786       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1787       NonConstBB = PN->getIncomingBlock(i);
1788       
1789       // If the incoming non-constant value is in I's block, we have an infinite
1790       // loop.
1791       if (NonConstBB == I.getParent())
1792         return 0;
1793     }
1794   
1795   // If there is exactly one non-constant value, we can insert a copy of the
1796   // operation in that block.  However, if this is a critical edge, we would be
1797   // inserting the computation one some other paths (e.g. inside a loop).  Only
1798   // do this if the pred block is unconditionally branching into the phi block.
1799   if (NonConstBB) {
1800     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1801     if (!BI || !BI->isUnconditional()) return 0;
1802   }
1803
1804   // Okay, we can do the transformation: create the new PHI node.
1805   PHINode *NewPN = PHINode::Create(I.getType(), "");
1806   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1807   InsertNewInstBefore(NewPN, *PN);
1808   NewPN->takeName(PN);
1809
1810   // Next, add all of the operands to the PHI.
1811   if (I.getNumOperands() == 2) {
1812     Constant *C = cast<Constant>(I.getOperand(1));
1813     for (unsigned i = 0; i != NumPHIValues; ++i) {
1814       Value *InV = 0;
1815       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1816         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1817           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1818         else
1819           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1820       } else {
1821         assert(PN->getIncomingBlock(i) == NonConstBB);
1822         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1823           InV = BinaryOperator::Create(BO->getOpcode(),
1824                                        PN->getIncomingValue(i), C, "phitmp",
1825                                        NonConstBB->getTerminator());
1826         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1827           InV = CmpInst::Create(CI->getOpcode(), 
1828                                 CI->getPredicate(),
1829                                 PN->getIncomingValue(i), C, "phitmp",
1830                                 NonConstBB->getTerminator());
1831         else
1832           assert(0 && "Unknown binop!");
1833         
1834         AddToWorkList(cast<Instruction>(InV));
1835       }
1836       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1837     }
1838   } else { 
1839     CastInst *CI = cast<CastInst>(&I);
1840     const Type *RetTy = CI->getType();
1841     for (unsigned i = 0; i != NumPHIValues; ++i) {
1842       Value *InV;
1843       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1844         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1845       } else {
1846         assert(PN->getIncomingBlock(i) == NonConstBB);
1847         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1848                                I.getType(), "phitmp", 
1849                                NonConstBB->getTerminator());
1850         AddToWorkList(cast<Instruction>(InV));
1851       }
1852       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1853     }
1854   }
1855   return ReplaceInstUsesWith(I, NewPN);
1856 }
1857
1858
1859 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1860 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1861 /// This basically requires proving that the add in the original type would not
1862 /// overflow to change the sign bit or have a carry out.
1863 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1864   // There are different heuristics we can use for this.  Here are some simple
1865   // ones.
1866   
1867   // Add has the property that adding any two 2's complement numbers can only 
1868   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1869   // have at least two sign bits, we know that the addition of the two values will
1870   // sign extend fine.
1871   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1872     return true;
1873   
1874   
1875   // If one of the operands only has one non-zero bit, and if the other operand
1876   // has a known-zero bit in a more significant place than it (not including the
1877   // sign bit) the ripple may go up to and fill the zero, but won't change the
1878   // sign.  For example, (X & ~4) + 1.
1879   
1880   // TODO: Implement.
1881   
1882   return false;
1883 }
1884
1885
1886 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1887   bool Changed = SimplifyCommutative(I);
1888   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1889
1890   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1891     // X + undef -> undef
1892     if (isa<UndefValue>(RHS))
1893       return ReplaceInstUsesWith(I, RHS);
1894
1895     // X + 0 --> X
1896     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1897       if (RHSC->isNullValue())
1898         return ReplaceInstUsesWith(I, LHS);
1899     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1900       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1901                               (I.getType())->getValueAPF()))
1902         return ReplaceInstUsesWith(I, LHS);
1903     }
1904
1905     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1906       // X + (signbit) --> X ^ signbit
1907       const APInt& Val = CI->getValue();
1908       uint32_t BitWidth = Val.getBitWidth();
1909       if (Val == APInt::getSignBit(BitWidth))
1910         return BinaryOperator::CreateXor(LHS, RHS);
1911       
1912       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1913       // (X & 254)+1 -> (X&254)|1
1914       if (!isa<VectorType>(I.getType())) {
1915         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1916         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1917                                  KnownZero, KnownOne))
1918           return &I;
1919       }
1920     }
1921
1922     if (isa<PHINode>(LHS))
1923       if (Instruction *NV = FoldOpIntoPhi(I))
1924         return NV;
1925     
1926     ConstantInt *XorRHS = 0;
1927     Value *XorLHS = 0;
1928     if (isa<ConstantInt>(RHSC) &&
1929         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1930       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1931       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1932       
1933       uint32_t Size = TySizeBits / 2;
1934       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1935       APInt CFF80Val(-C0080Val);
1936       do {
1937         if (TySizeBits > Size) {
1938           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1939           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1940           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1941               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1942             // This is a sign extend if the top bits are known zero.
1943             if (!MaskedValueIsZero(XorLHS, 
1944                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1945               Size = 0;  // Not a sign ext, but can't be any others either.
1946             break;
1947           }
1948         }
1949         Size >>= 1;
1950         C0080Val = APIntOps::lshr(C0080Val, Size);
1951         CFF80Val = APIntOps::ashr(CFF80Val, Size);
1952       } while (Size >= 1);
1953       
1954       // FIXME: This shouldn't be necessary. When the backends can handle types
1955       // with funny bit widths then this switch statement should be removed. It
1956       // is just here to get the size of the "middle" type back up to something
1957       // that the back ends can handle.
1958       const Type *MiddleType = 0;
1959       switch (Size) {
1960         default: break;
1961         case 32: MiddleType = Type::Int32Ty; break;
1962         case 16: MiddleType = Type::Int16Ty; break;
1963         case  8: MiddleType = Type::Int8Ty; break;
1964       }
1965       if (MiddleType) {
1966         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1967         InsertNewInstBefore(NewTrunc, I);
1968         return new SExtInst(NewTrunc, I.getType(), I.getName());
1969       }
1970     }
1971   }
1972
1973   if (I.getType() == Type::Int1Ty)
1974     return BinaryOperator::CreateXor(LHS, RHS);
1975
1976   // X + X --> X << 1
1977   if (I.getType()->isInteger()) {
1978     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1979
1980     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1981       if (RHSI->getOpcode() == Instruction::Sub)
1982         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1983           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1984     }
1985     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1986       if (LHSI->getOpcode() == Instruction::Sub)
1987         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1988           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1989     }
1990   }
1991
1992   // -A + B  -->  B - A
1993   // -A + -B  -->  -(A + B)
1994   if (Value *LHSV = dyn_castNegVal(LHS)) {
1995     if (LHS->getType()->isIntOrIntVector()) {
1996       if (Value *RHSV = dyn_castNegVal(RHS)) {
1997         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
1998         InsertNewInstBefore(NewAdd, I);
1999         return BinaryOperator::CreateNeg(NewAdd);
2000       }
2001     }
2002     
2003     return BinaryOperator::CreateSub(RHS, LHSV);
2004   }
2005
2006   // A + -B  -->  A - B
2007   if (!isa<Constant>(RHS))
2008     if (Value *V = dyn_castNegVal(RHS))
2009       return BinaryOperator::CreateSub(LHS, V);
2010
2011
2012   ConstantInt *C2;
2013   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2014     if (X == RHS)   // X*C + X --> X * (C+1)
2015       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2016
2017     // X*C1 + X*C2 --> X * (C1+C2)
2018     ConstantInt *C1;
2019     if (X == dyn_castFoldableMul(RHS, C1))
2020       return BinaryOperator::CreateMul(X, Add(C1, C2));
2021   }
2022
2023   // X + X*C --> X * (C+1)
2024   if (dyn_castFoldableMul(RHS, C2) == LHS)
2025     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2026
2027   // X + ~X --> -1   since   ~X = -X-1
2028   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2029     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2030   
2031
2032   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2033   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2034     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2035       return R;
2036   
2037   // A+B --> A|B iff A and B have no bits set in common.
2038   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2039     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2040     APInt LHSKnownOne(IT->getBitWidth(), 0);
2041     APInt LHSKnownZero(IT->getBitWidth(), 0);
2042     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2043     if (LHSKnownZero != 0) {
2044       APInt RHSKnownOne(IT->getBitWidth(), 0);
2045       APInt RHSKnownZero(IT->getBitWidth(), 0);
2046       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2047       
2048       // No bits in common -> bitwise or.
2049       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2050         return BinaryOperator::CreateOr(LHS, RHS);
2051     }
2052   }
2053
2054   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2055   if (I.getType()->isIntOrIntVector()) {
2056     Value *W, *X, *Y, *Z;
2057     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2058         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2059       if (W != Y) {
2060         if (W == Z) {
2061           std::swap(Y, Z);
2062         } else if (Y == X) {
2063           std::swap(W, X);
2064         } else if (X == Z) {
2065           std::swap(Y, Z);
2066           std::swap(W, X);
2067         }
2068       }
2069
2070       if (W == Y) {
2071         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2072                                                             LHS->getName()), I);
2073         return BinaryOperator::CreateMul(W, NewAdd);
2074       }
2075     }
2076   }
2077
2078   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2079     Value *X = 0;
2080     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2081       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2082
2083     // (X & FF00) + xx00  -> (X+xx00) & FF00
2084     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2085       Constant *Anded = And(CRHS, C2);
2086       if (Anded == CRHS) {
2087         // See if all bits from the first bit set in the Add RHS up are included
2088         // in the mask.  First, get the rightmost bit.
2089         const APInt& AddRHSV = CRHS->getValue();
2090
2091         // Form a mask of all bits from the lowest bit added through the top.
2092         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2093
2094         // See if the and mask includes all of these bits.
2095         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2096
2097         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2098           // Okay, the xform is safe.  Insert the new add pronto.
2099           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2100                                                             LHS->getName()), I);
2101           return BinaryOperator::CreateAnd(NewAdd, C2);
2102         }
2103       }
2104     }
2105
2106     // Try to fold constant add into select arguments.
2107     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2108       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2109         return R;
2110   }
2111
2112   // add (cast *A to intptrtype) B -> 
2113   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2114   {
2115     CastInst *CI = dyn_cast<CastInst>(LHS);
2116     Value *Other = RHS;
2117     if (!CI) {
2118       CI = dyn_cast<CastInst>(RHS);
2119       Other = LHS;
2120     }
2121     if (CI && CI->getType()->isSized() && 
2122         (CI->getType()->getPrimitiveSizeInBits() == 
2123          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2124         && isa<PointerType>(CI->getOperand(0)->getType())) {
2125       unsigned AS =
2126         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2127       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2128                                       PointerType::get(Type::Int8Ty, AS), I);
2129       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2130       return new PtrToIntInst(I2, CI->getType());
2131     }
2132   }
2133   
2134   // add (select X 0 (sub n A)) A  -->  select X A n
2135   {
2136     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2137     Value *Other = RHS;
2138     if (!SI) {
2139       SI = dyn_cast<SelectInst>(RHS);
2140       Other = LHS;
2141     }
2142     if (SI && SI->hasOneUse()) {
2143       Value *TV = SI->getTrueValue();
2144       Value *FV = SI->getFalseValue();
2145       Value *A, *N;
2146
2147       // Can we fold the add into the argument of the select?
2148       // We check both true and false select arguments for a matching subtract.
2149       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2150           A == Other)  // Fold the add into the true select value.
2151         return SelectInst::Create(SI->getCondition(), N, A);
2152       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2153           A == Other)  // Fold the add into the false select value.
2154         return SelectInst::Create(SI->getCondition(), A, N);
2155     }
2156   }
2157   
2158   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2159   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2160     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2161       return ReplaceInstUsesWith(I, LHS);
2162
2163   // Check for (add (sext x), y), see if we can merge this into an
2164   // integer add followed by a sext.
2165   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2166     // (add (sext x), cst) --> (sext (add x, cst'))
2167     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2168       Constant *CI = 
2169         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2170       if (LHSConv->hasOneUse() &&
2171           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2172           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2173         // Insert the new, smaller add.
2174         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2175                                                         CI, "addconv");
2176         InsertNewInstBefore(NewAdd, I);
2177         return new SExtInst(NewAdd, I.getType());
2178       }
2179     }
2180     
2181     // (add (sext x), (sext y)) --> (sext (add int x, y))
2182     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2183       // Only do this if x/y have the same type, if at last one of them has a
2184       // single use (so we don't increase the number of sexts), and if the
2185       // integer add will not overflow.
2186       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2187           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2188           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2189                                    RHSConv->getOperand(0))) {
2190         // Insert the new integer add.
2191         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2192                                                         RHSConv->getOperand(0),
2193                                                         "addconv");
2194         InsertNewInstBefore(NewAdd, I);
2195         return new SExtInst(NewAdd, I.getType());
2196       }
2197     }
2198   }
2199   
2200   // Check for (add double (sitofp x), y), see if we can merge this into an
2201   // integer add followed by a promotion.
2202   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2203     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2204     // ... if the constant fits in the integer value.  This is useful for things
2205     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2206     // requires a constant pool load, and generally allows the add to be better
2207     // instcombined.
2208     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2209       Constant *CI = 
2210       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2211       if (LHSConv->hasOneUse() &&
2212           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2213           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2214         // Insert the new integer add.
2215         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2216                                                         CI, "addconv");
2217         InsertNewInstBefore(NewAdd, I);
2218         return new SIToFPInst(NewAdd, I.getType());
2219       }
2220     }
2221     
2222     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2223     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2224       // Only do this if x/y have the same type, if at last one of them has a
2225       // single use (so we don't increase the number of int->fp conversions),
2226       // and if the integer add will not overflow.
2227       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2228           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2229           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2230                                    RHSConv->getOperand(0))) {
2231         // Insert the new integer add.
2232         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2233                                                         RHSConv->getOperand(0),
2234                                                         "addconv");
2235         InsertNewInstBefore(NewAdd, I);
2236         return new SIToFPInst(NewAdd, I.getType());
2237       }
2238     }
2239   }
2240   
2241   return Changed ? &I : 0;
2242 }
2243
2244 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2245   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2246
2247   if (Op0 == Op1)         // sub X, X  -> 0
2248     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2249
2250   // If this is a 'B = x-(-A)', change to B = x+A...
2251   if (Value *V = dyn_castNegVal(Op1))
2252     return BinaryOperator::CreateAdd(Op0, V);
2253
2254   if (isa<UndefValue>(Op0))
2255     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2256   if (isa<UndefValue>(Op1))
2257     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2258
2259   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2260     // Replace (-1 - A) with (~A)...
2261     if (C->isAllOnesValue())
2262       return BinaryOperator::CreateNot(Op1);
2263
2264     // C - ~X == X + (1+C)
2265     Value *X = 0;
2266     if (match(Op1, m_Not(m_Value(X))))
2267       return BinaryOperator::CreateAdd(X, AddOne(C));
2268
2269     // -(X >>u 31) -> (X >>s 31)
2270     // -(X >>s 31) -> (X >>u 31)
2271     if (C->isZero()) {
2272       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2273         if (SI->getOpcode() == Instruction::LShr) {
2274           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2275             // Check to see if we are shifting out everything but the sign bit.
2276             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2277                 SI->getType()->getPrimitiveSizeInBits()-1) {
2278               // Ok, the transformation is safe.  Insert AShr.
2279               return BinaryOperator::Create(Instruction::AShr, 
2280                                           SI->getOperand(0), CU, SI->getName());
2281             }
2282           }
2283         }
2284         else if (SI->getOpcode() == Instruction::AShr) {
2285           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2286             // Check to see if we are shifting out everything but the sign bit.
2287             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2288                 SI->getType()->getPrimitiveSizeInBits()-1) {
2289               // Ok, the transformation is safe.  Insert LShr. 
2290               return BinaryOperator::CreateLShr(
2291                                           SI->getOperand(0), CU, SI->getName());
2292             }
2293           }
2294         }
2295       }
2296     }
2297
2298     // Try to fold constant sub into select arguments.
2299     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2300       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2301         return R;
2302
2303     if (isa<PHINode>(Op0))
2304       if (Instruction *NV = FoldOpIntoPhi(I))
2305         return NV;
2306   }
2307
2308   if (I.getType() == Type::Int1Ty)
2309     return BinaryOperator::CreateXor(Op0, Op1);
2310
2311   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2312     if (Op1I->getOpcode() == Instruction::Add &&
2313         !Op0->getType()->isFPOrFPVector()) {
2314       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2315         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2316       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2317         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2318       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2319         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2320           // C1-(X+C2) --> (C1-C2)-X
2321           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2322                                            Op1I->getOperand(0));
2323       }
2324     }
2325
2326     if (Op1I->hasOneUse()) {
2327       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2328       // is not used by anyone else...
2329       //
2330       if (Op1I->getOpcode() == Instruction::Sub &&
2331           !Op1I->getType()->isFPOrFPVector()) {
2332         // Swap the two operands of the subexpr...
2333         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2334         Op1I->setOperand(0, IIOp1);
2335         Op1I->setOperand(1, IIOp0);
2336
2337         // Create the new top level add instruction...
2338         return BinaryOperator::CreateAdd(Op0, Op1);
2339       }
2340
2341       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2342       //
2343       if (Op1I->getOpcode() == Instruction::And &&
2344           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2345         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2346
2347         Value *NewNot =
2348           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2349         return BinaryOperator::CreateAnd(Op0, NewNot);
2350       }
2351
2352       // 0 - (X sdiv C)  -> (X sdiv -C)
2353       if (Op1I->getOpcode() == Instruction::SDiv)
2354         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2355           if (CSI->isZero())
2356             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2357               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2358                                                ConstantExpr::getNeg(DivRHS));
2359
2360       // X - X*C --> X * (1-C)
2361       ConstantInt *C2 = 0;
2362       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2363         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2364         return BinaryOperator::CreateMul(Op0, CP1);
2365       }
2366
2367       // X - ((X / Y) * Y) --> X % Y
2368       if (Op1I->getOpcode() == Instruction::Mul)
2369         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2370           if (Op0 == I->getOperand(0) &&
2371               Op1I->getOperand(1) == I->getOperand(1)) {
2372             if (I->getOpcode() == Instruction::SDiv)
2373               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2374             if (I->getOpcode() == Instruction::UDiv)
2375               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2376           }
2377     }
2378   }
2379
2380   if (!Op0->getType()->isFPOrFPVector())
2381     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2382       if (Op0I->getOpcode() == Instruction::Add) {
2383         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2384           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2385         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2386           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2387       } else if (Op0I->getOpcode() == Instruction::Sub) {
2388         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2389           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2390       }
2391     }
2392
2393   ConstantInt *C1;
2394   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2395     if (X == Op1)  // X*C - X --> X * (C-1)
2396       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2397
2398     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2399     if (X == dyn_castFoldableMul(Op1, C2))
2400       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2401   }
2402   return 0;
2403 }
2404
2405 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2406 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2407 /// TrueIfSigned if the result of the comparison is true when the input value is
2408 /// signed.
2409 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2410                            bool &TrueIfSigned) {
2411   switch (pred) {
2412   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2413     TrueIfSigned = true;
2414     return RHS->isZero();
2415   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2416     TrueIfSigned = true;
2417     return RHS->isAllOnesValue();
2418   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2419     TrueIfSigned = false;
2420     return RHS->isAllOnesValue();
2421   case ICmpInst::ICMP_UGT:
2422     // True if LHS u> RHS and RHS == high-bit-mask - 1
2423     TrueIfSigned = true;
2424     return RHS->getValue() ==
2425       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2426   case ICmpInst::ICMP_UGE: 
2427     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2428     TrueIfSigned = true;
2429     return RHS->getValue().isSignBit();
2430   default:
2431     return false;
2432   }
2433 }
2434
2435 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2436   bool Changed = SimplifyCommutative(I);
2437   Value *Op0 = I.getOperand(0);
2438
2439   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2440     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2441
2442   // Simplify mul instructions with a constant RHS...
2443   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2444     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2445
2446       // ((X << C1)*C2) == (X * (C2 << C1))
2447       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2448         if (SI->getOpcode() == Instruction::Shl)
2449           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2450             return BinaryOperator::CreateMul(SI->getOperand(0),
2451                                              ConstantExpr::getShl(CI, ShOp));
2452
2453       if (CI->isZero())
2454         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2455       if (CI->equalsInt(1))                  // X * 1  == X
2456         return ReplaceInstUsesWith(I, Op0);
2457       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2458         return BinaryOperator::CreateNeg(Op0, I.getName());
2459
2460       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2461       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2462         return BinaryOperator::CreateShl(Op0,
2463                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2464       }
2465     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2466       if (Op1F->isNullValue())
2467         return ReplaceInstUsesWith(I, Op1);
2468
2469       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2470       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2471       // We need a better interface for long double here.
2472       if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2473         if (Op1F->isExactlyValue(1.0))
2474           return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2475     }
2476     
2477     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2478       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2479           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2480         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2481         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2482                                                      Op1, "tmp");
2483         InsertNewInstBefore(Add, I);
2484         Value *C1C2 = ConstantExpr::getMul(Op1, 
2485                                            cast<Constant>(Op0I->getOperand(1)));
2486         return BinaryOperator::CreateAdd(Add, C1C2);
2487         
2488       }
2489
2490     // Try to fold constant mul into select arguments.
2491     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2492       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2493         return R;
2494
2495     if (isa<PHINode>(Op0))
2496       if (Instruction *NV = FoldOpIntoPhi(I))
2497         return NV;
2498   }
2499
2500   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2501     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2502       return BinaryOperator::CreateMul(Op0v, Op1v);
2503
2504   if (I.getType() == Type::Int1Ty)
2505     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2506
2507   // If one of the operands of the multiply is a cast from a boolean value, then
2508   // we know the bool is either zero or one, so this is a 'masking' multiply.
2509   // See if we can simplify things based on how the boolean was originally
2510   // formed.
2511   CastInst *BoolCast = 0;
2512   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2513     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2514       BoolCast = CI;
2515   if (!BoolCast)
2516     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2517       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2518         BoolCast = CI;
2519   if (BoolCast) {
2520     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2521       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2522       const Type *SCOpTy = SCIOp0->getType();
2523       bool TIS = false;
2524       
2525       // If the icmp is true iff the sign bit of X is set, then convert this
2526       // multiply into a shift/and combination.
2527       if (isa<ConstantInt>(SCIOp1) &&
2528           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2529           TIS) {
2530         // Shift the X value right to turn it into "all signbits".
2531         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2532                                           SCOpTy->getPrimitiveSizeInBits()-1);
2533         Value *V =
2534           InsertNewInstBefore(
2535             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2536                                             BoolCast->getOperand(0)->getName()+
2537                                             ".mask"), I);
2538
2539         // If the multiply type is not the same as the source type, sign extend
2540         // or truncate to the multiply type.
2541         if (I.getType() != V->getType()) {
2542           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2543           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2544           Instruction::CastOps opcode = 
2545             (SrcBits == DstBits ? Instruction::BitCast : 
2546              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2547           V = InsertCastBefore(opcode, V, I.getType(), I);
2548         }
2549
2550         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2551         return BinaryOperator::CreateAnd(V, OtherOp);
2552       }
2553     }
2554   }
2555
2556   return Changed ? &I : 0;
2557 }
2558
2559 /// This function implements the transforms on div instructions that work
2560 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2561 /// used by the visitors to those instructions.
2562 /// @brief Transforms common to all three div instructions
2563 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2564   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2565
2566   // undef / X -> 0        for integer.
2567   // undef / X -> undef    for FP (the undef could be a snan).
2568   if (isa<UndefValue>(Op0)) {
2569     if (Op0->getType()->isFPOrFPVector())
2570       return ReplaceInstUsesWith(I, Op0);
2571     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2572   }
2573
2574   // X / undef -> undef
2575   if (isa<UndefValue>(Op1))
2576     return ReplaceInstUsesWith(I, Op1);
2577
2578   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2579   // This does not apply for fdiv.
2580   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2581     // [su]div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in
2582     // the same basic block, then we replace the select with Y, and the
2583     // condition of the select with false (if the cond value is in the same BB).
2584     // If the select has uses other than the div, this allows them to be
2585     // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2586     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2587       if (ST->isNullValue()) {
2588         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2589         if (CondI && CondI->getParent() == I.getParent())
2590           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2591         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2592           I.setOperand(1, SI->getOperand(2));
2593         else
2594           UpdateValueUsesWith(SI, SI->getOperand(2));
2595         return &I;
2596       }
2597
2598     // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2599     if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2600       if (ST->isNullValue()) {
2601         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2602         if (CondI && CondI->getParent() == I.getParent())
2603           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2604         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2605           I.setOperand(1, SI->getOperand(1));
2606         else
2607           UpdateValueUsesWith(SI, SI->getOperand(1));
2608         return &I;
2609       }
2610   }
2611
2612   return 0;
2613 }
2614
2615 /// This function implements the transforms common to both integer division
2616 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2617 /// division instructions.
2618 /// @brief Common integer divide transforms
2619 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2620   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621
2622   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2623   if (Op0 == Op1) {
2624     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2625       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2626       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2627       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2628     }
2629
2630     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2631     return ReplaceInstUsesWith(I, CI);
2632   }
2633   
2634   if (Instruction *Common = commonDivTransforms(I))
2635     return Common;
2636
2637   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2638     // div X, 1 == X
2639     if (RHS->equalsInt(1))
2640       return ReplaceInstUsesWith(I, Op0);
2641
2642     // (X / C1) / C2  -> X / (C1*C2)
2643     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2644       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2645         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2646           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2647             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2648           else 
2649             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2650                                           Multiply(RHS, LHSRHS));
2651         }
2652
2653     if (!RHS->isZero()) { // avoid X udiv 0
2654       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2655         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2656           return R;
2657       if (isa<PHINode>(Op0))
2658         if (Instruction *NV = FoldOpIntoPhi(I))
2659           return NV;
2660     }
2661   }
2662
2663   // 0 / X == 0, we don't need to preserve faults!
2664   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2665     if (LHS->equalsInt(0))
2666       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2667
2668   // It can't be division by zero, hence it must be division by one.
2669   if (I.getType() == Type::Int1Ty)
2670     return ReplaceInstUsesWith(I, Op0);
2671
2672   return 0;
2673 }
2674
2675 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2676   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2677
2678   // Handle the integer div common cases
2679   if (Instruction *Common = commonIDivTransforms(I))
2680     return Common;
2681
2682   // X udiv C^2 -> X >> C
2683   // Check to see if this is an unsigned division with an exact power of 2,
2684   // if so, convert to a right shift.
2685   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2686     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2687       return BinaryOperator::CreateLShr(Op0, 
2688                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2689   }
2690
2691   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2692   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2693     if (RHSI->getOpcode() == Instruction::Shl &&
2694         isa<ConstantInt>(RHSI->getOperand(0))) {
2695       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2696       if (C1.isPowerOf2()) {
2697         Value *N = RHSI->getOperand(1);
2698         const Type *NTy = N->getType();
2699         if (uint32_t C2 = C1.logBase2()) {
2700           Constant *C2V = ConstantInt::get(NTy, C2);
2701           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2702         }
2703         return BinaryOperator::CreateLShr(Op0, N);
2704       }
2705     }
2706   }
2707   
2708   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2709   // where C1&C2 are powers of two.
2710   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2711     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2712       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2713         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2714         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2715           // Compute the shift amounts
2716           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2717           // Construct the "on true" case of the select
2718           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2719           Instruction *TSI = BinaryOperator::CreateLShr(
2720                                                  Op0, TC, SI->getName()+".t");
2721           TSI = InsertNewInstBefore(TSI, I);
2722   
2723           // Construct the "on false" case of the select
2724           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2725           Instruction *FSI = BinaryOperator::CreateLShr(
2726                                                  Op0, FC, SI->getName()+".f");
2727           FSI = InsertNewInstBefore(FSI, I);
2728
2729           // construct the select instruction and return it.
2730           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2731         }
2732       }
2733   return 0;
2734 }
2735
2736 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2737   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2738
2739   // Handle the integer div common cases
2740   if (Instruction *Common = commonIDivTransforms(I))
2741     return Common;
2742
2743   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2744     // sdiv X, -1 == -X
2745     if (RHS->isAllOnesValue())
2746       return BinaryOperator::CreateNeg(Op0);
2747
2748     // -X/C -> X/-C
2749     if (Value *LHSNeg = dyn_castNegVal(Op0))
2750       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2751   }
2752
2753   // If the sign bits of both operands are zero (i.e. we can prove they are
2754   // unsigned inputs), turn this into a udiv.
2755   if (I.getType()->isInteger()) {
2756     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2757     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2758       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2759       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2760     }
2761   }      
2762   
2763   return 0;
2764 }
2765
2766 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2767   return commonDivTransforms(I);
2768 }
2769
2770 /// This function implements the transforms on rem instructions that work
2771 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2772 /// is used by the visitors to those instructions.
2773 /// @brief Transforms common to all three rem instructions
2774 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2775   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2776
2777   // 0 % X == 0 for integer, we don't need to preserve faults!
2778   if (Constant *LHS = dyn_cast<Constant>(Op0))
2779     if (LHS->isNullValue())
2780       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2781
2782   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2783     if (I.getType()->isFPOrFPVector())
2784       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2785     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2786   }
2787   if (isa<UndefValue>(Op1))
2788     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2789
2790   // Handle cases involving: rem X, (select Cond, Y, Z)
2791   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2792     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2793     // the same basic block, then we replace the select with Y, and the
2794     // condition of the select with false (if the cond value is in the same
2795     // BB).  If the select has uses other than the div, this allows them to be
2796     // simplified also.
2797     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2798       if (ST->isNullValue()) {
2799         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2800         if (CondI && CondI->getParent() == I.getParent())
2801           UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2802         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2803           I.setOperand(1, SI->getOperand(2));
2804         else
2805           UpdateValueUsesWith(SI, SI->getOperand(2));
2806         return &I;
2807       }
2808     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2809     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2810       if (ST->isNullValue()) {
2811         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2812         if (CondI && CondI->getParent() == I.getParent())
2813           UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2814         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2815           I.setOperand(1, SI->getOperand(1));
2816         else
2817           UpdateValueUsesWith(SI, SI->getOperand(1));
2818         return &I;
2819       }
2820   }
2821
2822   return 0;
2823 }
2824
2825 /// This function implements the transforms common to both integer remainder
2826 /// instructions (urem and srem). It is called by the visitors to those integer
2827 /// remainder instructions.
2828 /// @brief Common integer remainder transforms
2829 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2830   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2831
2832   if (Instruction *common = commonRemTransforms(I))
2833     return common;
2834
2835   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2836     // X % 0 == undef, we don't need to preserve faults!
2837     if (RHS->equalsInt(0))
2838       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2839     
2840     if (RHS->equalsInt(1))  // X % 1 == 0
2841       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2842
2843     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2844       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2845         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2846           return R;
2847       } else if (isa<PHINode>(Op0I)) {
2848         if (Instruction *NV = FoldOpIntoPhi(I))
2849           return NV;
2850       }
2851
2852       // See if we can fold away this rem instruction.
2853       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2854       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2855       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2856                                KnownZero, KnownOne))
2857         return &I;
2858     }
2859   }
2860
2861   return 0;
2862 }
2863
2864 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2865   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2866
2867   if (Instruction *common = commonIRemTransforms(I))
2868     return common;
2869   
2870   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2871     // X urem C^2 -> X and C
2872     // Check to see if this is an unsigned remainder with an exact power of 2,
2873     // if so, convert to a bitwise and.
2874     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2875       if (C->getValue().isPowerOf2())
2876         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2877   }
2878
2879   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2880     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2881     if (RHSI->getOpcode() == Instruction::Shl &&
2882         isa<ConstantInt>(RHSI->getOperand(0))) {
2883       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2884         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2885         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2886                                                                    "tmp"), I);
2887         return BinaryOperator::CreateAnd(Op0, Add);
2888       }
2889     }
2890   }
2891
2892   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2893   // where C1&C2 are powers of two.
2894   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2895     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2896       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2897         // STO == 0 and SFO == 0 handled above.
2898         if ((STO->getValue().isPowerOf2()) && 
2899             (SFO->getValue().isPowerOf2())) {
2900           Value *TrueAnd = InsertNewInstBefore(
2901             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2902           Value *FalseAnd = InsertNewInstBefore(
2903             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2904           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2905         }
2906       }
2907   }
2908   
2909   return 0;
2910 }
2911
2912 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2913   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2914
2915   // Handle the integer rem common cases
2916   if (Instruction *common = commonIRemTransforms(I))
2917     return common;
2918   
2919   if (Value *RHSNeg = dyn_castNegVal(Op1))
2920     if (!isa<ConstantInt>(RHSNeg) || 
2921         cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2922       // X % -Y -> X % Y
2923       AddUsesToWorkList(I);
2924       I.setOperand(1, RHSNeg);
2925       return &I;
2926     }
2927  
2928   // If the sign bits of both operands are zero (i.e. we can prove they are
2929   // unsigned inputs), turn this into a urem.
2930   if (I.getType()->isInteger()) {
2931     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2932     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2933       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2934       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2935     }
2936   }
2937
2938   return 0;
2939 }
2940
2941 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2942   return commonRemTransforms(I);
2943 }
2944
2945 // isMaxValueMinusOne - return true if this is Max-1
2946 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2947   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2948   if (!isSigned)
2949     return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2950   return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2951 }
2952
2953 // isMinValuePlusOne - return true if this is Min+1
2954 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2955   if (!isSigned)
2956     return C->getValue() == 1; // unsigned
2957     
2958   // Calculate 1111111111000000000000
2959   uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2960   return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2961 }
2962
2963 // isOneBitSet - Return true if there is exactly one bit set in the specified
2964 // constant.
2965 static bool isOneBitSet(const ConstantInt *CI) {
2966   return CI->getValue().isPowerOf2();
2967 }
2968
2969 // isHighOnes - Return true if the constant is of the form 1+0+.
2970 // This is the same as lowones(~X).
2971 static bool isHighOnes(const ConstantInt *CI) {
2972   return (~CI->getValue() + 1).isPowerOf2();
2973 }
2974
2975 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
2976 /// are carefully arranged to allow folding of expressions such as:
2977 ///
2978 ///      (A < B) | (A > B) --> (A != B)
2979 ///
2980 /// Note that this is only valid if the first and second predicates have the
2981 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
2982 ///
2983 /// Three bits are used to represent the condition, as follows:
2984 ///   0  A > B
2985 ///   1  A == B
2986 ///   2  A < B
2987 ///
2988 /// <=>  Value  Definition
2989 /// 000     0   Always false
2990 /// 001     1   A >  B
2991 /// 010     2   A == B
2992 /// 011     3   A >= B
2993 /// 100     4   A <  B
2994 /// 101     5   A != B
2995 /// 110     6   A <= B
2996 /// 111     7   Always true
2997 ///  
2998 static unsigned getICmpCode(const ICmpInst *ICI) {
2999   switch (ICI->getPredicate()) {
3000     // False -> 0
3001   case ICmpInst::ICMP_UGT: return 1;  // 001
3002   case ICmpInst::ICMP_SGT: return 1;  // 001
3003   case ICmpInst::ICMP_EQ:  return 2;  // 010
3004   case ICmpInst::ICMP_UGE: return 3;  // 011
3005   case ICmpInst::ICMP_SGE: return 3;  // 011
3006   case ICmpInst::ICMP_ULT: return 4;  // 100
3007   case ICmpInst::ICMP_SLT: return 4;  // 100
3008   case ICmpInst::ICMP_NE:  return 5;  // 101
3009   case ICmpInst::ICMP_ULE: return 6;  // 110
3010   case ICmpInst::ICMP_SLE: return 6;  // 110
3011     // True -> 7
3012   default:
3013     assert(0 && "Invalid ICmp predicate!");
3014     return 0;
3015   }
3016 }
3017
3018 /// getICmpValue - This is the complement of getICmpCode, which turns an
3019 /// opcode and two operands into either a constant true or false, or a brand 
3020 /// new ICmp instruction. The sign is passed in to determine which kind
3021 /// of predicate to use in new icmp instructions.
3022 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3023   switch (code) {
3024   default: assert(0 && "Illegal ICmp code!");
3025   case  0: return ConstantInt::getFalse();
3026   case  1: 
3027     if (sign)
3028       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3029     else
3030       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3031   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3032   case  3: 
3033     if (sign)
3034       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3035     else
3036       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3037   case  4: 
3038     if (sign)
3039       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3040     else
3041       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3042   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3043   case  6: 
3044     if (sign)
3045       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3046     else
3047       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3048   case  7: return ConstantInt::getTrue();
3049   }
3050 }
3051
3052 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3053   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3054     (ICmpInst::isSignedPredicate(p1) && 
3055      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3056     (ICmpInst::isSignedPredicate(p2) && 
3057      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3058 }
3059
3060 namespace { 
3061 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3062 struct FoldICmpLogical {
3063   InstCombiner &IC;
3064   Value *LHS, *RHS;
3065   ICmpInst::Predicate pred;
3066   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3067     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3068       pred(ICI->getPredicate()) {}
3069   bool shouldApply(Value *V) const {
3070     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3071       if (PredicatesFoldable(pred, ICI->getPredicate()))
3072         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3073                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3074     return false;
3075   }
3076   Instruction *apply(Instruction &Log) const {
3077     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3078     if (ICI->getOperand(0) != LHS) {
3079       assert(ICI->getOperand(1) == LHS);
3080       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3081     }
3082
3083     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3084     unsigned LHSCode = getICmpCode(ICI);
3085     unsigned RHSCode = getICmpCode(RHSICI);
3086     unsigned Code;
3087     switch (Log.getOpcode()) {
3088     case Instruction::And: Code = LHSCode & RHSCode; break;
3089     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3090     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3091     default: assert(0 && "Illegal logical opcode!"); return 0;
3092     }
3093
3094     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3095                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3096       
3097     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3098     if (Instruction *I = dyn_cast<Instruction>(RV))
3099       return I;
3100     // Otherwise, it's a constant boolean value...
3101     return IC.ReplaceInstUsesWith(Log, RV);
3102   }
3103 };
3104 } // end anonymous namespace
3105
3106 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3107 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3108 // guaranteed to be a binary operator.
3109 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3110                                     ConstantInt *OpRHS,
3111                                     ConstantInt *AndRHS,
3112                                     BinaryOperator &TheAnd) {
3113   Value *X = Op->getOperand(0);
3114   Constant *Together = 0;
3115   if (!Op->isShift())
3116     Together = And(AndRHS, OpRHS);
3117
3118   switch (Op->getOpcode()) {
3119   case Instruction::Xor:
3120     if (Op->hasOneUse()) {
3121       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3122       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3123       InsertNewInstBefore(And, TheAnd);
3124       And->takeName(Op);
3125       return BinaryOperator::CreateXor(And, Together);
3126     }
3127     break;
3128   case Instruction::Or:
3129     if (Together == AndRHS) // (X | C) & C --> C
3130       return ReplaceInstUsesWith(TheAnd, AndRHS);
3131
3132     if (Op->hasOneUse() && Together != OpRHS) {
3133       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3134       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3135       InsertNewInstBefore(Or, TheAnd);
3136       Or->takeName(Op);
3137       return BinaryOperator::CreateAnd(Or, AndRHS);
3138     }
3139     break;
3140   case Instruction::Add:
3141     if (Op->hasOneUse()) {
3142       // Adding a one to a single bit bit-field should be turned into an XOR
3143       // of the bit.  First thing to check is to see if this AND is with a
3144       // single bit constant.
3145       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3146
3147       // If there is only one bit set...
3148       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3149         // Ok, at this point, we know that we are masking the result of the
3150         // ADD down to exactly one bit.  If the constant we are adding has
3151         // no bits set below this bit, then we can eliminate the ADD.
3152         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3153
3154         // Check to see if any bits below the one bit set in AndRHSV are set.
3155         if ((AddRHS & (AndRHSV-1)) == 0) {
3156           // If not, the only thing that can effect the output of the AND is
3157           // the bit specified by AndRHSV.  If that bit is set, the effect of
3158           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3159           // no effect.
3160           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3161             TheAnd.setOperand(0, X);
3162             return &TheAnd;
3163           } else {
3164             // Pull the XOR out of the AND.
3165             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3166             InsertNewInstBefore(NewAnd, TheAnd);
3167             NewAnd->takeName(Op);
3168             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3169           }
3170         }
3171       }
3172     }
3173     break;
3174
3175   case Instruction::Shl: {
3176     // We know that the AND will not produce any of the bits shifted in, so if
3177     // the anded constant includes them, clear them now!
3178     //
3179     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3180     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3181     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3182     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3183
3184     if (CI->getValue() == ShlMask) { 
3185     // Masking out bits that the shift already masks
3186       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3187     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3188       TheAnd.setOperand(1, CI);
3189       return &TheAnd;
3190     }
3191     break;
3192   }
3193   case Instruction::LShr:
3194   {
3195     // We know that the AND will not produce any of the bits shifted in, so if
3196     // the anded constant includes them, clear them now!  This only applies to
3197     // unsigned shifts, because a signed shr may bring in set bits!
3198     //
3199     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3200     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3201     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3202     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3203
3204     if (CI->getValue() == ShrMask) {   
3205     // Masking out bits that the shift already masks.
3206       return ReplaceInstUsesWith(TheAnd, Op);
3207     } else if (CI != AndRHS) {
3208       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3209       return &TheAnd;
3210     }
3211     break;
3212   }
3213   case Instruction::AShr:
3214     // Signed shr.
3215     // See if this is shifting in some sign extension, then masking it out
3216     // with an and.
3217     if (Op->hasOneUse()) {
3218       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3219       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3220       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3221       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3222       if (C == AndRHS) {          // Masking out bits shifted in.
3223         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3224         // Make the argument unsigned.
3225         Value *ShVal = Op->getOperand(0);
3226         ShVal = InsertNewInstBefore(
3227             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3228                                    Op->getName()), TheAnd);
3229         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3230       }
3231     }
3232     break;
3233   }
3234   return 0;
3235 }
3236
3237
3238 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3239 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3240 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3241 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3242 /// insert new instructions.
3243 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3244                                            bool isSigned, bool Inside, 
3245                                            Instruction &IB) {
3246   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3247             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3248          "Lo is not <= Hi in range emission code!");
3249     
3250   if (Inside) {
3251     if (Lo == Hi)  // Trivially false.
3252       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3253
3254     // V >= Min && V < Hi --> V < Hi
3255     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3256       ICmpInst::Predicate pred = (isSigned ? 
3257         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3258       return new ICmpInst(pred, V, Hi);
3259     }
3260
3261     // Emit V-Lo <u Hi-Lo
3262     Constant *NegLo = ConstantExpr::getNeg(Lo);
3263     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3264     InsertNewInstBefore(Add, IB);
3265     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3266     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3267   }
3268
3269   if (Lo == Hi)  // Trivially true.
3270     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3271
3272   // V < Min || V >= Hi -> V > Hi-1
3273   Hi = SubOne(cast<ConstantInt>(Hi));
3274   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3275     ICmpInst::Predicate pred = (isSigned ? 
3276         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3277     return new ICmpInst(pred, V, Hi);
3278   }
3279
3280   // Emit V-Lo >u Hi-1-Lo
3281   // Note that Hi has already had one subtracted from it, above.
3282   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3283   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3284   InsertNewInstBefore(Add, IB);
3285   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3286   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3287 }
3288
3289 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3290 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3291 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3292 // not, since all 1s are not contiguous.
3293 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3294   const APInt& V = Val->getValue();
3295   uint32_t BitWidth = Val->getType()->getBitWidth();
3296   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3297
3298   // look for the first zero bit after the run of ones
3299   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3300   // look for the first non-zero bit
3301   ME = V.getActiveBits(); 
3302   return true;
3303 }
3304
3305 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3306 /// where isSub determines whether the operator is a sub.  If we can fold one of
3307 /// the following xforms:
3308 /// 
3309 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3310 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3311 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3312 ///
3313 /// return (A +/- B).
3314 ///
3315 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3316                                         ConstantInt *Mask, bool isSub,
3317                                         Instruction &I) {
3318   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3319   if (!LHSI || LHSI->getNumOperands() != 2 ||
3320       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3321
3322   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3323
3324   switch (LHSI->getOpcode()) {
3325   default: return 0;
3326   case Instruction::And:
3327     if (And(N, Mask) == Mask) {
3328       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3329       if ((Mask->getValue().countLeadingZeros() + 
3330            Mask->getValue().countPopulation()) == 
3331           Mask->getValue().getBitWidth())
3332         break;
3333
3334       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3335       // part, we don't need any explicit masks to take them out of A.  If that
3336       // is all N is, ignore it.
3337       uint32_t MB = 0, ME = 0;
3338       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3339         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3340         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3341         if (MaskedValueIsZero(RHS, Mask))
3342           break;
3343       }
3344     }
3345     return 0;
3346   case Instruction::Or:
3347   case Instruction::Xor:
3348     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3349     if ((Mask->getValue().countLeadingZeros() + 
3350          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3351         && And(N, Mask)->isZero())
3352       break;
3353     return 0;
3354   }
3355   
3356   Instruction *New;
3357   if (isSub)
3358     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3359   else
3360     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3361   return InsertNewInstBefore(New, I);
3362 }
3363
3364 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3365   bool Changed = SimplifyCommutative(I);
3366   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3367
3368   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3369     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3370
3371   // and X, X = X
3372   if (Op0 == Op1)
3373     return ReplaceInstUsesWith(I, Op1);
3374
3375   // See if we can simplify any instructions used by the instruction whose sole 
3376   // purpose is to compute bits we don't care about.
3377   if (!isa<VectorType>(I.getType())) {
3378     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3379     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3380     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3381                              KnownZero, KnownOne))
3382       return &I;
3383   } else {
3384     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3385       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3386         return ReplaceInstUsesWith(I, I.getOperand(0));
3387     } else if (isa<ConstantAggregateZero>(Op1)) {
3388       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3389     }
3390   }
3391   
3392   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3393     const APInt& AndRHSMask = AndRHS->getValue();
3394     APInt NotAndRHS(~AndRHSMask);
3395
3396     // Optimize a variety of ((val OP C1) & C2) combinations...
3397     if (isa<BinaryOperator>(Op0)) {
3398       Instruction *Op0I = cast<Instruction>(Op0);
3399       Value *Op0LHS = Op0I->getOperand(0);
3400       Value *Op0RHS = Op0I->getOperand(1);
3401       switch (Op0I->getOpcode()) {
3402       case Instruction::Xor:
3403       case Instruction::Or:
3404         // If the mask is only needed on one incoming arm, push it up.
3405         if (Op0I->hasOneUse()) {
3406           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3407             // Not masking anything out for the LHS, move to RHS.
3408             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3409                                                    Op0RHS->getName()+".masked");
3410             InsertNewInstBefore(NewRHS, I);
3411             return BinaryOperator::Create(
3412                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3413           }
3414           if (!isa<Constant>(Op0RHS) &&
3415               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3416             // Not masking anything out for the RHS, move to LHS.
3417             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3418                                                    Op0LHS->getName()+".masked");
3419             InsertNewInstBefore(NewLHS, I);
3420             return BinaryOperator::Create(
3421                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3422           }
3423         }
3424
3425         break;
3426       case Instruction::Add:
3427         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3428         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3429         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3430         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3431           return BinaryOperator::CreateAnd(V, AndRHS);
3432         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3433           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3434         break;
3435
3436       case Instruction::Sub:
3437         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3438         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3439         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3440         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3441           return BinaryOperator::CreateAnd(V, AndRHS);
3442         break;
3443       }
3444
3445       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3446         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3447           return Res;
3448     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3449       // If this is an integer truncation or change from signed-to-unsigned, and
3450       // if the source is an and/or with immediate, transform it.  This
3451       // frequently occurs for bitfield accesses.
3452       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3453         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3454             CastOp->getNumOperands() == 2)
3455           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3456             if (CastOp->getOpcode() == Instruction::And) {
3457               // Change: and (cast (and X, C1) to T), C2
3458               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3459               // This will fold the two constants together, which may allow 
3460               // other simplifications.
3461               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3462                 CastOp->getOperand(0), I.getType(), 
3463                 CastOp->getName()+".shrunk");
3464               NewCast = InsertNewInstBefore(NewCast, I);
3465               // trunc_or_bitcast(C1)&C2
3466               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3467               C3 = ConstantExpr::getAnd(C3, AndRHS);
3468               return BinaryOperator::CreateAnd(NewCast, C3);
3469             } else if (CastOp->getOpcode() == Instruction::Or) {
3470               // Change: and (cast (or X, C1) to T), C2
3471               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3472               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3473               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3474                 return ReplaceInstUsesWith(I, AndRHS);
3475             }
3476           }
3477       }
3478     }
3479
3480     // Try to fold constant and into select arguments.
3481     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3482       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3483         return R;
3484     if (isa<PHINode>(Op0))
3485       if (Instruction *NV = FoldOpIntoPhi(I))
3486         return NV;
3487   }
3488
3489   Value *Op0NotVal = dyn_castNotVal(Op0);
3490   Value *Op1NotVal = dyn_castNotVal(Op1);
3491
3492   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3493     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3494
3495   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3496   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3497     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3498                                                I.getName()+".demorgan");
3499     InsertNewInstBefore(Or, I);
3500     return BinaryOperator::CreateNot(Or);
3501   }
3502   
3503   {
3504     Value *A = 0, *B = 0, *C = 0, *D = 0;
3505     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3506       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3507         return ReplaceInstUsesWith(I, Op1);
3508     
3509       // (A|B) & ~(A&B) -> A^B
3510       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3511         if ((A == C && B == D) || (A == D && B == C))
3512           return BinaryOperator::CreateXor(A, B);
3513       }
3514     }
3515     
3516     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3517       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3518         return ReplaceInstUsesWith(I, Op0);
3519
3520       // ~(A&B) & (A|B) -> A^B
3521       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3522         if ((A == C && B == D) || (A == D && B == C))
3523           return BinaryOperator::CreateXor(A, B);
3524       }
3525     }
3526     
3527     if (Op0->hasOneUse() &&
3528         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3529       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3530         I.swapOperands();     // Simplify below
3531         std::swap(Op0, Op1);
3532       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3533         cast<BinaryOperator>(Op0)->swapOperands();
3534         I.swapOperands();     // Simplify below
3535         std::swap(Op0, Op1);
3536       }
3537     }
3538     if (Op1->hasOneUse() &&
3539         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3540       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3541         cast<BinaryOperator>(Op1)->swapOperands();
3542         std::swap(A, B);
3543       }
3544       if (A == Op0) {                                // A&(A^B) -> A & ~B
3545         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3546         InsertNewInstBefore(NotB, I);
3547         return BinaryOperator::CreateAnd(A, NotB);
3548       }
3549     }
3550   }
3551   
3552   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3553     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3554     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3555       return R;
3556
3557     Value *LHSVal, *RHSVal;
3558     ConstantInt *LHSCst, *RHSCst;
3559     ICmpInst::Predicate LHSCC, RHSCC;
3560     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3561       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3562         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3563             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3564             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3565             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3566             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3567             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3568             
3569             // Don't try to fold ICMP_SLT + ICMP_ULT.
3570             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3571              ICmpInst::isSignedPredicate(LHSCC) == 
3572                  ICmpInst::isSignedPredicate(RHSCC))) {
3573           // Ensure that the larger constant is on the RHS.
3574           ICmpInst::Predicate GT;
3575           if (ICmpInst::isSignedPredicate(LHSCC) ||
3576               (ICmpInst::isEquality(LHSCC) && 
3577                ICmpInst::isSignedPredicate(RHSCC)))
3578             GT = ICmpInst::ICMP_SGT;
3579           else
3580             GT = ICmpInst::ICMP_UGT;
3581           
3582           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3583           ICmpInst *LHS = cast<ICmpInst>(Op0);
3584           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3585             std::swap(LHS, RHS);
3586             std::swap(LHSCst, RHSCst);
3587             std::swap(LHSCC, RHSCC);
3588           }
3589
3590           // At this point, we know we have have two icmp instructions
3591           // comparing a value against two constants and and'ing the result
3592           // together.  Because of the above check, we know that we only have
3593           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3594           // (from the FoldICmpLogical check above), that the two constants 
3595           // are not equal and that the larger constant is on the RHS
3596           assert(LHSCst != RHSCst && "Compares not folded above?");
3597
3598           switch (LHSCC) {
3599           default: assert(0 && "Unknown integer condition code!");
3600           case ICmpInst::ICMP_EQ:
3601             switch (RHSCC) {
3602             default: assert(0 && "Unknown integer condition code!");
3603             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3604             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3605             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3606               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3607             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3608             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3609             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3610               return ReplaceInstUsesWith(I, LHS);
3611             }
3612           case ICmpInst::ICMP_NE:
3613             switch (RHSCC) {
3614             default: assert(0 && "Unknown integer condition code!");
3615             case ICmpInst::ICMP_ULT:
3616               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3617                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3618               break;                        // (X != 13 & X u< 15) -> no change
3619             case ICmpInst::ICMP_SLT:
3620               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3621                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3622               break;                        // (X != 13 & X s< 15) -> no change
3623             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3624             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3625             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3626               return ReplaceInstUsesWith(I, RHS);
3627             case ICmpInst::ICMP_NE:
3628               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3629                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3630                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3631                                                       LHSVal->getName()+".off");
3632                 InsertNewInstBefore(Add, I);
3633                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3634                                     ConstantInt::get(Add->getType(), 1));
3635               }
3636               break;                        // (X != 13 & X != 15) -> no change
3637             }
3638             break;
3639           case ICmpInst::ICMP_ULT:
3640             switch (RHSCC) {
3641             default: assert(0 && "Unknown integer condition code!");
3642             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3643             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3644               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3645             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3646               break;
3647             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3648             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3649               return ReplaceInstUsesWith(I, LHS);
3650             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3651               break;
3652             }
3653             break;
3654           case ICmpInst::ICMP_SLT:
3655             switch (RHSCC) {
3656             default: assert(0 && "Unknown integer condition code!");
3657             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3658             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3659               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3660             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3661               break;
3662             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3663             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3664               return ReplaceInstUsesWith(I, LHS);
3665             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3666               break;
3667             }
3668             break;
3669           case ICmpInst::ICMP_UGT:
3670             switch (RHSCC) {
3671             default: assert(0 && "Unknown integer condition code!");
3672             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X > 13
3673               return ReplaceInstUsesWith(I, LHS);
3674             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3675               return ReplaceInstUsesWith(I, RHS);
3676             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3677               break;
3678             case ICmpInst::ICMP_NE:
3679               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3680                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3681               break;                        // (X u> 13 & X != 15) -> no change
3682             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3683               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3684                                      true, I);
3685             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3686               break;
3687             }
3688             break;
3689           case ICmpInst::ICMP_SGT:
3690             switch (RHSCC) {
3691             default: assert(0 && "Unknown integer condition code!");
3692             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3693             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3694               return ReplaceInstUsesWith(I, RHS);
3695             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3696               break;
3697             case ICmpInst::ICMP_NE:
3698               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3699                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3700               break;                        // (X s> 13 & X != 15) -> no change
3701             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3702               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3703                                      true, I);
3704             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3705               break;
3706             }
3707             break;
3708           }
3709         }
3710   }
3711
3712   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3713   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3714     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3715       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3716         const Type *SrcTy = Op0C->getOperand(0)->getType();
3717         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3718             // Only do this if the casts both really cause code to be generated.
3719             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3720                               I.getType(), TD) &&
3721             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3722                               I.getType(), TD)) {
3723           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3724                                                          Op1C->getOperand(0),
3725                                                          I.getName());
3726           InsertNewInstBefore(NewOp, I);
3727           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3728         }
3729       }
3730     
3731   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3732   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3733     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3734       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3735           SI0->getOperand(1) == SI1->getOperand(1) &&
3736           (SI0->hasOneUse() || SI1->hasOneUse())) {
3737         Instruction *NewOp =
3738           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3739                                                         SI1->getOperand(0),
3740                                                         SI0->getName()), I);
3741         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3742                                       SI1->getOperand(1));
3743       }
3744   }
3745
3746   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3747   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3748     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3749       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3750           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3751         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3752           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3753             // If either of the constants are nans, then the whole thing returns
3754             // false.
3755             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3756               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3757             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3758                                 RHS->getOperand(0));
3759           }
3760     }
3761   }
3762       
3763   return Changed ? &I : 0;
3764 }
3765
3766 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3767 /// in the result.  If it does, and if the specified byte hasn't been filled in
3768 /// yet, fill it in and return false.
3769 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3770   Instruction *I = dyn_cast<Instruction>(V);
3771   if (I == 0) return true;
3772
3773   // If this is an or instruction, it is an inner node of the bswap.
3774   if (I->getOpcode() == Instruction::Or)
3775     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3776            CollectBSwapParts(I->getOperand(1), ByteValues);
3777   
3778   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3779   // If this is a shift by a constant int, and it is "24", then its operand
3780   // defines a byte.  We only handle unsigned types here.
3781   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3782     // Not shifting the entire input by N-1 bytes?
3783     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3784         8*(ByteValues.size()-1))
3785       return true;
3786     
3787     unsigned DestNo;
3788     if (I->getOpcode() == Instruction::Shl) {
3789       // X << 24 defines the top byte with the lowest of the input bytes.
3790       DestNo = ByteValues.size()-1;
3791     } else {
3792       // X >>u 24 defines the low byte with the highest of the input bytes.
3793       DestNo = 0;
3794     }
3795     
3796     // If the destination byte value is already defined, the values are or'd
3797     // together, which isn't a bswap (unless it's an or of the same bits).
3798     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3799       return true;
3800     ByteValues[DestNo] = I->getOperand(0);
3801     return false;
3802   }
3803   
3804   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3805   // don't have this.
3806   Value *Shift = 0, *ShiftLHS = 0;
3807   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3808   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3809       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3810     return true;
3811   Instruction *SI = cast<Instruction>(Shift);
3812
3813   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3814   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3815       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3816     return true;
3817   
3818   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3819   unsigned DestByte;
3820   if (AndAmt->getValue().getActiveBits() > 64)
3821     return true;
3822   uint64_t AndAmtVal = AndAmt->getZExtValue();
3823   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3824     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3825       break;
3826   // Unknown mask for bswap.
3827   if (DestByte == ByteValues.size()) return true;
3828   
3829   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3830   unsigned SrcByte;
3831   if (SI->getOpcode() == Instruction::Shl)
3832     SrcByte = DestByte - ShiftBytes;
3833   else
3834     SrcByte = DestByte + ShiftBytes;
3835   
3836   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3837   if (SrcByte != ByteValues.size()-DestByte-1)
3838     return true;
3839   
3840   // If the destination byte value is already defined, the values are or'd
3841   // together, which isn't a bswap (unless it's an or of the same bits).
3842   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3843     return true;
3844   ByteValues[DestByte] = SI->getOperand(0);
3845   return false;
3846 }
3847
3848 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3849 /// If so, insert the new bswap intrinsic and return it.
3850 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3851   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3852   if (!ITy || ITy->getBitWidth() % 16) 
3853     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3854   
3855   /// ByteValues - For each byte of the result, we keep track of which value
3856   /// defines each byte.
3857   SmallVector<Value*, 8> ByteValues;
3858   ByteValues.resize(ITy->getBitWidth()/8);
3859     
3860   // Try to find all the pieces corresponding to the bswap.
3861   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3862       CollectBSwapParts(I.getOperand(1), ByteValues))
3863     return 0;
3864   
3865   // Check to see if all of the bytes come from the same value.
3866   Value *V = ByteValues[0];
3867   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3868   
3869   // Check to make sure that all of the bytes come from the same value.
3870   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3871     if (ByteValues[i] != V)
3872       return 0;
3873   const Type *Tys[] = { ITy };
3874   Module *M = I.getParent()->getParent()->getParent();
3875   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3876   return CallInst::Create(F, V);
3877 }
3878
3879
3880 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3881   bool Changed = SimplifyCommutative(I);
3882   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3883
3884   if (isa<UndefValue>(Op1))                       // X | undef -> -1
3885     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3886
3887   // or X, X = X
3888   if (Op0 == Op1)
3889     return ReplaceInstUsesWith(I, Op0);
3890
3891   // See if we can simplify any instructions used by the instruction whose sole 
3892   // purpose is to compute bits we don't care about.
3893   if (!isa<VectorType>(I.getType())) {
3894     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3895     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3896     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3897                              KnownZero, KnownOne))
3898       return &I;
3899   } else if (isa<ConstantAggregateZero>(Op1)) {
3900     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
3901   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3902     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
3903       return ReplaceInstUsesWith(I, I.getOperand(1));
3904   }
3905     
3906
3907   
3908   // or X, -1 == -1
3909   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3910     ConstantInt *C1 = 0; Value *X = 0;
3911     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3912     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3913       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3914       InsertNewInstBefore(Or, I);
3915       Or->takeName(Op0);
3916       return BinaryOperator::CreateAnd(Or, 
3917                ConstantInt::get(RHS->getValue() | C1->getValue()));
3918     }
3919
3920     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3921     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3922       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3923       InsertNewInstBefore(Or, I);
3924       Or->takeName(Op0);
3925       return BinaryOperator::CreateXor(Or,
3926                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3927     }
3928
3929     // Try to fold constant and into select arguments.
3930     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3931       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3932         return R;
3933     if (isa<PHINode>(Op0))
3934       if (Instruction *NV = FoldOpIntoPhi(I))
3935         return NV;
3936   }
3937
3938   Value *A = 0, *B = 0;
3939   ConstantInt *C1 = 0, *C2 = 0;
3940
3941   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3942     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3943       return ReplaceInstUsesWith(I, Op1);
3944   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3945     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3946       return ReplaceInstUsesWith(I, Op0);
3947
3948   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3949   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3950   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3951       match(Op1, m_Or(m_Value(), m_Value())) ||
3952       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3953        match(Op1, m_Shift(m_Value(), m_Value())))) {
3954     if (Instruction *BSwap = MatchBSwap(I))
3955       return BSwap;
3956   }
3957   
3958   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3959   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3960       MaskedValueIsZero(Op1, C1->getValue())) {
3961     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3962     InsertNewInstBefore(NOr, I);
3963     NOr->takeName(Op0);
3964     return BinaryOperator::CreateXor(NOr, C1);
3965   }
3966
3967   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3968   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3969       MaskedValueIsZero(Op0, C1->getValue())) {
3970     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
3971     InsertNewInstBefore(NOr, I);
3972     NOr->takeName(Op0);
3973     return BinaryOperator::CreateXor(NOr, C1);
3974   }
3975
3976   // (A & C)|(B & D)
3977   Value *C = 0, *D = 0;
3978   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3979       match(Op1, m_And(m_Value(B), m_Value(D)))) {
3980     Value *V1 = 0, *V2 = 0, *V3 = 0;
3981     C1 = dyn_cast<ConstantInt>(C);
3982     C2 = dyn_cast<ConstantInt>(D);
3983     if (C1 && C2) {  // (A & C1)|(B & C2)
3984       // If we have: ((V + N) & C1) | (V & C2)
3985       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3986       // replace with V+N.
3987       if (C1->getValue() == ~C2->getValue()) {
3988         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3989             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3990           // Add commutes, try both ways.
3991           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3992             return ReplaceInstUsesWith(I, A);
3993           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3994             return ReplaceInstUsesWith(I, A);
3995         }
3996         // Or commutes, try both ways.
3997         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3998             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3999           // Add commutes, try both ways.
4000           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4001             return ReplaceInstUsesWith(I, B);
4002           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4003             return ReplaceInstUsesWith(I, B);
4004         }
4005       }
4006       V1 = 0; V2 = 0; V3 = 0;
4007     }
4008     
4009     // Check to see if we have any common things being and'ed.  If so, find the
4010     // terms for V1 & (V2|V3).
4011     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4012       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4013         V1 = A, V2 = C, V3 = D;
4014       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4015         V1 = A, V2 = B, V3 = C;
4016       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4017         V1 = C, V2 = A, V3 = D;
4018       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4019         V1 = C, V2 = A, V3 = B;
4020       
4021       if (V1) {
4022         Value *Or =
4023           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4024         return BinaryOperator::CreateAnd(V1, Or);
4025       }
4026     }
4027   }
4028   
4029   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4030   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4033           SI0->getOperand(1) == SI1->getOperand(1) &&
4034           (SI0->hasOneUse() || SI1->hasOneUse())) {
4035         Instruction *NewOp =
4036         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4037                                                      SI1->getOperand(0),
4038                                                      SI0->getName()), I);
4039         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4040                                       SI1->getOperand(1));
4041       }
4042   }
4043
4044   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4045     if (A == Op1)   // ~A | A == -1
4046       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4047   } else {
4048     A = 0;
4049   }
4050   // Note, A is still live here!
4051   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4052     if (Op0 == B)
4053       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4054
4055     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4056     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4057       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4058                                               I.getName()+".demorgan"), I);
4059       return BinaryOperator::CreateNot(And);
4060     }
4061   }
4062
4063   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4064   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4065     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4066       return R;
4067
4068     Value *LHSVal, *RHSVal;
4069     ConstantInt *LHSCst, *RHSCst;
4070     ICmpInst::Predicate LHSCC, RHSCC;
4071     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4072       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4073         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4074             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4075             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4076             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4077             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4078             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4079             // We can't fold (ugt x, C) | (sgt x, C2).
4080             PredicatesFoldable(LHSCC, RHSCC)) {
4081           // Ensure that the larger constant is on the RHS.
4082           ICmpInst *LHS = cast<ICmpInst>(Op0);
4083           bool NeedsSwap;
4084           if (ICmpInst::isSignedPredicate(LHSCC))
4085             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4086           else
4087             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4088             
4089           if (NeedsSwap) {
4090             std::swap(LHS, RHS);
4091             std::swap(LHSCst, RHSCst);
4092             std::swap(LHSCC, RHSCC);
4093           }
4094
4095           // At this point, we know we have have two icmp instructions
4096           // comparing a value against two constants and or'ing the result
4097           // together.  Because of the above check, we know that we only have
4098           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4099           // FoldICmpLogical check above), that the two constants are not
4100           // equal.
4101           assert(LHSCst != RHSCst && "Compares not folded above?");
4102
4103           switch (LHSCC) {
4104           default: assert(0 && "Unknown integer condition code!");
4105           case ICmpInst::ICMP_EQ:
4106             switch (RHSCC) {
4107             default: assert(0 && "Unknown integer condition code!");
4108             case ICmpInst::ICMP_EQ:
4109               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4110                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4111                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4112                                                       LHSVal->getName()+".off");
4113                 InsertNewInstBefore(Add, I);
4114                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4115                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4116               }
4117               break;                         // (X == 13 | X == 15) -> no change
4118             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4119             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4120               break;
4121             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4122             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4123             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4124               return ReplaceInstUsesWith(I, RHS);
4125             }
4126             break;
4127           case ICmpInst::ICMP_NE:
4128             switch (RHSCC) {
4129             default: assert(0 && "Unknown integer condition code!");
4130             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4131             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4132             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4133               return ReplaceInstUsesWith(I, LHS);
4134             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4135             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4136             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4137               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4138             }
4139             break;
4140           case ICmpInst::ICMP_ULT:
4141             switch (RHSCC) {
4142             default: assert(0 && "Unknown integer condition code!");
4143             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4144               break;
4145             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4146               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4147               // this can cause overflow.
4148               if (RHSCst->isMaxValue(false))
4149                 return ReplaceInstUsesWith(I, LHS);
4150               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4151                                      false, I);
4152             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4153               break;
4154             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4155             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4156               return ReplaceInstUsesWith(I, RHS);
4157             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4158               break;
4159             }
4160             break;
4161           case ICmpInst::ICMP_SLT:
4162             switch (RHSCC) {
4163             default: assert(0 && "Unknown integer condition code!");
4164             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4165               break;
4166             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4167               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4168               // this can cause overflow.
4169               if (RHSCst->isMaxValue(true))
4170                 return ReplaceInstUsesWith(I, LHS);
4171               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4172                                      false, I);
4173             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4174               break;
4175             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4176             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4177               return ReplaceInstUsesWith(I, RHS);
4178             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4179               break;
4180             }
4181             break;
4182           case ICmpInst::ICMP_UGT:
4183             switch (RHSCC) {
4184             default: assert(0 && "Unknown integer condition code!");
4185             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4186             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4187               return ReplaceInstUsesWith(I, LHS);
4188             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4189               break;
4190             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4191             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4192               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4193             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4194               break;
4195             }
4196             break;
4197           case ICmpInst::ICMP_SGT:
4198             switch (RHSCC) {
4199             default: assert(0 && "Unknown integer condition code!");
4200             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4201             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4202               return ReplaceInstUsesWith(I, LHS);
4203             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4204               break;
4205             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4206             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4207               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4208             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4209               break;
4210             }
4211             break;
4212           }
4213         }
4214   }
4215     
4216   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4217   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4218     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4219       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4220         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4221             !isa<ICmpInst>(Op1C->getOperand(0))) {
4222           const Type *SrcTy = Op0C->getOperand(0)->getType();
4223           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4224               // Only do this if the casts both really cause code to be
4225               // generated.
4226               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4227                                 I.getType(), TD) &&
4228               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4229                                 I.getType(), TD)) {
4230             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4231                                                           Op1C->getOperand(0),
4232                                                           I.getName());
4233             InsertNewInstBefore(NewOp, I);
4234             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4235           }
4236         }
4237       }
4238   }
4239   
4240     
4241   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4242   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4243     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4244       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4245           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4246           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4247         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4248           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4249             // If either of the constants are nans, then the whole thing returns
4250             // true.
4251             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4252               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4253             
4254             // Otherwise, no need to compare the two constants, compare the
4255             // rest.
4256             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4257                                 RHS->getOperand(0));
4258           }
4259     }
4260   }
4261
4262   return Changed ? &I : 0;
4263 }
4264
4265 namespace {
4266
4267 // XorSelf - Implements: X ^ X --> 0
4268 struct XorSelf {
4269   Value *RHS;
4270   XorSelf(Value *rhs) : RHS(rhs) {}
4271   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4272   Instruction *apply(BinaryOperator &Xor) const {
4273     return &Xor;
4274   }
4275 };
4276
4277 }
4278
4279 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4280   bool Changed = SimplifyCommutative(I);
4281   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4282
4283   if (isa<UndefValue>(Op1)) {
4284     if (isa<UndefValue>(Op0))
4285       // Handle undef ^ undef -> 0 special case. This is a common
4286       // idiom (misuse).
4287       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4288     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4289   }
4290
4291   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4292   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4293     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4294     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4295   }
4296   
4297   // See if we can simplify any instructions used by the instruction whose sole 
4298   // purpose is to compute bits we don't care about.
4299   if (!isa<VectorType>(I.getType())) {
4300     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4301     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4302     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4303                              KnownZero, KnownOne))
4304       return &I;
4305   } else if (isa<ConstantAggregateZero>(Op1)) {
4306     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4307   }
4308
4309   // Is this a ~ operation?
4310   if (Value *NotOp = dyn_castNotVal(&I)) {
4311     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4312     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4313     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4314       if (Op0I->getOpcode() == Instruction::And || 
4315           Op0I->getOpcode() == Instruction::Or) {
4316         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4317         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4318           Instruction *NotY =
4319             BinaryOperator::CreateNot(Op0I->getOperand(1),
4320                                       Op0I->getOperand(1)->getName()+".not");
4321           InsertNewInstBefore(NotY, I);
4322           if (Op0I->getOpcode() == Instruction::And)
4323             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4324           else
4325             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4326         }
4327       }
4328     }
4329   }
4330   
4331   
4332   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4333     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4334     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4335       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4336         return new ICmpInst(ICI->getInversePredicate(),
4337                             ICI->getOperand(0), ICI->getOperand(1));
4338
4339       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4340         return new FCmpInst(FCI->getInversePredicate(),
4341                             FCI->getOperand(0), FCI->getOperand(1));
4342     }
4343
4344     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4345     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4346       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4347         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4348           Instruction::CastOps Opcode = Op0C->getOpcode();
4349           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4350             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4351                                              Op0C->getDestTy())) {
4352               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4353                                      CI->getOpcode(), CI->getInversePredicate(),
4354                                      CI->getOperand(0), CI->getOperand(1)), I);
4355               NewCI->takeName(CI);
4356               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4357             }
4358           }
4359         }
4360       }
4361     }
4362
4363     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4364       // ~(c-X) == X-c-1 == X+(-c-1)
4365       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4366         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4367           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4368           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4369                                               ConstantInt::get(I.getType(), 1));
4370           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4371         }
4372           
4373       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4374         if (Op0I->getOpcode() == Instruction::Add) {
4375           // ~(X-c) --> (-c-1)-X
4376           if (RHS->isAllOnesValue()) {
4377             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4378             return BinaryOperator::CreateSub(
4379                            ConstantExpr::getSub(NegOp0CI,
4380                                              ConstantInt::get(I.getType(), 1)),
4381                                           Op0I->getOperand(0));
4382           } else if (RHS->getValue().isSignBit()) {
4383             // (X + C) ^ signbit -> (X + C + signbit)
4384             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4385             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4386
4387           }
4388         } else if (Op0I->getOpcode() == Instruction::Or) {
4389           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4390           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4391             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4392             // Anything in both C1 and C2 is known to be zero, remove it from
4393             // NewRHS.
4394             Constant *CommonBits = And(Op0CI, RHS);
4395             NewRHS = ConstantExpr::getAnd(NewRHS, 
4396                                           ConstantExpr::getNot(CommonBits));
4397             AddToWorkList(Op0I);
4398             I.setOperand(0, Op0I->getOperand(0));
4399             I.setOperand(1, NewRHS);
4400             return &I;
4401           }
4402         }
4403       }
4404     }
4405
4406     // Try to fold constant and into select arguments.
4407     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4408       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4409         return R;
4410     if (isa<PHINode>(Op0))
4411       if (Instruction *NV = FoldOpIntoPhi(I))
4412         return NV;
4413   }
4414
4415   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4416     if (X == Op1)
4417       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4418
4419   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4420     if (X == Op0)
4421       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4422
4423   
4424   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4425   if (Op1I) {
4426     Value *A, *B;
4427     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4428       if (A == Op0) {              // B^(B|A) == (A|B)^B
4429         Op1I->swapOperands();
4430         I.swapOperands();
4431         std::swap(Op0, Op1);
4432       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4433         I.swapOperands();     // Simplified below.
4434         std::swap(Op0, Op1);
4435       }
4436     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4437       if (Op0 == A)                                          // A^(A^B) == B
4438         return ReplaceInstUsesWith(I, B);
4439       else if (Op0 == B)                                     // A^(B^A) == B
4440         return ReplaceInstUsesWith(I, A);
4441     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4442       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4443         Op1I->swapOperands();
4444         std::swap(A, B);
4445       }
4446       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4447         I.swapOperands();     // Simplified below.
4448         std::swap(Op0, Op1);
4449       }
4450     }
4451   }
4452   
4453   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4454   if (Op0I) {
4455     Value *A, *B;
4456     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4457       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4458         std::swap(A, B);
4459       if (B == Op1) {                                // (A|B)^B == A & ~B
4460         Instruction *NotB =
4461           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4462         return BinaryOperator::CreateAnd(A, NotB);
4463       }
4464     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4465       if (Op1 == A)                                          // (A^B)^A == B
4466         return ReplaceInstUsesWith(I, B);
4467       else if (Op1 == B)                                     // (B^A)^A == B
4468         return ReplaceInstUsesWith(I, A);
4469     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4470       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4471         std::swap(A, B);
4472       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4473           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4474         Instruction *N =
4475           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4476         return BinaryOperator::CreateAnd(N, Op1);
4477       }
4478     }
4479   }
4480   
4481   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4482   if (Op0I && Op1I && Op0I->isShift() && 
4483       Op0I->getOpcode() == Op1I->getOpcode() && 
4484       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4485       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4486     Instruction *NewOp =
4487       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4488                                                     Op1I->getOperand(0),
4489                                                     Op0I->getName()), I);
4490     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4491                                   Op1I->getOperand(1));
4492   }
4493     
4494   if (Op0I && Op1I) {
4495     Value *A, *B, *C, *D;
4496     // (A & B)^(A | B) -> A ^ B
4497     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4498         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4499       if ((A == C && B == D) || (A == D && B == C)) 
4500         return BinaryOperator::CreateXor(A, B);
4501     }
4502     // (A | B)^(A & B) -> A ^ B
4503     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4504         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4505       if ((A == C && B == D) || (A == D && B == C)) 
4506         return BinaryOperator::CreateXor(A, B);
4507     }
4508     
4509     // (A & B)^(C & D)
4510     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4511         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4512         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4513       // (X & Y)^(X & Y) -> (Y^Z) & X
4514       Value *X = 0, *Y = 0, *Z = 0;
4515       if (A == C)
4516         X = A, Y = B, Z = D;
4517       else if (A == D)
4518         X = A, Y = B, Z = C;
4519       else if (B == C)
4520         X = B, Y = A, Z = D;
4521       else if (B == D)
4522         X = B, Y = A, Z = C;
4523       
4524       if (X) {
4525         Instruction *NewOp =
4526         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4527         return BinaryOperator::CreateAnd(NewOp, X);
4528       }
4529     }
4530   }
4531     
4532   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4533   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4534     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4535       return R;
4536
4537   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4538   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4539     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4540       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4541         const Type *SrcTy = Op0C->getOperand(0)->getType();
4542         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4543             // Only do this if the casts both really cause code to be generated.
4544             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4545                               I.getType(), TD) &&
4546             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4547                               I.getType(), TD)) {
4548           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4549                                                          Op1C->getOperand(0),
4550                                                          I.getName());
4551           InsertNewInstBefore(NewOp, I);
4552           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4553         }
4554       }
4555   }
4556
4557   return Changed ? &I : 0;
4558 }
4559
4560 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4561 /// overflowed for this type.
4562 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4563                             ConstantInt *In2, bool IsSigned = false) {
4564   Result = cast<ConstantInt>(Add(In1, In2));
4565
4566   if (IsSigned)
4567     if (In2->getValue().isNegative())
4568       return Result->getValue().sgt(In1->getValue());
4569     else
4570       return Result->getValue().slt(In1->getValue());
4571   else
4572     return Result->getValue().ult(In1->getValue());
4573 }
4574
4575 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4576 /// code necessary to compute the offset from the base pointer (without adding
4577 /// in the base pointer).  Return the result as a signed integer of intptr size.
4578 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4579   TargetData &TD = IC.getTargetData();
4580   gep_type_iterator GTI = gep_type_begin(GEP);
4581   const Type *IntPtrTy = TD.getIntPtrType();
4582   Value *Result = Constant::getNullValue(IntPtrTy);
4583
4584   // Build a mask for high order bits.
4585   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4586   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4587
4588   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4589        ++i, ++GTI) {
4590     Value *Op = *i;
4591     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4592     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4593       if (OpC->isZero()) continue;
4594       
4595       // Handle a struct index, which adds its field offset to the pointer.
4596       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4597         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4598         
4599         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4600           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4601         else
4602           Result = IC.InsertNewInstBefore(
4603                    BinaryOperator::CreateAdd(Result,
4604                                              ConstantInt::get(IntPtrTy, Size),
4605                                              GEP->getName()+".offs"), I);
4606         continue;
4607       }
4608       
4609       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4610       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4611       Scale = ConstantExpr::getMul(OC, Scale);
4612       if (Constant *RC = dyn_cast<Constant>(Result))
4613         Result = ConstantExpr::getAdd(RC, Scale);
4614       else {
4615         // Emit an add instruction.
4616         Result = IC.InsertNewInstBefore(
4617            BinaryOperator::CreateAdd(Result, Scale,
4618                                      GEP->getName()+".offs"), I);
4619       }
4620       continue;
4621     }
4622     // Convert to correct type.
4623     if (Op->getType() != IntPtrTy) {
4624       if (Constant *OpC = dyn_cast<Constant>(Op))
4625         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4626       else
4627         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4628                                                  Op->getName()+".c"), I);
4629     }
4630     if (Size != 1) {
4631       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4632       if (Constant *OpC = dyn_cast<Constant>(Op))
4633         Op = ConstantExpr::getMul(OpC, Scale);
4634       else    // We'll let instcombine(mul) convert this to a shl if possible.
4635         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4636                                                   GEP->getName()+".idx"), I);
4637     }
4638
4639     // Emit an add instruction.
4640     if (isa<Constant>(Op) && isa<Constant>(Result))
4641       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4642                                     cast<Constant>(Result));
4643     else
4644       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4645                                                   GEP->getName()+".offs"), I);
4646   }
4647   return Result;
4648 }
4649
4650
4651 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4652 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4653 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4654 /// complex, and scales are involved.  The above expression would also be legal
4655 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4656 /// later form is less amenable to optimization though, and we are allowed to
4657 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4658 ///
4659 /// If we can't emit an optimized form for this expression, this returns null.
4660 /// 
4661 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4662                                           InstCombiner &IC) {
4663   TargetData &TD = IC.getTargetData();
4664   gep_type_iterator GTI = gep_type_begin(GEP);
4665
4666   // Check to see if this gep only has a single variable index.  If so, and if
4667   // any constant indices are a multiple of its scale, then we can compute this
4668   // in terms of the scale of the variable index.  For example, if the GEP
4669   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4670   // because the expression will cross zero at the same point.
4671   unsigned i, e = GEP->getNumOperands();
4672   int64_t Offset = 0;
4673   for (i = 1; i != e; ++i, ++GTI) {
4674     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4675       // Compute the aggregate offset of constant indices.
4676       if (CI->isZero()) continue;
4677
4678       // Handle a struct index, which adds its field offset to the pointer.
4679       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4680         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4681       } else {
4682         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4683         Offset += Size*CI->getSExtValue();
4684       }
4685     } else {
4686       // Found our variable index.
4687       break;
4688     }
4689   }
4690   
4691   // If there are no variable indices, we must have a constant offset, just
4692   // evaluate it the general way.
4693   if (i == e) return 0;
4694   
4695   Value *VariableIdx = GEP->getOperand(i);
4696   // Determine the scale factor of the variable element.  For example, this is
4697   // 4 if the variable index is into an array of i32.
4698   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4699   
4700   // Verify that there are no other variable indices.  If so, emit the hard way.
4701   for (++i, ++GTI; i != e; ++i, ++GTI) {
4702     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4703     if (!CI) return 0;
4704    
4705     // Compute the aggregate offset of constant indices.
4706     if (CI->isZero()) continue;
4707     
4708     // Handle a struct index, which adds its field offset to the pointer.
4709     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4710       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4711     } else {
4712       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4713       Offset += Size*CI->getSExtValue();
4714     }
4715   }
4716   
4717   // Okay, we know we have a single variable index, which must be a
4718   // pointer/array/vector index.  If there is no offset, life is simple, return
4719   // the index.
4720   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4721   if (Offset == 0) {
4722     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4723     // we don't need to bother extending: the extension won't affect where the
4724     // computation crosses zero.
4725     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4726       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4727                                   VariableIdx->getNameStart(), &I);
4728     return VariableIdx;
4729   }
4730   
4731   // Otherwise, there is an index.  The computation we will do will be modulo
4732   // the pointer size, so get it.
4733   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4734   
4735   Offset &= PtrSizeMask;
4736   VariableScale &= PtrSizeMask;
4737
4738   // To do this transformation, any constant index must be a multiple of the
4739   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4740   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4741   // multiple of the variable scale.
4742   int64_t NewOffs = Offset / (int64_t)VariableScale;
4743   if (Offset != NewOffs*(int64_t)VariableScale)
4744     return 0;
4745
4746   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4747   const Type *IntPtrTy = TD.getIntPtrType();
4748   if (VariableIdx->getType() != IntPtrTy)
4749     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4750                                               true /*SExt*/, 
4751                                               VariableIdx->getNameStart(), &I);
4752   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4753   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4754 }
4755
4756
4757 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4758 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4759 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4760                                        ICmpInst::Predicate Cond,
4761                                        Instruction &I) {
4762   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4763
4764   // Look through bitcasts.
4765   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4766     RHS = BCI->getOperand(0);
4767
4768   Value *PtrBase = GEPLHS->getOperand(0);
4769   if (PtrBase == RHS) {
4770     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4771     // This transformation (ignoring the base and scales) is valid because we
4772     // know pointers can't overflow.  See if we can output an optimized form.
4773     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4774     
4775     // If not, synthesize the offset the hard way.
4776     if (Offset == 0)
4777       Offset = EmitGEPOffset(GEPLHS, I, *this);
4778     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4779                         Constant::getNullValue(Offset->getType()));
4780   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4781     // If the base pointers are different, but the indices are the same, just
4782     // compare the base pointer.
4783     if (PtrBase != GEPRHS->getOperand(0)) {
4784       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4785       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4786                         GEPRHS->getOperand(0)->getType();
4787       if (IndicesTheSame)
4788         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4789           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4790             IndicesTheSame = false;
4791             break;
4792           }
4793
4794       // If all indices are the same, just compare the base pointers.
4795       if (IndicesTheSame)
4796         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4797                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4798
4799       // Otherwise, the base pointers are different and the indices are
4800       // different, bail out.
4801       return 0;
4802     }
4803
4804     // If one of the GEPs has all zero indices, recurse.
4805     bool AllZeros = true;
4806     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4807       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4808           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4809         AllZeros = false;
4810         break;
4811       }
4812     if (AllZeros)
4813       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4814                           ICmpInst::getSwappedPredicate(Cond), I);
4815
4816     // If the other GEP has all zero indices, recurse.
4817     AllZeros = true;
4818     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4819       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4820           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4821         AllZeros = false;
4822         break;
4823       }
4824     if (AllZeros)
4825       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4826
4827     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4828       // If the GEPs only differ by one index, compare it.
4829       unsigned NumDifferences = 0;  // Keep track of # differences.
4830       unsigned DiffOperand = 0;     // The operand that differs.
4831       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4832         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4833           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4834                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4835             // Irreconcilable differences.
4836             NumDifferences = 2;
4837             break;
4838           } else {
4839             if (NumDifferences++) break;
4840             DiffOperand = i;
4841           }
4842         }
4843
4844       if (NumDifferences == 0)   // SAME GEP?
4845         return ReplaceInstUsesWith(I, // No comparison is needed here.
4846                                    ConstantInt::get(Type::Int1Ty,
4847                                              ICmpInst::isTrueWhenEqual(Cond)));
4848
4849       else if (NumDifferences == 1) {
4850         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4851         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4852         // Make sure we do a signed comparison here.
4853         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4854       }
4855     }
4856
4857     // Only lower this if the icmp is the only user of the GEP or if we expect
4858     // the result to fold to a constant!
4859     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4860         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4861       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4862       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4863       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4864       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4865     }
4866   }
4867   return 0;
4868 }
4869
4870 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4871 ///
4872 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4873                                                 Instruction *LHSI,
4874                                                 Constant *RHSC) {
4875   if (!isa<ConstantFP>(RHSC)) return 0;
4876   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4877   
4878   // Get the width of the mantissa.  We don't want to hack on conversions that
4879   // might lose information from the integer, e.g. "i64 -> float"
4880   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4881   if (MantissaWidth == -1) return 0;  // Unknown.
4882   
4883   // Check to see that the input is converted from an integer type that is small
4884   // enough that preserves all bits.  TODO: check here for "known" sign bits.
4885   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4886   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4887   
4888   // If this is a uitofp instruction, we need an extra bit to hold the sign.
4889   if (isa<UIToFPInst>(LHSI))
4890     ++InputSize;
4891   
4892   // If the conversion would lose info, don't hack on this.
4893   if ((int)InputSize > MantissaWidth)
4894     return 0;
4895   
4896   // Otherwise, we can potentially simplify the comparison.  We know that it
4897   // will always come through as an integer value and we know the constant is
4898   // not a NAN (it would have been previously simplified).
4899   assert(!RHS.isNaN() && "NaN comparison not already folded!");
4900   
4901   ICmpInst::Predicate Pred;
4902   switch (I.getPredicate()) {
4903   default: assert(0 && "Unexpected predicate!");
4904   case FCmpInst::FCMP_UEQ:
4905   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4906   case FCmpInst::FCMP_UGT:
4907   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4908   case FCmpInst::FCMP_UGE:
4909   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4910   case FCmpInst::FCMP_ULT:
4911   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4912   case FCmpInst::FCMP_ULE:
4913   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4914   case FCmpInst::FCMP_UNE:
4915   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4916   case FCmpInst::FCMP_ORD:
4917     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4918   case FCmpInst::FCMP_UNO:
4919     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4920   }
4921   
4922   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4923   
4924   // Now we know that the APFloat is a normal number, zero or inf.
4925   
4926   // See if the FP constant is too large for the integer.  For example,
4927   // comparing an i8 to 300.0.
4928   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4929   
4930   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
4931   // and large values. 
4932   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4933   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4934                         APFloat::rmNearestTiesToEven);
4935   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
4936     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4937         Pred == ICmpInst::ICMP_SLE)
4938       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4939     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4940   }
4941   
4942   // See if the RHS value is < SignedMin.
4943   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4944   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4945                         APFloat::rmNearestTiesToEven);
4946   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4947     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4948         Pred == ICmpInst::ICMP_SGE)
4949       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4950     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4951   }
4952
4953   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4954   // it may still be fractional.  See if it is fractional by casting the FP
4955   // value to the integer value and back, checking for equality.  Don't do this
4956   // for zero, because -0.0 is not fractional.
4957   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4958   if (!RHS.isZero() &&
4959       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4960     // If we had a comparison against a fractional value, we have to adjust
4961     // the compare predicate and sometimes the value.  RHSC is rounded towards
4962     // zero at this point.
4963     switch (Pred) {
4964     default: assert(0 && "Unexpected integer comparison!");
4965     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
4966       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4967     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
4968       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4969     case ICmpInst::ICMP_SLE:
4970       // (float)int <= 4.4   --> int <= 4
4971       // (float)int <= -4.4  --> int < -4
4972       if (RHS.isNegative())
4973         Pred = ICmpInst::ICMP_SLT;
4974       break;
4975     case ICmpInst::ICMP_SLT:
4976       // (float)int < -4.4   --> int < -4
4977       // (float)int < 4.4    --> int <= 4
4978       if (!RHS.isNegative())
4979         Pred = ICmpInst::ICMP_SLE;
4980       break;
4981     case ICmpInst::ICMP_SGT:
4982       // (float)int > 4.4    --> int > 4
4983       // (float)int > -4.4   --> int >= -4
4984       if (RHS.isNegative())
4985         Pred = ICmpInst::ICMP_SGE;
4986       break;
4987     case ICmpInst::ICMP_SGE:
4988       // (float)int >= -4.4   --> int >= -4
4989       // (float)int >= 4.4    --> int > 4
4990       if (!RHS.isNegative())
4991         Pred = ICmpInst::ICMP_SGT;
4992       break;
4993     }
4994   }
4995
4996   // Lower this FP comparison into an appropriate integer version of the
4997   // comparison.
4998   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
4999 }
5000
5001 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5002   bool Changed = SimplifyCompare(I);
5003   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5004
5005   // Fold trivial predicates.
5006   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5007     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5008   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5009     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5010   
5011   // Simplify 'fcmp pred X, X'
5012   if (Op0 == Op1) {
5013     switch (I.getPredicate()) {
5014     default: assert(0 && "Unknown predicate!");
5015     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5016     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5017     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5018       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5019     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5020     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5021     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5022       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5023       
5024     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5025     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5026     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5027     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5028       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5029       I.setPredicate(FCmpInst::FCMP_UNO);
5030       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5031       return &I;
5032       
5033     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5034     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5035     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5036     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5037       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5038       I.setPredicate(FCmpInst::FCMP_ORD);
5039       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5040       return &I;
5041     }
5042   }
5043     
5044   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5045     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5046
5047   // Handle fcmp with constant RHS
5048   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5049     // If the constant is a nan, see if we can fold the comparison based on it.
5050     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5051       if (CFP->getValueAPF().isNaN()) {
5052         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5053           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5054         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5055                "Comparison must be either ordered or unordered!");
5056         // True if unordered.
5057         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5058       }
5059     }
5060     
5061     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5062       switch (LHSI->getOpcode()) {
5063       case Instruction::PHI:
5064         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5065         // block.  If in the same block, we're encouraging jump threading.  If
5066         // not, we are just pessimizing the code by making an i1 phi.
5067         if (LHSI->getParent() == I.getParent())
5068           if (Instruction *NV = FoldOpIntoPhi(I))
5069             return NV;
5070         break;
5071       case Instruction::SIToFP:
5072       case Instruction::UIToFP:
5073         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5074           return NV;
5075         break;
5076       case Instruction::Select:
5077         // If either operand of the select is a constant, we can fold the
5078         // comparison into the select arms, which will cause one to be
5079         // constant folded and the select turned into a bitwise or.
5080         Value *Op1 = 0, *Op2 = 0;
5081         if (LHSI->hasOneUse()) {
5082           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5083             // Fold the known value into the constant operand.
5084             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5085             // Insert a new FCmp of the other select operand.
5086             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5087                                                       LHSI->getOperand(2), RHSC,
5088                                                       I.getName()), I);
5089           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5090             // Fold the known value into the constant operand.
5091             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5092             // Insert a new FCmp of the other select operand.
5093             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5094                                                       LHSI->getOperand(1), RHSC,
5095                                                       I.getName()), I);
5096           }
5097         }
5098
5099         if (Op1)
5100           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5101         break;
5102       }
5103   }
5104
5105   return Changed ? &I : 0;
5106 }
5107
5108 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5109   bool Changed = SimplifyCompare(I);
5110   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5111   const Type *Ty = Op0->getType();
5112
5113   // icmp X, X
5114   if (Op0 == Op1)
5115     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5116                                                    I.isTrueWhenEqual()));
5117
5118   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5119     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5120   
5121   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5122   // addresses never equal each other!  We already know that Op0 != Op1.
5123   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5124        isa<ConstantPointerNull>(Op0)) &&
5125       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5126        isa<ConstantPointerNull>(Op1)))
5127     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5128                                                    !I.isTrueWhenEqual()));
5129
5130   // icmp's with boolean values can always be turned into bitwise operations
5131   if (Ty == Type::Int1Ty) {
5132     switch (I.getPredicate()) {
5133     default: assert(0 && "Invalid icmp instruction!");
5134     case ICmpInst::ICMP_EQ: {               // icmp eq bool %A, %B -> ~(A^B)
5135       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5136       InsertNewInstBefore(Xor, I);
5137       return BinaryOperator::CreateNot(Xor);
5138     }
5139     case ICmpInst::ICMP_NE:                  // icmp eq bool %A, %B -> A^B
5140       return BinaryOperator::CreateXor(Op0, Op1);
5141
5142     case ICmpInst::ICMP_UGT:
5143     case ICmpInst::ICMP_SGT:
5144       std::swap(Op0, Op1);                   // Change icmp gt -> icmp lt
5145       // FALL THROUGH
5146     case ICmpInst::ICMP_ULT:
5147     case ICmpInst::ICMP_SLT: {               // icmp lt bool A, B -> ~X & Y
5148       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5149       InsertNewInstBefore(Not, I);
5150       return BinaryOperator::CreateAnd(Not, Op1);
5151     }
5152     case ICmpInst::ICMP_UGE:
5153     case ICmpInst::ICMP_SGE:
5154       std::swap(Op0, Op1);                   // Change icmp ge -> icmp le
5155       // FALL THROUGH
5156     case ICmpInst::ICMP_ULE:
5157     case ICmpInst::ICMP_SLE: {               //  icmp le bool %A, %B -> ~A | B
5158       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5159       InsertNewInstBefore(Not, I);
5160       return BinaryOperator::CreateOr(Not, Op1);
5161     }
5162     }
5163   }
5164
5165   // See if we are doing a comparison between a constant and an instruction that
5166   // can be folded into the comparison.
5167   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5168       Value *A, *B;
5169     
5170     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5171     if (I.isEquality() && CI->isNullValue() &&
5172         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5173       // (icmp cond A B) if cond is equality
5174       return new ICmpInst(I.getPredicate(), A, B);
5175     }
5176     
5177     switch (I.getPredicate()) {
5178     default: break;
5179     case ICmpInst::ICMP_ULT:                        // A <u MIN -> FALSE
5180       if (CI->isMinValue(false))
5181         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5182       if (CI->isMaxValue(false))                    // A <u MAX -> A != MAX
5183         return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5184       if (isMinValuePlusOne(CI,false))              // A <u MIN+1 -> A == MIN
5185         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5186       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5187       if (CI->isMinValue(true))
5188         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5189                             ConstantInt::getAllOnesValue(Op0->getType()));
5190           
5191       break;
5192
5193     case ICmpInst::ICMP_SLT:
5194       if (CI->isMinValue(true))                    // A <s MIN -> FALSE
5195         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5196       if (CI->isMaxValue(true))                    // A <s MAX -> A != MAX
5197         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5198       if (isMinValuePlusOne(CI,true))              // A <s MIN+1 -> A == MIN
5199         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5200       break;
5201
5202     case ICmpInst::ICMP_UGT:
5203       if (CI->isMaxValue(false))                  // A >u MAX -> FALSE
5204         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5205       if (CI->isMinValue(false))                  // A >u MIN -> A != MIN
5206         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5207       if (isMaxValueMinusOne(CI, false))          // A >u MAX-1 -> A == MAX
5208         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5209         
5210       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5211       if (CI->isMaxValue(true))
5212         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5213                             ConstantInt::getNullValue(Op0->getType()));
5214       break;
5215
5216     case ICmpInst::ICMP_SGT:
5217       if (CI->isMaxValue(true))                   // A >s MAX -> FALSE
5218         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5219       if (CI->isMinValue(true))                   // A >s MIN -> A != MIN
5220         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5221       if (isMaxValueMinusOne(CI, true))           // A >s MAX-1 -> A == MAX
5222         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5223       break;
5224
5225     case ICmpInst::ICMP_ULE:
5226       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5227         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5228       if (CI->isMinValue(false))                 // A <=u MIN -> A == MIN
5229         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5230       if (isMaxValueMinusOne(CI,false))          // A <=u MAX-1 -> A != MAX
5231         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5232       break;
5233
5234     case ICmpInst::ICMP_SLE:
5235       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5236         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5237       if (CI->isMinValue(true))                  // A <=s MIN -> A == MIN
5238         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5239       if (isMaxValueMinusOne(CI,true))           // A <=s MAX-1 -> A != MAX
5240         return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5241       break;
5242
5243     case ICmpInst::ICMP_UGE:
5244       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5245         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5246       if (CI->isMaxValue(false))                 // A >=u MAX -> A == MAX
5247         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5248       if (isMinValuePlusOne(CI,false))           // A >=u MIN-1 -> A != MIN
5249         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5250       break;
5251
5252     case ICmpInst::ICMP_SGE:
5253       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5254         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5255       if (CI->isMaxValue(true))                  // A >=s MAX -> A == MAX
5256         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5257       if (isMinValuePlusOne(CI,true))            // A >=s MIN-1 -> A != MIN
5258         return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5259       break;
5260     }
5261
5262     // If we still have a icmp le or icmp ge instruction, turn it into the
5263     // appropriate icmp lt or icmp gt instruction.  Since the border cases have
5264     // already been handled above, this requires little checking.
5265     //
5266     switch (I.getPredicate()) {
5267     default: break;
5268     case ICmpInst::ICMP_ULE: 
5269       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5270     case ICmpInst::ICMP_SLE:
5271       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5272     case ICmpInst::ICMP_UGE:
5273       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5274     case ICmpInst::ICMP_SGE:
5275       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5276     }
5277     
5278     // See if we can fold the comparison based on bits known to be zero or one
5279     // in the input.  If this comparison is a normal comparison, it demands all
5280     // bits, if it is a sign bit comparison, it only demands the sign bit.
5281     
5282     bool UnusedBit;
5283     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5284     
5285     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5286     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5287     if (SimplifyDemandedBits(Op0, 
5288                              isSignBit ? APInt::getSignBit(BitWidth)
5289                                        : APInt::getAllOnesValue(BitWidth),
5290                              KnownZero, KnownOne, 0))
5291       return &I;
5292         
5293     // Given the known and unknown bits, compute a range that the LHS could be
5294     // in.
5295     if ((KnownOne | KnownZero) != 0) {
5296       // Compute the Min, Max and RHS values based on the known bits. For the
5297       // EQ and NE we use unsigned values.
5298       APInt Min(BitWidth, 0), Max(BitWidth, 0);
5299       const APInt& RHSVal = CI->getValue();
5300       if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5301         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5302                                                Max);
5303       } else {
5304         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, 
5305                                                  Max);
5306       }
5307       switch (I.getPredicate()) {  // LE/GE have been folded already.
5308       default: assert(0 && "Unknown icmp opcode!");
5309       case ICmpInst::ICMP_EQ:
5310         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5311           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5312         break;
5313       case ICmpInst::ICMP_NE:
5314         if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5315           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5316         break;
5317       case ICmpInst::ICMP_ULT:
5318         if (Max.ult(RHSVal))
5319           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5320         if (Min.uge(RHSVal))
5321           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5322         break;
5323       case ICmpInst::ICMP_UGT:
5324         if (Min.ugt(RHSVal))
5325           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5326         if (Max.ule(RHSVal))
5327           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5328         break;
5329       case ICmpInst::ICMP_SLT:
5330         if (Max.slt(RHSVal))
5331           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5332         if (Min.sgt(RHSVal))
5333           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5334         break;
5335       case ICmpInst::ICMP_SGT: 
5336         if (Min.sgt(RHSVal))
5337           return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5338         if (Max.sle(RHSVal))
5339           return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5340         break;
5341       }
5342     }
5343           
5344     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5345     // instruction, see if that instruction also has constants so that the 
5346     // instruction can be folded into the icmp 
5347     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5348       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5349         return Res;
5350   }
5351
5352   // Handle icmp with constant (but not simple integer constant) RHS
5353   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5354     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5355       switch (LHSI->getOpcode()) {
5356       case Instruction::GetElementPtr:
5357         if (RHSC->isNullValue()) {
5358           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5359           bool isAllZeros = true;
5360           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5361             if (!isa<Constant>(LHSI->getOperand(i)) ||
5362                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5363               isAllZeros = false;
5364               break;
5365             }
5366           if (isAllZeros)
5367             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5368                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5369         }
5370         break;
5371
5372       case Instruction::PHI:
5373         // Only fold icmp into the PHI if the phi and fcmp are in the same
5374         // block.  If in the same block, we're encouraging jump threading.  If
5375         // not, we are just pessimizing the code by making an i1 phi.
5376         if (LHSI->getParent() == I.getParent())
5377           if (Instruction *NV = FoldOpIntoPhi(I))
5378             return NV;
5379         break;
5380       case Instruction::Select: {
5381         // If either operand of the select is a constant, we can fold the
5382         // comparison into the select arms, which will cause one to be
5383         // constant folded and the select turned into a bitwise or.
5384         Value *Op1 = 0, *Op2 = 0;
5385         if (LHSI->hasOneUse()) {
5386           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5387             // Fold the known value into the constant operand.
5388             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5389             // Insert a new ICmp of the other select operand.
5390             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5391                                                    LHSI->getOperand(2), RHSC,
5392                                                    I.getName()), I);
5393           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5394             // Fold the known value into the constant operand.
5395             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5396             // Insert a new ICmp of the other select operand.
5397             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5398                                                    LHSI->getOperand(1), RHSC,
5399                                                    I.getName()), I);
5400           }
5401         }
5402
5403         if (Op1)
5404           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5405         break;
5406       }
5407       case Instruction::Malloc:
5408         // If we have (malloc != null), and if the malloc has a single use, we
5409         // can assume it is successful and remove the malloc.
5410         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5411           AddToWorkList(LHSI);
5412           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5413                                                          !I.isTrueWhenEqual()));
5414         }
5415         break;
5416       }
5417   }
5418
5419   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5420   if (User *GEP = dyn_castGetElementPtr(Op0))
5421     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5422       return NI;
5423   if (User *GEP = dyn_castGetElementPtr(Op1))
5424     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5425                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5426       return NI;
5427
5428   // Test to see if the operands of the icmp are casted versions of other
5429   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5430   // now.
5431   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5432     if (isa<PointerType>(Op0->getType()) && 
5433         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5434       // We keep moving the cast from the left operand over to the right
5435       // operand, where it can often be eliminated completely.
5436       Op0 = CI->getOperand(0);
5437
5438       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5439       // so eliminate it as well.
5440       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5441         Op1 = CI2->getOperand(0);
5442
5443       // If Op1 is a constant, we can fold the cast into the constant.
5444       if (Op0->getType() != Op1->getType()) {
5445         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5446           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5447         } else {
5448           // Otherwise, cast the RHS right before the icmp
5449           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5450         }
5451       }
5452       return new ICmpInst(I.getPredicate(), Op0, Op1);
5453     }
5454   }
5455   
5456   if (isa<CastInst>(Op0)) {
5457     // Handle the special case of: icmp (cast bool to X), <cst>
5458     // This comes up when you have code like
5459     //   int X = A < B;
5460     //   if (X) ...
5461     // For generality, we handle any zero-extension of any operand comparison
5462     // with a constant or another cast from the same type.
5463     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5464       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5465         return R;
5466   }
5467   
5468   // ~x < ~y --> y < x
5469   { Value *A, *B;
5470     if (match(Op0, m_Not(m_Value(A))) &&
5471         match(Op1, m_Not(m_Value(B))))
5472       return new ICmpInst(I.getPredicate(), B, A);
5473   }
5474   
5475   if (I.isEquality()) {
5476     Value *A, *B, *C, *D;
5477     
5478     // -x == -y --> x == y
5479     if (match(Op0, m_Neg(m_Value(A))) &&
5480         match(Op1, m_Neg(m_Value(B))))
5481       return new ICmpInst(I.getPredicate(), A, B);
5482     
5483     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5484       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5485         Value *OtherVal = A == Op1 ? B : A;
5486         return new ICmpInst(I.getPredicate(), OtherVal,
5487                             Constant::getNullValue(A->getType()));
5488       }
5489
5490       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5491         // A^c1 == C^c2 --> A == C^(c1^c2)
5492         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5493           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5494             if (Op1->hasOneUse()) {
5495               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5496               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5497               return new ICmpInst(I.getPredicate(), A,
5498                                   InsertNewInstBefore(Xor, I));
5499             }
5500         
5501         // A^B == A^D -> B == D
5502         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5503         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5504         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5505         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5506       }
5507     }
5508     
5509     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5510         (A == Op0 || B == Op0)) {
5511       // A == (A^B)  ->  B == 0
5512       Value *OtherVal = A == Op0 ? B : A;
5513       return new ICmpInst(I.getPredicate(), OtherVal,
5514                           Constant::getNullValue(A->getType()));
5515     }
5516     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5517       // (A-B) == A  ->  B == 0
5518       return new ICmpInst(I.getPredicate(), B,
5519                           Constant::getNullValue(B->getType()));
5520     }
5521     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5522       // A == (A-B)  ->  B == 0
5523       return new ICmpInst(I.getPredicate(), B,
5524                           Constant::getNullValue(B->getType()));
5525     }
5526     
5527     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5528     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5529         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5530         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5531       Value *X = 0, *Y = 0, *Z = 0;
5532       
5533       if (A == C) {
5534         X = B; Y = D; Z = A;
5535       } else if (A == D) {
5536         X = B; Y = C; Z = A;
5537       } else if (B == C) {
5538         X = A; Y = D; Z = B;
5539       } else if (B == D) {
5540         X = A; Y = C; Z = B;
5541       }
5542       
5543       if (X) {   // Build (X^Y) & Z
5544         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5545         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5546         I.setOperand(0, Op1);
5547         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5548         return &I;
5549       }
5550     }
5551   }
5552   return Changed ? &I : 0;
5553 }
5554
5555
5556 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5557 /// and CmpRHS are both known to be integer constants.
5558 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5559                                           ConstantInt *DivRHS) {
5560   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5561   const APInt &CmpRHSV = CmpRHS->getValue();
5562   
5563   // FIXME: If the operand types don't match the type of the divide 
5564   // then don't attempt this transform. The code below doesn't have the
5565   // logic to deal with a signed divide and an unsigned compare (and
5566   // vice versa). This is because (x /s C1) <s C2  produces different 
5567   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5568   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5569   // work. :(  The if statement below tests that condition and bails 
5570   // if it finds it. 
5571   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5572   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5573     return 0;
5574   if (DivRHS->isZero())
5575     return 0; // The ProdOV computation fails on divide by zero.
5576
5577   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5578   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5579   // C2 (CI). By solving for X we can turn this into a range check 
5580   // instead of computing a divide. 
5581   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5582
5583   // Determine if the product overflows by seeing if the product is
5584   // not equal to the divide. Make sure we do the same kind of divide
5585   // as in the LHS instruction that we're folding. 
5586   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5587                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5588
5589   // Get the ICmp opcode
5590   ICmpInst::Predicate Pred = ICI.getPredicate();
5591
5592   // Figure out the interval that is being checked.  For example, a comparison
5593   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5594   // Compute this interval based on the constants involved and the signedness of
5595   // the compare/divide.  This computes a half-open interval, keeping track of
5596   // whether either value in the interval overflows.  After analysis each
5597   // overflow variable is set to 0 if it's corresponding bound variable is valid
5598   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5599   int LoOverflow = 0, HiOverflow = 0;
5600   ConstantInt *LoBound = 0, *HiBound = 0;
5601   
5602   
5603   if (!DivIsSigned) {  // udiv
5604     // e.g. X/5 op 3  --> [15, 20)
5605     LoBound = Prod;
5606     HiOverflow = LoOverflow = ProdOV;
5607     if (!HiOverflow)
5608       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5609   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5610     if (CmpRHSV == 0) {       // (X / pos) op 0
5611       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5612       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5613       HiBound = DivRHS;
5614     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5615       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5616       HiOverflow = LoOverflow = ProdOV;
5617       if (!HiOverflow)
5618         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5619     } else {                       // (X / pos) op neg
5620       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5621       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5622       LoOverflow = AddWithOverflow(LoBound, Prod,
5623                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5624       HiBound = AddOne(Prod);
5625       HiOverflow = ProdOV ? -1 : 0;
5626     }
5627   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5628     if (CmpRHSV == 0) {       // (X / neg) op 0
5629       // e.g. X/-5 op 0  --> [-4, 5)
5630       LoBound = AddOne(DivRHS);
5631       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5632       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5633         HiOverflow = 1;            // [INTMIN+1, overflow)
5634         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5635       }
5636     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5637       // e.g. X/-5 op 3  --> [-19, -14)
5638       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5639       if (!LoOverflow)
5640         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5641       HiBound = AddOne(Prod);
5642     } else {                       // (X / neg) op neg
5643       // e.g. X/-5 op -3  --> [15, 20)
5644       LoBound = Prod;
5645       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5646       HiBound = Subtract(Prod, DivRHS);
5647     }
5648     
5649     // Dividing by a negative swaps the condition.  LT <-> GT
5650     Pred = ICmpInst::getSwappedPredicate(Pred);
5651   }
5652
5653   Value *X = DivI->getOperand(0);
5654   switch (Pred) {
5655   default: assert(0 && "Unhandled icmp opcode!");
5656   case ICmpInst::ICMP_EQ:
5657     if (LoOverflow && HiOverflow)
5658       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5659     else if (HiOverflow)
5660       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5661                           ICmpInst::ICMP_UGE, X, LoBound);
5662     else if (LoOverflow)
5663       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5664                           ICmpInst::ICMP_ULT, X, HiBound);
5665     else
5666       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5667   case ICmpInst::ICMP_NE:
5668     if (LoOverflow && HiOverflow)
5669       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5670     else if (HiOverflow)
5671       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5672                           ICmpInst::ICMP_ULT, X, LoBound);
5673     else if (LoOverflow)
5674       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5675                           ICmpInst::ICMP_UGE, X, HiBound);
5676     else
5677       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5678   case ICmpInst::ICMP_ULT:
5679   case ICmpInst::ICMP_SLT:
5680     if (LoOverflow == +1)   // Low bound is greater than input range.
5681       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5682     if (LoOverflow == -1)   // Low bound is less than input range.
5683       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5684     return new ICmpInst(Pred, X, LoBound);
5685   case ICmpInst::ICMP_UGT:
5686   case ICmpInst::ICMP_SGT:
5687     if (HiOverflow == +1)       // High bound greater than input range.
5688       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5689     else if (HiOverflow == -1)  // High bound less than input range.
5690       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5691     if (Pred == ICmpInst::ICMP_UGT)
5692       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5693     else
5694       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5695   }
5696 }
5697
5698
5699 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5700 ///
5701 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5702                                                           Instruction *LHSI,
5703                                                           ConstantInt *RHS) {
5704   const APInt &RHSV = RHS->getValue();
5705   
5706   switch (LHSI->getOpcode()) {
5707   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5708     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5709       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5710       // fold the xor.
5711       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5712           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5713         Value *CompareVal = LHSI->getOperand(0);
5714         
5715         // If the sign bit of the XorCST is not set, there is no change to
5716         // the operation, just stop using the Xor.
5717         if (!XorCST->getValue().isNegative()) {
5718           ICI.setOperand(0, CompareVal);
5719           AddToWorkList(LHSI);
5720           return &ICI;
5721         }
5722         
5723         // Was the old condition true if the operand is positive?
5724         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5725         
5726         // If so, the new one isn't.
5727         isTrueIfPositive ^= true;
5728         
5729         if (isTrueIfPositive)
5730           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5731         else
5732           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5733       }
5734     }
5735     break;
5736   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5737     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5738         LHSI->getOperand(0)->hasOneUse()) {
5739       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5740       
5741       // If the LHS is an AND of a truncating cast, we can widen the
5742       // and/compare to be the input width without changing the value
5743       // produced, eliminating a cast.
5744       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5745         // We can do this transformation if either the AND constant does not
5746         // have its sign bit set or if it is an equality comparison. 
5747         // Extending a relational comparison when we're checking the sign
5748         // bit would not work.
5749         if (Cast->hasOneUse() &&
5750             (ICI.isEquality() ||
5751              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5752           uint32_t BitWidth = 
5753             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5754           APInt NewCST = AndCST->getValue();
5755           NewCST.zext(BitWidth);
5756           APInt NewCI = RHSV;
5757           NewCI.zext(BitWidth);
5758           Instruction *NewAnd = 
5759             BinaryOperator::CreateAnd(Cast->getOperand(0),
5760                                       ConstantInt::get(NewCST),LHSI->getName());
5761           InsertNewInstBefore(NewAnd, ICI);
5762           return new ICmpInst(ICI.getPredicate(), NewAnd,
5763                               ConstantInt::get(NewCI));
5764         }
5765       }
5766       
5767       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5768       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5769       // happens a LOT in code produced by the C front-end, for bitfield
5770       // access.
5771       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5772       if (Shift && !Shift->isShift())
5773         Shift = 0;
5774       
5775       ConstantInt *ShAmt;
5776       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5777       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5778       const Type *AndTy = AndCST->getType();          // Type of the and.
5779       
5780       // We can fold this as long as we can't shift unknown bits
5781       // into the mask.  This can only happen with signed shift
5782       // rights, as they sign-extend.
5783       if (ShAmt) {
5784         bool CanFold = Shift->isLogicalShift();
5785         if (!CanFold) {
5786           // To test for the bad case of the signed shr, see if any
5787           // of the bits shifted in could be tested after the mask.
5788           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5789           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5790           
5791           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5792           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5793                AndCST->getValue()) == 0)
5794             CanFold = true;
5795         }
5796         
5797         if (CanFold) {
5798           Constant *NewCst;
5799           if (Shift->getOpcode() == Instruction::Shl)
5800             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5801           else
5802             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5803           
5804           // Check to see if we are shifting out any of the bits being
5805           // compared.
5806           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5807             // If we shifted bits out, the fold is not going to work out.
5808             // As a special case, check to see if this means that the
5809             // result is always true or false now.
5810             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5811               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5812             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5813               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5814           } else {
5815             ICI.setOperand(1, NewCst);
5816             Constant *NewAndCST;
5817             if (Shift->getOpcode() == Instruction::Shl)
5818               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5819             else
5820               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5821             LHSI->setOperand(1, NewAndCST);
5822             LHSI->setOperand(0, Shift->getOperand(0));
5823             AddToWorkList(Shift); // Shift is dead.
5824             AddUsesToWorkList(ICI);
5825             return &ICI;
5826           }
5827         }
5828       }
5829       
5830       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5831       // preferable because it allows the C<<Y expression to be hoisted out
5832       // of a loop if Y is invariant and X is not.
5833       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5834           ICI.isEquality() && !Shift->isArithmeticShift() &&
5835           isa<Instruction>(Shift->getOperand(0))) {
5836         // Compute C << Y.
5837         Value *NS;
5838         if (Shift->getOpcode() == Instruction::LShr) {
5839           NS = BinaryOperator::CreateShl(AndCST, 
5840                                          Shift->getOperand(1), "tmp");
5841         } else {
5842           // Insert a logical shift.
5843           NS = BinaryOperator::CreateLShr(AndCST,
5844                                           Shift->getOperand(1), "tmp");
5845         }
5846         InsertNewInstBefore(cast<Instruction>(NS), ICI);
5847         
5848         // Compute X & (C << Y).
5849         Instruction *NewAnd = 
5850           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5851         InsertNewInstBefore(NewAnd, ICI);
5852         
5853         ICI.setOperand(0, NewAnd);
5854         return &ICI;
5855       }
5856     }
5857     break;
5858     
5859   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
5860     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5861     if (!ShAmt) break;
5862     
5863     uint32_t TypeBits = RHSV.getBitWidth();
5864     
5865     // Check that the shift amount is in range.  If not, don't perform
5866     // undefined shifts.  When the shift is visited it will be
5867     // simplified.
5868     if (ShAmt->uge(TypeBits))
5869       break;
5870     
5871     if (ICI.isEquality()) {
5872       // If we are comparing against bits always shifted out, the
5873       // comparison cannot succeed.
5874       Constant *Comp =
5875         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5876       if (Comp != RHS) {// Comparing against a bit that we know is zero.
5877         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5878         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5879         return ReplaceInstUsesWith(ICI, Cst);
5880       }
5881       
5882       if (LHSI->hasOneUse()) {
5883         // Otherwise strength reduce the shift into an and.
5884         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5885         Constant *Mask =
5886           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5887         
5888         Instruction *AndI =
5889           BinaryOperator::CreateAnd(LHSI->getOperand(0),
5890                                     Mask, LHSI->getName()+".mask");
5891         Value *And = InsertNewInstBefore(AndI, ICI);
5892         return new ICmpInst(ICI.getPredicate(), And,
5893                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
5894       }
5895     }
5896     
5897     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5898     bool TrueIfSigned = false;
5899     if (LHSI->hasOneUse() &&
5900         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5901       // (X << 31) <s 0  --> (X&1) != 0
5902       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5903                                            (TypeBits-ShAmt->getZExtValue()-1));
5904       Instruction *AndI =
5905         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5906                                   Mask, LHSI->getName()+".mask");
5907       Value *And = InsertNewInstBefore(AndI, ICI);
5908       
5909       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5910                           And, Constant::getNullValue(And->getType()));
5911     }
5912     break;
5913   }
5914     
5915   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
5916   case Instruction::AShr: {
5917     // Only handle equality comparisons of shift-by-constant.
5918     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5919     if (!ShAmt || !ICI.isEquality()) break;
5920
5921     // Check that the shift amount is in range.  If not, don't perform
5922     // undefined shifts.  When the shift is visited it will be
5923     // simplified.
5924     uint32_t TypeBits = RHSV.getBitWidth();
5925     if (ShAmt->uge(TypeBits))
5926       break;
5927     
5928     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5929       
5930     // If we are comparing against bits always shifted out, the
5931     // comparison cannot succeed.
5932     APInt Comp = RHSV << ShAmtVal;
5933     if (LHSI->getOpcode() == Instruction::LShr)
5934       Comp = Comp.lshr(ShAmtVal);
5935     else
5936       Comp = Comp.ashr(ShAmtVal);
5937     
5938     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5939       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5940       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5941       return ReplaceInstUsesWith(ICI, Cst);
5942     }
5943     
5944     // Otherwise, check to see if the bits shifted out are known to be zero.
5945     // If so, we can compare against the unshifted value:
5946     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
5947     if (LHSI->hasOneUse() &&
5948         MaskedValueIsZero(LHSI->getOperand(0), 
5949                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5950       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5951                           ConstantExpr::getShl(RHS, ShAmt));
5952     }
5953       
5954     if (LHSI->hasOneUse()) {
5955       // Otherwise strength reduce the shift into an and.
5956       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5957       Constant *Mask = ConstantInt::get(Val);
5958       
5959       Instruction *AndI =
5960         BinaryOperator::CreateAnd(LHSI->getOperand(0),
5961                                   Mask, LHSI->getName()+".mask");
5962       Value *And = InsertNewInstBefore(AndI, ICI);
5963       return new ICmpInst(ICI.getPredicate(), And,
5964                           ConstantExpr::getShl(RHS, ShAmt));
5965     }
5966     break;
5967   }
5968     
5969   case Instruction::SDiv:
5970   case Instruction::UDiv:
5971     // Fold: icmp pred ([us]div X, C1), C2 -> range test
5972     // Fold this div into the comparison, producing a range check. 
5973     // Determine, based on the divide type, what the range is being 
5974     // checked.  If there is an overflow on the low or high side, remember 
5975     // it, otherwise compute the range [low, hi) bounding the new value.
5976     // See: InsertRangeTest above for the kinds of replacements possible.
5977     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5978       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5979                                           DivRHS))
5980         return R;
5981     break;
5982
5983   case Instruction::Add:
5984     // Fold: icmp pred (add, X, C1), C2
5985
5986     if (!ICI.isEquality()) {
5987       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5988       if (!LHSC) break;
5989       const APInt &LHSV = LHSC->getValue();
5990
5991       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5992                             .subtract(LHSV);
5993
5994       if (ICI.isSignedPredicate()) {
5995         if (CR.getLower().isSignBit()) {
5996           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5997                               ConstantInt::get(CR.getUpper()));
5998         } else if (CR.getUpper().isSignBit()) {
5999           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6000                               ConstantInt::get(CR.getLower()));
6001         }
6002       } else {
6003         if (CR.getLower().isMinValue()) {
6004           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6005                               ConstantInt::get(CR.getUpper()));
6006         } else if (CR.getUpper().isMinValue()) {
6007           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6008                               ConstantInt::get(CR.getLower()));
6009         }
6010       }
6011     }
6012     break;
6013   }
6014   
6015   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6016   if (ICI.isEquality()) {
6017     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6018     
6019     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6020     // the second operand is a constant, simplify a bit.
6021     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6022       switch (BO->getOpcode()) {
6023       case Instruction::SRem:
6024         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6025         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6026           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6027           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6028             Instruction *NewRem =
6029               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6030                                          BO->getName());
6031             InsertNewInstBefore(NewRem, ICI);
6032             return new ICmpInst(ICI.getPredicate(), NewRem, 
6033                                 Constant::getNullValue(BO->getType()));
6034           }
6035         }
6036         break;
6037       case Instruction::Add:
6038         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6039         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6040           if (BO->hasOneUse())
6041             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6042                                 Subtract(RHS, BOp1C));
6043         } else if (RHSV == 0) {
6044           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6045           // efficiently invertible, or if the add has just this one use.
6046           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6047           
6048           if (Value *NegVal = dyn_castNegVal(BOp1))
6049             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6050           else if (Value *NegVal = dyn_castNegVal(BOp0))
6051             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6052           else if (BO->hasOneUse()) {
6053             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6054             InsertNewInstBefore(Neg, ICI);
6055             Neg->takeName(BO);
6056             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6057           }
6058         }
6059         break;
6060       case Instruction::Xor:
6061         // For the xor case, we can xor two constants together, eliminating
6062         // the explicit xor.
6063         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6064           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6065                               ConstantExpr::getXor(RHS, BOC));
6066         
6067         // FALLTHROUGH
6068       case Instruction::Sub:
6069         // Replace (([sub|xor] A, B) != 0) with (A != B)
6070         if (RHSV == 0)
6071           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6072                               BO->getOperand(1));
6073         break;
6074         
6075       case Instruction::Or:
6076         // If bits are being or'd in that are not present in the constant we
6077         // are comparing against, then the comparison could never succeed!
6078         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6079           Constant *NotCI = ConstantExpr::getNot(RHS);
6080           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6081             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6082                                                              isICMP_NE));
6083         }
6084         break;
6085         
6086       case Instruction::And:
6087         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6088           // If bits are being compared against that are and'd out, then the
6089           // comparison can never succeed!
6090           if ((RHSV & ~BOC->getValue()) != 0)
6091             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6092                                                              isICMP_NE));
6093           
6094           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6095           if (RHS == BOC && RHSV.isPowerOf2())
6096             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6097                                 ICmpInst::ICMP_NE, LHSI,
6098                                 Constant::getNullValue(RHS->getType()));
6099           
6100           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6101           if (BOC->getValue().isSignBit()) {
6102             Value *X = BO->getOperand(0);
6103             Constant *Zero = Constant::getNullValue(X->getType());
6104             ICmpInst::Predicate pred = isICMP_NE ? 
6105               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6106             return new ICmpInst(pred, X, Zero);
6107           }
6108           
6109           // ((X & ~7) == 0) --> X < 8
6110           if (RHSV == 0 && isHighOnes(BOC)) {
6111             Value *X = BO->getOperand(0);
6112             Constant *NegX = ConstantExpr::getNeg(BOC);
6113             ICmpInst::Predicate pred = isICMP_NE ? 
6114               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6115             return new ICmpInst(pred, X, NegX);
6116           }
6117         }
6118       default: break;
6119       }
6120     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6121       // Handle icmp {eq|ne} <intrinsic>, intcst.
6122       if (II->getIntrinsicID() == Intrinsic::bswap) {
6123         AddToWorkList(II);
6124         ICI.setOperand(0, II->getOperand(1));
6125         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6126         return &ICI;
6127       }
6128     }
6129   } else {  // Not a ICMP_EQ/ICMP_NE
6130             // If the LHS is a cast from an integral value of the same size, 
6131             // then since we know the RHS is a constant, try to simlify.
6132     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6133       Value *CastOp = Cast->getOperand(0);
6134       const Type *SrcTy = CastOp->getType();
6135       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6136       if (SrcTy->isInteger() && 
6137           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6138         // If this is an unsigned comparison, try to make the comparison use
6139         // smaller constant values.
6140         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6141           // X u< 128 => X s> -1
6142           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6143                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6144         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6145                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6146           // X u> 127 => X s< 0
6147           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6148                               Constant::getNullValue(SrcTy));
6149         }
6150       }
6151     }
6152   }
6153   return 0;
6154 }
6155
6156 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6157 /// We only handle extending casts so far.
6158 ///
6159 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6160   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6161   Value *LHSCIOp        = LHSCI->getOperand(0);
6162   const Type *SrcTy     = LHSCIOp->getType();
6163   const Type *DestTy    = LHSCI->getType();
6164   Value *RHSCIOp;
6165
6166   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6167   // integer type is the same size as the pointer type.
6168   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6169       getTargetData().getPointerSizeInBits() == 
6170          cast<IntegerType>(DestTy)->getBitWidth()) {
6171     Value *RHSOp = 0;
6172     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6173       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6174     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6175       RHSOp = RHSC->getOperand(0);
6176       // If the pointer types don't match, insert a bitcast.
6177       if (LHSCIOp->getType() != RHSOp->getType())
6178         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6179     }
6180
6181     if (RHSOp)
6182       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6183   }
6184   
6185   // The code below only handles extension cast instructions, so far.
6186   // Enforce this.
6187   if (LHSCI->getOpcode() != Instruction::ZExt &&
6188       LHSCI->getOpcode() != Instruction::SExt)
6189     return 0;
6190
6191   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6192   bool isSignedCmp = ICI.isSignedPredicate();
6193
6194   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6195     // Not an extension from the same type?
6196     RHSCIOp = CI->getOperand(0);
6197     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6198       return 0;
6199     
6200     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6201     // and the other is a zext), then we can't handle this.
6202     if (CI->getOpcode() != LHSCI->getOpcode())
6203       return 0;
6204
6205     // Deal with equality cases early.
6206     if (ICI.isEquality())
6207       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6208
6209     // A signed comparison of sign extended values simplifies into a
6210     // signed comparison.
6211     if (isSignedCmp && isSignedExt)
6212       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6213
6214     // The other three cases all fold into an unsigned comparison.
6215     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6216   }
6217
6218   // If we aren't dealing with a constant on the RHS, exit early
6219   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6220   if (!CI)
6221     return 0;
6222
6223   // Compute the constant that would happen if we truncated to SrcTy then
6224   // reextended to DestTy.
6225   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6226   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6227
6228   // If the re-extended constant didn't change...
6229   if (Res2 == CI) {
6230     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6231     // For example, we might have:
6232     //    %A = sext short %X to uint
6233     //    %B = icmp ugt uint %A, 1330
6234     // It is incorrect to transform this into 
6235     //    %B = icmp ugt short %X, 1330 
6236     // because %A may have negative value. 
6237     //
6238     // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6239     // OR operation is EQ/NE.
6240     if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6241       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6242     else
6243       return 0;
6244   }
6245
6246   // The re-extended constant changed so the constant cannot be represented 
6247   // in the shorter type. Consequently, we cannot emit a simple comparison.
6248
6249   // First, handle some easy cases. We know the result cannot be equal at this
6250   // point so handle the ICI.isEquality() cases
6251   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6252     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6253   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6254     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6255
6256   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6257   // should have been folded away previously and not enter in here.
6258   Value *Result;
6259   if (isSignedCmp) {
6260     // We're performing a signed comparison.
6261     if (cast<ConstantInt>(CI)->getValue().isNegative())
6262       Result = ConstantInt::getFalse();          // X < (small) --> false
6263     else
6264       Result = ConstantInt::getTrue();           // X < (large) --> true
6265   } else {
6266     // We're performing an unsigned comparison.
6267     if (isSignedExt) {
6268       // We're performing an unsigned comp with a sign extended value.
6269       // This is true if the input is >= 0. [aka >s -1]
6270       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6271       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6272                                    NegOne, ICI.getName()), ICI);
6273     } else {
6274       // Unsigned extend & unsigned compare -> always true.
6275       Result = ConstantInt::getTrue();
6276     }
6277   }
6278
6279   // Finally, return the value computed.
6280   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6281       ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6282     return ReplaceInstUsesWith(ICI, Result);
6283   } else {
6284     assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6285             ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6286            "ICmp should be folded!");
6287     if (Constant *CI = dyn_cast<Constant>(Result))
6288       return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6289     else
6290       return BinaryOperator::CreateNot(Result);
6291   }
6292 }
6293
6294 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6295   return commonShiftTransforms(I);
6296 }
6297
6298 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6299   return commonShiftTransforms(I);
6300 }
6301
6302 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6303   if (Instruction *R = commonShiftTransforms(I))
6304     return R;
6305   
6306   Value *Op0 = I.getOperand(0);
6307   
6308   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6309   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6310     if (CSI->isAllOnesValue())
6311       return ReplaceInstUsesWith(I, CSI);
6312   
6313   // See if we can turn a signed shr into an unsigned shr.
6314   if (MaskedValueIsZero(Op0, 
6315                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6316     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6317   
6318   return 0;
6319 }
6320
6321 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6322   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6323   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6324
6325   // shl X, 0 == X and shr X, 0 == X
6326   // shl 0, X == 0 and shr 0, X == 0
6327   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6328       Op0 == Constant::getNullValue(Op0->getType()))
6329     return ReplaceInstUsesWith(I, Op0);
6330   
6331   if (isa<UndefValue>(Op0)) {            
6332     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6333       return ReplaceInstUsesWith(I, Op0);
6334     else                                    // undef << X -> 0, undef >>u X -> 0
6335       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6336   }
6337   if (isa<UndefValue>(Op1)) {
6338     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6339       return ReplaceInstUsesWith(I, Op0);          
6340     else                                     // X << undef, X >>u undef -> 0
6341       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6342   }
6343
6344   // Try to fold constant and into select arguments.
6345   if (isa<Constant>(Op0))
6346     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6347       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6348         return R;
6349
6350   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6351     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6352       return Res;
6353   return 0;
6354 }
6355
6356 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6357                                                BinaryOperator &I) {
6358   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6359
6360   // See if we can simplify any instructions used by the instruction whose sole 
6361   // purpose is to compute bits we don't care about.
6362   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6363   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6364   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6365                            KnownZero, KnownOne))
6366     return &I;
6367   
6368   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6369   // of a signed value.
6370   //
6371   if (Op1->uge(TypeBits)) {
6372     if (I.getOpcode() != Instruction::AShr)
6373       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6374     else {
6375       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6376       return &I;
6377     }
6378   }
6379   
6380   // ((X*C1) << C2) == (X * (C1 << C2))
6381   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6382     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6383       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6384         return BinaryOperator::CreateMul(BO->getOperand(0),
6385                                          ConstantExpr::getShl(BOOp, Op1));
6386   
6387   // Try to fold constant and into select arguments.
6388   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6389     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6390       return R;
6391   if (isa<PHINode>(Op0))
6392     if (Instruction *NV = FoldOpIntoPhi(I))
6393       return NV;
6394   
6395   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6396   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6397     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6398     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6399     // place.  Don't try to do this transformation in this case.  Also, we
6400     // require that the input operand is a shift-by-constant so that we have
6401     // confidence that the shifts will get folded together.  We could do this
6402     // xform in more cases, but it is unlikely to be profitable.
6403     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6404         isa<ConstantInt>(TrOp->getOperand(1))) {
6405       // Okay, we'll do this xform.  Make the shift of shift.
6406       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6407       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6408                                                 I.getName());
6409       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6410
6411       // For logical shifts, the truncation has the effect of making the high
6412       // part of the register be zeros.  Emulate this by inserting an AND to
6413       // clear the top bits as needed.  This 'and' will usually be zapped by
6414       // other xforms later if dead.
6415       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6416       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6417       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6418       
6419       // The mask we constructed says what the trunc would do if occurring
6420       // between the shifts.  We want to know the effect *after* the second
6421       // shift.  We know that it is a logical shift by a constant, so adjust the
6422       // mask as appropriate.
6423       if (I.getOpcode() == Instruction::Shl)
6424         MaskV <<= Op1->getZExtValue();
6425       else {
6426         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6427         MaskV = MaskV.lshr(Op1->getZExtValue());
6428       }
6429
6430       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6431                                                    TI->getName());
6432       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6433
6434       // Return the value truncated to the interesting size.
6435       return new TruncInst(And, I.getType());
6436     }
6437   }
6438   
6439   if (Op0->hasOneUse()) {
6440     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6441       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6442       Value *V1, *V2;
6443       ConstantInt *CC;
6444       switch (Op0BO->getOpcode()) {
6445         default: break;
6446         case Instruction::Add:
6447         case Instruction::And:
6448         case Instruction::Or:
6449         case Instruction::Xor: {
6450           // These operators commute.
6451           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6452           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6453               match(Op0BO->getOperand(1),
6454                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6455             Instruction *YS = BinaryOperator::CreateShl(
6456                                             Op0BO->getOperand(0), Op1,
6457                                             Op0BO->getName());
6458             InsertNewInstBefore(YS, I); // (Y << C)
6459             Instruction *X = 
6460               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6461                                      Op0BO->getOperand(1)->getName());
6462             InsertNewInstBefore(X, I);  // (X + (Y << C))
6463             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6464             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6465                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6466           }
6467           
6468           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6469           Value *Op0BOOp1 = Op0BO->getOperand(1);
6470           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6471               match(Op0BOOp1, 
6472                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6473               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6474               V2 == Op1) {
6475             Instruction *YS = BinaryOperator::CreateShl(
6476                                                      Op0BO->getOperand(0), Op1,
6477                                                      Op0BO->getName());
6478             InsertNewInstBefore(YS, I); // (Y << C)
6479             Instruction *XM =
6480               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6481                                         V1->getName()+".mask");
6482             InsertNewInstBefore(XM, I); // X & (CC << C)
6483             
6484             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6485           }
6486         }
6487           
6488         // FALL THROUGH.
6489         case Instruction::Sub: {
6490           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6491           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6492               match(Op0BO->getOperand(0),
6493                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6494             Instruction *YS = BinaryOperator::CreateShl(
6495                                                      Op0BO->getOperand(1), Op1,
6496                                                      Op0BO->getName());
6497             InsertNewInstBefore(YS, I); // (Y << C)
6498             Instruction *X =
6499               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6500                                      Op0BO->getOperand(0)->getName());
6501             InsertNewInstBefore(X, I);  // (X + (Y << C))
6502             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6503             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6504                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6505           }
6506           
6507           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6508           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6509               match(Op0BO->getOperand(0),
6510                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6511                           m_ConstantInt(CC))) && V2 == Op1 &&
6512               cast<BinaryOperator>(Op0BO->getOperand(0))
6513                   ->getOperand(0)->hasOneUse()) {
6514             Instruction *YS = BinaryOperator::CreateShl(
6515                                                      Op0BO->getOperand(1), Op1,
6516                                                      Op0BO->getName());
6517             InsertNewInstBefore(YS, I); // (Y << C)
6518             Instruction *XM =
6519               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6520                                         V1->getName()+".mask");
6521             InsertNewInstBefore(XM, I); // X & (CC << C)
6522             
6523             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6524           }
6525           
6526           break;
6527         }
6528       }
6529       
6530       
6531       // If the operand is an bitwise operator with a constant RHS, and the
6532       // shift is the only use, we can pull it out of the shift.
6533       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6534         bool isValid = true;     // Valid only for And, Or, Xor
6535         bool highBitSet = false; // Transform if high bit of constant set?
6536         
6537         switch (Op0BO->getOpcode()) {
6538           default: isValid = false; break;   // Do not perform transform!
6539           case Instruction::Add:
6540             isValid = isLeftShift;
6541             break;
6542           case Instruction::Or:
6543           case Instruction::Xor:
6544             highBitSet = false;
6545             break;
6546           case Instruction::And:
6547             highBitSet = true;
6548             break;
6549         }
6550         
6551         // If this is a signed shift right, and the high bit is modified
6552         // by the logical operation, do not perform the transformation.
6553         // The highBitSet boolean indicates the value of the high bit of
6554         // the constant which would cause it to be modified for this
6555         // operation.
6556         //
6557         if (isValid && I.getOpcode() == Instruction::AShr)
6558           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6559         
6560         if (isValid) {
6561           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6562           
6563           Instruction *NewShift =
6564             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6565           InsertNewInstBefore(NewShift, I);
6566           NewShift->takeName(Op0BO);
6567           
6568           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6569                                         NewRHS);
6570         }
6571       }
6572     }
6573   }
6574   
6575   // Find out if this is a shift of a shift by a constant.
6576   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6577   if (ShiftOp && !ShiftOp->isShift())
6578     ShiftOp = 0;
6579   
6580   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6581     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6582     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6583     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6584     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6585     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6586     Value *X = ShiftOp->getOperand(0);
6587     
6588     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6589     if (AmtSum > TypeBits)
6590       AmtSum = TypeBits;
6591     
6592     const IntegerType *Ty = cast<IntegerType>(I.getType());
6593     
6594     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6595     if (I.getOpcode() == ShiftOp->getOpcode()) {
6596       return BinaryOperator::Create(I.getOpcode(), X,
6597                                     ConstantInt::get(Ty, AmtSum));
6598     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6599                I.getOpcode() == Instruction::AShr) {
6600       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6601       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6602     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6603                I.getOpcode() == Instruction::LShr) {
6604       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6605       Instruction *Shift =
6606         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6607       InsertNewInstBefore(Shift, I);
6608
6609       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6610       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6611     }
6612     
6613     // Okay, if we get here, one shift must be left, and the other shift must be
6614     // right.  See if the amounts are equal.
6615     if (ShiftAmt1 == ShiftAmt2) {
6616       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6617       if (I.getOpcode() == Instruction::Shl) {
6618         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6619         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6620       }
6621       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6622       if (I.getOpcode() == Instruction::LShr) {
6623         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6624         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6625       }
6626       // We can simplify ((X << C) >>s C) into a trunc + sext.
6627       // NOTE: we could do this for any C, but that would make 'unusual' integer
6628       // types.  For now, just stick to ones well-supported by the code
6629       // generators.
6630       const Type *SExtType = 0;
6631       switch (Ty->getBitWidth() - ShiftAmt1) {
6632       case 1  :
6633       case 8  :
6634       case 16 :
6635       case 32 :
6636       case 64 :
6637       case 128:
6638         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6639         break;
6640       default: break;
6641       }
6642       if (SExtType) {
6643         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6644         InsertNewInstBefore(NewTrunc, I);
6645         return new SExtInst(NewTrunc, Ty);
6646       }
6647       // Otherwise, we can't handle it yet.
6648     } else if (ShiftAmt1 < ShiftAmt2) {
6649       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6650       
6651       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6652       if (I.getOpcode() == Instruction::Shl) {
6653         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6654                ShiftOp->getOpcode() == Instruction::AShr);
6655         Instruction *Shift =
6656           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6657         InsertNewInstBefore(Shift, I);
6658         
6659         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6660         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6661       }
6662       
6663       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6664       if (I.getOpcode() == Instruction::LShr) {
6665         assert(ShiftOp->getOpcode() == Instruction::Shl);
6666         Instruction *Shift =
6667           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6668         InsertNewInstBefore(Shift, I);
6669         
6670         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6671         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6672       }
6673       
6674       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6675     } else {
6676       assert(ShiftAmt2 < ShiftAmt1);
6677       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6678
6679       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6680       if (I.getOpcode() == Instruction::Shl) {
6681         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6682                ShiftOp->getOpcode() == Instruction::AShr);
6683         Instruction *Shift =
6684           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6685                                  ConstantInt::get(Ty, ShiftDiff));
6686         InsertNewInstBefore(Shift, I);
6687         
6688         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6689         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6690       }
6691       
6692       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6693       if (I.getOpcode() == Instruction::LShr) {
6694         assert(ShiftOp->getOpcode() == Instruction::Shl);
6695         Instruction *Shift =
6696           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6697         InsertNewInstBefore(Shift, I);
6698         
6699         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6700         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6701       }
6702       
6703       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6704     }
6705   }
6706   return 0;
6707 }
6708
6709
6710 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6711 /// expression.  If so, decompose it, returning some value X, such that Val is
6712 /// X*Scale+Offset.
6713 ///
6714 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6715                                         int &Offset) {
6716   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6717   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6718     Offset = CI->getZExtValue();
6719     Scale  = 0;
6720     return ConstantInt::get(Type::Int32Ty, 0);
6721   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6722     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6723       if (I->getOpcode() == Instruction::Shl) {
6724         // This is a value scaled by '1 << the shift amt'.
6725         Scale = 1U << RHS->getZExtValue();
6726         Offset = 0;
6727         return I->getOperand(0);
6728       } else if (I->getOpcode() == Instruction::Mul) {
6729         // This value is scaled by 'RHS'.
6730         Scale = RHS->getZExtValue();
6731         Offset = 0;
6732         return I->getOperand(0);
6733       } else if (I->getOpcode() == Instruction::Add) {
6734         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6735         // where C1 is divisible by C2.
6736         unsigned SubScale;
6737         Value *SubVal = 
6738           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6739         Offset += RHS->getZExtValue();
6740         Scale = SubScale;
6741         return SubVal;
6742       }
6743     }
6744   }
6745
6746   // Otherwise, we can't look past this.
6747   Scale = 1;
6748   Offset = 0;
6749   return Val;
6750 }
6751
6752
6753 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6754 /// try to eliminate the cast by moving the type information into the alloc.
6755 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6756                                                    AllocationInst &AI) {
6757   const PointerType *PTy = cast<PointerType>(CI.getType());
6758   
6759   // Remove any uses of AI that are dead.
6760   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6761   
6762   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6763     Instruction *User = cast<Instruction>(*UI++);
6764     if (isInstructionTriviallyDead(User)) {
6765       while (UI != E && *UI == User)
6766         ++UI; // If this instruction uses AI more than once, don't break UI.
6767       
6768       ++NumDeadInst;
6769       DOUT << "IC: DCE: " << *User;
6770       EraseInstFromFunction(*User);
6771     }
6772   }
6773   
6774   // Get the type really allocated and the type casted to.
6775   const Type *AllocElTy = AI.getAllocatedType();
6776   const Type *CastElTy = PTy->getElementType();
6777   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6778
6779   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6780   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6781   if (CastElTyAlign < AllocElTyAlign) return 0;
6782
6783   // If the allocation has multiple uses, only promote it if we are strictly
6784   // increasing the alignment of the resultant allocation.  If we keep it the
6785   // same, we open the door to infinite loops of various kinds.
6786   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6787
6788   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6789   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6790   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6791
6792   // See if we can satisfy the modulus by pulling a scale out of the array
6793   // size argument.
6794   unsigned ArraySizeScale;
6795   int ArrayOffset;
6796   Value *NumElements = // See if the array size is a decomposable linear expr.
6797     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6798  
6799   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6800   // do the xform.
6801   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6802       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6803
6804   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6805   Value *Amt = 0;
6806   if (Scale == 1) {
6807     Amt = NumElements;
6808   } else {
6809     // If the allocation size is constant, form a constant mul expression
6810     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6811     if (isa<ConstantInt>(NumElements))
6812       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6813     // otherwise multiply the amount and the number of elements
6814     else if (Scale != 1) {
6815       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6816       Amt = InsertNewInstBefore(Tmp, AI);
6817     }
6818   }
6819   
6820   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6821     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6822     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6823     Amt = InsertNewInstBefore(Tmp, AI);
6824   }
6825   
6826   AllocationInst *New;
6827   if (isa<MallocInst>(AI))
6828     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6829   else
6830     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6831   InsertNewInstBefore(New, AI);
6832   New->takeName(&AI);
6833   
6834   // If the allocation has multiple uses, insert a cast and change all things
6835   // that used it to use the new cast.  This will also hack on CI, but it will
6836   // die soon.
6837   if (!AI.hasOneUse()) {
6838     AddUsesToWorkList(AI);
6839     // New is the allocation instruction, pointer typed. AI is the original
6840     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6841     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6842     InsertNewInstBefore(NewCast, AI);
6843     AI.replaceAllUsesWith(NewCast);
6844   }
6845   return ReplaceInstUsesWith(CI, New);
6846 }
6847
6848 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6849 /// and return it as type Ty without inserting any new casts and without
6850 /// changing the computed value.  This is used by code that tries to decide
6851 /// whether promoting or shrinking integer operations to wider or smaller types
6852 /// will allow us to eliminate a truncate or extend.
6853 ///
6854 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6855 /// extension operation if Ty is larger.
6856 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6857                                               unsigned CastOpc,
6858                                               int &NumCastsRemoved) {
6859   // We can always evaluate constants in another type.
6860   if (isa<ConstantInt>(V))
6861     return true;
6862   
6863   Instruction *I = dyn_cast<Instruction>(V);
6864   if (!I) return false;
6865   
6866   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6867   
6868   // If this is an extension or truncate, we can often eliminate it.
6869   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6870     // If this is a cast from the destination type, we can trivially eliminate
6871     // it, and this will remove a cast overall.
6872     if (I->getOperand(0)->getType() == Ty) {
6873       // If the first operand is itself a cast, and is eliminable, do not count
6874       // this as an eliminable cast.  We would prefer to eliminate those two
6875       // casts first.
6876       if (!isa<CastInst>(I->getOperand(0)))
6877         ++NumCastsRemoved;
6878       return true;
6879     }
6880   }
6881
6882   // We can't extend or shrink something that has multiple uses: doing so would
6883   // require duplicating the instruction in general, which isn't profitable.
6884   if (!I->hasOneUse()) return false;
6885
6886   switch (I->getOpcode()) {
6887   case Instruction::Add:
6888   case Instruction::Sub:
6889   case Instruction::And:
6890   case Instruction::Or:
6891   case Instruction::Xor:
6892     // These operators can all arbitrarily be extended or truncated.
6893     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6894                                       NumCastsRemoved) &&
6895            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6896                                       NumCastsRemoved);
6897
6898   case Instruction::Mul:
6899     // A multiply can be truncated by truncating its operands.
6900     return Ty->getBitWidth() < OrigTy->getBitWidth() && 
6901            CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6902                                       NumCastsRemoved) &&
6903            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6904                                       NumCastsRemoved);
6905
6906   case Instruction::Shl:
6907     // If we are truncating the result of this SHL, and if it's a shift of a
6908     // constant amount, we can always perform a SHL in a smaller type.
6909     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6910       uint32_t BitWidth = Ty->getBitWidth();
6911       if (BitWidth < OrigTy->getBitWidth() && 
6912           CI->getLimitedValue(BitWidth) < BitWidth)
6913         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6914                                           NumCastsRemoved);
6915     }
6916     break;
6917   case Instruction::LShr:
6918     // If this is a truncate of a logical shr, we can truncate it to a smaller
6919     // lshr iff we know that the bits we would otherwise be shifting in are
6920     // already zeros.
6921     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6922       uint32_t OrigBitWidth = OrigTy->getBitWidth();
6923       uint32_t BitWidth = Ty->getBitWidth();
6924       if (BitWidth < OrigBitWidth &&
6925           MaskedValueIsZero(I->getOperand(0),
6926             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6927           CI->getLimitedValue(BitWidth) < BitWidth) {
6928         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6929                                           NumCastsRemoved);
6930       }
6931     }
6932     break;
6933   case Instruction::ZExt:
6934   case Instruction::SExt:
6935   case Instruction::Trunc:
6936     // If this is the same kind of case as our original (e.g. zext+zext), we
6937     // can safely replace it.  Note that replacing it does not reduce the number
6938     // of casts in the input.
6939     if (I->getOpcode() == CastOpc)
6940       return true;
6941     
6942     break;
6943   default:
6944     // TODO: Can handle more cases here.
6945     break;
6946   }
6947   
6948   return false;
6949 }
6950
6951 /// EvaluateInDifferentType - Given an expression that 
6952 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6953 /// evaluate the expression.
6954 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
6955                                              bool isSigned) {
6956   if (Constant *C = dyn_cast<Constant>(V))
6957     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6958
6959   // Otherwise, it must be an instruction.
6960   Instruction *I = cast<Instruction>(V);
6961   Instruction *Res = 0;
6962   switch (I->getOpcode()) {
6963   case Instruction::Add:
6964   case Instruction::Sub:
6965   case Instruction::Mul:
6966   case Instruction::And:
6967   case Instruction::Or:
6968   case Instruction::Xor:
6969   case Instruction::AShr:
6970   case Instruction::LShr:
6971   case Instruction::Shl: {
6972     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6973     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6974     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
6975                                  LHS, RHS, I->getName());
6976     break;
6977   }    
6978   case Instruction::Trunc:
6979   case Instruction::ZExt:
6980   case Instruction::SExt:
6981     // If the source type of the cast is the type we're trying for then we can
6982     // just return the source.  There's no need to insert it because it is not
6983     // new.
6984     if (I->getOperand(0)->getType() == Ty)
6985       return I->getOperand(0);
6986     
6987     // Otherwise, must be the same type of case, so just reinsert a new one.
6988     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6989                            Ty, I->getName());
6990     break;
6991   default: 
6992     // TODO: Can handle more cases here.
6993     assert(0 && "Unreachable!");
6994     break;
6995   }
6996   
6997   return InsertNewInstBefore(Res, *I);
6998 }
6999
7000 /// @brief Implement the transforms common to all CastInst visitors.
7001 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7002   Value *Src = CI.getOperand(0);
7003
7004   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7005   // eliminate it now.
7006   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7007     if (Instruction::CastOps opc = 
7008         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7009       // The first cast (CSrc) is eliminable so we need to fix up or replace
7010       // the second cast (CI). CSrc will then have a good chance of being dead.
7011       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7012     }
7013   }
7014
7015   // If we are casting a select then fold the cast into the select
7016   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7017     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7018       return NV;
7019
7020   // If we are casting a PHI then fold the cast into the PHI
7021   if (isa<PHINode>(Src))
7022     if (Instruction *NV = FoldOpIntoPhi(CI))
7023       return NV;
7024   
7025   return 0;
7026 }
7027
7028 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7029 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7030   Value *Src = CI.getOperand(0);
7031   
7032   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7033     // If casting the result of a getelementptr instruction with no offset, turn
7034     // this into a cast of the original pointer!
7035     if (GEP->hasAllZeroIndices()) {
7036       // Changing the cast operand is usually not a good idea but it is safe
7037       // here because the pointer operand is being replaced with another 
7038       // pointer operand so the opcode doesn't need to change.
7039       AddToWorkList(GEP);
7040       CI.setOperand(0, GEP->getOperand(0));
7041       return &CI;
7042     }
7043     
7044     // If the GEP has a single use, and the base pointer is a bitcast, and the
7045     // GEP computes a constant offset, see if we can convert these three
7046     // instructions into fewer.  This typically happens with unions and other
7047     // non-type-safe code.
7048     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7049       if (GEP->hasAllConstantIndices()) {
7050         // We are guaranteed to get a constant from EmitGEPOffset.
7051         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7052         int64_t Offset = OffsetV->getSExtValue();
7053         
7054         // Get the base pointer input of the bitcast, and the type it points to.
7055         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7056         const Type *GEPIdxTy =
7057           cast<PointerType>(OrigBase->getType())->getElementType();
7058         if (GEPIdxTy->isSized()) {
7059           SmallVector<Value*, 8> NewIndices;
7060           
7061           // Start with the index over the outer type.  Note that the type size
7062           // might be zero (even if the offset isn't zero) if the indexed type
7063           // is something like [0 x {int, int}]
7064           const Type *IntPtrTy = TD->getIntPtrType();
7065           int64_t FirstIdx = 0;
7066           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7067             FirstIdx = Offset/TySize;
7068             Offset %= TySize;
7069           
7070             // Handle silly modulus not returning values values [0..TySize).
7071             if (Offset < 0) {
7072               --FirstIdx;
7073               Offset += TySize;
7074               assert(Offset >= 0);
7075             }
7076             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7077           }
7078           
7079           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7080
7081           // Index into the types.  If we fail, set OrigBase to null.
7082           while (Offset) {
7083             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7084               const StructLayout *SL = TD->getStructLayout(STy);
7085               if (Offset < (int64_t)SL->getSizeInBytes()) {
7086                 unsigned Elt = SL->getElementContainingOffset(Offset);
7087                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7088               
7089                 Offset -= SL->getElementOffset(Elt);
7090                 GEPIdxTy = STy->getElementType(Elt);
7091               } else {
7092                 // Otherwise, we can't index into this, bail out.
7093                 Offset = 0;
7094                 OrigBase = 0;
7095               }
7096             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7097               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7098               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7099                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7100                 Offset %= EltSize;
7101               } else {
7102                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7103               }
7104               GEPIdxTy = STy->getElementType();
7105             } else {
7106               // Otherwise, we can't index into this, bail out.
7107               Offset = 0;
7108               OrigBase = 0;
7109             }
7110           }
7111           if (OrigBase) {
7112             // If we were able to index down into an element, create the GEP
7113             // and bitcast the result.  This eliminates one bitcast, potentially
7114             // two.
7115             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7116                                                           NewIndices.begin(),
7117                                                           NewIndices.end(), "");
7118             InsertNewInstBefore(NGEP, CI);
7119             NGEP->takeName(GEP);
7120             
7121             if (isa<BitCastInst>(CI))
7122               return new BitCastInst(NGEP, CI.getType());
7123             assert(isa<PtrToIntInst>(CI));
7124             return new PtrToIntInst(NGEP, CI.getType());
7125           }
7126         }
7127       }      
7128     }
7129   }
7130     
7131   return commonCastTransforms(CI);
7132 }
7133
7134
7135
7136 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7137 /// integer types. This function implements the common transforms for all those
7138 /// cases.
7139 /// @brief Implement the transforms common to CastInst with integer operands
7140 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7141   if (Instruction *Result = commonCastTransforms(CI))
7142     return Result;
7143
7144   Value *Src = CI.getOperand(0);
7145   const Type *SrcTy = Src->getType();
7146   const Type *DestTy = CI.getType();
7147   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7148   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7149
7150   // See if we can simplify any instructions used by the LHS whose sole 
7151   // purpose is to compute bits we don't care about.
7152   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7153   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7154                            KnownZero, KnownOne))
7155     return &CI;
7156
7157   // If the source isn't an instruction or has more than one use then we
7158   // can't do anything more. 
7159   Instruction *SrcI = dyn_cast<Instruction>(Src);
7160   if (!SrcI || !Src->hasOneUse())
7161     return 0;
7162
7163   // Attempt to propagate the cast into the instruction for int->int casts.
7164   int NumCastsRemoved = 0;
7165   if (!isa<BitCastInst>(CI) &&
7166       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7167                                  CI.getOpcode(), NumCastsRemoved)) {
7168     // If this cast is a truncate, evaluting in a different type always
7169     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7170     // we need to do an AND to maintain the clear top-part of the computation,
7171     // so we require that the input have eliminated at least one cast.  If this
7172     // is a sign extension, we insert two new casts (to do the extension) so we
7173     // require that two casts have been eliminated.
7174     bool DoXForm;
7175     switch (CI.getOpcode()) {
7176     default:
7177       // All the others use floating point so we shouldn't actually 
7178       // get here because of the check above.
7179       assert(0 && "Unknown cast type");
7180     case Instruction::Trunc:
7181       DoXForm = true;
7182       break;
7183     case Instruction::ZExt:
7184       DoXForm = NumCastsRemoved >= 1;
7185       break;
7186     case Instruction::SExt:
7187       DoXForm = NumCastsRemoved >= 2;
7188       break;
7189     }
7190     
7191     if (DoXForm) {
7192       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7193                                            CI.getOpcode() == Instruction::SExt);
7194       assert(Res->getType() == DestTy);
7195       switch (CI.getOpcode()) {
7196       default: assert(0 && "Unknown cast type!");
7197       case Instruction::Trunc:
7198       case Instruction::BitCast:
7199         // Just replace this cast with the result.
7200         return ReplaceInstUsesWith(CI, Res);
7201       case Instruction::ZExt: {
7202         // We need to emit an AND to clear the high bits.
7203         assert(SrcBitSize < DestBitSize && "Not a zext?");
7204         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7205                                                             SrcBitSize));
7206         return BinaryOperator::CreateAnd(Res, C);
7207       }
7208       case Instruction::SExt:
7209         // We need to emit a cast to truncate, then a cast to sext.
7210         return CastInst::Create(Instruction::SExt,
7211             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7212                              CI), DestTy);
7213       }
7214     }
7215   }
7216   
7217   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7218   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7219
7220   switch (SrcI->getOpcode()) {
7221   case Instruction::Add:
7222   case Instruction::Mul:
7223   case Instruction::And:
7224   case Instruction::Or:
7225   case Instruction::Xor:
7226     // If we are discarding information, rewrite.
7227     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7228       // Don't insert two casts if they cannot be eliminated.  We allow 
7229       // two casts to be inserted if the sizes are the same.  This could 
7230       // only be converting signedness, which is a noop.
7231       if (DestBitSize == SrcBitSize || 
7232           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7233           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7234         Instruction::CastOps opcode = CI.getOpcode();
7235         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7236         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7237         return BinaryOperator::Create(
7238             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7239       }
7240     }
7241
7242     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7243     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7244         SrcI->getOpcode() == Instruction::Xor &&
7245         Op1 == ConstantInt::getTrue() &&
7246         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7247       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7248       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7249     }
7250     break;
7251   case Instruction::SDiv:
7252   case Instruction::UDiv:
7253   case Instruction::SRem:
7254   case Instruction::URem:
7255     // If we are just changing the sign, rewrite.
7256     if (DestBitSize == SrcBitSize) {
7257       // Don't insert two casts if they cannot be eliminated.  We allow 
7258       // two casts to be inserted if the sizes are the same.  This could 
7259       // only be converting signedness, which is a noop.
7260       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7261           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7262         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7263                                               Op0, DestTy, SrcI);
7264         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7265                                               Op1, DestTy, SrcI);
7266         return BinaryOperator::Create(
7267           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7268       }
7269     }
7270     break;
7271
7272   case Instruction::Shl:
7273     // Allow changing the sign of the source operand.  Do not allow 
7274     // changing the size of the shift, UNLESS the shift amount is a 
7275     // constant.  We must not change variable sized shifts to a smaller 
7276     // size, because it is undefined to shift more bits out than exist 
7277     // in the value.
7278     if (DestBitSize == SrcBitSize ||
7279         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7280       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7281           Instruction::BitCast : Instruction::Trunc);
7282       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7283       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7284       return BinaryOperator::CreateShl(Op0c, Op1c);
7285     }
7286     break;
7287   case Instruction::AShr:
7288     // If this is a signed shr, and if all bits shifted in are about to be
7289     // truncated off, turn it into an unsigned shr to allow greater
7290     // simplifications.
7291     if (DestBitSize < SrcBitSize &&
7292         isa<ConstantInt>(Op1)) {
7293       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7294       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7295         // Insert the new logical shift right.
7296         return BinaryOperator::CreateLShr(Op0, Op1);
7297       }
7298     }
7299     break;
7300   }
7301   return 0;
7302 }
7303
7304 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7305   if (Instruction *Result = commonIntCastTransforms(CI))
7306     return Result;
7307   
7308   Value *Src = CI.getOperand(0);
7309   const Type *Ty = CI.getType();
7310   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7311   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7312   
7313   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7314     switch (SrcI->getOpcode()) {
7315     default: break;
7316     case Instruction::LShr:
7317       // We can shrink lshr to something smaller if we know the bits shifted in
7318       // are already zeros.
7319       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7320         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7321         
7322         // Get a mask for the bits shifting in.
7323         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7324         Value* SrcIOp0 = SrcI->getOperand(0);
7325         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7326           if (ShAmt >= DestBitWidth)        // All zeros.
7327             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7328
7329           // Okay, we can shrink this.  Truncate the input, then return a new
7330           // shift.
7331           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7332           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7333                                        Ty, CI);
7334           return BinaryOperator::CreateLShr(V1, V2);
7335         }
7336       } else {     // This is a variable shr.
7337         
7338         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7339         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7340         // loop-invariant and CSE'd.
7341         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7342           Value *One = ConstantInt::get(SrcI->getType(), 1);
7343
7344           Value *V = InsertNewInstBefore(
7345               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7346                                      "tmp"), CI);
7347           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7348                                                             SrcI->getOperand(0),
7349                                                             "tmp"), CI);
7350           Value *Zero = Constant::getNullValue(V->getType());
7351           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7352         }
7353       }
7354       break;
7355     }
7356   }
7357   
7358   return 0;
7359 }
7360
7361 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7362 /// in order to eliminate the icmp.
7363 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7364                                              bool DoXform) {
7365   // If we are just checking for a icmp eq of a single bit and zext'ing it
7366   // to an integer, then shift the bit to the appropriate place and then
7367   // cast to integer to avoid the comparison.
7368   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7369     const APInt &Op1CV = Op1C->getValue();
7370       
7371     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7372     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7373     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7374         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7375       if (!DoXform) return ICI;
7376
7377       Value *In = ICI->getOperand(0);
7378       Value *Sh = ConstantInt::get(In->getType(),
7379                                    In->getType()->getPrimitiveSizeInBits()-1);
7380       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7381                                                         In->getName()+".lobit"),
7382                                CI);
7383       if (In->getType() != CI.getType())
7384         In = CastInst::CreateIntegerCast(In, CI.getType(),
7385                                          false/*ZExt*/, "tmp", &CI);
7386
7387       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7388         Constant *One = ConstantInt::get(In->getType(), 1);
7389         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7390                                                          In->getName()+".not"),
7391                                  CI);
7392       }
7393
7394       return ReplaceInstUsesWith(CI, In);
7395     }
7396       
7397       
7398       
7399     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7400     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7401     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7402     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7403     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7404     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7405     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7406     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7407     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7408         // This only works for EQ and NE
7409         ICI->isEquality()) {
7410       // If Op1C some other power of two, convert:
7411       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7412       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7413       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7414       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7415         
7416       APInt KnownZeroMask(~KnownZero);
7417       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7418         if (!DoXform) return ICI;
7419
7420         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7421         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7422           // (X&4) == 2 --> false
7423           // (X&4) != 2 --> true
7424           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7425           Res = ConstantExpr::getZExt(Res, CI.getType());
7426           return ReplaceInstUsesWith(CI, Res);
7427         }
7428           
7429         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7430         Value *In = ICI->getOperand(0);
7431         if (ShiftAmt) {
7432           // Perform a logical shr by shiftamt.
7433           // Insert the shift to put the result in the low bit.
7434           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7435                                   ConstantInt::get(In->getType(), ShiftAmt),
7436                                                    In->getName()+".lobit"), CI);
7437         }
7438           
7439         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7440           Constant *One = ConstantInt::get(In->getType(), 1);
7441           In = BinaryOperator::CreateXor(In, One, "tmp");
7442           InsertNewInstBefore(cast<Instruction>(In), CI);
7443         }
7444           
7445         if (CI.getType() == In->getType())
7446           return ReplaceInstUsesWith(CI, In);
7447         else
7448           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7449       }
7450     }
7451   }
7452
7453   return 0;
7454 }
7455
7456 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7457   // If one of the common conversion will work ..
7458   if (Instruction *Result = commonIntCastTransforms(CI))
7459     return Result;
7460
7461   Value *Src = CI.getOperand(0);
7462
7463   // If this is a cast of a cast
7464   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7465     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7466     // types and if the sizes are just right we can convert this into a logical
7467     // 'and' which will be much cheaper than the pair of casts.
7468     if (isa<TruncInst>(CSrc)) {
7469       // Get the sizes of the types involved
7470       Value *A = CSrc->getOperand(0);
7471       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7472       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7473       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7474       // If we're actually extending zero bits and the trunc is a no-op
7475       if (MidSize < DstSize && SrcSize == DstSize) {
7476         // Replace both of the casts with an And of the type mask.
7477         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7478         Constant *AndConst = ConstantInt::get(AndValue);
7479         Instruction *And = 
7480           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7481         // Unfortunately, if the type changed, we need to cast it back.
7482         if (And->getType() != CI.getType()) {
7483           And->setName(CSrc->getName()+".mask");
7484           InsertNewInstBefore(And, CI);
7485           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7486         }
7487         return And;
7488       }
7489     }
7490   }
7491
7492   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7493     return transformZExtICmp(ICI, CI);
7494
7495   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7496   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7497     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7498     // of the (zext icmp) will be transformed.
7499     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7500     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7501     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7502         (transformZExtICmp(LHS, CI, false) ||
7503          transformZExtICmp(RHS, CI, false))) {
7504       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7505       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7506       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7507     }
7508   }
7509
7510   return 0;
7511 }
7512
7513 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7514   if (Instruction *I = commonIntCastTransforms(CI))
7515     return I;
7516   
7517   Value *Src = CI.getOperand(0);
7518   
7519   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7520   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7521   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7522     // If we are just checking for a icmp eq of a single bit and zext'ing it
7523     // to an integer, then shift the bit to the appropriate place and then
7524     // cast to integer to avoid the comparison.
7525     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7526       const APInt &Op1CV = Op1C->getValue();
7527       
7528       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7529       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7530       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7531           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7532         Value *In = ICI->getOperand(0);
7533         Value *Sh = ConstantInt::get(In->getType(),
7534                                      In->getType()->getPrimitiveSizeInBits()-1);
7535         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7536                                                         In->getName()+".lobit"),
7537                                  CI);
7538         if (In->getType() != CI.getType())
7539           In = CastInst::CreateIntegerCast(In, CI.getType(),
7540                                            true/*SExt*/, "tmp", &CI);
7541         
7542         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7543           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7544                                      In->getName()+".not"), CI);
7545         
7546         return ReplaceInstUsesWith(CI, In);
7547       }
7548     }
7549   }
7550
7551   // See if the value being truncated is already sign extended.  If so, just
7552   // eliminate the trunc/sext pair.
7553   if (getOpcode(Src) == Instruction::Trunc) {
7554     Value *Op = cast<User>(Src)->getOperand(0);
7555     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7556     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7557     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7558     unsigned NumSignBits = ComputeNumSignBits(Op);
7559
7560     if (OpBits == DestBits) {
7561       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7562       // bits, it is already ready.
7563       if (NumSignBits > DestBits-MidBits)
7564         return ReplaceInstUsesWith(CI, Op);
7565     } else if (OpBits < DestBits) {
7566       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7567       // bits, just sext from i32.
7568       if (NumSignBits > OpBits-MidBits)
7569         return new SExtInst(Op, CI.getType(), "tmp");
7570     } else {
7571       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7572       // bits, just truncate to i32.
7573       if (NumSignBits > OpBits-MidBits)
7574         return new TruncInst(Op, CI.getType(), "tmp");
7575     }
7576   }
7577       
7578   return 0;
7579 }
7580
7581 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7582 /// in the specified FP type without changing its value.
7583 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7584   APFloat F = CFP->getValueAPF();
7585   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7586     return ConstantFP::get(F);
7587   return 0;
7588 }
7589
7590 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7591 /// through it until we get the source value.
7592 static Value *LookThroughFPExtensions(Value *V) {
7593   if (Instruction *I = dyn_cast<Instruction>(V))
7594     if (I->getOpcode() == Instruction::FPExt)
7595       return LookThroughFPExtensions(I->getOperand(0));
7596   
7597   // If this value is a constant, return the constant in the smallest FP type
7598   // that can accurately represent it.  This allows us to turn
7599   // (float)((double)X+2.0) into x+2.0f.
7600   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7601     if (CFP->getType() == Type::PPC_FP128Ty)
7602       return V;  // No constant folding of this.
7603     // See if the value can be truncated to float and then reextended.
7604     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7605       return V;
7606     if (CFP->getType() == Type::DoubleTy)
7607       return V;  // Won't shrink.
7608     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7609       return V;
7610     // Don't try to shrink to various long double types.
7611   }
7612   
7613   return V;
7614 }
7615
7616 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7617   if (Instruction *I = commonCastTransforms(CI))
7618     return I;
7619   
7620   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7621   // smaller than the destination type, we can eliminate the truncate by doing
7622   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7623   // many builtins (sqrt, etc).
7624   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7625   if (OpI && OpI->hasOneUse()) {
7626     switch (OpI->getOpcode()) {
7627     default: break;
7628     case Instruction::Add:
7629     case Instruction::Sub:
7630     case Instruction::Mul:
7631     case Instruction::FDiv:
7632     case Instruction::FRem:
7633       const Type *SrcTy = OpI->getType();
7634       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7635       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7636       if (LHSTrunc->getType() != SrcTy && 
7637           RHSTrunc->getType() != SrcTy) {
7638         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7639         // If the source types were both smaller than the destination type of
7640         // the cast, do this xform.
7641         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7642             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7643           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7644                                       CI.getType(), CI);
7645           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7646                                       CI.getType(), CI);
7647           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7648         }
7649       }
7650       break;  
7651     }
7652   }
7653   return 0;
7654 }
7655
7656 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7657   return commonCastTransforms(CI);
7658 }
7659
7660 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7661   // fptoui(uitofp(X)) --> X  if the intermediate type has enough bits in its
7662   // mantissa to accurately represent all values of X.  For example, do not
7663   // do this with i64->float->i64.
7664   if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7665     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7666         (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7667                     SrcI->getType()->getFPMantissaWidth())
7668       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7669
7670   return commonCastTransforms(FI);
7671 }
7672
7673 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7674   // fptosi(sitofp(X)) --> X  if the intermediate type has enough bits in its
7675   // mantissa to accurately represent all values of X.  For example, do not
7676   // do this with i64->float->i64.
7677   if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7678     if (SrcI->getOperand(0)->getType() == FI.getType() &&
7679         (int)FI.getType()->getPrimitiveSizeInBits() <= 
7680                     SrcI->getType()->getFPMantissaWidth())
7681       return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7682   
7683   return commonCastTransforms(FI);
7684 }
7685
7686 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7687   return commonCastTransforms(CI);
7688 }
7689
7690 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7691   return commonCastTransforms(CI);
7692 }
7693
7694 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7695   return commonPointerCastTransforms(CI);
7696 }
7697
7698 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7699   if (Instruction *I = commonCastTransforms(CI))
7700     return I;
7701   
7702   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7703   if (!DestPointee->isSized()) return 0;
7704
7705   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7706   ConstantInt *Cst;
7707   Value *X;
7708   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7709                                     m_ConstantInt(Cst)))) {
7710     // If the source and destination operands have the same type, see if this
7711     // is a single-index GEP.
7712     if (X->getType() == CI.getType()) {
7713       // Get the size of the pointee type.
7714       uint64_t Size = TD->getABITypeSize(DestPointee);
7715
7716       // Convert the constant to intptr type.
7717       APInt Offset = Cst->getValue();
7718       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7719
7720       // If Offset is evenly divisible by Size, we can do this xform.
7721       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7722         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7723         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7724       }
7725     }
7726     // TODO: Could handle other cases, e.g. where add is indexing into field of
7727     // struct etc.
7728   } else if (CI.getOperand(0)->hasOneUse() &&
7729              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7730     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7731     // "inttoptr+GEP" instead of "add+intptr".
7732     
7733     // Get the size of the pointee type.
7734     uint64_t Size = TD->getABITypeSize(DestPointee);
7735     
7736     // Convert the constant to intptr type.
7737     APInt Offset = Cst->getValue();
7738     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7739     
7740     // If Offset is evenly divisible by Size, we can do this xform.
7741     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7742       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7743       
7744       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7745                                                             "tmp"), CI);
7746       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7747     }
7748   }
7749   return 0;
7750 }
7751
7752 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7753   // If the operands are integer typed then apply the integer transforms,
7754   // otherwise just apply the common ones.
7755   Value *Src = CI.getOperand(0);
7756   const Type *SrcTy = Src->getType();
7757   const Type *DestTy = CI.getType();
7758
7759   if (SrcTy->isInteger() && DestTy->isInteger()) {
7760     if (Instruction *Result = commonIntCastTransforms(CI))
7761       return Result;
7762   } else if (isa<PointerType>(SrcTy)) {
7763     if (Instruction *I = commonPointerCastTransforms(CI))
7764       return I;
7765   } else {
7766     if (Instruction *Result = commonCastTransforms(CI))
7767       return Result;
7768   }
7769
7770
7771   // Get rid of casts from one type to the same type. These are useless and can
7772   // be replaced by the operand.
7773   if (DestTy == Src->getType())
7774     return ReplaceInstUsesWith(CI, Src);
7775
7776   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7777     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7778     const Type *DstElTy = DstPTy->getElementType();
7779     const Type *SrcElTy = SrcPTy->getElementType();
7780     
7781     // If the address spaces don't match, don't eliminate the bitcast, which is
7782     // required for changing types.
7783     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7784       return 0;
7785     
7786     // If we are casting a malloc or alloca to a pointer to a type of the same
7787     // size, rewrite the allocation instruction to allocate the "right" type.
7788     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7789       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7790         return V;
7791     
7792     // If the source and destination are pointers, and this cast is equivalent
7793     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
7794     // This can enhance SROA and other transforms that want type-safe pointers.
7795     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7796     unsigned NumZeros = 0;
7797     while (SrcElTy != DstElTy && 
7798            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7799            SrcElTy->getNumContainedTypes() /* not "{}" */) {
7800       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7801       ++NumZeros;
7802     }
7803
7804     // If we found a path from the src to dest, create the getelementptr now.
7805     if (SrcElTy == DstElTy) {
7806       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7807       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
7808                                        ((Instruction*) NULL));
7809     }
7810   }
7811
7812   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7813     if (SVI->hasOneUse()) {
7814       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
7815       // a bitconvert to a vector with the same # elts.
7816       if (isa<VectorType>(DestTy) && 
7817           cast<VectorType>(DestTy)->getNumElements() == 
7818                 SVI->getType()->getNumElements()) {
7819         CastInst *Tmp;
7820         // If either of the operands is a cast from CI.getType(), then
7821         // evaluating the shuffle in the casted destination's type will allow
7822         // us to eliminate at least one cast.
7823         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
7824              Tmp->getOperand(0)->getType() == DestTy) ||
7825             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
7826              Tmp->getOperand(0)->getType() == DestTy)) {
7827           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7828                                                SVI->getOperand(0), DestTy, &CI);
7829           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7830                                                SVI->getOperand(1), DestTy, &CI);
7831           // Return a new shuffle vector.  Use the same element ID's, as we
7832           // know the vector types match #elts.
7833           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7834         }
7835       }
7836     }
7837   }
7838   return 0;
7839 }
7840
7841 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7842 ///   %C = or %A, %B
7843 ///   %D = select %cond, %C, %A
7844 /// into:
7845 ///   %C = select %cond, %B, 0
7846 ///   %D = or %A, %C
7847 ///
7848 /// Assuming that the specified instruction is an operand to the select, return
7849 /// a bitmask indicating which operands of this instruction are foldable if they
7850 /// equal the other incoming value of the select.
7851 ///
7852 static unsigned GetSelectFoldableOperands(Instruction *I) {
7853   switch (I->getOpcode()) {
7854   case Instruction::Add:
7855   case Instruction::Mul:
7856   case Instruction::And:
7857   case Instruction::Or:
7858   case Instruction::Xor:
7859     return 3;              // Can fold through either operand.
7860   case Instruction::Sub:   // Can only fold on the amount subtracted.
7861   case Instruction::Shl:   // Can only fold on the shift amount.
7862   case Instruction::LShr:
7863   case Instruction::AShr:
7864     return 1;
7865   default:
7866     return 0;              // Cannot fold
7867   }
7868 }
7869
7870 /// GetSelectFoldableConstant - For the same transformation as the previous
7871 /// function, return the identity constant that goes into the select.
7872 static Constant *GetSelectFoldableConstant(Instruction *I) {
7873   switch (I->getOpcode()) {
7874   default: assert(0 && "This cannot happen!"); abort();
7875   case Instruction::Add:
7876   case Instruction::Sub:
7877   case Instruction::Or:
7878   case Instruction::Xor:
7879   case Instruction::Shl:
7880   case Instruction::LShr:
7881   case Instruction::AShr:
7882     return Constant::getNullValue(I->getType());
7883   case Instruction::And:
7884     return Constant::getAllOnesValue(I->getType());
7885   case Instruction::Mul:
7886     return ConstantInt::get(I->getType(), 1);
7887   }
7888 }
7889
7890 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7891 /// have the same opcode and only one use each.  Try to simplify this.
7892 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7893                                           Instruction *FI) {
7894   if (TI->getNumOperands() == 1) {
7895     // If this is a non-volatile load or a cast from the same type,
7896     // merge.
7897     if (TI->isCast()) {
7898       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7899         return 0;
7900     } else {
7901       return 0;  // unknown unary op.
7902     }
7903
7904     // Fold this by inserting a select from the input values.
7905     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7906                                            FI->getOperand(0), SI.getName()+".v");
7907     InsertNewInstBefore(NewSI, SI);
7908     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
7909                             TI->getType());
7910   }
7911
7912   // Only handle binary operators here.
7913   if (!isa<BinaryOperator>(TI))
7914     return 0;
7915
7916   // Figure out if the operations have any operands in common.
7917   Value *MatchOp, *OtherOpT, *OtherOpF;
7918   bool MatchIsOpZero;
7919   if (TI->getOperand(0) == FI->getOperand(0)) {
7920     MatchOp  = TI->getOperand(0);
7921     OtherOpT = TI->getOperand(1);
7922     OtherOpF = FI->getOperand(1);
7923     MatchIsOpZero = true;
7924   } else if (TI->getOperand(1) == FI->getOperand(1)) {
7925     MatchOp  = TI->getOperand(1);
7926     OtherOpT = TI->getOperand(0);
7927     OtherOpF = FI->getOperand(0);
7928     MatchIsOpZero = false;
7929   } else if (!TI->isCommutative()) {
7930     return 0;
7931   } else if (TI->getOperand(0) == FI->getOperand(1)) {
7932     MatchOp  = TI->getOperand(0);
7933     OtherOpT = TI->getOperand(1);
7934     OtherOpF = FI->getOperand(0);
7935     MatchIsOpZero = true;
7936   } else if (TI->getOperand(1) == FI->getOperand(0)) {
7937     MatchOp  = TI->getOperand(1);
7938     OtherOpT = TI->getOperand(0);
7939     OtherOpF = FI->getOperand(1);
7940     MatchIsOpZero = true;
7941   } else {
7942     return 0;
7943   }
7944
7945   // If we reach here, they do have operations in common.
7946   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
7947                                          OtherOpF, SI.getName()+".v");
7948   InsertNewInstBefore(NewSI, SI);
7949
7950   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7951     if (MatchIsOpZero)
7952       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
7953     else
7954       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
7955   }
7956   assert(0 && "Shouldn't get here");
7957   return 0;
7958 }
7959
7960 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7961   Value *CondVal = SI.getCondition();
7962   Value *TrueVal = SI.getTrueValue();
7963   Value *FalseVal = SI.getFalseValue();
7964
7965   // select true, X, Y  -> X
7966   // select false, X, Y -> Y
7967   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7968     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7969
7970   // select C, X, X -> X
7971   if (TrueVal == FalseVal)
7972     return ReplaceInstUsesWith(SI, TrueVal);
7973
7974   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
7975     return ReplaceInstUsesWith(SI, FalseVal);
7976   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
7977     return ReplaceInstUsesWith(SI, TrueVal);
7978   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
7979     if (isa<Constant>(TrueVal))
7980       return ReplaceInstUsesWith(SI, TrueVal);
7981     else
7982       return ReplaceInstUsesWith(SI, FalseVal);
7983   }
7984
7985   if (SI.getType() == Type::Int1Ty) {
7986     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7987       if (C->getZExtValue()) {
7988         // Change: A = select B, true, C --> A = or B, C
7989         return BinaryOperator::CreateOr(CondVal, FalseVal);
7990       } else {
7991         // Change: A = select B, false, C --> A = and !B, C
7992         Value *NotCond =
7993           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
7994                                              "not."+CondVal->getName()), SI);
7995         return BinaryOperator::CreateAnd(NotCond, FalseVal);
7996       }
7997     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7998       if (C->getZExtValue() == false) {
7999         // Change: A = select B, C, false --> A = and B, C
8000         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8001       } else {
8002         // Change: A = select B, C, true --> A = or !B, C
8003         Value *NotCond =
8004           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8005                                              "not."+CondVal->getName()), SI);
8006         return BinaryOperator::CreateOr(NotCond, TrueVal);
8007       }
8008     }
8009     
8010     // select a, b, a  -> a&b
8011     // select a, a, b  -> a|b
8012     if (CondVal == TrueVal)
8013       return BinaryOperator::CreateOr(CondVal, FalseVal);
8014     else if (CondVal == FalseVal)
8015       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8016   }
8017
8018   // Selecting between two integer constants?
8019   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8020     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8021       // select C, 1, 0 -> zext C to int
8022       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8023         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8024       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8025         // select C, 0, 1 -> zext !C to int
8026         Value *NotCond =
8027           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8028                                                "not."+CondVal->getName()), SI);
8029         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8030       }
8031       
8032       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8033
8034       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8035
8036         // (x <s 0) ? -1 : 0 -> ashr x, 31
8037         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8038           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8039             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8040               // The comparison constant and the result are not neccessarily the
8041               // same width. Make an all-ones value by inserting a AShr.
8042               Value *X = IC->getOperand(0);
8043               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8044               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8045               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8046                                                         ShAmt, "ones");
8047               InsertNewInstBefore(SRA, SI);
8048               
8049               // Finally, convert to the type of the select RHS.  We figure out
8050               // if this requires a SExt, Trunc or BitCast based on the sizes.
8051               Instruction::CastOps opc = Instruction::BitCast;
8052               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8053               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8054               if (SRASize < SISize)
8055                 opc = Instruction::SExt;
8056               else if (SRASize > SISize)
8057                 opc = Instruction::Trunc;
8058               return CastInst::Create(opc, SRA, SI.getType());
8059             }
8060           }
8061
8062
8063         // If one of the constants is zero (we know they can't both be) and we
8064         // have an icmp instruction with zero, and we have an 'and' with the
8065         // non-constant value, eliminate this whole mess.  This corresponds to
8066         // cases like this: ((X & 27) ? 27 : 0)
8067         if (TrueValC->isZero() || FalseValC->isZero())
8068           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8069               cast<Constant>(IC->getOperand(1))->isNullValue())
8070             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8071               if (ICA->getOpcode() == Instruction::And &&
8072                   isa<ConstantInt>(ICA->getOperand(1)) &&
8073                   (ICA->getOperand(1) == TrueValC ||
8074                    ICA->getOperand(1) == FalseValC) &&
8075                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8076                 // Okay, now we know that everything is set up, we just don't
8077                 // know whether we have a icmp_ne or icmp_eq and whether the 
8078                 // true or false val is the zero.
8079                 bool ShouldNotVal = !TrueValC->isZero();
8080                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8081                 Value *V = ICA;
8082                 if (ShouldNotVal)
8083                   V = InsertNewInstBefore(BinaryOperator::Create(
8084                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8085                 return ReplaceInstUsesWith(SI, V);
8086               }
8087       }
8088     }
8089
8090   // See if we are selecting two values based on a comparison of the two values.
8091   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8092     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8093       // Transform (X == Y) ? X : Y  -> Y
8094       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8095         // This is not safe in general for floating point:  
8096         // consider X== -0, Y== +0.
8097         // It becomes safe if either operand is a nonzero constant.
8098         ConstantFP *CFPt, *CFPf;
8099         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8100               !CFPt->getValueAPF().isZero()) ||
8101             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8102              !CFPf->getValueAPF().isZero()))
8103         return ReplaceInstUsesWith(SI, FalseVal);
8104       }
8105       // Transform (X != Y) ? X : Y  -> X
8106       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8107         return ReplaceInstUsesWith(SI, TrueVal);
8108       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8109
8110     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8111       // Transform (X == Y) ? Y : X  -> X
8112       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8113         // This is not safe in general for floating point:  
8114         // consider X== -0, Y== +0.
8115         // It becomes safe if either operand is a nonzero constant.
8116         ConstantFP *CFPt, *CFPf;
8117         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8118               !CFPt->getValueAPF().isZero()) ||
8119             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8120              !CFPf->getValueAPF().isZero()))
8121           return ReplaceInstUsesWith(SI, FalseVal);
8122       }
8123       // Transform (X != Y) ? Y : X  -> Y
8124       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8125         return ReplaceInstUsesWith(SI, TrueVal);
8126       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8127     }
8128   }
8129
8130   // See if we are selecting two values based on a comparison of the two values.
8131   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8132     if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8133       // Transform (X == Y) ? X : Y  -> Y
8134       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8135         return ReplaceInstUsesWith(SI, FalseVal);
8136       // Transform (X != Y) ? X : Y  -> X
8137       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8138         return ReplaceInstUsesWith(SI, TrueVal);
8139       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8140
8141     } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8142       // Transform (X == Y) ? Y : X  -> X
8143       if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8144         return ReplaceInstUsesWith(SI, FalseVal);
8145       // Transform (X != Y) ? Y : X  -> Y
8146       if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8147         return ReplaceInstUsesWith(SI, TrueVal);
8148       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8149     }
8150   }
8151
8152   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8153     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8154       if (TI->hasOneUse() && FI->hasOneUse()) {
8155         Instruction *AddOp = 0, *SubOp = 0;
8156
8157         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8158         if (TI->getOpcode() == FI->getOpcode())
8159           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8160             return IV;
8161
8162         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8163         // even legal for FP.
8164         if (TI->getOpcode() == Instruction::Sub &&
8165             FI->getOpcode() == Instruction::Add) {
8166           AddOp = FI; SubOp = TI;
8167         } else if (FI->getOpcode() == Instruction::Sub &&
8168                    TI->getOpcode() == Instruction::Add) {
8169           AddOp = TI; SubOp = FI;
8170         }
8171
8172         if (AddOp) {
8173           Value *OtherAddOp = 0;
8174           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8175             OtherAddOp = AddOp->getOperand(1);
8176           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8177             OtherAddOp = AddOp->getOperand(0);
8178           }
8179
8180           if (OtherAddOp) {
8181             // So at this point we know we have (Y -> OtherAddOp):
8182             //        select C, (add X, Y), (sub X, Z)
8183             Value *NegVal;  // Compute -Z
8184             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8185               NegVal = ConstantExpr::getNeg(C);
8186             } else {
8187               NegVal = InsertNewInstBefore(
8188                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8189             }
8190
8191             Value *NewTrueOp = OtherAddOp;
8192             Value *NewFalseOp = NegVal;
8193             if (AddOp != TI)
8194               std::swap(NewTrueOp, NewFalseOp);
8195             Instruction *NewSel =
8196               SelectInst::Create(CondVal, NewTrueOp,
8197                                  NewFalseOp, SI.getName() + ".p");
8198
8199             NewSel = InsertNewInstBefore(NewSel, SI);
8200             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8201           }
8202         }
8203       }
8204
8205   // See if we can fold the select into one of our operands.
8206   if (SI.getType()->isInteger()) {
8207     // See the comment above GetSelectFoldableOperands for a description of the
8208     // transformation we are doing here.
8209     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8210       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8211           !isa<Constant>(FalseVal))
8212         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8213           unsigned OpToFold = 0;
8214           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8215             OpToFold = 1;
8216           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8217             OpToFold = 2;
8218           }
8219
8220           if (OpToFold) {
8221             Constant *C = GetSelectFoldableConstant(TVI);
8222             Instruction *NewSel =
8223               SelectInst::Create(SI.getCondition(),
8224                                  TVI->getOperand(2-OpToFold), C);
8225             InsertNewInstBefore(NewSel, SI);
8226             NewSel->takeName(TVI);
8227             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8228               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8229             else {
8230               assert(0 && "Unknown instruction!!");
8231             }
8232           }
8233         }
8234
8235     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8236       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8237           !isa<Constant>(TrueVal))
8238         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8239           unsigned OpToFold = 0;
8240           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8241             OpToFold = 1;
8242           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8243             OpToFold = 2;
8244           }
8245
8246           if (OpToFold) {
8247             Constant *C = GetSelectFoldableConstant(FVI);
8248             Instruction *NewSel =
8249               SelectInst::Create(SI.getCondition(), C,
8250                                  FVI->getOperand(2-OpToFold));
8251             InsertNewInstBefore(NewSel, SI);
8252             NewSel->takeName(FVI);
8253             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8254               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8255             else
8256               assert(0 && "Unknown instruction!!");
8257           }
8258         }
8259   }
8260
8261   if (BinaryOperator::isNot(CondVal)) {
8262     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8263     SI.setOperand(1, FalseVal);
8264     SI.setOperand(2, TrueVal);
8265     return &SI;
8266   }
8267
8268   return 0;
8269 }
8270
8271 /// EnforceKnownAlignment - If the specified pointer points to an object that
8272 /// we control, modify the object's alignment to PrefAlign. This isn't
8273 /// often possible though. If alignment is important, a more reliable approach
8274 /// is to simply align all global variables and allocation instructions to
8275 /// their preferred alignment from the beginning.
8276 ///
8277 static unsigned EnforceKnownAlignment(Value *V,
8278                                       unsigned Align, unsigned PrefAlign) {
8279
8280   User *U = dyn_cast<User>(V);
8281   if (!U) return Align;
8282
8283   switch (getOpcode(U)) {
8284   default: break;
8285   case Instruction::BitCast:
8286     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8287   case Instruction::GetElementPtr: {
8288     // If all indexes are zero, it is just the alignment of the base pointer.
8289     bool AllZeroOperands = true;
8290     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8291       if (!isa<Constant>(*i) ||
8292           !cast<Constant>(*i)->isNullValue()) {
8293         AllZeroOperands = false;
8294         break;
8295       }
8296
8297     if (AllZeroOperands) {
8298       // Treat this like a bitcast.
8299       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8300     }
8301     break;
8302   }
8303   }
8304
8305   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8306     // If there is a large requested alignment and we can, bump up the alignment
8307     // of the global.
8308     if (!GV->isDeclaration()) {
8309       GV->setAlignment(PrefAlign);
8310       Align = PrefAlign;
8311     }
8312   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8313     // If there is a requested alignment and if this is an alloca, round up.  We
8314     // don't do this for malloc, because some systems can't respect the request.
8315     if (isa<AllocaInst>(AI)) {
8316       AI->setAlignment(PrefAlign);
8317       Align = PrefAlign;
8318     }
8319   }
8320
8321   return Align;
8322 }
8323
8324 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8325 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8326 /// and it is more than the alignment of the ultimate object, see if we can
8327 /// increase the alignment of the ultimate object, making this check succeed.
8328 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8329                                                   unsigned PrefAlign) {
8330   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8331                       sizeof(PrefAlign) * CHAR_BIT;
8332   APInt Mask = APInt::getAllOnesValue(BitWidth);
8333   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8334   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8335   unsigned TrailZ = KnownZero.countTrailingOnes();
8336   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8337
8338   if (PrefAlign > Align)
8339     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8340   
8341     // We don't need to make any adjustment.
8342   return Align;
8343 }
8344
8345 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8346   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8347   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8348   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8349   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8350
8351   if (CopyAlign < MinAlign) {
8352     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8353     return MI;
8354   }
8355   
8356   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8357   // load/store.
8358   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8359   if (MemOpLength == 0) return 0;
8360   
8361   // Source and destination pointer types are always "i8*" for intrinsic.  See
8362   // if the size is something we can handle with a single primitive load/store.
8363   // A single load+store correctly handles overlapping memory in the memmove
8364   // case.
8365   unsigned Size = MemOpLength->getZExtValue();
8366   if (Size == 0) return MI;  // Delete this mem transfer.
8367   
8368   if (Size > 8 || (Size&(Size-1)))
8369     return 0;  // If not 1/2/4/8 bytes, exit.
8370   
8371   // Use an integer load+store unless we can find something better.
8372   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8373   
8374   // Memcpy forces the use of i8* for the source and destination.  That means
8375   // that if you're using memcpy to move one double around, you'll get a cast
8376   // from double* to i8*.  We'd much rather use a double load+store rather than
8377   // an i64 load+store, here because this improves the odds that the source or
8378   // dest address will be promotable.  See if we can find a better type than the
8379   // integer datatype.
8380   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8381     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8382     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8383       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8384       // down through these levels if so.
8385       while (!SrcETy->isSingleValueType()) {
8386         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8387           if (STy->getNumElements() == 1)
8388             SrcETy = STy->getElementType(0);
8389           else
8390             break;
8391         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8392           if (ATy->getNumElements() == 1)
8393             SrcETy = ATy->getElementType();
8394           else
8395             break;
8396         } else
8397           break;
8398       }
8399       
8400       if (SrcETy->isSingleValueType())
8401         NewPtrTy = PointerType::getUnqual(SrcETy);
8402     }
8403   }
8404   
8405   
8406   // If the memcpy/memmove provides better alignment info than we can
8407   // infer, use it.
8408   SrcAlign = std::max(SrcAlign, CopyAlign);
8409   DstAlign = std::max(DstAlign, CopyAlign);
8410   
8411   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8412   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8413   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8414   InsertNewInstBefore(L, *MI);
8415   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8416
8417   // Set the size of the copy to 0, it will be deleted on the next iteration.
8418   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8419   return MI;
8420 }
8421
8422 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8423   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8424   if (MI->getAlignment()->getZExtValue() < Alignment) {
8425     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8426     return MI;
8427   }
8428   
8429   // Extract the length and alignment and fill if they are constant.
8430   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8431   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8432   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8433     return 0;
8434   uint64_t Len = LenC->getZExtValue();
8435   Alignment = MI->getAlignment()->getZExtValue();
8436   
8437   // If the length is zero, this is a no-op
8438   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8439   
8440   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8441   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8442     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8443     
8444     Value *Dest = MI->getDest();
8445     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8446
8447     // Alignment 0 is identity for alignment 1 for memset, but not store.
8448     if (Alignment == 0) Alignment = 1;
8449     
8450     // Extract the fill value and store.
8451     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8452     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8453                                       Alignment), *MI);
8454     
8455     // Set the size of the copy to 0, it will be deleted on the next iteration.
8456     MI->setLength(Constant::getNullValue(LenC->getType()));
8457     return MI;
8458   }
8459
8460   return 0;
8461 }
8462
8463
8464 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8465 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8466 /// the heavy lifting.
8467 ///
8468 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8469   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8470   if (!II) return visitCallSite(&CI);
8471   
8472   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8473   // visitCallSite.
8474   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8475     bool Changed = false;
8476
8477     // memmove/cpy/set of zero bytes is a noop.
8478     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8479       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8480
8481       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8482         if (CI->getZExtValue() == 1) {
8483           // Replace the instruction with just byte operations.  We would
8484           // transform other cases to loads/stores, but we don't know if
8485           // alignment is sufficient.
8486         }
8487     }
8488
8489     // If we have a memmove and the source operation is a constant global,
8490     // then the source and dest pointers can't alias, so we can change this
8491     // into a call to memcpy.
8492     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8493       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8494         if (GVSrc->isConstant()) {
8495           Module *M = CI.getParent()->getParent()->getParent();
8496           Intrinsic::ID MemCpyID;
8497           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8498             MemCpyID = Intrinsic::memcpy_i32;
8499           else
8500             MemCpyID = Intrinsic::memcpy_i64;
8501           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8502           Changed = true;
8503         }
8504
8505       // memmove(x,x,size) -> noop.
8506       if (MMI->getSource() == MMI->getDest())
8507         return EraseInstFromFunction(CI);
8508     }
8509
8510     // If we can determine a pointer alignment that is bigger than currently
8511     // set, update the alignment.
8512     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8513       if (Instruction *I = SimplifyMemTransfer(MI))
8514         return I;
8515     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8516       if (Instruction *I = SimplifyMemSet(MSI))
8517         return I;
8518     }
8519           
8520     if (Changed) return II;
8521   } else {
8522     switch (II->getIntrinsicID()) {
8523     default: break;
8524     case Intrinsic::ppc_altivec_lvx:
8525     case Intrinsic::ppc_altivec_lvxl:
8526     case Intrinsic::x86_sse_loadu_ps:
8527     case Intrinsic::x86_sse2_loadu_pd:
8528     case Intrinsic::x86_sse2_loadu_dq:
8529       // Turn PPC lvx     -> load if the pointer is known aligned.
8530       // Turn X86 loadups -> load if the pointer is known aligned.
8531       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8532         Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8533                                          PointerType::getUnqual(II->getType()),
8534                                          CI);
8535         return new LoadInst(Ptr);
8536       }
8537       break;
8538     case Intrinsic::ppc_altivec_stvx:
8539     case Intrinsic::ppc_altivec_stvxl:
8540       // Turn stvx -> store if the pointer is known aligned.
8541       if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8542         const Type *OpPtrTy = 
8543           PointerType::getUnqual(II->getOperand(1)->getType());
8544         Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8545         return new StoreInst(II->getOperand(1), Ptr);
8546       }
8547       break;
8548     case Intrinsic::x86_sse_storeu_ps:
8549     case Intrinsic::x86_sse2_storeu_pd:
8550     case Intrinsic::x86_sse2_storeu_dq:
8551     case Intrinsic::x86_sse2_storel_dq:
8552       // Turn X86 storeu -> store if the pointer is known aligned.
8553       if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8554         const Type *OpPtrTy = 
8555           PointerType::getUnqual(II->getOperand(2)->getType());
8556         Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8557         return new StoreInst(II->getOperand(2), Ptr);
8558       }
8559       break;
8560       
8561     case Intrinsic::x86_sse_cvttss2si: {
8562       // These intrinsics only demands the 0th element of its input vector.  If
8563       // we can simplify the input based on that, do so now.
8564       uint64_t UndefElts;
8565       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8566                                                 UndefElts)) {
8567         II->setOperand(1, V);
8568         return II;
8569       }
8570       break;
8571     }
8572       
8573     case Intrinsic::ppc_altivec_vperm:
8574       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8575       if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8576         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8577         
8578         // Check that all of the elements are integer constants or undefs.
8579         bool AllEltsOk = true;
8580         for (unsigned i = 0; i != 16; ++i) {
8581           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8582               !isa<UndefValue>(Mask->getOperand(i))) {
8583             AllEltsOk = false;
8584             break;
8585           }
8586         }
8587         
8588         if (AllEltsOk) {
8589           // Cast the input vectors to byte vectors.
8590           Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8591           Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8592           Value *Result = UndefValue::get(Op0->getType());
8593           
8594           // Only extract each element once.
8595           Value *ExtractedElts[32];
8596           memset(ExtractedElts, 0, sizeof(ExtractedElts));
8597           
8598           for (unsigned i = 0; i != 16; ++i) {
8599             if (isa<UndefValue>(Mask->getOperand(i)))
8600               continue;
8601             unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8602             Idx &= 31;  // Match the hardware behavior.
8603             
8604             if (ExtractedElts[Idx] == 0) {
8605               Instruction *Elt = 
8606                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8607               InsertNewInstBefore(Elt, CI);
8608               ExtractedElts[Idx] = Elt;
8609             }
8610           
8611             // Insert this value into the result vector.
8612             Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8613                                                i, "tmp");
8614             InsertNewInstBefore(cast<Instruction>(Result), CI);
8615           }
8616           return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8617         }
8618       }
8619       break;
8620
8621     case Intrinsic::stackrestore: {
8622       // If the save is right next to the restore, remove the restore.  This can
8623       // happen when variable allocas are DCE'd.
8624       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8625         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8626           BasicBlock::iterator BI = SS;
8627           if (&*++BI == II)
8628             return EraseInstFromFunction(CI);
8629         }
8630       }
8631       
8632       // Scan down this block to see if there is another stack restore in the
8633       // same block without an intervening call/alloca.
8634       BasicBlock::iterator BI = II;
8635       TerminatorInst *TI = II->getParent()->getTerminator();
8636       bool CannotRemove = false;
8637       for (++BI; &*BI != TI; ++BI) {
8638         if (isa<AllocaInst>(BI)) {
8639           CannotRemove = true;
8640           break;
8641         }
8642         if (isa<CallInst>(BI)) {
8643           if (!isa<IntrinsicInst>(BI)) {
8644             CannotRemove = true;
8645             break;
8646           }
8647           // If there is a stackrestore below this one, remove this one.
8648           return EraseInstFromFunction(CI);
8649         }
8650       }
8651       
8652       // If the stack restore is in a return/unwind block and if there are no
8653       // allocas or calls between the restore and the return, nuke the restore.
8654       if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8655         return EraseInstFromFunction(CI);
8656       break;
8657     }
8658     }
8659   }
8660
8661   return visitCallSite(II);
8662 }
8663
8664 // InvokeInst simplification
8665 //
8666 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8667   return visitCallSite(&II);
8668 }
8669
8670 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8671 /// passed through the varargs area, we can eliminate the use of the cast.
8672 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8673                                          const CastInst * const CI,
8674                                          const TargetData * const TD,
8675                                          const int ix) {
8676   if (!CI->isLosslessCast())
8677     return false;
8678
8679   // The size of ByVal arguments is derived from the type, so we
8680   // can't change to a type with a different size.  If the size were
8681   // passed explicitly we could avoid this check.
8682   if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8683     return true;
8684
8685   const Type* SrcTy = 
8686             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8687   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8688   if (!SrcTy->isSized() || !DstTy->isSized())
8689     return false;
8690   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8691     return false;
8692   return true;
8693 }
8694
8695 // visitCallSite - Improvements for call and invoke instructions.
8696 //
8697 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8698   bool Changed = false;
8699
8700   // If the callee is a constexpr cast of a function, attempt to move the cast
8701   // to the arguments of the call/invoke.
8702   if (transformConstExprCastCall(CS)) return 0;
8703
8704   Value *Callee = CS.getCalledValue();
8705
8706   if (Function *CalleeF = dyn_cast<Function>(Callee))
8707     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8708       Instruction *OldCall = CS.getInstruction();
8709       // If the call and callee calling conventions don't match, this call must
8710       // be unreachable, as the call is undefined.
8711       new StoreInst(ConstantInt::getTrue(),
8712                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
8713                                     OldCall);
8714       if (!OldCall->use_empty())
8715         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8716       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
8717         return EraseInstFromFunction(*OldCall);
8718       return 0;
8719     }
8720
8721   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8722     // This instruction is not reachable, just remove it.  We insert a store to
8723     // undef so that we know that this code is not reachable, despite the fact
8724     // that we can't modify the CFG here.
8725     new StoreInst(ConstantInt::getTrue(),
8726                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8727                   CS.getInstruction());
8728
8729     if (!CS.getInstruction()->use_empty())
8730       CS.getInstruction()->
8731         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8732
8733     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8734       // Don't break the CFG, insert a dummy cond branch.
8735       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8736                          ConstantInt::getTrue(), II);
8737     }
8738     return EraseInstFromFunction(*CS.getInstruction());
8739   }
8740
8741   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8742     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8743       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8744         return transformCallThroughTrampoline(CS);
8745
8746   const PointerType *PTy = cast<PointerType>(Callee->getType());
8747   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8748   if (FTy->isVarArg()) {
8749     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8750     // See if we can optimize any arguments passed through the varargs area of
8751     // the call.
8752     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8753            E = CS.arg_end(); I != E; ++I, ++ix) {
8754       CastInst *CI = dyn_cast<CastInst>(*I);
8755       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8756         *I = CI->getOperand(0);
8757         Changed = true;
8758       }
8759     }
8760   }
8761
8762   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8763     // Inline asm calls cannot throw - mark them 'nounwind'.
8764     CS.setDoesNotThrow();
8765     Changed = true;
8766   }
8767
8768   return Changed ? CS.getInstruction() : 0;
8769 }
8770
8771 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8772 // attempt to move the cast to the arguments of the call/invoke.
8773 //
8774 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8775   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8776   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8777   if (CE->getOpcode() != Instruction::BitCast || 
8778       !isa<Function>(CE->getOperand(0)))
8779     return false;
8780   Function *Callee = cast<Function>(CE->getOperand(0));
8781   Instruction *Caller = CS.getInstruction();
8782   const PAListPtr &CallerPAL = CS.getParamAttrs();
8783
8784   // Okay, this is a cast from a function to a different type.  Unless doing so
8785   // would cause a type conversion of one of our arguments, change this call to
8786   // be a direct call with arguments casted to the appropriate types.
8787   //
8788   const FunctionType *FT = Callee->getFunctionType();
8789   const Type *OldRetTy = Caller->getType();
8790   const Type *NewRetTy = FT->getReturnType();
8791
8792   if (isa<StructType>(NewRetTy))
8793     return false; // TODO: Handle multiple return values.
8794
8795   // Check to see if we are changing the return type...
8796   if (OldRetTy != NewRetTy) {
8797     if (Callee->isDeclaration() &&
8798         // Conversion is ok if changing from one pointer type to another or from
8799         // a pointer to an integer of the same size.
8800         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8801           isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType()))
8802       return false;   // Cannot transform this return value.
8803
8804     if (!Caller->use_empty() &&
8805         // void -> non-void is handled specially
8806         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8807       return false;   // Cannot transform this return value.
8808
8809     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8810       ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8811       if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8812         return false;   // Attribute not compatible with transformed value.
8813     }
8814
8815     // If the callsite is an invoke instruction, and the return value is used by
8816     // a PHI node in a successor, we cannot change the return type of the call
8817     // because there is no place to put the cast instruction (without breaking
8818     // the critical edge).  Bail out in this case.
8819     if (!Caller->use_empty())
8820       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8821         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8822              UI != E; ++UI)
8823           if (PHINode *PN = dyn_cast<PHINode>(*UI))
8824             if (PN->getParent() == II->getNormalDest() ||
8825                 PN->getParent() == II->getUnwindDest())
8826               return false;
8827   }
8828
8829   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8830   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8831
8832   CallSite::arg_iterator AI = CS.arg_begin();
8833   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8834     const Type *ParamTy = FT->getParamType(i);
8835     const Type *ActTy = (*AI)->getType();
8836
8837     if (!CastInst::isCastable(ActTy, ParamTy))
8838       return false;   // Cannot transform this parameter value.
8839
8840     if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8841       return false;   // Attribute not compatible with transformed value.
8842
8843     // Converting from one pointer type to another or between a pointer and an
8844     // integer of the same size is safe even if we do not have a body.
8845     bool isConvertible = ActTy == ParamTy ||
8846       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8847        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8848     if (Callee->isDeclaration() && !isConvertible) return false;
8849   }
8850
8851   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8852       Callee->isDeclaration())
8853     return false;   // Do not delete arguments unless we have a function body.
8854
8855   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8856       !CallerPAL.isEmpty())
8857     // In this case we have more arguments than the new function type, but we
8858     // won't be dropping them.  Check that these extra arguments have attributes
8859     // that are compatible with being a vararg call argument.
8860     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8861       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8862         break;
8863       ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8864       if (PAttrs & ParamAttr::VarArgsIncompatible)
8865         return false;
8866     }
8867
8868   // Okay, we decided that this is a safe thing to do: go ahead and start
8869   // inserting cast instructions as necessary...
8870   std::vector<Value*> Args;
8871   Args.reserve(NumActualArgs);
8872   SmallVector<ParamAttrsWithIndex, 8> attrVec;
8873   attrVec.reserve(NumCommonArgs);
8874
8875   // Get any return attributes.
8876   ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8877
8878   // If the return value is not being used, the type may not be compatible
8879   // with the existing attributes.  Wipe out any problematic attributes.
8880   RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8881
8882   // Add the new return attributes.
8883   if (RAttrs)
8884     attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8885
8886   AI = CS.arg_begin();
8887   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8888     const Type *ParamTy = FT->getParamType(i);
8889     if ((*AI)->getType() == ParamTy) {
8890       Args.push_back(*AI);
8891     } else {
8892       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8893           false, ParamTy, false);
8894       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8895       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8896     }
8897
8898     // Add any parameter attributes.
8899     if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8900       attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8901   }
8902
8903   // If the function takes more arguments than the call was taking, add them
8904   // now...
8905   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8906     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8907
8908   // If we are removing arguments to the function, emit an obnoxious warning...
8909   if (FT->getNumParams() < NumActualArgs) {
8910     if (!FT->isVarArg()) {
8911       cerr << "WARNING: While resolving call to function '"
8912            << Callee->getName() << "' arguments were dropped!\n";
8913     } else {
8914       // Add all of the arguments in their promoted form to the arg list...
8915       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8916         const Type *PTy = getPromotedType((*AI)->getType());
8917         if (PTy != (*AI)->getType()) {
8918           // Must promote to pass through va_arg area!
8919           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
8920                                                                 PTy, false);
8921           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
8922           InsertNewInstBefore(Cast, *Caller);
8923           Args.push_back(Cast);
8924         } else {
8925           Args.push_back(*AI);
8926         }
8927
8928         // Add any parameter attributes.
8929         if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8930           attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8931       }
8932     }
8933   }
8934
8935   if (NewRetTy == Type::VoidTy)
8936     Caller->setName("");   // Void type should not have a name.
8937
8938   const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
8939
8940   Instruction *NC;
8941   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8942     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
8943                             Args.begin(), Args.end(),
8944                             Caller->getName(), Caller);
8945     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8946     cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8947   } else {
8948     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
8949                           Caller->getName(), Caller);
8950     CallInst *CI = cast<CallInst>(Caller);
8951     if (CI->isTailCall())
8952       cast<CallInst>(NC)->setTailCall();
8953     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8954     cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8955   }
8956
8957   // Insert a cast of the return type as necessary.
8958   Value *NV = NC;
8959   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8960     if (NV->getType() != Type::VoidTy) {
8961       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
8962                                                             OldRetTy, false);
8963       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
8964
8965       // If this is an invoke instruction, we should insert it after the first
8966       // non-phi, instruction in the normal successor block.
8967       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8968         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
8969         InsertNewInstBefore(NC, *I);
8970       } else {
8971         // Otherwise, it's a call, just insert cast right after the call instr
8972         InsertNewInstBefore(NC, *Caller);
8973       }
8974       AddUsersToWorkList(*Caller);
8975     } else {
8976       NV = UndefValue::get(Caller->getType());
8977     }
8978   }
8979
8980   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8981     Caller->replaceAllUsesWith(NV);
8982   Caller->eraseFromParent();
8983   RemoveFromWorkList(Caller);
8984   return true;
8985 }
8986
8987 // transformCallThroughTrampoline - Turn a call to a function created by the
8988 // init_trampoline intrinsic into a direct call to the underlying function.
8989 //
8990 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8991   Value *Callee = CS.getCalledValue();
8992   const PointerType *PTy = cast<PointerType>(Callee->getType());
8993   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8994   const PAListPtr &Attrs = CS.getParamAttrs();
8995
8996   // If the call already has the 'nest' attribute somewhere then give up -
8997   // otherwise 'nest' would occur twice after splicing in the chain.
8998   if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
8999     return 0;
9000
9001   IntrinsicInst *Tramp =
9002     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9003
9004   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9005   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9006   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9007
9008   const PAListPtr &NestAttrs = NestF->getParamAttrs();
9009   if (!NestAttrs.isEmpty()) {
9010     unsigned NestIdx = 1;
9011     const Type *NestTy = 0;
9012     ParameterAttributes NestAttr = ParamAttr::None;
9013
9014     // Look for a parameter marked with the 'nest' attribute.
9015     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9016          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9017       if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9018         // Record the parameter type and any other attributes.
9019         NestTy = *I;
9020         NestAttr = NestAttrs.getParamAttrs(NestIdx);
9021         break;
9022       }
9023
9024     if (NestTy) {
9025       Instruction *Caller = CS.getInstruction();
9026       std::vector<Value*> NewArgs;
9027       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9028
9029       SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9030       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9031
9032       // Insert the nest argument into the call argument list, which may
9033       // mean appending it.  Likewise for attributes.
9034
9035       // Add any function result attributes.
9036       if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9037         NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9038
9039       {
9040         unsigned Idx = 1;
9041         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9042         do {
9043           if (Idx == NestIdx) {
9044             // Add the chain argument and attributes.
9045             Value *NestVal = Tramp->getOperand(3);
9046             if (NestVal->getType() != NestTy)
9047               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9048             NewArgs.push_back(NestVal);
9049             NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9050           }
9051
9052           if (I == E)
9053             break;
9054
9055           // Add the original argument and attributes.
9056           NewArgs.push_back(*I);
9057           if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9058             NewAttrs.push_back
9059               (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9060
9061           ++Idx, ++I;
9062         } while (1);
9063       }
9064
9065       // The trampoline may have been bitcast to a bogus type (FTy).
9066       // Handle this by synthesizing a new function type, equal to FTy
9067       // with the chain parameter inserted.
9068
9069       std::vector<const Type*> NewTypes;
9070       NewTypes.reserve(FTy->getNumParams()+1);
9071
9072       // Insert the chain's type into the list of parameter types, which may
9073       // mean appending it.
9074       {
9075         unsigned Idx = 1;
9076         FunctionType::param_iterator I = FTy->param_begin(),
9077           E = FTy->param_end();
9078
9079         do {
9080           if (Idx == NestIdx)
9081             // Add the chain's type.
9082             NewTypes.push_back(NestTy);
9083
9084           if (I == E)
9085             break;
9086
9087           // Add the original type.
9088           NewTypes.push_back(*I);
9089
9090           ++Idx, ++I;
9091         } while (1);
9092       }
9093
9094       // Replace the trampoline call with a direct call.  Let the generic
9095       // code sort out any function type mismatches.
9096       FunctionType *NewFTy =
9097         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9098       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9099         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9100       const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9101
9102       Instruction *NewCaller;
9103       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9104         NewCaller = InvokeInst::Create(NewCallee,
9105                                        II->getNormalDest(), II->getUnwindDest(),
9106                                        NewArgs.begin(), NewArgs.end(),
9107                                        Caller->getName(), Caller);
9108         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9109         cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9110       } else {
9111         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9112                                      Caller->getName(), Caller);
9113         if (cast<CallInst>(Caller)->isTailCall())
9114           cast<CallInst>(NewCaller)->setTailCall();
9115         cast<CallInst>(NewCaller)->
9116           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9117         cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9118       }
9119       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9120         Caller->replaceAllUsesWith(NewCaller);
9121       Caller->eraseFromParent();
9122       RemoveFromWorkList(Caller);
9123       return 0;
9124     }
9125   }
9126
9127   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9128   // parameter, there is no need to adjust the argument list.  Let the generic
9129   // code sort out any function type mismatches.
9130   Constant *NewCallee =
9131     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9132   CS.setCalledFunction(NewCallee);
9133   return CS.getInstruction();
9134 }
9135
9136 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9137 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9138 /// and a single binop.
9139 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9140   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9141   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9142          isa<CmpInst>(FirstInst));
9143   unsigned Opc = FirstInst->getOpcode();
9144   Value *LHSVal = FirstInst->getOperand(0);
9145   Value *RHSVal = FirstInst->getOperand(1);
9146     
9147   const Type *LHSType = LHSVal->getType();
9148   const Type *RHSType = RHSVal->getType();
9149   
9150   // Scan to see if all operands are the same opcode, all have one use, and all
9151   // kill their operands (i.e. the operands have one use).
9152   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9153     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9154     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9155         // Verify type of the LHS matches so we don't fold cmp's of different
9156         // types or GEP's with different index types.
9157         I->getOperand(0)->getType() != LHSType ||
9158         I->getOperand(1)->getType() != RHSType)
9159       return 0;
9160
9161     // If they are CmpInst instructions, check their predicates
9162     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9163       if (cast<CmpInst>(I)->getPredicate() !=
9164           cast<CmpInst>(FirstInst)->getPredicate())
9165         return 0;
9166     
9167     // Keep track of which operand needs a phi node.
9168     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9169     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9170   }
9171   
9172   // Otherwise, this is safe to transform, determine if it is profitable.
9173
9174   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9175   // Indexes are often folded into load/store instructions, so we don't want to
9176   // hide them behind a phi.
9177   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9178     return 0;
9179   
9180   Value *InLHS = FirstInst->getOperand(0);
9181   Value *InRHS = FirstInst->getOperand(1);
9182   PHINode *NewLHS = 0, *NewRHS = 0;
9183   if (LHSVal == 0) {
9184     NewLHS = PHINode::Create(LHSType,
9185                              FirstInst->getOperand(0)->getName() + ".pn");
9186     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9187     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9188     InsertNewInstBefore(NewLHS, PN);
9189     LHSVal = NewLHS;
9190   }
9191   
9192   if (RHSVal == 0) {
9193     NewRHS = PHINode::Create(RHSType,
9194                              FirstInst->getOperand(1)->getName() + ".pn");
9195     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9196     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9197     InsertNewInstBefore(NewRHS, PN);
9198     RHSVal = NewRHS;
9199   }
9200   
9201   // Add all operands to the new PHIs.
9202   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9203     if (NewLHS) {
9204       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9205       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9206     }
9207     if (NewRHS) {
9208       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9209       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9210     }
9211   }
9212     
9213   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9214     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9215   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9216     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9217                            RHSVal);
9218   else {
9219     assert(isa<GetElementPtrInst>(FirstInst));
9220     return GetElementPtrInst::Create(LHSVal, RHSVal);
9221   }
9222 }
9223
9224 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9225 /// of the block that defines it.  This means that it must be obvious the value
9226 /// of the load is not changed from the point of the load to the end of the
9227 /// block it is in.
9228 ///
9229 /// Finally, it is safe, but not profitable, to sink a load targetting a
9230 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9231 /// to a register.
9232 static bool isSafeToSinkLoad(LoadInst *L) {
9233   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9234   
9235   for (++BBI; BBI != E; ++BBI)
9236     if (BBI->mayWriteToMemory())
9237       return false;
9238   
9239   // Check for non-address taken alloca.  If not address-taken already, it isn't
9240   // profitable to do this xform.
9241   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9242     bool isAddressTaken = false;
9243     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9244          UI != E; ++UI) {
9245       if (isa<LoadInst>(UI)) continue;
9246       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9247         // If storing TO the alloca, then the address isn't taken.
9248         if (SI->getOperand(1) == AI) continue;
9249       }
9250       isAddressTaken = true;
9251       break;
9252     }
9253     
9254     if (!isAddressTaken)
9255       return false;
9256   }
9257   
9258   return true;
9259 }
9260
9261
9262 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9263 // operator and they all are only used by the PHI, PHI together their
9264 // inputs, and do the operation once, to the result of the PHI.
9265 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9266   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9267
9268   // Scan the instruction, looking for input operations that can be folded away.
9269   // If all input operands to the phi are the same instruction (e.g. a cast from
9270   // the same type or "+42") we can pull the operation through the PHI, reducing
9271   // code size and simplifying code.
9272   Constant *ConstantOp = 0;
9273   const Type *CastSrcTy = 0;
9274   bool isVolatile = false;
9275   if (isa<CastInst>(FirstInst)) {
9276     CastSrcTy = FirstInst->getOperand(0)->getType();
9277   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9278     // Can fold binop, compare or shift here if the RHS is a constant, 
9279     // otherwise call FoldPHIArgBinOpIntoPHI.
9280     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9281     if (ConstantOp == 0)
9282       return FoldPHIArgBinOpIntoPHI(PN);
9283   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9284     isVolatile = LI->isVolatile();
9285     // We can't sink the load if the loaded value could be modified between the
9286     // load and the PHI.
9287     if (LI->getParent() != PN.getIncomingBlock(0) ||
9288         !isSafeToSinkLoad(LI))
9289       return 0;
9290   } else if (isa<GetElementPtrInst>(FirstInst)) {
9291     if (FirstInst->getNumOperands() == 2)
9292       return FoldPHIArgBinOpIntoPHI(PN);
9293     // Can't handle general GEPs yet.
9294     return 0;
9295   } else {
9296     return 0;  // Cannot fold this operation.
9297   }
9298
9299   // Check to see if all arguments are the same operation.
9300   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9301     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9302     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9303     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9304       return 0;
9305     if (CastSrcTy) {
9306       if (I->getOperand(0)->getType() != CastSrcTy)
9307         return 0;  // Cast operation must match.
9308     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9309       // We can't sink the load if the loaded value could be modified between 
9310       // the load and the PHI.
9311       if (LI->isVolatile() != isVolatile ||
9312           LI->getParent() != PN.getIncomingBlock(i) ||
9313           !isSafeToSinkLoad(LI))
9314         return 0;
9315       
9316       // If the PHI is volatile and its block has multiple successors, sinking
9317       // it would remove a load of the volatile value from the path through the
9318       // other successor.
9319       if (isVolatile &&
9320           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9321         return 0;
9322
9323       
9324     } else if (I->getOperand(1) != ConstantOp) {
9325       return 0;
9326     }
9327   }
9328
9329   // Okay, they are all the same operation.  Create a new PHI node of the
9330   // correct type, and PHI together all of the LHS's of the instructions.
9331   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9332                                    PN.getName()+".in");
9333   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9334
9335   Value *InVal = FirstInst->getOperand(0);
9336   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9337
9338   // Add all operands to the new PHI.
9339   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9340     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9341     if (NewInVal != InVal)
9342       InVal = 0;
9343     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9344   }
9345
9346   Value *PhiVal;
9347   if (InVal) {
9348     // The new PHI unions all of the same values together.  This is really
9349     // common, so we handle it intelligently here for compile-time speed.
9350     PhiVal = InVal;
9351     delete NewPN;
9352   } else {
9353     InsertNewInstBefore(NewPN, PN);
9354     PhiVal = NewPN;
9355   }
9356
9357   // Insert and return the new operation.
9358   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9359     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9360   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9361     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9362   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9363     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9364                            PhiVal, ConstantOp);
9365   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9366   
9367   // If this was a volatile load that we are merging, make sure to loop through
9368   // and mark all the input loads as non-volatile.  If we don't do this, we will
9369   // insert a new volatile load and the old ones will not be deletable.
9370   if (isVolatile)
9371     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9372       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9373   
9374   return new LoadInst(PhiVal, "", isVolatile);
9375 }
9376
9377 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9378 /// that is dead.
9379 static bool DeadPHICycle(PHINode *PN,
9380                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9381   if (PN->use_empty()) return true;
9382   if (!PN->hasOneUse()) return false;
9383
9384   // Remember this node, and if we find the cycle, return.
9385   if (!PotentiallyDeadPHIs.insert(PN))
9386     return true;
9387   
9388   // Don't scan crazily complex things.
9389   if (PotentiallyDeadPHIs.size() == 16)
9390     return false;
9391
9392   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9393     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9394
9395   return false;
9396 }
9397
9398 /// PHIsEqualValue - Return true if this phi node is always equal to
9399 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9400 ///   z = some value; x = phi (y, z); y = phi (x, z)
9401 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9402                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9403   // See if we already saw this PHI node.
9404   if (!ValueEqualPHIs.insert(PN))
9405     return true;
9406   
9407   // Don't scan crazily complex things.
9408   if (ValueEqualPHIs.size() == 16)
9409     return false;
9410  
9411   // Scan the operands to see if they are either phi nodes or are equal to
9412   // the value.
9413   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9414     Value *Op = PN->getIncomingValue(i);
9415     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9416       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9417         return false;
9418     } else if (Op != NonPhiInVal)
9419       return false;
9420   }
9421   
9422   return true;
9423 }
9424
9425
9426 // PHINode simplification
9427 //
9428 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9429   // If LCSSA is around, don't mess with Phi nodes
9430   if (MustPreserveLCSSA) return 0;
9431   
9432   if (Value *V = PN.hasConstantValue())
9433     return ReplaceInstUsesWith(PN, V);
9434
9435   // If all PHI operands are the same operation, pull them through the PHI,
9436   // reducing code size.
9437   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9438       PN.getIncomingValue(0)->hasOneUse())
9439     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9440       return Result;
9441
9442   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9443   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9444   // PHI)... break the cycle.
9445   if (PN.hasOneUse()) {
9446     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9447     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9448       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9449       PotentiallyDeadPHIs.insert(&PN);
9450       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9451         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9452     }
9453    
9454     // If this phi has a single use, and if that use just computes a value for
9455     // the next iteration of a loop, delete the phi.  This occurs with unused
9456     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9457     // common case here is good because the only other things that catch this
9458     // are induction variable analysis (sometimes) and ADCE, which is only run
9459     // late.
9460     if (PHIUser->hasOneUse() &&
9461         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9462         PHIUser->use_back() == &PN) {
9463       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9464     }
9465   }
9466
9467   // We sometimes end up with phi cycles that non-obviously end up being the
9468   // same value, for example:
9469   //   z = some value; x = phi (y, z); y = phi (x, z)
9470   // where the phi nodes don't necessarily need to be in the same block.  Do a
9471   // quick check to see if the PHI node only contains a single non-phi value, if
9472   // so, scan to see if the phi cycle is actually equal to that value.
9473   {
9474     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9475     // Scan for the first non-phi operand.
9476     while (InValNo != NumOperandVals && 
9477            isa<PHINode>(PN.getIncomingValue(InValNo)))
9478       ++InValNo;
9479
9480     if (InValNo != NumOperandVals) {
9481       Value *NonPhiInVal = PN.getOperand(InValNo);
9482       
9483       // Scan the rest of the operands to see if there are any conflicts, if so
9484       // there is no need to recursively scan other phis.
9485       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9486         Value *OpVal = PN.getIncomingValue(InValNo);
9487         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9488           break;
9489       }
9490       
9491       // If we scanned over all operands, then we have one unique value plus
9492       // phi values.  Scan PHI nodes to see if they all merge in each other or
9493       // the value.
9494       if (InValNo == NumOperandVals) {
9495         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9496         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9497           return ReplaceInstUsesWith(PN, NonPhiInVal);
9498       }
9499     }
9500   }
9501   return 0;
9502 }
9503
9504 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9505                                    Instruction *InsertPoint,
9506                                    InstCombiner *IC) {
9507   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9508   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9509   // We must cast correctly to the pointer type. Ensure that we
9510   // sign extend the integer value if it is smaller as this is
9511   // used for address computation.
9512   Instruction::CastOps opcode = 
9513      (VTySize < PtrSize ? Instruction::SExt :
9514       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9515   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9516 }
9517
9518
9519 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9520   Value *PtrOp = GEP.getOperand(0);
9521   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9522   // If so, eliminate the noop.
9523   if (GEP.getNumOperands() == 1)
9524     return ReplaceInstUsesWith(GEP, PtrOp);
9525
9526   if (isa<UndefValue>(GEP.getOperand(0)))
9527     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9528
9529   bool HasZeroPointerIndex = false;
9530   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9531     HasZeroPointerIndex = C->isNullValue();
9532
9533   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9534     return ReplaceInstUsesWith(GEP, PtrOp);
9535
9536   // Eliminate unneeded casts for indices.
9537   bool MadeChange = false;
9538   
9539   gep_type_iterator GTI = gep_type_begin(GEP);
9540   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9541        i != e; ++i, ++GTI) {
9542     if (isa<SequentialType>(*GTI)) {
9543       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9544         if (CI->getOpcode() == Instruction::ZExt ||
9545             CI->getOpcode() == Instruction::SExt) {
9546           const Type *SrcTy = CI->getOperand(0)->getType();
9547           // We can eliminate a cast from i32 to i64 iff the target 
9548           // is a 32-bit pointer target.
9549           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9550             MadeChange = true;
9551             *i = CI->getOperand(0);
9552           }
9553         }
9554       }
9555       // If we are using a wider index than needed for this platform, shrink it
9556       // to what we need.  If the incoming value needs a cast instruction,
9557       // insert it.  This explicit cast can make subsequent optimizations more
9558       // obvious.
9559       Value *Op = *i;
9560       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9561         if (Constant *C = dyn_cast<Constant>(Op)) {
9562           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9563           MadeChange = true;
9564         } else {
9565           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9566                                 GEP);
9567           *i = Op;
9568           MadeChange = true;
9569         }
9570       }
9571     }
9572   }
9573   if (MadeChange) return &GEP;
9574
9575   // If this GEP instruction doesn't move the pointer, and if the input operand
9576   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9577   // real input to the dest type.
9578   if (GEP.hasAllZeroIndices()) {
9579     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9580       // If the bitcast is of an allocation, and the allocation will be
9581       // converted to match the type of the cast, don't touch this.
9582       if (isa<AllocationInst>(BCI->getOperand(0))) {
9583         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9584         if (Instruction *I = visitBitCast(*BCI)) {
9585           if (I != BCI) {
9586             I->takeName(BCI);
9587             BCI->getParent()->getInstList().insert(BCI, I);
9588             ReplaceInstUsesWith(*BCI, I);
9589           }
9590           return &GEP;
9591         }
9592       }
9593       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9594     }
9595   }
9596   
9597   // Combine Indices - If the source pointer to this getelementptr instruction
9598   // is a getelementptr instruction, combine the indices of the two
9599   // getelementptr instructions into a single instruction.
9600   //
9601   SmallVector<Value*, 8> SrcGEPOperands;
9602   if (User *Src = dyn_castGetElementPtr(PtrOp))
9603     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9604
9605   if (!SrcGEPOperands.empty()) {
9606     // Note that if our source is a gep chain itself that we wait for that
9607     // chain to be resolved before we perform this transformation.  This
9608     // avoids us creating a TON of code in some cases.
9609     //
9610     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9611         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9612       return 0;   // Wait until our source is folded to completion.
9613
9614     SmallVector<Value*, 8> Indices;
9615
9616     // Find out whether the last index in the source GEP is a sequential idx.
9617     bool EndsWithSequential = false;
9618     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9619            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9620       EndsWithSequential = !isa<StructType>(*I);
9621
9622     // Can we combine the two pointer arithmetics offsets?
9623     if (EndsWithSequential) {
9624       // Replace: gep (gep %P, long B), long A, ...
9625       // With:    T = long A+B; gep %P, T, ...
9626       //
9627       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9628       if (SO1 == Constant::getNullValue(SO1->getType())) {
9629         Sum = GO1;
9630       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9631         Sum = SO1;
9632       } else {
9633         // If they aren't the same type, convert both to an integer of the
9634         // target's pointer size.
9635         if (SO1->getType() != GO1->getType()) {
9636           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9637             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9638           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9639             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9640           } else {
9641             unsigned PS = TD->getPointerSizeInBits();
9642             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9643               // Convert GO1 to SO1's type.
9644               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9645
9646             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9647               // Convert SO1 to GO1's type.
9648               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9649             } else {
9650               const Type *PT = TD->getIntPtrType();
9651               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9652               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9653             }
9654           }
9655         }
9656         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9657           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9658         else {
9659           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9660           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9661         }
9662       }
9663
9664       // Recycle the GEP we already have if possible.
9665       if (SrcGEPOperands.size() == 2) {
9666         GEP.setOperand(0, SrcGEPOperands[0]);
9667         GEP.setOperand(1, Sum);
9668         return &GEP;
9669       } else {
9670         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9671                        SrcGEPOperands.end()-1);
9672         Indices.push_back(Sum);
9673         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9674       }
9675     } else if (isa<Constant>(*GEP.idx_begin()) &&
9676                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9677                SrcGEPOperands.size() != 1) {
9678       // Otherwise we can do the fold if the first index of the GEP is a zero
9679       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9680                      SrcGEPOperands.end());
9681       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9682     }
9683
9684     if (!Indices.empty())
9685       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9686                                        Indices.end(), GEP.getName());
9687
9688   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9689     // GEP of global variable.  If all of the indices for this GEP are
9690     // constants, we can promote this to a constexpr instead of an instruction.
9691
9692     // Scan for nonconstants...
9693     SmallVector<Constant*, 8> Indices;
9694     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9695     for (; I != E && isa<Constant>(*I); ++I)
9696       Indices.push_back(cast<Constant>(*I));
9697
9698     if (I == E) {  // If they are all constants...
9699       Constant *CE = ConstantExpr::getGetElementPtr(GV,
9700                                                     &Indices[0],Indices.size());
9701
9702       // Replace all uses of the GEP with the new constexpr...
9703       return ReplaceInstUsesWith(GEP, CE);
9704     }
9705   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
9706     if (!isa<PointerType>(X->getType())) {
9707       // Not interesting.  Source pointer must be a cast from pointer.
9708     } else if (HasZeroPointerIndex) {
9709       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9710       // into     : GEP [10 x i8]* X, i32 0, ...
9711       //
9712       // This occurs when the program declares an array extern like "int X[];"
9713       //
9714       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9715       const PointerType *XTy = cast<PointerType>(X->getType());
9716       if (const ArrayType *XATy =
9717           dyn_cast<ArrayType>(XTy->getElementType()))
9718         if (const ArrayType *CATy =
9719             dyn_cast<ArrayType>(CPTy->getElementType()))
9720           if (CATy->getElementType() == XATy->getElementType()) {
9721             // At this point, we know that the cast source type is a pointer
9722             // to an array of the same type as the destination pointer
9723             // array.  Because the array type is never stepped over (there
9724             // is a leading zero) we can fold the cast into this GEP.
9725             GEP.setOperand(0, X);
9726             return &GEP;
9727           }
9728     } else if (GEP.getNumOperands() == 2) {
9729       // Transform things like:
9730       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9731       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9732       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9733       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9734       if (isa<ArrayType>(SrcElTy) &&
9735           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9736           TD->getABITypeSize(ResElTy)) {
9737         Value *Idx[2];
9738         Idx[0] = Constant::getNullValue(Type::Int32Ty);
9739         Idx[1] = GEP.getOperand(1);
9740         Value *V = InsertNewInstBefore(
9741                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9742         // V and GEP are both pointer types --> BitCast
9743         return new BitCastInst(V, GEP.getType());
9744       }
9745       
9746       // Transform things like:
9747       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9748       //   (where tmp = 8*tmp2) into:
9749       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9750       
9751       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9752         uint64_t ArrayEltSize =
9753             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9754         
9755         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
9756         // allow either a mul, shift, or constant here.
9757         Value *NewIdx = 0;
9758         ConstantInt *Scale = 0;
9759         if (ArrayEltSize == 1) {
9760           NewIdx = GEP.getOperand(1);
9761           Scale = ConstantInt::get(NewIdx->getType(), 1);
9762         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9763           NewIdx = ConstantInt::get(CI->getType(), 1);
9764           Scale = CI;
9765         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9766           if (Inst->getOpcode() == Instruction::Shl &&
9767               isa<ConstantInt>(Inst->getOperand(1))) {
9768             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9769             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9770             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9771             NewIdx = Inst->getOperand(0);
9772           } else if (Inst->getOpcode() == Instruction::Mul &&
9773                      isa<ConstantInt>(Inst->getOperand(1))) {
9774             Scale = cast<ConstantInt>(Inst->getOperand(1));
9775             NewIdx = Inst->getOperand(0);
9776           }
9777         }
9778         
9779         // If the index will be to exactly the right offset with the scale taken
9780         // out, perform the transformation. Note, we don't know whether Scale is
9781         // signed or not. We'll use unsigned version of division/modulo
9782         // operation after making sure Scale doesn't have the sign bit set.
9783         if (Scale && Scale->getSExtValue() >= 0LL &&
9784             Scale->getZExtValue() % ArrayEltSize == 0) {
9785           Scale = ConstantInt::get(Scale->getType(),
9786                                    Scale->getZExtValue() / ArrayEltSize);
9787           if (Scale->getZExtValue() != 1) {
9788             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9789                                                        false /*ZExt*/);
9790             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9791             NewIdx = InsertNewInstBefore(Sc, GEP);
9792           }
9793
9794           // Insert the new GEP instruction.
9795           Value *Idx[2];
9796           Idx[0] = Constant::getNullValue(Type::Int32Ty);
9797           Idx[1] = NewIdx;
9798           Instruction *NewGEP =
9799             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9800           NewGEP = InsertNewInstBefore(NewGEP, GEP);
9801           // The NewGEP must be pointer typed, so must the old one -> BitCast
9802           return new BitCastInst(NewGEP, GEP.getType());
9803         }
9804       }
9805     }
9806   }
9807
9808   return 0;
9809 }
9810
9811 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9812   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9813   if (AI.isArrayAllocation()) {  // Check C != 1
9814     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9815       const Type *NewTy = 
9816         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9817       AllocationInst *New = 0;
9818
9819       // Create and insert the replacement instruction...
9820       if (isa<MallocInst>(AI))
9821         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9822       else {
9823         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9824         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9825       }
9826
9827       InsertNewInstBefore(New, AI);
9828
9829       // Scan to the end of the allocation instructions, to skip over a block of
9830       // allocas if possible...
9831       //
9832       BasicBlock::iterator It = New;
9833       while (isa<AllocationInst>(*It)) ++It;
9834
9835       // Now that I is pointing to the first non-allocation-inst in the block,
9836       // insert our getelementptr instruction...
9837       //
9838       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9839       Value *Idx[2];
9840       Idx[0] = NullIdx;
9841       Idx[1] = NullIdx;
9842       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9843                                            New->getName()+".sub", It);
9844
9845       // Now make everything use the getelementptr instead of the original
9846       // allocation.
9847       return ReplaceInstUsesWith(AI, V);
9848     } else if (isa<UndefValue>(AI.getArraySize())) {
9849       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9850     }
9851   }
9852
9853   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9854   // Note that we only do this for alloca's, because malloc should allocate and
9855   // return a unique pointer, even for a zero byte allocation.
9856   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9857       TD->getABITypeSize(AI.getAllocatedType()) == 0)
9858     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9859
9860   return 0;
9861 }
9862
9863 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9864   Value *Op = FI.getOperand(0);
9865
9866   // free undef -> unreachable.
9867   if (isa<UndefValue>(Op)) {
9868     // Insert a new store to null because we cannot modify the CFG here.
9869     new StoreInst(ConstantInt::getTrue(),
9870                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9871     return EraseInstFromFunction(FI);
9872   }
9873   
9874   // If we have 'free null' delete the instruction.  This can happen in stl code
9875   // when lots of inlining happens.
9876   if (isa<ConstantPointerNull>(Op))
9877     return EraseInstFromFunction(FI);
9878   
9879   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9880   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9881     FI.setOperand(0, CI->getOperand(0));
9882     return &FI;
9883   }
9884   
9885   // Change free (gep X, 0,0,0,0) into free(X)
9886   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9887     if (GEPI->hasAllZeroIndices()) {
9888       AddToWorkList(GEPI);
9889       FI.setOperand(0, GEPI->getOperand(0));
9890       return &FI;
9891     }
9892   }
9893   
9894   // Change free(malloc) into nothing, if the malloc has a single use.
9895   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9896     if (MI->hasOneUse()) {
9897       EraseInstFromFunction(FI);
9898       return EraseInstFromFunction(*MI);
9899     }
9900
9901   return 0;
9902 }
9903
9904
9905 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9906 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9907                                         const TargetData *TD) {
9908   User *CI = cast<User>(LI.getOperand(0));
9909   Value *CastOp = CI->getOperand(0);
9910
9911   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9912     // Instead of loading constant c string, use corresponding integer value
9913     // directly if string length is small enough.
9914     const std::string &Str = CE->getOperand(0)->getStringValue();
9915     if (!Str.empty()) {
9916       unsigned len = Str.length();
9917       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9918       unsigned numBits = Ty->getPrimitiveSizeInBits();
9919       // Replace LI with immediate integer store.
9920       if ((numBits >> 3) == len + 1) {
9921         APInt StrVal(numBits, 0);
9922         APInt SingleChar(numBits, 0);
9923         if (TD->isLittleEndian()) {
9924           for (signed i = len-1; i >= 0; i--) {
9925             SingleChar = (uint64_t) Str[i];
9926             StrVal = (StrVal << 8) | SingleChar;
9927           }
9928         } else {
9929           for (unsigned i = 0; i < len; i++) {
9930             SingleChar = (uint64_t) Str[i];
9931             StrVal = (StrVal << 8) | SingleChar;
9932           }
9933           // Append NULL at the end.
9934           SingleChar = 0;
9935           StrVal = (StrVal << 8) | SingleChar;
9936         }
9937         Value *NL = ConstantInt::get(StrVal);
9938         return IC.ReplaceInstUsesWith(LI, NL);
9939       }
9940     }
9941   }
9942
9943   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9944   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9945     const Type *SrcPTy = SrcTy->getElementType();
9946
9947     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
9948          isa<VectorType>(DestPTy)) {
9949       // If the source is an array, the code below will not succeed.  Check to
9950       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
9951       // constants.
9952       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9953         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9954           if (ASrcTy->getNumElements() != 0) {
9955             Value *Idxs[2];
9956             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9957             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9958             SrcTy = cast<PointerType>(CastOp->getType());
9959             SrcPTy = SrcTy->getElementType();
9960           }
9961
9962       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
9963             isa<VectorType>(SrcPTy)) &&
9964           // Do not allow turning this into a load of an integer, which is then
9965           // casted to a pointer, this pessimizes pointer analysis a lot.
9966           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9967           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9968                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9969
9970         // Okay, we are casting from one integer or pointer type to another of
9971         // the same size.  Instead of casting the pointer before the load, cast
9972         // the result of the loaded value.
9973         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9974                                                              CI->getName(),
9975                                                          LI.isVolatile()),LI);
9976         // Now cast the result of the load.
9977         return new BitCastInst(NewLoad, LI.getType());
9978       }
9979     }
9980   }
9981   return 0;
9982 }
9983
9984 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9985 /// from this value cannot trap.  If it is not obviously safe to load from the
9986 /// specified pointer, we do a quick local scan of the basic block containing
9987 /// ScanFrom, to determine if the address is already accessed.
9988 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9989   // If it is an alloca it is always safe to load from.
9990   if (isa<AllocaInst>(V)) return true;
9991
9992   // If it is a global variable it is mostly safe to load from.
9993   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9994     // Don't try to evaluate aliases.  External weak GV can be null.
9995     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9996
9997   // Otherwise, be a little bit agressive by scanning the local block where we
9998   // want to check to see if the pointer is already being loaded or stored
9999   // from/to.  If so, the previous load or store would have already trapped,
10000   // so there is no harm doing an extra load (also, CSE will later eliminate
10001   // the load entirely).
10002   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10003
10004   while (BBI != E) {
10005     --BBI;
10006
10007     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10008       if (LI->getOperand(0) == V) return true;
10009     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10010       if (SI->getOperand(1) == V) return true;
10011
10012   }
10013   return false;
10014 }
10015
10016 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10017 /// until we find the underlying object a pointer is referring to or something
10018 /// we don't understand.  Note that the returned pointer may be offset from the
10019 /// input, because we ignore GEP indices.
10020 static Value *GetUnderlyingObject(Value *Ptr) {
10021   while (1) {
10022     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10023       if (CE->getOpcode() == Instruction::BitCast ||
10024           CE->getOpcode() == Instruction::GetElementPtr)
10025         Ptr = CE->getOperand(0);
10026       else
10027         return Ptr;
10028     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10029       Ptr = BCI->getOperand(0);
10030     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10031       Ptr = GEP->getOperand(0);
10032     } else {
10033       return Ptr;
10034     }
10035   }
10036 }
10037
10038 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10039   Value *Op = LI.getOperand(0);
10040
10041   // Attempt to improve the alignment.
10042   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10043   if (KnownAlign >
10044       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10045                                 LI.getAlignment()))
10046     LI.setAlignment(KnownAlign);
10047
10048   // load (cast X) --> cast (load X) iff safe
10049   if (isa<CastInst>(Op))
10050     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10051       return Res;
10052
10053   // None of the following transforms are legal for volatile loads.
10054   if (LI.isVolatile()) return 0;
10055   
10056   if (&LI.getParent()->front() != &LI) {
10057     BasicBlock::iterator BBI = &LI; --BBI;
10058     // If the instruction immediately before this is a store to the same
10059     // address, do a simple form of store->load forwarding.
10060     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10061       if (SI->getOperand(1) == LI.getOperand(0))
10062         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10063     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10064       if (LIB->getOperand(0) == LI.getOperand(0))
10065         return ReplaceInstUsesWith(LI, LIB);
10066   }
10067
10068   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10069     const Value *GEPI0 = GEPI->getOperand(0);
10070     // TODO: Consider a target hook for valid address spaces for this xform.
10071     if (isa<ConstantPointerNull>(GEPI0) &&
10072         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10073       // Insert a new store to null instruction before the load to indicate
10074       // that this code is not reachable.  We do this instead of inserting
10075       // an unreachable instruction directly because we cannot modify the
10076       // CFG.
10077       new StoreInst(UndefValue::get(LI.getType()),
10078                     Constant::getNullValue(Op->getType()), &LI);
10079       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10080     }
10081   } 
10082
10083   if (Constant *C = dyn_cast<Constant>(Op)) {
10084     // load null/undef -> undef
10085     // TODO: Consider a target hook for valid address spaces for this xform.
10086     if (isa<UndefValue>(C) || (C->isNullValue() && 
10087         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10088       // Insert a new store to null instruction before the load to indicate that
10089       // this code is not reachable.  We do this instead of inserting an
10090       // unreachable instruction directly because we cannot modify the CFG.
10091       new StoreInst(UndefValue::get(LI.getType()),
10092                     Constant::getNullValue(Op->getType()), &LI);
10093       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10094     }
10095
10096     // Instcombine load (constant global) into the value loaded.
10097     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10098       if (GV->isConstant() && !GV->isDeclaration())
10099         return ReplaceInstUsesWith(LI, GV->getInitializer());
10100
10101     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10102     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10103       if (CE->getOpcode() == Instruction::GetElementPtr) {
10104         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10105           if (GV->isConstant() && !GV->isDeclaration())
10106             if (Constant *V = 
10107                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10108               return ReplaceInstUsesWith(LI, V);
10109         if (CE->getOperand(0)->isNullValue()) {
10110           // Insert a new store to null instruction before the load to indicate
10111           // that this code is not reachable.  We do this instead of inserting
10112           // an unreachable instruction directly because we cannot modify the
10113           // CFG.
10114           new StoreInst(UndefValue::get(LI.getType()),
10115                         Constant::getNullValue(Op->getType()), &LI);
10116           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10117         }
10118
10119       } else if (CE->isCast()) {
10120         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10121           return Res;
10122       }
10123     }
10124   }
10125     
10126   // If this load comes from anywhere in a constant global, and if the global
10127   // is all undef or zero, we know what it loads.
10128   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10129     if (GV->isConstant() && GV->hasInitializer()) {
10130       if (GV->getInitializer()->isNullValue())
10131         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10132       else if (isa<UndefValue>(GV->getInitializer()))
10133         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10134     }
10135   }
10136
10137   if (Op->hasOneUse()) {
10138     // Change select and PHI nodes to select values instead of addresses: this
10139     // helps alias analysis out a lot, allows many others simplifications, and
10140     // exposes redundancy in the code.
10141     //
10142     // Note that we cannot do the transformation unless we know that the
10143     // introduced loads cannot trap!  Something like this is valid as long as
10144     // the condition is always false: load (select bool %C, int* null, int* %G),
10145     // but it would not be valid if we transformed it to load from null
10146     // unconditionally.
10147     //
10148     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10149       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10150       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10151           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10152         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10153                                      SI->getOperand(1)->getName()+".val"), LI);
10154         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10155                                      SI->getOperand(2)->getName()+".val"), LI);
10156         return SelectInst::Create(SI->getCondition(), V1, V2);
10157       }
10158
10159       // load (select (cond, null, P)) -> load P
10160       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10161         if (C->isNullValue()) {
10162           LI.setOperand(0, SI->getOperand(2));
10163           return &LI;
10164         }
10165
10166       // load (select (cond, P, null)) -> load P
10167       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10168         if (C->isNullValue()) {
10169           LI.setOperand(0, SI->getOperand(1));
10170           return &LI;
10171         }
10172     }
10173   }
10174   return 0;
10175 }
10176
10177 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10178 /// when possible.
10179 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10180   User *CI = cast<User>(SI.getOperand(1));
10181   Value *CastOp = CI->getOperand(0);
10182
10183   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10184   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10185     const Type *SrcPTy = SrcTy->getElementType();
10186
10187     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10188       // If the source is an array, the code below will not succeed.  Check to
10189       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10190       // constants.
10191       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10192         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10193           if (ASrcTy->getNumElements() != 0) {
10194             Value* Idxs[2];
10195             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10196             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10197             SrcTy = cast<PointerType>(CastOp->getType());
10198             SrcPTy = SrcTy->getElementType();
10199           }
10200
10201       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10202           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10203                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10204
10205         // Okay, we are casting from one integer or pointer type to another of
10206         // the same size.  Instead of casting the pointer before 
10207         // the store, cast the value to be stored.
10208         Value *NewCast;
10209         Value *SIOp0 = SI.getOperand(0);
10210         Instruction::CastOps opcode = Instruction::BitCast;
10211         const Type* CastSrcTy = SIOp0->getType();
10212         const Type* CastDstTy = SrcPTy;
10213         if (isa<PointerType>(CastDstTy)) {
10214           if (CastSrcTy->isInteger())
10215             opcode = Instruction::IntToPtr;
10216         } else if (isa<IntegerType>(CastDstTy)) {
10217           if (isa<PointerType>(SIOp0->getType()))
10218             opcode = Instruction::PtrToInt;
10219         }
10220         if (Constant *C = dyn_cast<Constant>(SIOp0))
10221           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10222         else
10223           NewCast = IC.InsertNewInstBefore(
10224             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10225             SI);
10226         return new StoreInst(NewCast, CastOp);
10227       }
10228     }
10229   }
10230   return 0;
10231 }
10232
10233 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10234   Value *Val = SI.getOperand(0);
10235   Value *Ptr = SI.getOperand(1);
10236
10237   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10238     EraseInstFromFunction(SI);
10239     ++NumCombined;
10240     return 0;
10241   }
10242   
10243   // If the RHS is an alloca with a single use, zapify the store, making the
10244   // alloca dead.
10245   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10246     if (isa<AllocaInst>(Ptr)) {
10247       EraseInstFromFunction(SI);
10248       ++NumCombined;
10249       return 0;
10250     }
10251     
10252     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10253       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10254           GEP->getOperand(0)->hasOneUse()) {
10255         EraseInstFromFunction(SI);
10256         ++NumCombined;
10257         return 0;
10258       }
10259   }
10260
10261   // Attempt to improve the alignment.
10262   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10263   if (KnownAlign >
10264       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10265                                 SI.getAlignment()))
10266     SI.setAlignment(KnownAlign);
10267
10268   // Do really simple DSE, to catch cases where there are several consequtive
10269   // stores to the same location, separated by a few arithmetic operations. This
10270   // situation often occurs with bitfield accesses.
10271   BasicBlock::iterator BBI = &SI;
10272   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10273        --ScanInsts) {
10274     --BBI;
10275     
10276     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10277       // Prev store isn't volatile, and stores to the same location?
10278       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10279         ++NumDeadStore;
10280         ++BBI;
10281         EraseInstFromFunction(*PrevSI);
10282         continue;
10283       }
10284       break;
10285     }
10286     
10287     // If this is a load, we have to stop.  However, if the loaded value is from
10288     // the pointer we're loading and is producing the pointer we're storing,
10289     // then *this* store is dead (X = load P; store X -> P).
10290     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10291       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10292         EraseInstFromFunction(SI);
10293         ++NumCombined;
10294         return 0;
10295       }
10296       // Otherwise, this is a load from some other location.  Stores before it
10297       // may not be dead.
10298       break;
10299     }
10300     
10301     // Don't skip over loads or things that can modify memory.
10302     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10303       break;
10304   }
10305   
10306   
10307   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10308
10309   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10310   if (isa<ConstantPointerNull>(Ptr)) {
10311     if (!isa<UndefValue>(Val)) {
10312       SI.setOperand(0, UndefValue::get(Val->getType()));
10313       if (Instruction *U = dyn_cast<Instruction>(Val))
10314         AddToWorkList(U);  // Dropped a use.
10315       ++NumCombined;
10316     }
10317     return 0;  // Do not modify these!
10318   }
10319
10320   // store undef, Ptr -> noop
10321   if (isa<UndefValue>(Val)) {
10322     EraseInstFromFunction(SI);
10323     ++NumCombined;
10324     return 0;
10325   }
10326
10327   // If the pointer destination is a cast, see if we can fold the cast into the
10328   // source instead.
10329   if (isa<CastInst>(Ptr))
10330     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10331       return Res;
10332   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10333     if (CE->isCast())
10334       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10335         return Res;
10336
10337   
10338   // If this store is the last instruction in the basic block, and if the block
10339   // ends with an unconditional branch, try to move it to the successor block.
10340   BBI = &SI; ++BBI;
10341   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10342     if (BI->isUnconditional())
10343       if (SimplifyStoreAtEndOfBlock(SI))
10344         return 0;  // xform done!
10345   
10346   return 0;
10347 }
10348
10349 /// SimplifyStoreAtEndOfBlock - Turn things like:
10350 ///   if () { *P = v1; } else { *P = v2 }
10351 /// into a phi node with a store in the successor.
10352 ///
10353 /// Simplify things like:
10354 ///   *P = v1; if () { *P = v2; }
10355 /// into a phi node with a store in the successor.
10356 ///
10357 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10358   BasicBlock *StoreBB = SI.getParent();
10359   
10360   // Check to see if the successor block has exactly two incoming edges.  If
10361   // so, see if the other predecessor contains a store to the same location.
10362   // if so, insert a PHI node (if needed) and move the stores down.
10363   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10364   
10365   // Determine whether Dest has exactly two predecessors and, if so, compute
10366   // the other predecessor.
10367   pred_iterator PI = pred_begin(DestBB);
10368   BasicBlock *OtherBB = 0;
10369   if (*PI != StoreBB)
10370     OtherBB = *PI;
10371   ++PI;
10372   if (PI == pred_end(DestBB))
10373     return false;
10374   
10375   if (*PI != StoreBB) {
10376     if (OtherBB)
10377       return false;
10378     OtherBB = *PI;
10379   }
10380   if (++PI != pred_end(DestBB))
10381     return false;
10382   
10383   
10384   // Verify that the other block ends in a branch and is not otherwise empty.
10385   BasicBlock::iterator BBI = OtherBB->getTerminator();
10386   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10387   if (!OtherBr || BBI == OtherBB->begin())
10388     return false;
10389   
10390   // If the other block ends in an unconditional branch, check for the 'if then
10391   // else' case.  there is an instruction before the branch.
10392   StoreInst *OtherStore = 0;
10393   if (OtherBr->isUnconditional()) {
10394     // If this isn't a store, or isn't a store to the same location, bail out.
10395     --BBI;
10396     OtherStore = dyn_cast<StoreInst>(BBI);
10397     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10398       return false;
10399   } else {
10400     // Otherwise, the other block ended with a conditional branch. If one of the
10401     // destinations is StoreBB, then we have the if/then case.
10402     if (OtherBr->getSuccessor(0) != StoreBB && 
10403         OtherBr->getSuccessor(1) != StoreBB)
10404       return false;
10405     
10406     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10407     // if/then triangle.  See if there is a store to the same ptr as SI that
10408     // lives in OtherBB.
10409     for (;; --BBI) {
10410       // Check to see if we find the matching store.
10411       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10412         if (OtherStore->getOperand(1) != SI.getOperand(1))
10413           return false;
10414         break;
10415       }
10416       // If we find something that may be using the stored value, or if we run
10417       // out of instructions, we can't do the xform.
10418       if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10419           BBI == OtherBB->begin())
10420         return false;
10421     }
10422     
10423     // In order to eliminate the store in OtherBr, we have to
10424     // make sure nothing reads the stored value in StoreBB.
10425     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10426       // FIXME: This should really be AA driven.
10427       if (isa<LoadInst>(I) || I->mayWriteToMemory())
10428         return false;
10429     }
10430   }
10431   
10432   // Insert a PHI node now if we need it.
10433   Value *MergedVal = OtherStore->getOperand(0);
10434   if (MergedVal != SI.getOperand(0)) {
10435     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10436     PN->reserveOperandSpace(2);
10437     PN->addIncoming(SI.getOperand(0), SI.getParent());
10438     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10439     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10440   }
10441   
10442   // Advance to a place where it is safe to insert the new store and
10443   // insert it.
10444   BBI = DestBB->getFirstNonPHI();
10445   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10446                                     OtherStore->isVolatile()), *BBI);
10447   
10448   // Nuke the old stores.
10449   EraseInstFromFunction(SI);
10450   EraseInstFromFunction(*OtherStore);
10451   ++NumCombined;
10452   return true;
10453 }
10454
10455
10456 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10457   // Change br (not X), label True, label False to: br X, label False, True
10458   Value *X = 0;
10459   BasicBlock *TrueDest;
10460   BasicBlock *FalseDest;
10461   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10462       !isa<Constant>(X)) {
10463     // Swap Destinations and condition...
10464     BI.setCondition(X);
10465     BI.setSuccessor(0, FalseDest);
10466     BI.setSuccessor(1, TrueDest);
10467     return &BI;
10468   }
10469
10470   // Cannonicalize fcmp_one -> fcmp_oeq
10471   FCmpInst::Predicate FPred; Value *Y;
10472   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10473                              TrueDest, FalseDest)))
10474     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10475          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10476       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10477       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10478       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10479       NewSCC->takeName(I);
10480       // Swap Destinations and condition...
10481       BI.setCondition(NewSCC);
10482       BI.setSuccessor(0, FalseDest);
10483       BI.setSuccessor(1, TrueDest);
10484       RemoveFromWorkList(I);
10485       I->eraseFromParent();
10486       AddToWorkList(NewSCC);
10487       return &BI;
10488     }
10489
10490   // Cannonicalize icmp_ne -> icmp_eq
10491   ICmpInst::Predicate IPred;
10492   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10493                       TrueDest, FalseDest)))
10494     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10495          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10496          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10497       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10498       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10499       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10500       NewSCC->takeName(I);
10501       // Swap Destinations and condition...
10502       BI.setCondition(NewSCC);
10503       BI.setSuccessor(0, FalseDest);
10504       BI.setSuccessor(1, TrueDest);
10505       RemoveFromWorkList(I);
10506       I->eraseFromParent();;
10507       AddToWorkList(NewSCC);
10508       return &BI;
10509     }
10510
10511   return 0;
10512 }
10513
10514 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10515   Value *Cond = SI.getCondition();
10516   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10517     if (I->getOpcode() == Instruction::Add)
10518       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10519         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10520         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10521           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10522                                                 AddRHS));
10523         SI.setOperand(0, I->getOperand(0));
10524         AddToWorkList(I);
10525         return &SI;
10526       }
10527   }
10528   return 0;
10529 }
10530
10531 // This is the recursive version of BuildSubAggregate. It takes a few different
10532 // arguments. Idxs is the index within the nested struct From that we are
10533 // looking at now (which is of type IndexedType). IdxSkip is the number of
10534 // indices from Idxs that should be left out when inserting into the resulting
10535 // struct. To is the result struct built so far, new insertvalue instructions
10536 // build on that.
10537 Value *InstCombiner::BuildSubAggregate(Value *From, Value* To, const Type *IndexedType,
10538                                  SmallVector<unsigned, 10> &Idxs,
10539                                  unsigned IdxSkip,
10540                                  Instruction &InsertBefore) {
10541   const llvm::StructType *STy = llvm::dyn_cast<llvm::StructType>(IndexedType);
10542   if (STy) {
10543     // General case, the type indexed by Idxs is a struct
10544     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
10545       // Process each struct element recursively
10546       Idxs.push_back(i);
10547       To = BuildSubAggregate(From, To, STy->getElementType(i), Idxs, IdxSkip, InsertBefore);
10548       Idxs.pop_back();
10549     }
10550     return To;
10551   } else {
10552     // Base case, the type indexed by SourceIdxs is not a struct
10553     // Load the value from the nested struct into the sub struct (and skip
10554     // IdxSkip indices when indexing the sub struct).
10555     Instruction *V = llvm::ExtractValueInst::Create(From, Idxs.begin(), Idxs.end(), "tmp");
10556     InsertNewInstBefore(V, InsertBefore);
10557     Instruction *Ins = llvm::InsertValueInst::Create(To, V, Idxs.begin() + IdxSkip, Idxs.end(), "tmp");
10558     InsertNewInstBefore(Ins, InsertBefore);
10559     return Ins;
10560   }
10561 }
10562
10563 // This helper takes a nested struct and extracts a part of it (which is again a
10564 // struct) into a new value. For example, given the struct:
10565 // { a, { b, { c, d }, e } }
10566 // and the indices "1, 1" this returns
10567 // { c, d }.
10568 //
10569 // It does this by inserting an extractvalue and insertvalue for each element in
10570 // the resulting struct, as opposed to just inserting a single struct. This
10571 // allows for later folding of these individual extractvalue instructions with
10572 // insertvalue instructions that fill the nested struct.
10573 //
10574 // Any inserted instructions are inserted before InsertBefore
10575 Value *InstCombiner::BuildSubAggregate(Value *From, const unsigned *idx_begin, const unsigned *idx_end, Instruction &InsertBefore) {
10576   const Type *IndexedType = ExtractValueInst::getIndexedType(From->getType(), idx_begin, idx_end);
10577   Value *To = UndefValue::get(IndexedType);
10578   SmallVector<unsigned, 10> Idxs(idx_begin, idx_end);
10579   unsigned IdxSkip = Idxs.size();
10580
10581   return BuildSubAggregate(From, To, IndexedType, Idxs, IdxSkip, InsertBefore);
10582 }
10583
10584 /// FindScalarValue - Given an aggregrate and an sequence of indices, see if the
10585 /// scalar value indexed is already around as a register, for example if it were
10586 /// inserted directly into the aggregrate.
10587 Value *InstCombiner::FindScalarValue(Value *V, const unsigned *idx_begin,
10588                                 const unsigned *idx_end, Instruction &InsertBefore) {
10589   // Nothing to index? Just return V then (this is useful at the end of our
10590   // recursion)
10591   if (idx_begin == idx_end)
10592     return V;
10593   // We have indices, so V should have an indexable type
10594   assert((isa<StructType>(V->getType()) || isa<ArrayType>(V->getType()))
10595          && "Not looking at a struct or array?");
10596   assert(ExtractValueInst::getIndexedType(V->getType(), idx_begin, idx_end)
10597          && "Invalid indices for type?");
10598   const CompositeType *PTy = cast<CompositeType>(V->getType());
10599   
10600   if (isa<UndefValue>(V))
10601     return UndefValue::get(ExtractValueInst::getIndexedType(PTy,
10602                                                               idx_begin,
10603                                                               idx_end));
10604   else if (isa<ConstantAggregateZero>(V))
10605     return Constant::getNullValue(ExtractValueInst::getIndexedType(PTy, 
10606                                                                      idx_begin,
10607                                                                      idx_end));
10608   else if (Constant *C = dyn_cast<Constant>(V)) {
10609     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C))
10610       // Recursively process this constant
10611       return FindScalarValue(C->getOperand(*idx_begin), ++idx_begin, idx_end, InsertBefore);
10612   } else if (InsertValueInst *I = dyn_cast<InsertValueInst>(V)) {
10613     // Loop the indices for the insertvalue instruction in parallel with the
10614     // requested indices
10615     const unsigned *req_idx = idx_begin;
10616     for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++req_idx) {
10617       if (req_idx == idx_end)
10618         // The requested index is a part of a nested aggregate. Handle this
10619         // specially.
10620         return BuildSubAggregate(V, idx_begin, req_idx, InsertBefore);
10621       
10622       // This insert value inserts something else than what we are looking for.
10623       // See if the (aggregrate) value inserted into has the value we are
10624       // looking for, then.
10625       if (*req_idx != *i)
10626         return FindScalarValue(I->getAggregateOperand(), idx_begin, idx_end, InsertBefore);
10627     }
10628     // If we end up here, the indices of the insertvalue match with those
10629     // requested (though possibly only partially). Now we recursively look at
10630     // the inserted value, passing any remaining indices.
10631     return FindScalarValue(I->getInsertedValueOperand(), req_idx, idx_end, InsertBefore);
10632   } else if (ExtractValueInst *I = dyn_cast<ExtractValueInst>(V)) {
10633     // If we're extracting a value from an aggregrate that was extracted from
10634     // something else, we can extract from that something else directly instead.
10635     // However, we will need to chain I's indices with the requested indices.
10636    
10637     // Calculate the number of indices required 
10638     unsigned size = I->getNumIndices() + (idx_end - idx_begin);
10639     // Allocate some space to put the new indices in
10640     unsigned *new_begin = new unsigned[size];
10641     // Auto cleanup this array
10642     std::auto_ptr<unsigned> newptr(new_begin);
10643     // Start inserting at the beginning
10644     unsigned *new_end = new_begin;
10645     // Add indices from the extract value instruction
10646     for (const unsigned *i = I->idx_begin(), *e = I->idx_end(); i != e; ++i, ++new_end)
10647       *new_end = *i;
10648     
10649     // Add requested indices
10650     for (const unsigned *i = idx_begin, *e = idx_end; i != e; ++i, ++new_end)
10651       *new_end = *i;
10652
10653     assert((unsigned)(new_end - new_begin) == size && "Number of indices added not correct?");
10654     
10655     return FindScalarValue(I->getAggregateOperand(), new_begin, new_end, InsertBefore);
10656   }
10657   // Otherwise, we don't know (such as, extracting from a function return value
10658   // or load instruction)
10659   return 0;
10660 }
10661
10662 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10663   // See if we are trying to extract a known value. If so, use that instead.
10664   if (Value *Elt = FindScalarValue(EV.getOperand(0), EV.idx_begin(), EV.idx_end(), EV))
10665     return ReplaceInstUsesWith(EV, Elt);
10666
10667   // No changes
10668   return 0;
10669 }
10670
10671 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10672 /// is to leave as a vector operation.
10673 static bool CheapToScalarize(Value *V, bool isConstant) {
10674   if (isa<ConstantAggregateZero>(V)) 
10675     return true;
10676   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10677     if (isConstant) return true;
10678     // If all elts are the same, we can extract.
10679     Constant *Op0 = C->getOperand(0);
10680     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10681       if (C->getOperand(i) != Op0)
10682         return false;
10683     return true;
10684   }
10685   Instruction *I = dyn_cast<Instruction>(V);
10686   if (!I) return false;
10687   
10688   // Insert element gets simplified to the inserted element or is deleted if
10689   // this is constant idx extract element and its a constant idx insertelt.
10690   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10691       isa<ConstantInt>(I->getOperand(2)))
10692     return true;
10693   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10694     return true;
10695   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10696     if (BO->hasOneUse() &&
10697         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10698          CheapToScalarize(BO->getOperand(1), isConstant)))
10699       return true;
10700   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10701     if (CI->hasOneUse() &&
10702         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10703          CheapToScalarize(CI->getOperand(1), isConstant)))
10704       return true;
10705   
10706   return false;
10707 }
10708
10709 /// Read and decode a shufflevector mask.
10710 ///
10711 /// It turns undef elements into values that are larger than the number of
10712 /// elements in the input.
10713 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10714   unsigned NElts = SVI->getType()->getNumElements();
10715   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10716     return std::vector<unsigned>(NElts, 0);
10717   if (isa<UndefValue>(SVI->getOperand(2)))
10718     return std::vector<unsigned>(NElts, 2*NElts);
10719
10720   std::vector<unsigned> Result;
10721   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10722   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10723     if (isa<UndefValue>(*i))
10724       Result.push_back(NElts*2);  // undef -> 8
10725     else
10726       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10727   return Result;
10728 }
10729
10730 /// FindScalarElement - Given a vector and an element number, see if the scalar
10731 /// value is already around as a register, for example if it were inserted then
10732 /// extracted from the vector.
10733 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10734   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10735   const VectorType *PTy = cast<VectorType>(V->getType());
10736   unsigned Width = PTy->getNumElements();
10737   if (EltNo >= Width)  // Out of range access.
10738     return UndefValue::get(PTy->getElementType());
10739   
10740   if (isa<UndefValue>(V))
10741     return UndefValue::get(PTy->getElementType());
10742   else if (isa<ConstantAggregateZero>(V))
10743     return Constant::getNullValue(PTy->getElementType());
10744   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10745     return CP->getOperand(EltNo);
10746   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10747     // If this is an insert to a variable element, we don't know what it is.
10748     if (!isa<ConstantInt>(III->getOperand(2))) 
10749       return 0;
10750     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10751     
10752     // If this is an insert to the element we are looking for, return the
10753     // inserted value.
10754     if (EltNo == IIElt) 
10755       return III->getOperand(1);
10756     
10757     // Otherwise, the insertelement doesn't modify the value, recurse on its
10758     // vector input.
10759     return FindScalarElement(III->getOperand(0), EltNo);
10760   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10761     unsigned InEl = getShuffleMask(SVI)[EltNo];
10762     if (InEl < Width)
10763       return FindScalarElement(SVI->getOperand(0), InEl);
10764     else if (InEl < Width*2)
10765       return FindScalarElement(SVI->getOperand(1), InEl - Width);
10766     else
10767       return UndefValue::get(PTy->getElementType());
10768   }
10769   
10770   // Otherwise, we don't know.
10771   return 0;
10772 }
10773
10774 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10775   // If vector val is undef, replace extract with scalar undef.
10776   if (isa<UndefValue>(EI.getOperand(0)))
10777     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10778
10779   // If vector val is constant 0, replace extract with scalar 0.
10780   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10781     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10782   
10783   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10784     // If vector val is constant with all elements the same, replace EI with
10785     // that element. When the elements are not identical, we cannot replace yet
10786     // (we do that below, but only when the index is constant).
10787     Constant *op0 = C->getOperand(0);
10788     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10789       if (C->getOperand(i) != op0) {
10790         op0 = 0; 
10791         break;
10792       }
10793     if (op0)
10794       return ReplaceInstUsesWith(EI, op0);
10795   }
10796   
10797   // If extracting a specified index from the vector, see if we can recursively
10798   // find a previously computed scalar that was inserted into the vector.
10799   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10800     unsigned IndexVal = IdxC->getZExtValue();
10801     unsigned VectorWidth = 
10802       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10803       
10804     // If this is extracting an invalid index, turn this into undef, to avoid
10805     // crashing the code below.
10806     if (IndexVal >= VectorWidth)
10807       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10808     
10809     // This instruction only demands the single element from the input vector.
10810     // If the input vector has a single use, simplify it based on this use
10811     // property.
10812     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10813       uint64_t UndefElts;
10814       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10815                                                 1 << IndexVal,
10816                                                 UndefElts)) {
10817         EI.setOperand(0, V);
10818         return &EI;
10819       }
10820     }
10821     
10822     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10823       return ReplaceInstUsesWith(EI, Elt);
10824     
10825     // If the this extractelement is directly using a bitcast from a vector of
10826     // the same number of elements, see if we can find the source element from
10827     // it.  In this case, we will end up needing to bitcast the scalars.
10828     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10829       if (const VectorType *VT = 
10830               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10831         if (VT->getNumElements() == VectorWidth)
10832           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10833             return new BitCastInst(Elt, EI.getType());
10834     }
10835   }
10836   
10837   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10838     if (I->hasOneUse()) {
10839       // Push extractelement into predecessor operation if legal and
10840       // profitable to do so
10841       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10842         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10843         if (CheapToScalarize(BO, isConstantElt)) {
10844           ExtractElementInst *newEI0 = 
10845             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10846                                    EI.getName()+".lhs");
10847           ExtractElementInst *newEI1 =
10848             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10849                                    EI.getName()+".rhs");
10850           InsertNewInstBefore(newEI0, EI);
10851           InsertNewInstBefore(newEI1, EI);
10852           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10853         }
10854       } else if (isa<LoadInst>(I)) {
10855         unsigned AS = 
10856           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10857         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10858                                          PointerType::get(EI.getType(), AS),EI);
10859         GetElementPtrInst *GEP =
10860           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10861         InsertNewInstBefore(GEP, EI);
10862         return new LoadInst(GEP);
10863       }
10864     }
10865     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10866       // Extracting the inserted element?
10867       if (IE->getOperand(2) == EI.getOperand(1))
10868         return ReplaceInstUsesWith(EI, IE->getOperand(1));
10869       // If the inserted and extracted elements are constants, they must not
10870       // be the same value, extract from the pre-inserted value instead.
10871       if (isa<Constant>(IE->getOperand(2)) &&
10872           isa<Constant>(EI.getOperand(1))) {
10873         AddUsesToWorkList(EI);
10874         EI.setOperand(0, IE->getOperand(0));
10875         return &EI;
10876       }
10877     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10878       // If this is extracting an element from a shufflevector, figure out where
10879       // it came from and extract from the appropriate input element instead.
10880       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10881         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10882         Value *Src;
10883         if (SrcIdx < SVI->getType()->getNumElements())
10884           Src = SVI->getOperand(0);
10885         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10886           SrcIdx -= SVI->getType()->getNumElements();
10887           Src = SVI->getOperand(1);
10888         } else {
10889           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10890         }
10891         return new ExtractElementInst(Src, SrcIdx);
10892       }
10893     }
10894   }
10895   return 0;
10896 }
10897
10898 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10899 /// elements from either LHS or RHS, return the shuffle mask and true. 
10900 /// Otherwise, return false.
10901 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10902                                          std::vector<Constant*> &Mask) {
10903   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10904          "Invalid CollectSingleShuffleElements");
10905   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10906
10907   if (isa<UndefValue>(V)) {
10908     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10909     return true;
10910   } else if (V == LHS) {
10911     for (unsigned i = 0; i != NumElts; ++i)
10912       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10913     return true;
10914   } else if (V == RHS) {
10915     for (unsigned i = 0; i != NumElts; ++i)
10916       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10917     return true;
10918   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10919     // If this is an insert of an extract from some other vector, include it.
10920     Value *VecOp    = IEI->getOperand(0);
10921     Value *ScalarOp = IEI->getOperand(1);
10922     Value *IdxOp    = IEI->getOperand(2);
10923     
10924     if (!isa<ConstantInt>(IdxOp))
10925       return false;
10926     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10927     
10928     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
10929       // Okay, we can handle this if the vector we are insertinting into is
10930       // transitively ok.
10931       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10932         // If so, update the mask to reflect the inserted undef.
10933         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10934         return true;
10935       }      
10936     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10937       if (isa<ConstantInt>(EI->getOperand(1)) &&
10938           EI->getOperand(0)->getType() == V->getType()) {
10939         unsigned ExtractedIdx =
10940           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10941         
10942         // This must be extracting from either LHS or RHS.
10943         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10944           // Okay, we can handle this if the vector we are insertinting into is
10945           // transitively ok.
10946           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10947             // If so, update the mask to reflect the inserted value.
10948             if (EI->getOperand(0) == LHS) {
10949               Mask[InsertedIdx & (NumElts-1)] = 
10950                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10951             } else {
10952               assert(EI->getOperand(0) == RHS);
10953               Mask[InsertedIdx & (NumElts-1)] = 
10954                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10955               
10956             }
10957             return true;
10958           }
10959         }
10960       }
10961     }
10962   }
10963   // TODO: Handle shufflevector here!
10964   
10965   return false;
10966 }
10967
10968 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10969 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
10970 /// that computes V and the LHS value of the shuffle.
10971 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10972                                      Value *&RHS) {
10973   assert(isa<VectorType>(V->getType()) && 
10974          (RHS == 0 || V->getType() == RHS->getType()) &&
10975          "Invalid shuffle!");
10976   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10977
10978   if (isa<UndefValue>(V)) {
10979     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10980     return V;
10981   } else if (isa<ConstantAggregateZero>(V)) {
10982     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10983     return V;
10984   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10985     // If this is an insert of an extract from some other vector, include it.
10986     Value *VecOp    = IEI->getOperand(0);
10987     Value *ScalarOp = IEI->getOperand(1);
10988     Value *IdxOp    = IEI->getOperand(2);
10989     
10990     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10991       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10992           EI->getOperand(0)->getType() == V->getType()) {
10993         unsigned ExtractedIdx =
10994           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10995         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10996         
10997         // Either the extracted from or inserted into vector must be RHSVec,
10998         // otherwise we'd end up with a shuffle of three inputs.
10999         if (EI->getOperand(0) == RHS || RHS == 0) {
11000           RHS = EI->getOperand(0);
11001           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11002           Mask[InsertedIdx & (NumElts-1)] = 
11003             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11004           return V;
11005         }
11006         
11007         if (VecOp == RHS) {
11008           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11009           // Everything but the extracted element is replaced with the RHS.
11010           for (unsigned i = 0; i != NumElts; ++i) {
11011             if (i != InsertedIdx)
11012               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11013           }
11014           return V;
11015         }
11016         
11017         // If this insertelement is a chain that comes from exactly these two
11018         // vectors, return the vector and the effective shuffle.
11019         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11020           return EI->getOperand(0);
11021         
11022       }
11023     }
11024   }
11025   // TODO: Handle shufflevector here!
11026   
11027   // Otherwise, can't do anything fancy.  Return an identity vector.
11028   for (unsigned i = 0; i != NumElts; ++i)
11029     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11030   return V;
11031 }
11032
11033 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11034   Value *VecOp    = IE.getOperand(0);
11035   Value *ScalarOp = IE.getOperand(1);
11036   Value *IdxOp    = IE.getOperand(2);
11037   
11038   // Inserting an undef or into an undefined place, remove this.
11039   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11040     ReplaceInstUsesWith(IE, VecOp);
11041   
11042   // If the inserted element was extracted from some other vector, and if the 
11043   // indexes are constant, try to turn this into a shufflevector operation.
11044   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11045     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11046         EI->getOperand(0)->getType() == IE.getType()) {
11047       unsigned NumVectorElts = IE.getType()->getNumElements();
11048       unsigned ExtractedIdx =
11049         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11050       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11051       
11052       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11053         return ReplaceInstUsesWith(IE, VecOp);
11054       
11055       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11056         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11057       
11058       // If we are extracting a value from a vector, then inserting it right
11059       // back into the same place, just use the input vector.
11060       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11061         return ReplaceInstUsesWith(IE, VecOp);      
11062       
11063       // We could theoretically do this for ANY input.  However, doing so could
11064       // turn chains of insertelement instructions into a chain of shufflevector
11065       // instructions, and right now we do not merge shufflevectors.  As such,
11066       // only do this in a situation where it is clear that there is benefit.
11067       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11068         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11069         // the values of VecOp, except then one read from EIOp0.
11070         // Build a new shuffle mask.
11071         std::vector<Constant*> Mask;
11072         if (isa<UndefValue>(VecOp))
11073           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11074         else {
11075           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11076           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11077                                                        NumVectorElts));
11078         } 
11079         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11080         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11081                                      ConstantVector::get(Mask));
11082       }
11083       
11084       // If this insertelement isn't used by some other insertelement, turn it
11085       // (and any insertelements it points to), into one big shuffle.
11086       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11087         std::vector<Constant*> Mask;
11088         Value *RHS = 0;
11089         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11090         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11091         // We now have a shuffle of LHS, RHS, Mask.
11092         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11093       }
11094     }
11095   }
11096
11097   return 0;
11098 }
11099
11100
11101 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11102   Value *LHS = SVI.getOperand(0);
11103   Value *RHS = SVI.getOperand(1);
11104   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11105
11106   bool MadeChange = false;
11107   
11108   // Undefined shuffle mask -> undefined value.
11109   if (isa<UndefValue>(SVI.getOperand(2)))
11110     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11111   
11112   // If we have shuffle(x, undef, mask) and any elements of mask refer to
11113   // the undef, change them to undefs.
11114   if (isa<UndefValue>(SVI.getOperand(1))) {
11115     // Scan to see if there are any references to the RHS.  If so, replace them
11116     // with undef element refs and set MadeChange to true.
11117     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11118       if (Mask[i] >= e && Mask[i] != 2*e) {
11119         Mask[i] = 2*e;
11120         MadeChange = true;
11121       }
11122     }
11123     
11124     if (MadeChange) {
11125       // Remap any references to RHS to use LHS.
11126       std::vector<Constant*> Elts;
11127       for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11128         if (Mask[i] == 2*e)
11129           Elts.push_back(UndefValue::get(Type::Int32Ty));
11130         else
11131           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11132       }
11133       SVI.setOperand(2, ConstantVector::get(Elts));
11134     }
11135   }
11136   
11137   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11138   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11139   if (LHS == RHS || isa<UndefValue>(LHS)) {
11140     if (isa<UndefValue>(LHS) && LHS == RHS) {
11141       // shuffle(undef,undef,mask) -> undef.
11142       return ReplaceInstUsesWith(SVI, LHS);
11143     }
11144     
11145     // Remap any references to RHS to use LHS.
11146     std::vector<Constant*> Elts;
11147     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11148       if (Mask[i] >= 2*e)
11149         Elts.push_back(UndefValue::get(Type::Int32Ty));
11150       else {
11151         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11152             (Mask[i] <  e && isa<UndefValue>(LHS)))
11153           Mask[i] = 2*e;     // Turn into undef.
11154         else
11155           Mask[i] &= (e-1);  // Force to LHS.
11156         Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11157       }
11158     }
11159     SVI.setOperand(0, SVI.getOperand(1));
11160     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11161     SVI.setOperand(2, ConstantVector::get(Elts));
11162     LHS = SVI.getOperand(0);
11163     RHS = SVI.getOperand(1);
11164     MadeChange = true;
11165   }
11166   
11167   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11168   bool isLHSID = true, isRHSID = true;
11169     
11170   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11171     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11172     // Is this an identity shuffle of the LHS value?
11173     isLHSID &= (Mask[i] == i);
11174       
11175     // Is this an identity shuffle of the RHS value?
11176     isRHSID &= (Mask[i]-e == i);
11177   }
11178
11179   // Eliminate identity shuffles.
11180   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11181   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11182   
11183   // If the LHS is a shufflevector itself, see if we can combine it with this
11184   // one without producing an unusual shuffle.  Here we are really conservative:
11185   // we are absolutely afraid of producing a shuffle mask not in the input
11186   // program, because the code gen may not be smart enough to turn a merged
11187   // shuffle into two specific shuffles: it may produce worse code.  As such,
11188   // we only merge two shuffles if the result is one of the two input shuffle
11189   // masks.  In this case, merging the shuffles just removes one instruction,
11190   // which we know is safe.  This is good for things like turning:
11191   // (splat(splat)) -> splat.
11192   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11193     if (isa<UndefValue>(RHS)) {
11194       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11195
11196       std::vector<unsigned> NewMask;
11197       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11198         if (Mask[i] >= 2*e)
11199           NewMask.push_back(2*e);
11200         else
11201           NewMask.push_back(LHSMask[Mask[i]]);
11202       
11203       // If the result mask is equal to the src shuffle or this shuffle mask, do
11204       // the replacement.
11205       if (NewMask == LHSMask || NewMask == Mask) {
11206         std::vector<Constant*> Elts;
11207         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11208           if (NewMask[i] >= e*2) {
11209             Elts.push_back(UndefValue::get(Type::Int32Ty));
11210           } else {
11211             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11212           }
11213         }
11214         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11215                                      LHSSVI->getOperand(1),
11216                                      ConstantVector::get(Elts));
11217       }
11218     }
11219   }
11220
11221   return MadeChange ? &SVI : 0;
11222 }
11223
11224
11225
11226
11227 /// TryToSinkInstruction - Try to move the specified instruction from its
11228 /// current block into the beginning of DestBlock, which can only happen if it's
11229 /// safe to move the instruction past all of the instructions between it and the
11230 /// end of its block.
11231 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11232   assert(I->hasOneUse() && "Invariants didn't hold!");
11233
11234   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11235   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11236     return false;
11237
11238   // Do not sink alloca instructions out of the entry block.
11239   if (isa<AllocaInst>(I) && I->getParent() ==
11240         &DestBlock->getParent()->getEntryBlock())
11241     return false;
11242
11243   // We can only sink load instructions if there is nothing between the load and
11244   // the end of block that could change the value.
11245   if (I->mayReadFromMemory()) {
11246     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11247          Scan != E; ++Scan)
11248       if (Scan->mayWriteToMemory())
11249         return false;
11250   }
11251
11252   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11253
11254   I->moveBefore(InsertPos);
11255   ++NumSunkInst;
11256   return true;
11257 }
11258
11259
11260 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11261 /// all reachable code to the worklist.
11262 ///
11263 /// This has a couple of tricks to make the code faster and more powerful.  In
11264 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11265 /// them to the worklist (this significantly speeds up instcombine on code where
11266 /// many instructions are dead or constant).  Additionally, if we find a branch
11267 /// whose condition is a known constant, we only visit the reachable successors.
11268 ///
11269 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11270                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11271                                        InstCombiner &IC,
11272                                        const TargetData *TD) {
11273   std::vector<BasicBlock*> Worklist;
11274   Worklist.push_back(BB);
11275
11276   while (!Worklist.empty()) {
11277     BB = Worklist.back();
11278     Worklist.pop_back();
11279     
11280     // We have now visited this block!  If we've already been here, ignore it.
11281     if (!Visited.insert(BB)) continue;
11282     
11283     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11284       Instruction *Inst = BBI++;
11285       
11286       // DCE instruction if trivially dead.
11287       if (isInstructionTriviallyDead(Inst)) {
11288         ++NumDeadInst;
11289         DOUT << "IC: DCE: " << *Inst;
11290         Inst->eraseFromParent();
11291         continue;
11292       }
11293       
11294       // ConstantProp instruction if trivially constant.
11295       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11296         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11297         Inst->replaceAllUsesWith(C);
11298         ++NumConstProp;
11299         Inst->eraseFromParent();
11300         continue;
11301       }
11302      
11303       IC.AddToWorkList(Inst);
11304     }
11305
11306     // Recursively visit successors.  If this is a branch or switch on a
11307     // constant, only visit the reachable successor.
11308     TerminatorInst *TI = BB->getTerminator();
11309     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11310       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11311         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11312         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11313         Worklist.push_back(ReachableBB);
11314         continue;
11315       }
11316     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11317       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11318         // See if this is an explicit destination.
11319         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11320           if (SI->getCaseValue(i) == Cond) {
11321             BasicBlock *ReachableBB = SI->getSuccessor(i);
11322             Worklist.push_back(ReachableBB);
11323             continue;
11324           }
11325         
11326         // Otherwise it is the default destination.
11327         Worklist.push_back(SI->getSuccessor(0));
11328         continue;
11329       }
11330     }
11331     
11332     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11333       Worklist.push_back(TI->getSuccessor(i));
11334   }
11335 }
11336
11337 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11338   bool Changed = false;
11339   TD = &getAnalysis<TargetData>();
11340   
11341   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11342              << F.getNameStr() << "\n");
11343
11344   {
11345     // Do a depth-first traversal of the function, populate the worklist with
11346     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11347     // track of which blocks we visit.
11348     SmallPtrSet<BasicBlock*, 64> Visited;
11349     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11350
11351     // Do a quick scan over the function.  If we find any blocks that are
11352     // unreachable, remove any instructions inside of them.  This prevents
11353     // the instcombine code from having to deal with some bad special cases.
11354     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11355       if (!Visited.count(BB)) {
11356         Instruction *Term = BB->getTerminator();
11357         while (Term != BB->begin()) {   // Remove instrs bottom-up
11358           BasicBlock::iterator I = Term; --I;
11359
11360           DOUT << "IC: DCE: " << *I;
11361           ++NumDeadInst;
11362
11363           if (!I->use_empty())
11364             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11365           I->eraseFromParent();
11366         }
11367       }
11368   }
11369
11370   while (!Worklist.empty()) {
11371     Instruction *I = RemoveOneFromWorkList();
11372     if (I == 0) continue;  // skip null values.
11373
11374     // Check to see if we can DCE the instruction.
11375     if (isInstructionTriviallyDead(I)) {
11376       // Add operands to the worklist.
11377       if (I->getNumOperands() < 4)
11378         AddUsesToWorkList(*I);
11379       ++NumDeadInst;
11380
11381       DOUT << "IC: DCE: " << *I;
11382
11383       I->eraseFromParent();
11384       RemoveFromWorkList(I);
11385       continue;
11386     }
11387
11388     // Instruction isn't dead, see if we can constant propagate it.
11389     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11390       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11391
11392       // Add operands to the worklist.
11393       AddUsesToWorkList(*I);
11394       ReplaceInstUsesWith(*I, C);
11395
11396       ++NumConstProp;
11397       I->eraseFromParent();
11398       RemoveFromWorkList(I);
11399       continue;
11400     }
11401
11402     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11403       // See if we can constant fold its operands.
11404       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11405         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11406           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11407             i->set(NewC);
11408         }
11409       }
11410     }
11411
11412     // See if we can trivially sink this instruction to a successor basic block.
11413     // FIXME: Remove GetResultInst test when first class support for aggregates
11414     // is implemented.
11415     if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11416       BasicBlock *BB = I->getParent();
11417       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11418       if (UserParent != BB) {
11419         bool UserIsSuccessor = false;
11420         // See if the user is one of our successors.
11421         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11422           if (*SI == UserParent) {
11423             UserIsSuccessor = true;
11424             break;
11425           }
11426
11427         // If the user is one of our immediate successors, and if that successor
11428         // only has us as a predecessors (we'd have to split the critical edge
11429         // otherwise), we can keep going.
11430         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11431             next(pred_begin(UserParent)) == pred_end(UserParent))
11432           // Okay, the CFG is simple enough, try to sink this instruction.
11433           Changed |= TryToSinkInstruction(I, UserParent);
11434       }
11435     }
11436
11437     // Now that we have an instruction, try combining it to simplify it...
11438 #ifndef NDEBUG
11439     std::string OrigI;
11440 #endif
11441     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11442     if (Instruction *Result = visit(*I)) {
11443       ++NumCombined;
11444       // Should we replace the old instruction with a new one?
11445       if (Result != I) {
11446         DOUT << "IC: Old = " << *I
11447              << "    New = " << *Result;
11448
11449         // Everything uses the new instruction now.
11450         I->replaceAllUsesWith(Result);
11451
11452         // Push the new instruction and any users onto the worklist.
11453         AddToWorkList(Result);
11454         AddUsersToWorkList(*Result);
11455
11456         // Move the name to the new instruction first.
11457         Result->takeName(I);
11458
11459         // Insert the new instruction into the basic block...
11460         BasicBlock *InstParent = I->getParent();
11461         BasicBlock::iterator InsertPos = I;
11462
11463         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11464           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11465             ++InsertPos;
11466
11467         InstParent->getInstList().insert(InsertPos, Result);
11468
11469         // Make sure that we reprocess all operands now that we reduced their
11470         // use counts.
11471         AddUsesToWorkList(*I);
11472
11473         // Instructions can end up on the worklist more than once.  Make sure
11474         // we do not process an instruction that has been deleted.
11475         RemoveFromWorkList(I);
11476
11477         // Erase the old instruction.
11478         InstParent->getInstList().erase(I);
11479       } else {
11480 #ifndef NDEBUG
11481         DOUT << "IC: Mod = " << OrigI
11482              << "    New = " << *I;
11483 #endif
11484
11485         // If the instruction was modified, it's possible that it is now dead.
11486         // if so, remove it.
11487         if (isInstructionTriviallyDead(I)) {
11488           // Make sure we process all operands now that we are reducing their
11489           // use counts.
11490           AddUsesToWorkList(*I);
11491
11492           // Instructions may end up in the worklist more than once.  Erase all
11493           // occurrences of this instruction.
11494           RemoveFromWorkList(I);
11495           I->eraseFromParent();
11496         } else {
11497           AddToWorkList(I);
11498           AddUsersToWorkList(*I);
11499         }
11500       }
11501       Changed = true;
11502     }
11503   }
11504
11505   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11506     
11507   // Do an explicit clear, this shrinks the map if needed.
11508   WorklistMap.clear();
11509   return Changed;
11510 }
11511
11512
11513 bool InstCombiner::runOnFunction(Function &F) {
11514   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11515   
11516   bool EverMadeChange = false;
11517
11518   // Iterate while there is work to do.
11519   unsigned Iteration = 0;
11520   while (DoOneIteration(F, Iteration++))
11521     EverMadeChange = true;
11522   return EverMadeChange;
11523 }
11524
11525 FunctionPass *llvm::createInstructionCombiningPass() {
11526   return new InstCombiner();
11527 }
11528