Large mechanical patch.
[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     SmallVector<Instruction*, 256> 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(&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())).second)
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     bool SimplifyDivRemOfSelect(BinaryOperator &I);
176     Instruction *commonRemTransforms(BinaryOperator &I);
177     Instruction *commonIRemTransforms(BinaryOperator &I);
178     Instruction *commonDivTransforms(BinaryOperator &I);
179     Instruction *commonIDivTransforms(BinaryOperator &I);
180     Instruction *visitUDiv(BinaryOperator &I);
181     Instruction *visitSDiv(BinaryOperator &I);
182     Instruction *visitFDiv(BinaryOperator &I);
183     Instruction *visitAnd(BinaryOperator &I);
184     Instruction *visitOr (BinaryOperator &I);
185     Instruction *visitXor(BinaryOperator &I);
186     Instruction *visitShl(BinaryOperator &I);
187     Instruction *visitAShr(BinaryOperator &I);
188     Instruction *visitLShr(BinaryOperator &I);
189     Instruction *commonShiftTransforms(BinaryOperator &I);
190     Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191                                       Constant *RHSC);
192     Instruction *visitFCmpInst(FCmpInst &I);
193     Instruction *visitICmpInst(ICmpInst &I);
194     Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195     Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196                                                 Instruction *LHS,
197                                                 ConstantInt *RHS);
198     Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199                                 ConstantInt *DivRHS);
200
201     Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202                              ICmpInst::Predicate Cond, Instruction &I);
203     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
204                                      BinaryOperator &I);
205     Instruction *commonCastTransforms(CastInst &CI);
206     Instruction *commonIntCastTransforms(CastInst &CI);
207     Instruction *commonPointerCastTransforms(CastInst &CI);
208     Instruction *visitTrunc(TruncInst &CI);
209     Instruction *visitZExt(ZExtInst &CI);
210     Instruction *visitSExt(SExtInst &CI);
211     Instruction *visitFPTrunc(FPTruncInst &CI);
212     Instruction *visitFPExt(CastInst &CI);
213     Instruction *visitFPToUI(FPToUIInst &FI);
214     Instruction *visitFPToSI(FPToSIInst &FI);
215     Instruction *visitUIToFP(CastInst &CI);
216     Instruction *visitSIToFP(CastInst &CI);
217     Instruction *visitPtrToInt(CastInst &CI);
218     Instruction *visitIntToPtr(IntToPtrInst &CI);
219     Instruction *visitBitCast(BitCastInst &CI);
220     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221                                 Instruction *FI);
222     Instruction *visitSelectInst(SelectInst &SI);
223     Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
224     Instruction *visitCallInst(CallInst &CI);
225     Instruction *visitInvokeInst(InvokeInst &II);
226     Instruction *visitPHINode(PHINode &PN);
227     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
228     Instruction *visitAllocationInst(AllocationInst &AI);
229     Instruction *visitFreeInst(FreeInst &FI);
230     Instruction *visitLoadInst(LoadInst &LI);
231     Instruction *visitStoreInst(StoreInst &SI);
232     Instruction *visitBranchInst(BranchInst &BI);
233     Instruction *visitSwitchInst(SwitchInst &SI);
234     Instruction *visitInsertElementInst(InsertElementInst &IE);
235     Instruction *visitExtractElementInst(ExtractElementInst &EI);
236     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
237     Instruction *visitExtractValueInst(ExtractValueInst &EV);
238
239     // visitInstruction - Specify what to return for unhandled instructions...
240     Instruction *visitInstruction(Instruction &I) { return 0; }
241
242   private:
243     Instruction *visitCallSite(CallSite CS);
244     bool transformConstExprCastCall(CallSite CS);
245     Instruction *transformCallThroughTrampoline(CallSite CS);
246     Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
247                                    bool DoXform = true);
248     bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
249
250   public:
251     // InsertNewInstBefore - insert an instruction New before instruction Old
252     // in the program.  Add the new instruction to the worklist.
253     //
254     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
255       assert(New && New->getParent() == 0 &&
256              "New instruction already inserted into a basic block!");
257       BasicBlock *BB = Old.getParent();
258       BB->getInstList().insert(&Old, New);  // Insert inst
259       AddToWorkList(New);
260       return New;
261     }
262
263     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
264     /// This also adds the cast to the worklist.  Finally, this returns the
265     /// cast.
266     Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
267                             Instruction &Pos) {
268       if (V->getType() == Ty) return V;
269
270       if (Constant *CV = dyn_cast<Constant>(V))
271         return ConstantExpr::getCast(opc, CV, Ty);
272       
273       Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
274       AddToWorkList(C);
275       return C;
276     }
277         
278     Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
279       return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
280     }
281
282
283     // ReplaceInstUsesWith - This method is to be used when an instruction is
284     // found to be dead, replacable with another preexisting expression.  Here
285     // we add all uses of I to the worklist, replace all uses of I with the new
286     // value, then return I, so that the inst combiner will know that I was
287     // modified.
288     //
289     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
290       AddUsersToWorkList(I);         // Add all modified instrs to worklist
291       if (&I != V) {
292         I.replaceAllUsesWith(V);
293         return &I;
294       } else {
295         // If we are replacing the instruction with itself, this must be in a
296         // segment of unreachable code, so just clobber the instruction.
297         I.replaceAllUsesWith(UndefValue::get(I.getType()));
298         return &I;
299       }
300     }
301
302     // UpdateValueUsesWith - This method is to be used when an value is
303     // found to be replacable with another preexisting expression or was
304     // updated.  Here we add all uses of I to the worklist, replace all uses of
305     // I with the new value (unless the instruction was just updated), then
306     // return true, so that the inst combiner will know that I was modified.
307     //
308     bool UpdateValueUsesWith(Value *Old, Value *New) {
309       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
310       if (Old != New)
311         Old->replaceAllUsesWith(New);
312       if (Instruction *I = dyn_cast<Instruction>(Old))
313         AddToWorkList(I);
314       if (Instruction *I = dyn_cast<Instruction>(New))
315         AddToWorkList(I);
316       return true;
317     }
318     
319     // EraseInstFromFunction - When dealing with an instruction that has side
320     // effects or produces a void value, we can't rely on DCE to delete the
321     // instruction.  Instead, visit methods should return the value returned by
322     // this function.
323     Instruction *EraseInstFromFunction(Instruction &I) {
324       assert(I.use_empty() && "Cannot erase instruction that is used!");
325       AddUsesToWorkList(I);
326       RemoveFromWorkList(&I);
327       I.eraseFromParent();
328       return 0;  // Don't do anything with FI
329     }
330         
331     void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
332                            APInt &KnownOne, unsigned Depth = 0) const {
333       return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
334     }
335     
336     bool MaskedValueIsZero(Value *V, const APInt &Mask, 
337                            unsigned Depth = 0) const {
338       return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
339     }
340     unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
341       return llvm::ComputeNumSignBits(Op, TD, Depth);
342     }
343
344   private:
345     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
346     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
347     /// casts that are known to not do anything...
348     ///
349     Value *InsertOperandCastBefore(Instruction::CastOps opcode,
350                                    Value *V, const Type *DestTy,
351                                    Instruction *InsertBefore);
352
353     /// SimplifyCommutative - This performs a few simplifications for 
354     /// commutative operators.
355     bool SimplifyCommutative(BinaryOperator &I);
356
357     /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
358     /// most-complex to least-complex order.
359     bool SimplifyCompare(CmpInst &I);
360
361     /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
362     /// on the demanded bits.
363     bool SimplifyDemandedBits(Value *V, APInt DemandedMask, 
364                               APInt& KnownZero, APInt& KnownOne,
365                               unsigned Depth = 0);
366
367     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
368                                       uint64_t &UndefElts, unsigned Depth = 0);
369       
370     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
371     // PHI node as operand #0, see if we can fold the instruction into the PHI
372     // (which is only possible if all operands to the PHI are constants).
373     Instruction *FoldOpIntoPhi(Instruction &I);
374
375     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
376     // operator and they all are only used by the PHI, PHI together their
377     // inputs, and do the operation once, to the result of the PHI.
378     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
379     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
380     
381     
382     Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
383                           ConstantInt *AndRHS, BinaryOperator &TheAnd);
384     
385     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
386                               bool isSub, Instruction &I);
387     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
388                                  bool isSigned, bool Inside, Instruction &IB);
389     Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
390     Instruction *MatchBSwap(BinaryOperator &I);
391     bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
392     Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
393     Instruction *SimplifyMemSet(MemSetInst *MI);
394
395
396     Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
397
398     bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
399                                     unsigned CastOpc,
400                                     int &NumCastsRemoved);
401     unsigned GetOrEnforceKnownAlignment(Value *V,
402                                         unsigned PrefAlign = 0);
403
404   };
405 }
406
407 char InstCombiner::ID = 0;
408 static RegisterPass<InstCombiner>
409 X("instcombine", "Combine redundant instructions");
410
411 // getComplexity:  Assign a complexity or rank value to LLVM Values...
412 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
413 static unsigned getComplexity(Value *V) {
414   if (isa<Instruction>(V)) {
415     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
416       return 3;
417     return 4;
418   }
419   if (isa<Argument>(V)) return 3;
420   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
421 }
422
423 // isOnlyUse - Return true if this instruction will be deleted if we stop using
424 // it.
425 static bool isOnlyUse(Value *V) {
426   return V->hasOneUse() || isa<Constant>(V);
427 }
428
429 // getPromotedType - Return the specified type promoted as it would be to pass
430 // though a va_arg area...
431 static const Type *getPromotedType(const Type *Ty) {
432   if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
433     if (ITy->getBitWidth() < 32)
434       return Type::Int32Ty;
435   }
436   return Ty;
437 }
438
439 /// getBitCastOperand - If the specified operand is a CastInst or a constant 
440 /// expression bitcast,  return the operand value, otherwise return null.
441 static Value *getBitCastOperand(Value *V) {
442   if (BitCastInst *I = dyn_cast<BitCastInst>(V))
443     return I->getOperand(0);
444   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
445     if (CE->getOpcode() == Instruction::BitCast)
446       return CE->getOperand(0);
447   return 0;
448 }
449
450 /// This function is a wrapper around CastInst::isEliminableCastPair. It
451 /// simply extracts arguments and returns what that function returns.
452 static Instruction::CastOps 
453 isEliminableCastPair(
454   const CastInst *CI, ///< The first cast instruction
455   unsigned opcode,       ///< The opcode of the second cast instruction
456   const Type *DstTy,     ///< The target type for the second cast instruction
457   TargetData *TD         ///< The target data for pointer size
458 ) {
459   
460   const Type *SrcTy = CI->getOperand(0)->getType();   // A from above
461   const Type *MidTy = CI->getType();                  // B from above
462
463   // Get the opcodes of the two Cast instructions
464   Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
465   Instruction::CastOps secondOp = Instruction::CastOps(opcode);
466
467   return Instruction::CastOps(
468       CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
469                                      DstTy, TD->getIntPtrType()));
470 }
471
472 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
473 /// in any code being generated.  It does not require codegen if V is simple
474 /// enough or if the cast can be folded into other casts.
475 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V, 
476                               const Type *Ty, TargetData *TD) {
477   if (V->getType() == Ty || isa<Constant>(V)) return false;
478   
479   // If this is another cast that can be eliminated, it isn't codegen either.
480   if (const CastInst *CI = dyn_cast<CastInst>(V))
481     if (isEliminableCastPair(CI, opcode, Ty, TD)) 
482       return false;
483   return true;
484 }
485
486 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
487 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
488 /// casts that are known to not do anything...
489 ///
490 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
491                                              Value *V, const Type *DestTy,
492                                              Instruction *InsertBefore) {
493   if (V->getType() == DestTy) return V;
494   if (Constant *C = dyn_cast<Constant>(V))
495     return ConstantExpr::getCast(opcode, C, DestTy);
496   
497   return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
498 }
499
500 // SimplifyCommutative - This performs a few simplifications for commutative
501 // operators:
502 //
503 //  1. Order operands such that they are listed from right (least complex) to
504 //     left (most complex).  This puts constants before unary operators before
505 //     binary operators.
506 //
507 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
508 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
509 //
510 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
511   bool Changed = false;
512   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
513     Changed = !I.swapOperands();
514
515   if (!I.isAssociative()) return Changed;
516   Instruction::BinaryOps Opcode = I.getOpcode();
517   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
518     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
519       if (isa<Constant>(I.getOperand(1))) {
520         Constant *Folded = ConstantExpr::get(I.getOpcode(),
521                                              cast<Constant>(I.getOperand(1)),
522                                              cast<Constant>(Op->getOperand(1)));
523         I.setOperand(0, Op->getOperand(0));
524         I.setOperand(1, Folded);
525         return true;
526       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
527         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
528             isOnlyUse(Op) && isOnlyUse(Op1)) {
529           Constant *C1 = cast<Constant>(Op->getOperand(1));
530           Constant *C2 = cast<Constant>(Op1->getOperand(1));
531
532           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
533           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
534           Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
535                                                     Op1->getOperand(0),
536                                                     Op1->getName(), &I);
537           AddToWorkList(New);
538           I.setOperand(0, New);
539           I.setOperand(1, Folded);
540           return true;
541         }
542     }
543   return Changed;
544 }
545
546 /// SimplifyCompare - For a CmpInst this function just orders the operands
547 /// so that theyare listed from right (least complex) to left (most complex).
548 /// This puts constants before unary operators before binary operators.
549 bool InstCombiner::SimplifyCompare(CmpInst &I) {
550   if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
551     return false;
552   I.swapOperands();
553   // Compare instructions are not associative so there's nothing else we can do.
554   return true;
555 }
556
557 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
558 // if the LHS is a constant zero (which is the 'negate' form).
559 //
560 static inline Value *dyn_castNegVal(Value *V) {
561   if (BinaryOperator::isNeg(V))
562     return BinaryOperator::getNegArgument(V);
563
564   // Constants can be considered to be negated values if they can be folded.
565   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
566     return ConstantExpr::getNeg(C);
567
568   if (ConstantVector *C = dyn_cast<ConstantVector>(V))
569     if (C->getType()->getElementType()->isInteger())
570       return ConstantExpr::getNeg(C);
571
572   return 0;
573 }
574
575 static inline Value *dyn_castNotVal(Value *V) {
576   if (BinaryOperator::isNot(V))
577     return BinaryOperator::getNotArgument(V);
578
579   // Constants can be considered to be not'ed values...
580   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
581     return ConstantInt::get(~C->getValue());
582   return 0;
583 }
584
585 // dyn_castFoldableMul - If this value is a multiply that can be folded into
586 // other computations (because it has a constant operand), return the
587 // non-constant operand of the multiply, and set CST to point to the multiplier.
588 // Otherwise, return null.
589 //
590 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
591   if (V->hasOneUse() && V->getType()->isInteger())
592     if (Instruction *I = dyn_cast<Instruction>(V)) {
593       if (I->getOpcode() == Instruction::Mul)
594         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
595           return I->getOperand(0);
596       if (I->getOpcode() == Instruction::Shl)
597         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
598           // The multiplier is really 1 << CST.
599           uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
600           uint32_t CSTVal = CST->getLimitedValue(BitWidth);
601           CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
602           return I->getOperand(0);
603         }
604     }
605   return 0;
606 }
607
608 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
609 /// expression, return it.
610 static User *dyn_castGetElementPtr(Value *V) {
611   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
612   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
613     if (CE->getOpcode() == Instruction::GetElementPtr)
614       return cast<User>(V);
615   return false;
616 }
617
618 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
619 /// opcode value. Otherwise return UserOp1.
620 static unsigned getOpcode(const Value *V) {
621   if (const Instruction *I = dyn_cast<Instruction>(V))
622     return I->getOpcode();
623   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
624     return CE->getOpcode();
625   // Use UserOp1 to mean there's no opcode.
626   return Instruction::UserOp1;
627 }
628
629 /// AddOne - Add one to a ConstantInt
630 static ConstantInt *AddOne(ConstantInt *C) {
631   APInt Val(C->getValue());
632   return ConstantInt::get(++Val);
633 }
634 /// SubOne - Subtract one from a ConstantInt
635 static ConstantInt *SubOne(ConstantInt *C) {
636   APInt Val(C->getValue());
637   return ConstantInt::get(--Val);
638 }
639 /// Add - Add two ConstantInts together
640 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
641   return ConstantInt::get(C1->getValue() + C2->getValue());
642 }
643 /// And - Bitwise AND two ConstantInts together
644 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
645   return ConstantInt::get(C1->getValue() & C2->getValue());
646 }
647 /// Subtract - Subtract one ConstantInt from another
648 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
649   return ConstantInt::get(C1->getValue() - C2->getValue());
650 }
651 /// Multiply - Multiply two ConstantInts together
652 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
653   return ConstantInt::get(C1->getValue() * C2->getValue());
654 }
655 /// MultiplyOverflows - True if the multiply can not be expressed in an int
656 /// this size.
657 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
658   uint32_t W = C1->getBitWidth();
659   APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
660   if (sign) {
661     LHSExt.sext(W * 2);
662     RHSExt.sext(W * 2);
663   } else {
664     LHSExt.zext(W * 2);
665     RHSExt.zext(W * 2);
666   }
667
668   APInt MulExt = LHSExt * RHSExt;
669
670   if (sign) {
671     APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
672     APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
673     return MulExt.slt(Min) || MulExt.sgt(Max);
674   } else 
675     return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
676 }
677
678
679 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
680 /// specified instruction is a constant integer.  If so, check to see if there
681 /// are any bits set in the constant that are not demanded.  If so, shrink the
682 /// constant and return true.
683 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
684                                    APInt Demanded) {
685   assert(I && "No instruction?");
686   assert(OpNo < I->getNumOperands() && "Operand index too large");
687
688   // If the operand is not a constant integer, nothing to do.
689   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
690   if (!OpC) return false;
691
692   // If there are no bits set that aren't demanded, nothing to do.
693   Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
694   if ((~Demanded & OpC->getValue()) == 0)
695     return false;
696
697   // This instruction is producing bits that are not demanded. Shrink the RHS.
698   Demanded &= OpC->getValue();
699   I->setOperand(OpNo, ConstantInt::get(Demanded));
700   return true;
701 }
702
703 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
704 // set of known zero and one bits, compute the maximum and minimum values that
705 // could have the specified known zero and known one bits, returning them in
706 // min/max.
707 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
708                                                    const APInt& KnownZero,
709                                                    const APInt& KnownOne,
710                                                    APInt& Min, APInt& Max) {
711   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
712   assert(KnownZero.getBitWidth() == BitWidth && 
713          KnownOne.getBitWidth() == BitWidth &&
714          Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
715          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
716   APInt UnknownBits = ~(KnownZero|KnownOne);
717
718   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
719   // bit if it is unknown.
720   Min = KnownOne;
721   Max = KnownOne|UnknownBits;
722   
723   if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
724     Min.set(BitWidth-1);
725     Max.clear(BitWidth-1);
726   }
727 }
728
729 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
730 // a set of known zero and one bits, compute the maximum and minimum values that
731 // could have the specified known zero and known one bits, returning them in
732 // min/max.
733 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
734                                                      const APInt &KnownZero,
735                                                      const APInt &KnownOne,
736                                                      APInt &Min, APInt &Max) {
737   uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
738   assert(KnownZero.getBitWidth() == BitWidth && 
739          KnownOne.getBitWidth() == BitWidth &&
740          Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
741          "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
742   APInt UnknownBits = ~(KnownZero|KnownOne);
743   
744   // The minimum value is when the unknown bits are all zeros.
745   Min = KnownOne;
746   // The maximum value is when the unknown bits are all ones.
747   Max = KnownOne|UnknownBits;
748 }
749
750 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
751 /// value based on the demanded bits. When this function is called, it is known
752 /// that only the bits set in DemandedMask of the result of V are ever used
753 /// downstream. Consequently, depending on the mask and V, it may be possible
754 /// to replace V with a constant or one of its operands. In such cases, this
755 /// function does the replacement and returns true. In all other cases, it
756 /// returns false after analyzing the expression and setting KnownOne and known
757 /// to be one in the expression. KnownZero contains all the bits that are known
758 /// to be zero in the expression. These are provided to potentially allow the
759 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
760 /// the expression. KnownOne and KnownZero always follow the invariant that 
761 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
762 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
763 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
764 /// and KnownOne must all be the same.
765 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
766                                         APInt& KnownZero, APInt& KnownOne,
767                                         unsigned Depth) {
768   assert(V != 0 && "Null pointer of Value???");
769   assert(Depth <= 6 && "Limit Search Depth");
770   uint32_t BitWidth = DemandedMask.getBitWidth();
771   const IntegerType *VTy = cast<IntegerType>(V->getType());
772   assert(VTy->getBitWidth() == BitWidth && 
773          KnownZero.getBitWidth() == BitWidth && 
774          KnownOne.getBitWidth() == BitWidth &&
775          "Value *V, DemandedMask, KnownZero and KnownOne \
776           must have same BitWidth");
777   if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
778     // We know all of the bits for a constant!
779     KnownOne = CI->getValue() & DemandedMask;
780     KnownZero = ~KnownOne & DemandedMask;
781     return false;
782   }
783   
784   KnownZero.clear(); 
785   KnownOne.clear();
786   if (!V->hasOneUse()) {    // Other users may use these bits.
787     if (Depth != 0) {       // Not at the root.
788       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
789       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
790       return false;
791     }
792     // If this is the root being simplified, allow it to have multiple uses,
793     // just set the DemandedMask to all bits.
794     DemandedMask = APInt::getAllOnesValue(BitWidth);
795   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
796     if (V != UndefValue::get(VTy))
797       return UpdateValueUsesWith(V, UndefValue::get(VTy));
798     return false;
799   } else if (Depth == 6) {        // Limit search depth.
800     return false;
801   }
802   
803   Instruction *I = dyn_cast<Instruction>(V);
804   if (!I) return false;        // Only analyze instructions.
805
806   APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
807   APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
808   switch (I->getOpcode()) {
809   default:
810     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
811     break;
812   case Instruction::And:
813     // If either the LHS or the RHS are Zero, the result is zero.
814     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
815                              RHSKnownZero, RHSKnownOne, Depth+1))
816       return true;
817     assert((RHSKnownZero & RHSKnownOne) == 0 && 
818            "Bits known to be one AND zero?"); 
819
820     // If something is known zero on the RHS, the bits aren't demanded on the
821     // LHS.
822     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
823                              LHSKnownZero, LHSKnownOne, Depth+1))
824       return true;
825     assert((LHSKnownZero & LHSKnownOne) == 0 && 
826            "Bits known to be one AND zero?"); 
827
828     // If all of the demanded bits are known 1 on one side, return the other.
829     // These bits cannot contribute to the result of the 'and'.
830     if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) == 
831         (DemandedMask & ~LHSKnownZero))
832       return UpdateValueUsesWith(I, I->getOperand(0));
833     if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) == 
834         (DemandedMask & ~RHSKnownZero))
835       return UpdateValueUsesWith(I, I->getOperand(1));
836     
837     // If all of the demanded bits in the inputs are known zeros, return zero.
838     if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
839       return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
840       
841     // If the RHS is a constant, see if we can simplify it.
842     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
843       return UpdateValueUsesWith(I, I);
844       
845     // Output known-1 bits are only known if set in both the LHS & RHS.
846     RHSKnownOne &= LHSKnownOne;
847     // Output known-0 are known to be clear if zero in either the LHS | RHS.
848     RHSKnownZero |= LHSKnownZero;
849     break;
850   case Instruction::Or:
851     // If either the LHS or the RHS are One, the result is One.
852     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
853                              RHSKnownZero, RHSKnownOne, Depth+1))
854       return true;
855     assert((RHSKnownZero & RHSKnownOne) == 0 && 
856            "Bits known to be one AND zero?"); 
857     // If something is known one on the RHS, the bits aren't demanded on the
858     // LHS.
859     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne, 
860                              LHSKnownZero, LHSKnownOne, Depth+1))
861       return true;
862     assert((LHSKnownZero & LHSKnownOne) == 0 && 
863            "Bits known to be one AND zero?"); 
864     
865     // If all of the demanded bits are known zero on one side, return the other.
866     // These bits cannot contribute to the result of the 'or'.
867     if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) == 
868         (DemandedMask & ~LHSKnownOne))
869       return UpdateValueUsesWith(I, I->getOperand(0));
870     if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) == 
871         (DemandedMask & ~RHSKnownOne))
872       return UpdateValueUsesWith(I, I->getOperand(1));
873
874     // If all of the potentially set bits on one side are known to be set on
875     // the other side, just use the 'other' side.
876     if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) == 
877         (DemandedMask & (~RHSKnownZero)))
878       return UpdateValueUsesWith(I, I->getOperand(0));
879     if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) == 
880         (DemandedMask & (~LHSKnownZero)))
881       return UpdateValueUsesWith(I, I->getOperand(1));
882         
883     // If the RHS is a constant, see if we can simplify it.
884     if (ShrinkDemandedConstant(I, 1, DemandedMask))
885       return UpdateValueUsesWith(I, I);
886           
887     // Output known-0 bits are only known if clear in both the LHS & RHS.
888     RHSKnownZero &= LHSKnownZero;
889     // Output known-1 are known to be set if set in either the LHS | RHS.
890     RHSKnownOne |= LHSKnownOne;
891     break;
892   case Instruction::Xor: {
893     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
894                              RHSKnownZero, RHSKnownOne, Depth+1))
895       return true;
896     assert((RHSKnownZero & RHSKnownOne) == 0 && 
897            "Bits known to be one AND zero?"); 
898     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
899                              LHSKnownZero, LHSKnownOne, Depth+1))
900       return true;
901     assert((LHSKnownZero & LHSKnownOne) == 0 && 
902            "Bits known to be one AND zero?"); 
903     
904     // If all of the demanded bits are known zero on one side, return the other.
905     // These bits cannot contribute to the result of the 'xor'.
906     if ((DemandedMask & RHSKnownZero) == DemandedMask)
907       return UpdateValueUsesWith(I, I->getOperand(0));
908     if ((DemandedMask & LHSKnownZero) == DemandedMask)
909       return UpdateValueUsesWith(I, I->getOperand(1));
910     
911     // Output known-0 bits are known if clear or set in both the LHS & RHS.
912     APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) | 
913                          (RHSKnownOne & LHSKnownOne);
914     // Output known-1 are known to be set if set in only one of the LHS, RHS.
915     APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) | 
916                         (RHSKnownOne & LHSKnownZero);
917     
918     // If all of the demanded bits are known to be zero on one side or the
919     // other, turn this into an *inclusive* or.
920     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
921     if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
922       Instruction *Or =
923         BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
924                                  I->getName());
925       InsertNewInstBefore(Or, *I);
926       return UpdateValueUsesWith(I, Or);
927     }
928     
929     // If all of the demanded bits on one side are known, and all of the set
930     // bits on that side are also known to be set on the other side, turn this
931     // into an AND, as we know the bits will be cleared.
932     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
933     if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) { 
934       // all known
935       if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
936         Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
937         Instruction *And = 
938           BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
939         InsertNewInstBefore(And, *I);
940         return UpdateValueUsesWith(I, And);
941       }
942     }
943     
944     // If the RHS is a constant, see if we can simplify it.
945     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
946     if (ShrinkDemandedConstant(I, 1, DemandedMask))
947       return UpdateValueUsesWith(I, I);
948     
949     RHSKnownZero = KnownZeroOut;
950     RHSKnownOne  = KnownOneOut;
951     break;
952   }
953   case Instruction::Select:
954     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
955                              RHSKnownZero, RHSKnownOne, Depth+1))
956       return true;
957     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
958                              LHSKnownZero, LHSKnownOne, Depth+1))
959       return true;
960     assert((RHSKnownZero & RHSKnownOne) == 0 && 
961            "Bits known to be one AND zero?"); 
962     assert((LHSKnownZero & LHSKnownOne) == 0 && 
963            "Bits known to be one AND zero?"); 
964     
965     // If the operands are constants, see if we can simplify them.
966     if (ShrinkDemandedConstant(I, 1, DemandedMask))
967       return UpdateValueUsesWith(I, I);
968     if (ShrinkDemandedConstant(I, 2, DemandedMask))
969       return UpdateValueUsesWith(I, I);
970     
971     // Only known if known in both the LHS and RHS.
972     RHSKnownOne &= LHSKnownOne;
973     RHSKnownZero &= LHSKnownZero;
974     break;
975   case Instruction::Trunc: {
976     uint32_t truncBf = 
977       cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
978     DemandedMask.zext(truncBf);
979     RHSKnownZero.zext(truncBf);
980     RHSKnownOne.zext(truncBf);
981     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
982                              RHSKnownZero, RHSKnownOne, Depth+1))
983       return true;
984     DemandedMask.trunc(BitWidth);
985     RHSKnownZero.trunc(BitWidth);
986     RHSKnownOne.trunc(BitWidth);
987     assert((RHSKnownZero & RHSKnownOne) == 0 && 
988            "Bits known to be one AND zero?"); 
989     break;
990   }
991   case Instruction::BitCast:
992     if (!I->getOperand(0)->getType()->isInteger())
993       return false;
994       
995     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
996                              RHSKnownZero, RHSKnownOne, Depth+1))
997       return true;
998     assert((RHSKnownZero & RHSKnownOne) == 0 && 
999            "Bits known to be one AND zero?"); 
1000     break;
1001   case Instruction::ZExt: {
1002     // Compute the bits in the result that are not present in the input.
1003     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1004     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1005     
1006     DemandedMask.trunc(SrcBitWidth);
1007     RHSKnownZero.trunc(SrcBitWidth);
1008     RHSKnownOne.trunc(SrcBitWidth);
1009     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1010                              RHSKnownZero, RHSKnownOne, Depth+1))
1011       return true;
1012     DemandedMask.zext(BitWidth);
1013     RHSKnownZero.zext(BitWidth);
1014     RHSKnownOne.zext(BitWidth);
1015     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1016            "Bits known to be one AND zero?"); 
1017     // The top bits are known to be zero.
1018     RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1019     break;
1020   }
1021   case Instruction::SExt: {
1022     // Compute the bits in the result that are not present in the input.
1023     const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1024     uint32_t SrcBitWidth = SrcTy->getBitWidth();
1025     
1026     APInt InputDemandedBits = DemandedMask & 
1027                               APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1028
1029     APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1030     // If any of the sign extended bits are demanded, we know that the sign
1031     // bit is demanded.
1032     if ((NewBits & DemandedMask) != 0)
1033       InputDemandedBits.set(SrcBitWidth-1);
1034       
1035     InputDemandedBits.trunc(SrcBitWidth);
1036     RHSKnownZero.trunc(SrcBitWidth);
1037     RHSKnownOne.trunc(SrcBitWidth);
1038     if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1039                              RHSKnownZero, RHSKnownOne, Depth+1))
1040       return true;
1041     InputDemandedBits.zext(BitWidth);
1042     RHSKnownZero.zext(BitWidth);
1043     RHSKnownOne.zext(BitWidth);
1044     assert((RHSKnownZero & RHSKnownOne) == 0 && 
1045            "Bits known to be one AND zero?"); 
1046       
1047     // If the sign bit of the input is known set or clear, then we know the
1048     // top bits of the result.
1049
1050     // If the input sign bit is known zero, or if the NewBits are not demanded
1051     // convert this into a zero extension.
1052     if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1053     {
1054       // Convert to ZExt cast
1055       CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1056       return UpdateValueUsesWith(I, NewCast);
1057     } else if (RHSKnownOne[SrcBitWidth-1]) {    // Input sign bit known set
1058       RHSKnownOne |= NewBits;
1059     }
1060     break;
1061   }
1062   case Instruction::Add: {
1063     // Figure out what the input bits are.  If the top bits of the and result
1064     // are not demanded, then the add doesn't demand them from its input
1065     // either.
1066     uint32_t NLZ = DemandedMask.countLeadingZeros();
1067       
1068     // If there is a constant on the RHS, there are a variety of xformations
1069     // we can do.
1070     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1071       // If null, this should be simplified elsewhere.  Some of the xforms here
1072       // won't work if the RHS is zero.
1073       if (RHS->isZero())
1074         break;
1075       
1076       // If the top bit of the output is demanded, demand everything from the
1077       // input.  Otherwise, we demand all the input bits except NLZ top bits.
1078       APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1079
1080       // Find information about known zero/one bits in the input.
1081       if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits, 
1082                                LHSKnownZero, LHSKnownOne, Depth+1))
1083         return true;
1084
1085       // If the RHS of the add has bits set that can't affect the input, reduce
1086       // the constant.
1087       if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1088         return UpdateValueUsesWith(I, I);
1089       
1090       // Avoid excess work.
1091       if (LHSKnownZero == 0 && LHSKnownOne == 0)
1092         break;
1093       
1094       // Turn it into OR if input bits are zero.
1095       if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1096         Instruction *Or =
1097           BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1098                                    I->getName());
1099         InsertNewInstBefore(Or, *I);
1100         return UpdateValueUsesWith(I, Or);
1101       }
1102       
1103       // We can say something about the output known-zero and known-one bits,
1104       // depending on potential carries from the input constant and the
1105       // unknowns.  For example if the LHS is known to have at most the 0x0F0F0
1106       // bits set and the RHS constant is 0x01001, then we know we have a known
1107       // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1108       
1109       // To compute this, we first compute the potential carry bits.  These are
1110       // the bits which may be modified.  I'm not aware of a better way to do
1111       // this scan.
1112       const APInt& RHSVal = RHS->getValue();
1113       APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1114       
1115       // Now that we know which bits have carries, compute the known-1/0 sets.
1116       
1117       // Bits are known one if they are known zero in one operand and one in the
1118       // other, and there is no input carry.
1119       RHSKnownOne = ((LHSKnownZero & RHSVal) | 
1120                      (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1121       
1122       // Bits are known zero if they are known zero in both operands and there
1123       // is no input carry.
1124       RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1125     } else {
1126       // If the high-bits of this ADD are not demanded, then it does not demand
1127       // the high bits of its LHS or RHS.
1128       if (DemandedMask[BitWidth-1] == 0) {
1129         // Right fill the mask of bits for this ADD to demand the most
1130         // significant bit and all those below it.
1131         APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1132         if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1133                                  LHSKnownZero, LHSKnownOne, Depth+1))
1134           return true;
1135         if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1136                                  LHSKnownZero, LHSKnownOne, Depth+1))
1137           return true;
1138       }
1139     }
1140     break;
1141   }
1142   case Instruction::Sub:
1143     // If the high-bits of this SUB are not demanded, then it does not demand
1144     // the high bits of its LHS or RHS.
1145     if (DemandedMask[BitWidth-1] == 0) {
1146       // Right fill the mask of bits for this SUB to demand the most
1147       // significant bit and all those below it.
1148       uint32_t NLZ = DemandedMask.countLeadingZeros();
1149       APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1150       if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1151                                LHSKnownZero, LHSKnownOne, Depth+1))
1152         return true;
1153       if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1154                                LHSKnownZero, LHSKnownOne, Depth+1))
1155         return true;
1156     }
1157     // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1158     // the known zeros and ones.
1159     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1160     break;
1161   case Instruction::Shl:
1162     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1164       APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1165       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn, 
1166                                RHSKnownZero, RHSKnownOne, Depth+1))
1167         return true;
1168       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1169              "Bits known to be one AND zero?"); 
1170       RHSKnownZero <<= ShiftAmt;
1171       RHSKnownOne  <<= ShiftAmt;
1172       // low bits known zero.
1173       if (ShiftAmt)
1174         RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1175     }
1176     break;
1177   case Instruction::LShr:
1178     // For a logical shift right
1179     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1180       uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1181       
1182       // Unsigned shift right.
1183       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1184       if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1185                                RHSKnownZero, RHSKnownOne, Depth+1))
1186         return true;
1187       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1188              "Bits known to be one AND zero?"); 
1189       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1190       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1191       if (ShiftAmt) {
1192         // Compute the new bits that are at the top now.
1193         APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1194         RHSKnownZero |= HighBits;  // high bits known zero.
1195       }
1196     }
1197     break;
1198   case Instruction::AShr:
1199     // If this is an arithmetic shift right and only the low-bit is set, we can
1200     // always convert this into a logical shr, even if the shift amount is
1201     // variable.  The low bit of the shift cannot be an input sign bit unless
1202     // the shift amount is >= the size of the datatype, which is undefined.
1203     if (DemandedMask == 1) {
1204       // Perform the logical shift right.
1205       Value *NewVal = BinaryOperator::CreateLShr(
1206                         I->getOperand(0), I->getOperand(1), I->getName());
1207       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1208       return UpdateValueUsesWith(I, NewVal);
1209     }    
1210
1211     // If the sign bit is the only bit demanded by this ashr, then there is no
1212     // need to do it, the shift doesn't change the high bit.
1213     if (DemandedMask.isSignBit())
1214       return UpdateValueUsesWith(I, I->getOperand(0));
1215     
1216     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1217       uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1218       
1219       // Signed shift right.
1220       APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1221       // If any of the "high bits" are demanded, we should set the sign bit as
1222       // demanded.
1223       if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1224         DemandedMaskIn.set(BitWidth-1);
1225       if (SimplifyDemandedBits(I->getOperand(0),
1226                                DemandedMaskIn,
1227                                RHSKnownZero, RHSKnownOne, Depth+1))
1228         return true;
1229       assert((RHSKnownZero & RHSKnownOne) == 0 && 
1230              "Bits known to be one AND zero?"); 
1231       // Compute the new bits that are at the top now.
1232       APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1233       RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1234       RHSKnownOne  = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1235         
1236       // Handle the sign bits.
1237       APInt SignBit(APInt::getSignBit(BitWidth));
1238       // Adjust to where it is now in the mask.
1239       SignBit = APIntOps::lshr(SignBit, ShiftAmt);  
1240         
1241       // If the input sign bit is known to be zero, or if none of the top bits
1242       // are demanded, turn this into an unsigned shift right.
1243       if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] || 
1244           (HighBits & ~DemandedMask) == HighBits) {
1245         // Perform the logical shift right.
1246         Value *NewVal = BinaryOperator::CreateLShr(
1247                           I->getOperand(0), SA, I->getName());
1248         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1249         return UpdateValueUsesWith(I, NewVal);
1250       } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1251         RHSKnownOne |= HighBits;
1252       }
1253     }
1254     break;
1255   case Instruction::SRem:
1256     if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1257       APInt RA = Rem->getValue();
1258       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1259         if (DemandedMask.ule(RA))    // srem won't affect demanded bits
1260           return UpdateValueUsesWith(I, I->getOperand(0));
1261
1262         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1263         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1264         if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1265                                  LHSKnownZero, LHSKnownOne, Depth+1))
1266           return true;
1267
1268         if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1269           LHSKnownZero |= ~LowBits;
1270
1271         KnownZero |= LHSKnownZero & DemandedMask;
1272
1273         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
1274       }
1275     }
1276     break;
1277   case Instruction::URem: {
1278     APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1279     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1280     if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1281                              KnownZero2, KnownOne2, Depth+1))
1282       return true;
1283
1284     uint32_t Leaders = KnownZero2.countLeadingOnes();
1285     if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1286                              KnownZero2, KnownOne2, Depth+1))
1287       return true;
1288
1289     Leaders = std::max(Leaders,
1290                        KnownZero2.countLeadingOnes());
1291     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1292     break;
1293   }
1294   case Instruction::Call:
1295     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1296       switch (II->getIntrinsicID()) {
1297       default: break;
1298       case Intrinsic::bswap: {
1299         // If the only bits demanded come from one byte of the bswap result,
1300         // just shift the input byte into position to eliminate the bswap.
1301         unsigned NLZ = DemandedMask.countLeadingZeros();
1302         unsigned NTZ = DemandedMask.countTrailingZeros();
1303           
1304         // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
1305         // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
1306         // have 14 leading zeros, round to 8.
1307         NLZ &= ~7;
1308         NTZ &= ~7;
1309         // If we need exactly one byte, we can do this transformation.
1310         if (BitWidth-NLZ-NTZ == 8) {
1311           unsigned ResultBit = NTZ;
1312           unsigned InputBit = BitWidth-NTZ-8;
1313           
1314           // Replace this with either a left or right shift to get the byte into
1315           // the right place.
1316           Instruction *NewVal;
1317           if (InputBit > ResultBit)
1318             NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1319                     ConstantInt::get(I->getType(), InputBit-ResultBit));
1320           else
1321             NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1322                     ConstantInt::get(I->getType(), ResultBit-InputBit));
1323           NewVal->takeName(I);
1324           InsertNewInstBefore(NewVal, *I);
1325           return UpdateValueUsesWith(I, NewVal);
1326         }
1327           
1328         // TODO: Could compute known zero/one bits based on the input.
1329         break;
1330       }
1331       }
1332     }
1333     ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1334     break;
1335   }
1336   
1337   // If the client is only demanding bits that we know, return the known
1338   // constant.
1339   if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1340     return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1341   return false;
1342 }
1343
1344
1345 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1346 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1347 /// actually used by the caller.  This method analyzes which elements of the
1348 /// operand are undef and returns that information in UndefElts.
1349 ///
1350 /// If the information about demanded elements can be used to simplify the
1351 /// operation, the operation is simplified, then the resultant value is
1352 /// returned.  This returns null if no change was made.
1353 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1354                                                 uint64_t &UndefElts,
1355                                                 unsigned Depth) {
1356   unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1357   assert(VWidth <= 64 && "Vector too wide to analyze!");
1358   uint64_t EltMask = ~0ULL >> (64-VWidth);
1359   assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1360
1361   if (isa<UndefValue>(V)) {
1362     // If the entire vector is undefined, just return this info.
1363     UndefElts = EltMask;
1364     return 0;
1365   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1366     UndefElts = EltMask;
1367     return UndefValue::get(V->getType());
1368   }
1369   
1370   UndefElts = 0;
1371   if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1372     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1373     Constant *Undef = UndefValue::get(EltTy);
1374
1375     std::vector<Constant*> Elts;
1376     for (unsigned i = 0; i != VWidth; ++i)
1377       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1378         Elts.push_back(Undef);
1379         UndefElts |= (1ULL << i);
1380       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1381         Elts.push_back(Undef);
1382         UndefElts |= (1ULL << i);
1383       } else {                               // Otherwise, defined.
1384         Elts.push_back(CP->getOperand(i));
1385       }
1386         
1387     // If we changed the constant, return it.
1388     Constant *NewCP = ConstantVector::get(Elts);
1389     return NewCP != CP ? NewCP : 0;
1390   } else if (isa<ConstantAggregateZero>(V)) {
1391     // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1392     // set to undef.
1393     const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1394     Constant *Zero = Constant::getNullValue(EltTy);
1395     Constant *Undef = UndefValue::get(EltTy);
1396     std::vector<Constant*> Elts;
1397     for (unsigned i = 0; i != VWidth; ++i)
1398       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1399     UndefElts = DemandedElts ^ EltMask;
1400     return ConstantVector::get(Elts);
1401   }
1402   
1403   // Limit search depth.
1404   if (Depth == 10)
1405     return false;
1406
1407   // If multiple users are using the root value, procede with
1408   // simplification conservatively assuming that all elements
1409   // are needed.
1410   if (!V->hasOneUse()) {
1411     // Quit if we find multiple users of a non-root value though.
1412     // They'll be handled when it's their turn to be visited by
1413     // the main instcombine process.
1414     if (Depth != 0)
1415       // TODO: Just compute the UndefElts information recursively.
1416       return false;
1417
1418     // Conservatively assume that all elements are needed.
1419     DemandedElts = EltMask;
1420   }
1421   
1422   Instruction *I = dyn_cast<Instruction>(V);
1423   if (!I) return false;        // Only analyze instructions.
1424   
1425   bool MadeChange = false;
1426   uint64_t UndefElts2;
1427   Value *TmpV;
1428   switch (I->getOpcode()) {
1429   default: break;
1430     
1431   case Instruction::InsertElement: {
1432     // If this is a variable index, we don't know which element it overwrites.
1433     // demand exactly the same input as we produce.
1434     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1435     if (Idx == 0) {
1436       // Note that we can't propagate undef elt info, because we don't know
1437       // which elt is getting updated.
1438       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1439                                         UndefElts2, Depth+1);
1440       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1441       break;
1442     }
1443     
1444     // If this is inserting an element that isn't demanded, remove this
1445     // insertelement.
1446     unsigned IdxNo = Idx->getZExtValue();
1447     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1448       return AddSoonDeadInstToWorklist(*I, 0);
1449     
1450     // Otherwise, the element inserted overwrites whatever was there, so the
1451     // input demanded set is simpler than the output set.
1452     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1453                                       DemandedElts & ~(1ULL << IdxNo),
1454                                       UndefElts, Depth+1);
1455     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1456
1457     // The inserted element is defined.
1458     UndefElts &= ~(1ULL << IdxNo);
1459     break;
1460   }
1461   case Instruction::ShuffleVector: {
1462     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1463     uint64_t LeftDemanded = 0, RightDemanded = 0;
1464     for (unsigned i = 0; i < VWidth; i++) {
1465       if (DemandedElts & (1ULL << i)) {
1466         unsigned MaskVal = Shuffle->getMaskValue(i);
1467         if (MaskVal != -1u) {
1468           assert(MaskVal < VWidth * 2 &&
1469                  "shufflevector mask index out of range!");
1470           if (MaskVal < VWidth)
1471             LeftDemanded |= 1ULL << MaskVal;
1472           else
1473             RightDemanded |= 1ULL << (MaskVal - VWidth);
1474         }
1475       }
1476     }
1477
1478     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1479                                       UndefElts2, Depth+1);
1480     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1481
1482     uint64_t UndefElts3;
1483     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1484                                       UndefElts3, Depth+1);
1485     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1486
1487     bool NewUndefElts = false;
1488     for (unsigned i = 0; i < VWidth; i++) {
1489       unsigned MaskVal = Shuffle->getMaskValue(i);
1490       if (MaskVal == -1u) {
1491         uint64_t NewBit = 1ULL << i;
1492         UndefElts |= NewBit;
1493       } else if (MaskVal < VWidth) {
1494         uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1495         NewUndefElts |= NewBit;
1496         UndefElts |= NewBit;
1497       } else {
1498         uint64_t NewBit = ((UndefElts3 >> (MaskVal - VWidth)) & 1) << i;
1499         NewUndefElts |= NewBit;
1500         UndefElts |= NewBit;
1501       }
1502     }
1503
1504     if (NewUndefElts) {
1505       // Add additional discovered undefs.
1506       std::vector<Constant*> Elts;
1507       for (unsigned i = 0; i < VWidth; ++i) {
1508         if (UndefElts & (1ULL << i))
1509           Elts.push_back(UndefValue::get(Type::Int32Ty));
1510         else
1511           Elts.push_back(ConstantInt::get(Type::Int32Ty,
1512                                           Shuffle->getMaskValue(i)));
1513       }
1514       I->setOperand(2, ConstantVector::get(Elts));
1515       MadeChange = true;
1516     }
1517     break;
1518   }
1519   case Instruction::BitCast: {
1520     // Vector->vector casts only.
1521     const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1522     if (!VTy) break;
1523     unsigned InVWidth = VTy->getNumElements();
1524     uint64_t InputDemandedElts = 0;
1525     unsigned Ratio;
1526
1527     if (VWidth == InVWidth) {
1528       // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1529       // elements as are demanded of us.
1530       Ratio = 1;
1531       InputDemandedElts = DemandedElts;
1532     } else if (VWidth > InVWidth) {
1533       // Untested so far.
1534       break;
1535       
1536       // If there are more elements in the result than there are in the source,
1537       // then an input element is live if any of the corresponding output
1538       // elements are live.
1539       Ratio = VWidth/InVWidth;
1540       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1541         if (DemandedElts & (1ULL << OutIdx))
1542           InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1543       }
1544     } else {
1545       // Untested so far.
1546       break;
1547       
1548       // If there are more elements in the source than there are in the result,
1549       // then an input element is live if the corresponding output element is
1550       // live.
1551       Ratio = InVWidth/VWidth;
1552       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1553         if (DemandedElts & (1ULL << InIdx/Ratio))
1554           InputDemandedElts |= 1ULL << InIdx;
1555     }
1556     
1557     // div/rem demand all inputs, because they don't want divide by zero.
1558     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1559                                       UndefElts2, Depth+1);
1560     if (TmpV) {
1561       I->setOperand(0, TmpV);
1562       MadeChange = true;
1563     }
1564     
1565     UndefElts = UndefElts2;
1566     if (VWidth > InVWidth) {
1567       assert(0 && "Unimp");
1568       // If there are more elements in the result than there are in the source,
1569       // then an output element is undef if the corresponding input element is
1570       // undef.
1571       for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1572         if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1573           UndefElts |= 1ULL << OutIdx;
1574     } else if (VWidth < InVWidth) {
1575       assert(0 && "Unimp");
1576       // If there are more elements in the source than there are in the result,
1577       // then a result element is undef if all of the corresponding input
1578       // elements are undef.
1579       UndefElts = ~0ULL >> (64-VWidth);  // Start out all undef.
1580       for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1581         if ((UndefElts2 & (1ULL << InIdx)) == 0)    // Not undef?
1582           UndefElts &= ~(1ULL << (InIdx/Ratio));    // Clear undef bit.
1583     }
1584     break;
1585   }
1586   case Instruction::And:
1587   case Instruction::Or:
1588   case Instruction::Xor:
1589   case Instruction::Add:
1590   case Instruction::Sub:
1591   case Instruction::Mul:
1592     // div/rem demand all inputs, because they don't want divide by zero.
1593     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1594                                       UndefElts, Depth+1);
1595     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1596     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1597                                       UndefElts2, Depth+1);
1598     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1599       
1600     // Output elements are undefined if both are undefined.  Consider things
1601     // like undef&0.  The result is known zero, not undef.
1602     UndefElts &= UndefElts2;
1603     break;
1604     
1605   case Instruction::Call: {
1606     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1607     if (!II) break;
1608     switch (II->getIntrinsicID()) {
1609     default: break;
1610       
1611     // Binary vector operations that work column-wise.  A dest element is a
1612     // function of the corresponding input elements from the two inputs.
1613     case Intrinsic::x86_sse_sub_ss:
1614     case Intrinsic::x86_sse_mul_ss:
1615     case Intrinsic::x86_sse_min_ss:
1616     case Intrinsic::x86_sse_max_ss:
1617     case Intrinsic::x86_sse2_sub_sd:
1618     case Intrinsic::x86_sse2_mul_sd:
1619     case Intrinsic::x86_sse2_min_sd:
1620     case Intrinsic::x86_sse2_max_sd:
1621       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1622                                         UndefElts, Depth+1);
1623       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1624       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1625                                         UndefElts2, Depth+1);
1626       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1627
1628       // If only the low elt is demanded and this is a scalarizable intrinsic,
1629       // scalarize it now.
1630       if (DemandedElts == 1) {
1631         switch (II->getIntrinsicID()) {
1632         default: break;
1633         case Intrinsic::x86_sse_sub_ss:
1634         case Intrinsic::x86_sse_mul_ss:
1635         case Intrinsic::x86_sse2_sub_sd:
1636         case Intrinsic::x86_sse2_mul_sd:
1637           // TODO: Lower MIN/MAX/ABS/etc
1638           Value *LHS = II->getOperand(1);
1639           Value *RHS = II->getOperand(2);
1640           // Extract the element as scalars.
1641           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1642           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1643           
1644           switch (II->getIntrinsicID()) {
1645           default: assert(0 && "Case stmts out of sync!");
1646           case Intrinsic::x86_sse_sub_ss:
1647           case Intrinsic::x86_sse2_sub_sd:
1648             TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1649                                                         II->getName()), *II);
1650             break;
1651           case Intrinsic::x86_sse_mul_ss:
1652           case Intrinsic::x86_sse2_mul_sd:
1653             TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1654                                                          II->getName()), *II);
1655             break;
1656           }
1657           
1658           Instruction *New =
1659             InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1660                                       II->getName());
1661           InsertNewInstBefore(New, *II);
1662           AddSoonDeadInstToWorklist(*II, 0);
1663           return New;
1664         }            
1665       }
1666         
1667       // Output elements are undefined if both are undefined.  Consider things
1668       // like undef&0.  The result is known zero, not undef.
1669       UndefElts &= UndefElts2;
1670       break;
1671     }
1672     break;
1673   }
1674   }
1675   return MadeChange ? I : 0;
1676 }
1677
1678
1679 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1680 /// function is designed to check a chain of associative operators for a
1681 /// potential to apply a certain optimization.  Since the optimization may be
1682 /// applicable if the expression was reassociated, this checks the chain, then
1683 /// reassociates the expression as necessary to expose the optimization
1684 /// opportunity.  This makes use of a special Functor, which must define
1685 /// 'shouldApply' and 'apply' methods.
1686 ///
1687 template<typename Functor>
1688 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1689   unsigned Opcode = Root.getOpcode();
1690   Value *LHS = Root.getOperand(0);
1691
1692   // Quick check, see if the immediate LHS matches...
1693   if (F.shouldApply(LHS))
1694     return F.apply(Root);
1695
1696   // Otherwise, if the LHS is not of the same opcode as the root, return.
1697   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1698   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1699     // Should we apply this transform to the RHS?
1700     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1701
1702     // If not to the RHS, check to see if we should apply to the LHS...
1703     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1704       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1705       ShouldApply = true;
1706     }
1707
1708     // If the functor wants to apply the optimization to the RHS of LHSI,
1709     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1710     if (ShouldApply) {
1711       // Now all of the instructions are in the current basic block, go ahead
1712       // and perform the reassociation.
1713       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1714
1715       // First move the selected RHS to the LHS of the root...
1716       Root.setOperand(0, LHSI->getOperand(1));
1717
1718       // Make what used to be the LHS of the root be the user of the root...
1719       Value *ExtraOperand = TmpLHSI->getOperand(1);
1720       if (&Root == TmpLHSI) {
1721         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1722         return 0;
1723       }
1724       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1725       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1726       BasicBlock::iterator ARI = &Root; ++ARI;
1727       TmpLHSI->moveBefore(ARI);                  // Move TmpLHSI to after Root
1728       ARI = Root;
1729
1730       // Now propagate the ExtraOperand down the chain of instructions until we
1731       // get to LHSI.
1732       while (TmpLHSI != LHSI) {
1733         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1734         // Move the instruction to immediately before the chain we are
1735         // constructing to avoid breaking dominance properties.
1736         NextLHSI->moveBefore(ARI);
1737         ARI = NextLHSI;
1738
1739         Value *NextOp = NextLHSI->getOperand(1);
1740         NextLHSI->setOperand(1, ExtraOperand);
1741         TmpLHSI = NextLHSI;
1742         ExtraOperand = NextOp;
1743       }
1744
1745       // Now that the instructions are reassociated, have the functor perform
1746       // the transformation...
1747       return F.apply(Root);
1748     }
1749
1750     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1751   }
1752   return 0;
1753 }
1754
1755 namespace {
1756
1757 // AddRHS - Implements: X + X --> X << 1
1758 struct AddRHS {
1759   Value *RHS;
1760   AddRHS(Value *rhs) : RHS(rhs) {}
1761   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1762   Instruction *apply(BinaryOperator &Add) const {
1763     return BinaryOperator::CreateShl(Add.getOperand(0),
1764                                      ConstantInt::get(Add.getType(), 1));
1765   }
1766 };
1767
1768 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1769 //                 iff C1&C2 == 0
1770 struct AddMaskingAnd {
1771   Constant *C2;
1772   AddMaskingAnd(Constant *c) : C2(c) {}
1773   bool shouldApply(Value *LHS) const {
1774     ConstantInt *C1;
1775     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1776            ConstantExpr::getAnd(C1, C2)->isNullValue();
1777   }
1778   Instruction *apply(BinaryOperator &Add) const {
1779     return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1780   }
1781 };
1782
1783 }
1784
1785 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1786                                              InstCombiner *IC) {
1787   if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1788     if (Constant *SOC = dyn_cast<Constant>(SO))
1789       return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1790
1791     return IC->InsertNewInstBefore(CastInst::Create(
1792           CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1793   }
1794
1795   // Figure out if the constant is the left or the right argument.
1796   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1797   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1798
1799   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1800     if (ConstIsRHS)
1801       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1802     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1803   }
1804
1805   Value *Op0 = SO, *Op1 = ConstOperand;
1806   if (!ConstIsRHS)
1807     std::swap(Op0, Op1);
1808   Instruction *New;
1809   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1810     New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1811   else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1812     New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1, 
1813                           SO->getName()+".cmp");
1814   else {
1815     assert(0 && "Unknown binary instruction type!");
1816     abort();
1817   }
1818   return IC->InsertNewInstBefore(New, I);
1819 }
1820
1821 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1822 // constant as the other operand, try to fold the binary operator into the
1823 // select arguments.  This also works for Cast instructions, which obviously do
1824 // not have a second operand.
1825 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1826                                      InstCombiner *IC) {
1827   // Don't modify shared select instructions
1828   if (!SI->hasOneUse()) return 0;
1829   Value *TV = SI->getOperand(1);
1830   Value *FV = SI->getOperand(2);
1831
1832   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1833     // Bool selects with constant operands can be folded to logical ops.
1834     if (SI->getType() == Type::Int1Ty) return 0;
1835
1836     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1837     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1838
1839     return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1840                               SelectFalseVal);
1841   }
1842   return 0;
1843 }
1844
1845
1846 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1847 /// node as operand #0, see if we can fold the instruction into the PHI (which
1848 /// is only possible if all operands to the PHI are constants).
1849 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1850   PHINode *PN = cast<PHINode>(I.getOperand(0));
1851   unsigned NumPHIValues = PN->getNumIncomingValues();
1852   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1853
1854   // Check to see if all of the operands of the PHI are constants.  If there is
1855   // one non-constant value, remember the BB it is.  If there is more than one
1856   // or if *it* is a PHI, bail out.
1857   BasicBlock *NonConstBB = 0;
1858   for (unsigned i = 0; i != NumPHIValues; ++i)
1859     if (!isa<Constant>(PN->getIncomingValue(i))) {
1860       if (NonConstBB) return 0;  // More than one non-const value.
1861       if (isa<PHINode>(PN->getIncomingValue(i))) return 0;  // Itself a phi.
1862       NonConstBB = PN->getIncomingBlock(i);
1863       
1864       // If the incoming non-constant value is in I's block, we have an infinite
1865       // loop.
1866       if (NonConstBB == I.getParent())
1867         return 0;
1868     }
1869   
1870   // If there is exactly one non-constant value, we can insert a copy of the
1871   // operation in that block.  However, if this is a critical edge, we would be
1872   // inserting the computation one some other paths (e.g. inside a loop).  Only
1873   // do this if the pred block is unconditionally branching into the phi block.
1874   if (NonConstBB) {
1875     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1876     if (!BI || !BI->isUnconditional()) return 0;
1877   }
1878
1879   // Okay, we can do the transformation: create the new PHI node.
1880   PHINode *NewPN = PHINode::Create(I.getType(), "");
1881   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1882   InsertNewInstBefore(NewPN, *PN);
1883   NewPN->takeName(PN);
1884
1885   // Next, add all of the operands to the PHI.
1886   if (I.getNumOperands() == 2) {
1887     Constant *C = cast<Constant>(I.getOperand(1));
1888     for (unsigned i = 0; i != NumPHIValues; ++i) {
1889       Value *InV = 0;
1890       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1891         if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1892           InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1893         else
1894           InV = ConstantExpr::get(I.getOpcode(), InC, C);
1895       } else {
1896         assert(PN->getIncomingBlock(i) == NonConstBB);
1897         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1898           InV = BinaryOperator::Create(BO->getOpcode(),
1899                                        PN->getIncomingValue(i), C, "phitmp",
1900                                        NonConstBB->getTerminator());
1901         else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1902           InV = CmpInst::Create(CI->getOpcode(), 
1903                                 CI->getPredicate(),
1904                                 PN->getIncomingValue(i), C, "phitmp",
1905                                 NonConstBB->getTerminator());
1906         else
1907           assert(0 && "Unknown binop!");
1908         
1909         AddToWorkList(cast<Instruction>(InV));
1910       }
1911       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1912     }
1913   } else { 
1914     CastInst *CI = cast<CastInst>(&I);
1915     const Type *RetTy = CI->getType();
1916     for (unsigned i = 0; i != NumPHIValues; ++i) {
1917       Value *InV;
1918       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1919         InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1920       } else {
1921         assert(PN->getIncomingBlock(i) == NonConstBB);
1922         InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i), 
1923                                I.getType(), "phitmp", 
1924                                NonConstBB->getTerminator());
1925         AddToWorkList(cast<Instruction>(InV));
1926       }
1927       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1928     }
1929   }
1930   return ReplaceInstUsesWith(I, NewPN);
1931 }
1932
1933
1934 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1935 ///    (sext (add LHS, RHS))  === (add (sext LHS), (sext RHS))
1936 /// This basically requires proving that the add in the original type would not
1937 /// overflow to change the sign bit or have a carry out.
1938 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1939   // There are different heuristics we can use for this.  Here are some simple
1940   // ones.
1941   
1942   // Add has the property that adding any two 2's complement numbers can only 
1943   // have one carry bit which can change a sign.  As such, if LHS and RHS each
1944   // have at least two sign bits, we know that the addition of the two values will
1945   // sign extend fine.
1946   if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1947     return true;
1948   
1949   
1950   // If one of the operands only has one non-zero bit, and if the other operand
1951   // has a known-zero bit in a more significant place than it (not including the
1952   // sign bit) the ripple may go up to and fill the zero, but won't change the
1953   // sign.  For example, (X & ~4) + 1.
1954   
1955   // TODO: Implement.
1956   
1957   return false;
1958 }
1959
1960
1961 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1962   bool Changed = SimplifyCommutative(I);
1963   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1964
1965   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1966     // X + undef -> undef
1967     if (isa<UndefValue>(RHS))
1968       return ReplaceInstUsesWith(I, RHS);
1969
1970     // X + 0 --> X
1971     if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1972       if (RHSC->isNullValue())
1973         return ReplaceInstUsesWith(I, LHS);
1974     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1975       if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1976                               (I.getType())->getValueAPF()))
1977         return ReplaceInstUsesWith(I, LHS);
1978     }
1979
1980     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1981       // X + (signbit) --> X ^ signbit
1982       const APInt& Val = CI->getValue();
1983       uint32_t BitWidth = Val.getBitWidth();
1984       if (Val == APInt::getSignBit(BitWidth))
1985         return BinaryOperator::CreateXor(LHS, RHS);
1986       
1987       // See if SimplifyDemandedBits can simplify this.  This handles stuff like
1988       // (X & 254)+1 -> (X&254)|1
1989       if (!isa<VectorType>(I.getType())) {
1990         APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1991         if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1992                                  KnownZero, KnownOne))
1993           return &I;
1994       }
1995     }
1996
1997     if (isa<PHINode>(LHS))
1998       if (Instruction *NV = FoldOpIntoPhi(I))
1999         return NV;
2000     
2001     ConstantInt *XorRHS = 0;
2002     Value *XorLHS = 0;
2003     if (isa<ConstantInt>(RHSC) &&
2004         match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2005       uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2006       const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2007       
2008       uint32_t Size = TySizeBits / 2;
2009       APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2010       APInt CFF80Val(-C0080Val);
2011       do {
2012         if (TySizeBits > Size) {
2013           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2014           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2015           if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2016               (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2017             // This is a sign extend if the top bits are known zero.
2018             if (!MaskedValueIsZero(XorLHS, 
2019                    APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2020               Size = 0;  // Not a sign ext, but can't be any others either.
2021             break;
2022           }
2023         }
2024         Size >>= 1;
2025         C0080Val = APIntOps::lshr(C0080Val, Size);
2026         CFF80Val = APIntOps::ashr(CFF80Val, Size);
2027       } while (Size >= 1);
2028       
2029       // FIXME: This shouldn't be necessary. When the backends can handle types
2030       // with funny bit widths then this switch statement should be removed. It
2031       // is just here to get the size of the "middle" type back up to something
2032       // that the back ends can handle.
2033       const Type *MiddleType = 0;
2034       switch (Size) {
2035         default: break;
2036         case 32: MiddleType = Type::Int32Ty; break;
2037         case 16: MiddleType = Type::Int16Ty; break;
2038         case  8: MiddleType = Type::Int8Ty; break;
2039       }
2040       if (MiddleType) {
2041         Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2042         InsertNewInstBefore(NewTrunc, I);
2043         return new SExtInst(NewTrunc, I.getType(), I.getName());
2044       }
2045     }
2046   }
2047
2048   if (I.getType() == Type::Int1Ty)
2049     return BinaryOperator::CreateXor(LHS, RHS);
2050
2051   // X + X --> X << 1
2052   if (I.getType()->isInteger()) {
2053     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2054
2055     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2056       if (RHSI->getOpcode() == Instruction::Sub)
2057         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
2058           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2059     }
2060     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2061       if (LHSI->getOpcode() == Instruction::Sub)
2062         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
2063           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2064     }
2065   }
2066
2067   // -A + B  -->  B - A
2068   // -A + -B  -->  -(A + B)
2069   if (Value *LHSV = dyn_castNegVal(LHS)) {
2070     if (LHS->getType()->isIntOrIntVector()) {
2071       if (Value *RHSV = dyn_castNegVal(RHS)) {
2072         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2073         InsertNewInstBefore(NewAdd, I);
2074         return BinaryOperator::CreateNeg(NewAdd);
2075       }
2076     }
2077     
2078     return BinaryOperator::CreateSub(RHS, LHSV);
2079   }
2080
2081   // A + -B  -->  A - B
2082   if (!isa<Constant>(RHS))
2083     if (Value *V = dyn_castNegVal(RHS))
2084       return BinaryOperator::CreateSub(LHS, V);
2085
2086
2087   ConstantInt *C2;
2088   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2089     if (X == RHS)   // X*C + X --> X * (C+1)
2090       return BinaryOperator::CreateMul(RHS, AddOne(C2));
2091
2092     // X*C1 + X*C2 --> X * (C1+C2)
2093     ConstantInt *C1;
2094     if (X == dyn_castFoldableMul(RHS, C1))
2095       return BinaryOperator::CreateMul(X, Add(C1, C2));
2096   }
2097
2098   // X + X*C --> X * (C+1)
2099   if (dyn_castFoldableMul(RHS, C2) == LHS)
2100     return BinaryOperator::CreateMul(LHS, AddOne(C2));
2101
2102   // X + ~X --> -1   since   ~X = -X-1
2103   if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2104     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2105   
2106
2107   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2108   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2109     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2110       return R;
2111   
2112   // A+B --> A|B iff A and B have no bits set in common.
2113   if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2114     APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2115     APInt LHSKnownOne(IT->getBitWidth(), 0);
2116     APInt LHSKnownZero(IT->getBitWidth(), 0);
2117     ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2118     if (LHSKnownZero != 0) {
2119       APInt RHSKnownOne(IT->getBitWidth(), 0);
2120       APInt RHSKnownZero(IT->getBitWidth(), 0);
2121       ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2122       
2123       // No bits in common -> bitwise or.
2124       if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2125         return BinaryOperator::CreateOr(LHS, RHS);
2126     }
2127   }
2128
2129   // W*X + Y*Z --> W * (X+Z)  iff W == Y
2130   if (I.getType()->isIntOrIntVector()) {
2131     Value *W, *X, *Y, *Z;
2132     if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2133         match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2134       if (W != Y) {
2135         if (W == Z) {
2136           std::swap(Y, Z);
2137         } else if (Y == X) {
2138           std::swap(W, X);
2139         } else if (X == Z) {
2140           std::swap(Y, Z);
2141           std::swap(W, X);
2142         }
2143       }
2144
2145       if (W == Y) {
2146         Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2147                                                             LHS->getName()), I);
2148         return BinaryOperator::CreateMul(W, NewAdd);
2149       }
2150     }
2151   }
2152
2153   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2154     Value *X = 0;
2155     if (match(LHS, m_Not(m_Value(X))))    // ~X + C --> (C-1) - X
2156       return BinaryOperator::CreateSub(SubOne(CRHS), X);
2157
2158     // (X & FF00) + xx00  -> (X+xx00) & FF00
2159     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2160       Constant *Anded = And(CRHS, C2);
2161       if (Anded == CRHS) {
2162         // See if all bits from the first bit set in the Add RHS up are included
2163         // in the mask.  First, get the rightmost bit.
2164         const APInt& AddRHSV = CRHS->getValue();
2165
2166         // Form a mask of all bits from the lowest bit added through the top.
2167         APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2168
2169         // See if the and mask includes all of these bits.
2170         APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2171
2172         if (AddRHSHighBits == AddRHSHighBitsAnd) {
2173           // Okay, the xform is safe.  Insert the new add pronto.
2174           Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2175                                                             LHS->getName()), I);
2176           return BinaryOperator::CreateAnd(NewAdd, C2);
2177         }
2178       }
2179     }
2180
2181     // Try to fold constant add into select arguments.
2182     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2183       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2184         return R;
2185   }
2186
2187   // add (cast *A to intptrtype) B -> 
2188   //   cast (GEP (cast *A to sbyte*) B)  -->  intptrtype
2189   {
2190     CastInst *CI = dyn_cast<CastInst>(LHS);
2191     Value *Other = RHS;
2192     if (!CI) {
2193       CI = dyn_cast<CastInst>(RHS);
2194       Other = LHS;
2195     }
2196     if (CI && CI->getType()->isSized() && 
2197         (CI->getType()->getPrimitiveSizeInBits() == 
2198          TD->getIntPtrType()->getPrimitiveSizeInBits()) 
2199         && isa<PointerType>(CI->getOperand(0)->getType())) {
2200       unsigned AS =
2201         cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2202       Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2203                                       PointerType::get(Type::Int8Ty, AS), I);
2204       I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2205       return new PtrToIntInst(I2, CI->getType());
2206     }
2207   }
2208   
2209   // add (select X 0 (sub n A)) A  -->  select X A n
2210   {
2211     SelectInst *SI = dyn_cast<SelectInst>(LHS);
2212     Value *Other = RHS;
2213     if (!SI) {
2214       SI = dyn_cast<SelectInst>(RHS);
2215       Other = LHS;
2216     }
2217     if (SI && SI->hasOneUse()) {
2218       Value *TV = SI->getTrueValue();
2219       Value *FV = SI->getFalseValue();
2220       Value *A, *N;
2221
2222       // Can we fold the add into the argument of the select?
2223       // We check both true and false select arguments for a matching subtract.
2224       if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2225           A == Other)  // Fold the add into the true select value.
2226         return SelectInst::Create(SI->getCondition(), N, A);
2227       if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) && 
2228           A == Other)  // Fold the add into the false select value.
2229         return SelectInst::Create(SI->getCondition(), A, N);
2230     }
2231   }
2232   
2233   // Check for X+0.0.  Simplify it to X if we know X is not -0.0.
2234   if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2235     if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2236       return ReplaceInstUsesWith(I, LHS);
2237
2238   // Check for (add (sext x), y), see if we can merge this into an
2239   // integer add followed by a sext.
2240   if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2241     // (add (sext x), cst) --> (sext (add x, cst'))
2242     if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2243       Constant *CI = 
2244         ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2245       if (LHSConv->hasOneUse() &&
2246           ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2247           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2248         // Insert the new, smaller add.
2249         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2250                                                         CI, "addconv");
2251         InsertNewInstBefore(NewAdd, I);
2252         return new SExtInst(NewAdd, I.getType());
2253       }
2254     }
2255     
2256     // (add (sext x), (sext y)) --> (sext (add int x, y))
2257     if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2258       // Only do this if x/y have the same type, if at last one of them has a
2259       // single use (so we don't increase the number of sexts), and if the
2260       // integer add will not overflow.
2261       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2262           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2263           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2264                                    RHSConv->getOperand(0))) {
2265         // Insert the new integer add.
2266         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2267                                                         RHSConv->getOperand(0),
2268                                                         "addconv");
2269         InsertNewInstBefore(NewAdd, I);
2270         return new SExtInst(NewAdd, I.getType());
2271       }
2272     }
2273   }
2274   
2275   // Check for (add double (sitofp x), y), see if we can merge this into an
2276   // integer add followed by a promotion.
2277   if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2278     // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2279     // ... if the constant fits in the integer value.  This is useful for things
2280     // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2281     // requires a constant pool load, and generally allows the add to be better
2282     // instcombined.
2283     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2284       Constant *CI = 
2285       ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2286       if (LHSConv->hasOneUse() &&
2287           ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2288           WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2289         // Insert the new integer add.
2290         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2291                                                         CI, "addconv");
2292         InsertNewInstBefore(NewAdd, I);
2293         return new SIToFPInst(NewAdd, I.getType());
2294       }
2295     }
2296     
2297     // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2298     if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2299       // Only do this if x/y have the same type, if at last one of them has a
2300       // single use (so we don't increase the number of int->fp conversions),
2301       // and if the integer add will not overflow.
2302       if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2303           (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2304           WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2305                                    RHSConv->getOperand(0))) {
2306         // Insert the new integer add.
2307         Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0), 
2308                                                         RHSConv->getOperand(0),
2309                                                         "addconv");
2310         InsertNewInstBefore(NewAdd, I);
2311         return new SIToFPInst(NewAdd, I.getType());
2312       }
2313     }
2314   }
2315   
2316   return Changed ? &I : 0;
2317 }
2318
2319 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2320   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2321
2322   if (Op0 == Op1 &&                        // sub X, X  -> 0
2323       !I.getType()->isFPOrFPVector())
2324     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2325
2326   // If this is a 'B = x-(-A)', change to B = x+A...
2327   if (Value *V = dyn_castNegVal(Op1))
2328     return BinaryOperator::CreateAdd(Op0, V);
2329
2330   if (isa<UndefValue>(Op0))
2331     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
2332   if (isa<UndefValue>(Op1))
2333     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
2334
2335   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2336     // Replace (-1 - A) with (~A)...
2337     if (C->isAllOnesValue())
2338       return BinaryOperator::CreateNot(Op1);
2339
2340     // C - ~X == X + (1+C)
2341     Value *X = 0;
2342     if (match(Op1, m_Not(m_Value(X))))
2343       return BinaryOperator::CreateAdd(X, AddOne(C));
2344
2345     // -(X >>u 31) -> (X >>s 31)
2346     // -(X >>s 31) -> (X >>u 31)
2347     if (C->isZero()) {
2348       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2349         if (SI->getOpcode() == Instruction::LShr) {
2350           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2351             // Check to see if we are shifting out everything but the sign bit.
2352             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2353                 SI->getType()->getPrimitiveSizeInBits()-1) {
2354               // Ok, the transformation is safe.  Insert AShr.
2355               return BinaryOperator::Create(Instruction::AShr, 
2356                                           SI->getOperand(0), CU, SI->getName());
2357             }
2358           }
2359         }
2360         else if (SI->getOpcode() == Instruction::AShr) {
2361           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2362             // Check to see if we are shifting out everything but the sign bit.
2363             if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2364                 SI->getType()->getPrimitiveSizeInBits()-1) {
2365               // Ok, the transformation is safe.  Insert LShr. 
2366               return BinaryOperator::CreateLShr(
2367                                           SI->getOperand(0), CU, SI->getName());
2368             }
2369           }
2370         }
2371       }
2372     }
2373
2374     // Try to fold constant sub into select arguments.
2375     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2376       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2377         return R;
2378
2379     if (isa<PHINode>(Op0))
2380       if (Instruction *NV = FoldOpIntoPhi(I))
2381         return NV;
2382   }
2383
2384   if (I.getType() == Type::Int1Ty)
2385     return BinaryOperator::CreateXor(Op0, Op1);
2386
2387   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2388     if (Op1I->getOpcode() == Instruction::Add &&
2389         !Op0->getType()->isFPOrFPVector()) {
2390       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
2391         return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2392       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
2393         return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2394       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2395         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2396           // C1-(X+C2) --> (C1-C2)-X
2397           return BinaryOperator::CreateSub(Subtract(CI1, CI2), 
2398                                            Op1I->getOperand(0));
2399       }
2400     }
2401
2402     if (Op1I->hasOneUse()) {
2403       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2404       // is not used by anyone else...
2405       //
2406       if (Op1I->getOpcode() == Instruction::Sub &&
2407           !Op1I->getType()->isFPOrFPVector()) {
2408         // Swap the two operands of the subexpr...
2409         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2410         Op1I->setOperand(0, IIOp1);
2411         Op1I->setOperand(1, IIOp0);
2412
2413         // Create the new top level add instruction...
2414         return BinaryOperator::CreateAdd(Op0, Op1);
2415       }
2416
2417       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2418       //
2419       if (Op1I->getOpcode() == Instruction::And &&
2420           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2421         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2422
2423         Value *NewNot =
2424           InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2425         return BinaryOperator::CreateAnd(Op0, NewNot);
2426       }
2427
2428       // 0 - (X sdiv C)  -> (X sdiv -C)
2429       if (Op1I->getOpcode() == Instruction::SDiv)
2430         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2431           if (CSI->isZero())
2432             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2433               return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2434                                                ConstantExpr::getNeg(DivRHS));
2435
2436       // X - X*C --> X * (1-C)
2437       ConstantInt *C2 = 0;
2438       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2439         Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2440         return BinaryOperator::CreateMul(Op0, CP1);
2441       }
2442
2443       // X - ((X / Y) * Y) --> X % Y
2444       if (Op1I->getOpcode() == Instruction::Mul)
2445         if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2446           if (Op0 == I->getOperand(0) &&
2447               Op1I->getOperand(1) == I->getOperand(1)) {
2448             if (I->getOpcode() == Instruction::SDiv)
2449               return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2450             if (I->getOpcode() == Instruction::UDiv)
2451               return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2452           }
2453     }
2454   }
2455
2456   if (!Op0->getType()->isFPOrFPVector())
2457     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2458       if (Op0I->getOpcode() == Instruction::Add) {
2459         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2460           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2461         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2462           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2463       } else if (Op0I->getOpcode() == Instruction::Sub) {
2464         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2465           return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2466       }
2467     }
2468
2469   ConstantInt *C1;
2470   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2471     if (X == Op1)  // X*C - X --> X * (C-1)
2472       return BinaryOperator::CreateMul(Op1, SubOne(C1));
2473
2474     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2475     if (X == dyn_castFoldableMul(Op1, C2))
2476       return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2477   }
2478   return 0;
2479 }
2480
2481 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2482 /// comparison only checks the sign bit.  If it only checks the sign bit, set
2483 /// TrueIfSigned if the result of the comparison is true when the input value is
2484 /// signed.
2485 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2486                            bool &TrueIfSigned) {
2487   switch (pred) {
2488   case ICmpInst::ICMP_SLT:   // True if LHS s< 0
2489     TrueIfSigned = true;
2490     return RHS->isZero();
2491   case ICmpInst::ICMP_SLE:   // True if LHS s<= RHS and RHS == -1
2492     TrueIfSigned = true;
2493     return RHS->isAllOnesValue();
2494   case ICmpInst::ICMP_SGT:   // True if LHS s> -1
2495     TrueIfSigned = false;
2496     return RHS->isAllOnesValue();
2497   case ICmpInst::ICMP_UGT:
2498     // True if LHS u> RHS and RHS == high-bit-mask - 1
2499     TrueIfSigned = true;
2500     return RHS->getValue() ==
2501       APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2502   case ICmpInst::ICMP_UGE: 
2503     // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2504     TrueIfSigned = true;
2505     return RHS->getValue().isSignBit();
2506   default:
2507     return false;
2508   }
2509 }
2510
2511 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2512   bool Changed = SimplifyCommutative(I);
2513   Value *Op0 = I.getOperand(0);
2514
2515   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2516     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
2518   // Simplify mul instructions with a constant RHS...
2519   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2520     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2521
2522       // ((X << C1)*C2) == (X * (C2 << C1))
2523       if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2524         if (SI->getOpcode() == Instruction::Shl)
2525           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2526             return BinaryOperator::CreateMul(SI->getOperand(0),
2527                                              ConstantExpr::getShl(CI, ShOp));
2528
2529       if (CI->isZero())
2530         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2531       if (CI->equalsInt(1))                  // X * 1  == X
2532         return ReplaceInstUsesWith(I, Op0);
2533       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2534         return BinaryOperator::CreateNeg(Op0, I.getName());
2535
2536       const APInt& Val = cast<ConstantInt>(CI)->getValue();
2537       if (Val.isPowerOf2()) {          // Replace X*(2^C) with X << C
2538         return BinaryOperator::CreateShl(Op0,
2539                  ConstantInt::get(Op0->getType(), Val.logBase2()));
2540       }
2541     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2542       if (Op1F->isNullValue())
2543         return ReplaceInstUsesWith(I, Op1);
2544
2545       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2546       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2547       if (Op1F->isExactlyValue(1.0))
2548         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2549     } else if (isa<VectorType>(Op1->getType())) {
2550       if (isa<ConstantAggregateZero>(Op1))
2551         return ReplaceInstUsesWith(I, Op1);
2552       
2553       // As above, vector X*splat(1.0) -> X in all defined cases.
2554       if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1))
2555         if (ConstantFP *F = dyn_cast_or_null<ConstantFP>(Op1V->getSplatValue()))
2556           if (F->isExactlyValue(1.0))
2557             return ReplaceInstUsesWith(I, Op0);
2558     }
2559     
2560     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2561       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2562           isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2563         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2564         Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2565                                                      Op1, "tmp");
2566         InsertNewInstBefore(Add, I);
2567         Value *C1C2 = ConstantExpr::getMul(Op1, 
2568                                            cast<Constant>(Op0I->getOperand(1)));
2569         return BinaryOperator::CreateAdd(Add, C1C2);
2570         
2571       }
2572
2573     // Try to fold constant mul into select arguments.
2574     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2575       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2576         return R;
2577
2578     if (isa<PHINode>(Op0))
2579       if (Instruction *NV = FoldOpIntoPhi(I))
2580         return NV;
2581   }
2582
2583   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2584     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2585       return BinaryOperator::CreateMul(Op0v, Op1v);
2586
2587   if (I.getType() == Type::Int1Ty)
2588     return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2589
2590   // If one of the operands of the multiply is a cast from a boolean value, then
2591   // we know the bool is either zero or one, so this is a 'masking' multiply.
2592   // See if we can simplify things based on how the boolean was originally
2593   // formed.
2594   CastInst *BoolCast = 0;
2595   if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2596     if (CI->getOperand(0)->getType() == Type::Int1Ty)
2597       BoolCast = CI;
2598   if (!BoolCast)
2599     if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2600       if (CI->getOperand(0)->getType() == Type::Int1Ty)
2601         BoolCast = CI;
2602   if (BoolCast) {
2603     if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2604       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2605       const Type *SCOpTy = SCIOp0->getType();
2606       bool TIS = false;
2607       
2608       // If the icmp is true iff the sign bit of X is set, then convert this
2609       // multiply into a shift/and combination.
2610       if (isa<ConstantInt>(SCIOp1) &&
2611           isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2612           TIS) {
2613         // Shift the X value right to turn it into "all signbits".
2614         Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2615                                           SCOpTy->getPrimitiveSizeInBits()-1);
2616         Value *V =
2617           InsertNewInstBefore(
2618             BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2619                                             BoolCast->getOperand(0)->getName()+
2620                                             ".mask"), I);
2621
2622         // If the multiply type is not the same as the source type, sign extend
2623         // or truncate to the multiply type.
2624         if (I.getType() != V->getType()) {
2625           uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2626           uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2627           Instruction::CastOps opcode = 
2628             (SrcBits == DstBits ? Instruction::BitCast : 
2629              (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2630           V = InsertCastBefore(opcode, V, I.getType(), I);
2631         }
2632
2633         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2634         return BinaryOperator::CreateAnd(V, OtherOp);
2635       }
2636     }
2637   }
2638
2639   return Changed ? &I : 0;
2640 }
2641
2642 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2643 /// instruction.
2644 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2645   SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2646   
2647   // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2648   int NonNullOperand = -1;
2649   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2650     if (ST->isNullValue())
2651       NonNullOperand = 2;
2652   // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2653   if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2654     if (ST->isNullValue())
2655       NonNullOperand = 1;
2656   
2657   if (NonNullOperand == -1)
2658     return false;
2659   
2660   Value *SelectCond = SI->getOperand(0);
2661   
2662   // Change the div/rem to use 'Y' instead of the select.
2663   I.setOperand(1, SI->getOperand(NonNullOperand));
2664   
2665   // Okay, we know we replace the operand of the div/rem with 'Y' with no
2666   // problem.  However, the select, or the condition of the select may have
2667   // multiple uses.  Based on our knowledge that the operand must be non-zero,
2668   // propagate the known value for the select into other uses of it, and
2669   // propagate a known value of the condition into its other users.
2670   
2671   // If the select and condition only have a single use, don't bother with this,
2672   // early exit.
2673   if (SI->use_empty() && SelectCond->hasOneUse())
2674     return true;
2675   
2676   // Scan the current block backward, looking for other uses of SI.
2677   BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2678   
2679   while (BBI != BBFront) {
2680     --BBI;
2681     // If we found a call to a function, we can't assume it will return, so
2682     // information from below it cannot be propagated above it.
2683     if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2684       break;
2685     
2686     // Replace uses of the select or its condition with the known values.
2687     for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2688          I != E; ++I) {
2689       if (*I == SI) {
2690         *I = SI->getOperand(NonNullOperand);
2691         AddToWorkList(BBI);
2692       } else if (*I == SelectCond) {
2693         *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2694                                    ConstantInt::getFalse();
2695         AddToWorkList(BBI);
2696       }
2697     }
2698     
2699     // If we past the instruction, quit looking for it.
2700     if (&*BBI == SI)
2701       SI = 0;
2702     if (&*BBI == SelectCond)
2703       SelectCond = 0;
2704     
2705     // If we ran out of things to eliminate, break out of the loop.
2706     if (SelectCond == 0 && SI == 0)
2707       break;
2708     
2709   }
2710   return true;
2711 }
2712
2713
2714 /// This function implements the transforms on div instructions that work
2715 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2716 /// used by the visitors to those instructions.
2717 /// @brief Transforms common to all three div instructions
2718 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2719   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2720
2721   // undef / X -> 0        for integer.
2722   // undef / X -> undef    for FP (the undef could be a snan).
2723   if (isa<UndefValue>(Op0)) {
2724     if (Op0->getType()->isFPOrFPVector())
2725       return ReplaceInstUsesWith(I, Op0);
2726     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2727   }
2728
2729   // X / undef -> undef
2730   if (isa<UndefValue>(Op1))
2731     return ReplaceInstUsesWith(I, Op1);
2732
2733   return 0;
2734 }
2735
2736 /// This function implements the transforms common to both integer division
2737 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2738 /// division instructions.
2739 /// @brief Common integer divide transforms
2740 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2741   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2742
2743   // (sdiv X, X) --> 1     (udiv X, X) --> 1
2744   if (Op0 == Op1) {
2745     if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2746       ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2747       std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2748       return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2749     }
2750
2751     ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2752     return ReplaceInstUsesWith(I, CI);
2753   }
2754   
2755   if (Instruction *Common = commonDivTransforms(I))
2756     return Common;
2757   
2758   // Handle cases involving: [su]div X, (select Cond, Y, Z)
2759   // This does not apply for fdiv.
2760   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2761     return &I;
2762
2763   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2764     // div X, 1 == X
2765     if (RHS->equalsInt(1))
2766       return ReplaceInstUsesWith(I, Op0);
2767
2768     // (X / C1) / C2  -> X / (C1*C2)
2769     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2770       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2771         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2772           if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2773             return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2774           else 
2775             return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2776                                           Multiply(RHS, LHSRHS));
2777         }
2778
2779     if (!RHS->isZero()) { // avoid X udiv 0
2780       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2781         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2782           return R;
2783       if (isa<PHINode>(Op0))
2784         if (Instruction *NV = FoldOpIntoPhi(I))
2785           return NV;
2786     }
2787   }
2788
2789   // 0 / X == 0, we don't need to preserve faults!
2790   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2791     if (LHS->equalsInt(0))
2792       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2793
2794   // It can't be division by zero, hence it must be division by one.
2795   if (I.getType() == Type::Int1Ty)
2796     return ReplaceInstUsesWith(I, Op0);
2797
2798   return 0;
2799 }
2800
2801 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2802   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2803
2804   // Handle the integer div common cases
2805   if (Instruction *Common = commonIDivTransforms(I))
2806     return Common;
2807
2808   // X udiv C^2 -> X >> C
2809   // Check to see if this is an unsigned division with an exact power of 2,
2810   // if so, convert to a right shift.
2811   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2812     if (C->getValue().isPowerOf2())  // 0 not included in isPowerOf2
2813       return BinaryOperator::CreateLShr(Op0, 
2814                ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2815   }
2816
2817   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2818   if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2819     if (RHSI->getOpcode() == Instruction::Shl &&
2820         isa<ConstantInt>(RHSI->getOperand(0))) {
2821       const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2822       if (C1.isPowerOf2()) {
2823         Value *N = RHSI->getOperand(1);
2824         const Type *NTy = N->getType();
2825         if (uint32_t C2 = C1.logBase2()) {
2826           Constant *C2V = ConstantInt::get(NTy, C2);
2827           N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2828         }
2829         return BinaryOperator::CreateLShr(Op0, N);
2830       }
2831     }
2832   }
2833   
2834   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2835   // where C1&C2 are powers of two.
2836   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) 
2837     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2838       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))  {
2839         const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2840         if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2841           // Compute the shift amounts
2842           uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2843           // Construct the "on true" case of the select
2844           Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2845           Instruction *TSI = BinaryOperator::CreateLShr(
2846                                                  Op0, TC, SI->getName()+".t");
2847           TSI = InsertNewInstBefore(TSI, I);
2848   
2849           // Construct the "on false" case of the select
2850           Constant *FC = ConstantInt::get(Op0->getType(), FSA); 
2851           Instruction *FSI = BinaryOperator::CreateLShr(
2852                                                  Op0, FC, SI->getName()+".f");
2853           FSI = InsertNewInstBefore(FSI, I);
2854
2855           // construct the select instruction and return it.
2856           return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2857         }
2858       }
2859   return 0;
2860 }
2861
2862 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2863   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2864
2865   // Handle the integer div common cases
2866   if (Instruction *Common = commonIDivTransforms(I))
2867     return Common;
2868
2869   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2870     // sdiv X, -1 == -X
2871     if (RHS->isAllOnesValue())
2872       return BinaryOperator::CreateNeg(Op0);
2873
2874     // -X/C -> X/-C
2875     if (Value *LHSNeg = dyn_castNegVal(Op0))
2876       return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2877   }
2878
2879   // If the sign bits of both operands are zero (i.e. we can prove they are
2880   // unsigned inputs), turn this into a udiv.
2881   if (I.getType()->isInteger()) {
2882     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2883     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2884       // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2885       return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2886     }
2887   }      
2888   
2889   return 0;
2890 }
2891
2892 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2893   return commonDivTransforms(I);
2894 }
2895
2896 /// This function implements the transforms on rem instructions that work
2897 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2898 /// is used by the visitors to those instructions.
2899 /// @brief Transforms common to all three rem instructions
2900 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2901   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2902
2903   // 0 % X == 0 for integer, we don't need to preserve faults!
2904   if (Constant *LHS = dyn_cast<Constant>(Op0))
2905     if (LHS->isNullValue())
2906       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2907
2908   if (isa<UndefValue>(Op0)) {             // undef % X -> 0
2909     if (I.getType()->isFPOrFPVector())
2910       return ReplaceInstUsesWith(I, Op0);  // X % undef -> undef (could be SNaN)
2911     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2912   }
2913   if (isa<UndefValue>(Op1))
2914     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2915
2916   // Handle cases involving: rem X, (select Cond, Y, Z)
2917   if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2918     return &I;
2919
2920   return 0;
2921 }
2922
2923 /// This function implements the transforms common to both integer remainder
2924 /// instructions (urem and srem). It is called by the visitors to those integer
2925 /// remainder instructions.
2926 /// @brief Common integer remainder transforms
2927 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2928   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
2930   if (Instruction *common = commonRemTransforms(I))
2931     return common;
2932
2933   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2934     // X % 0 == undef, we don't need to preserve faults!
2935     if (RHS->equalsInt(0))
2936       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2937     
2938     if (RHS->equalsInt(1))  // X % 1 == 0
2939       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2940
2941     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2942       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2943         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2944           return R;
2945       } else if (isa<PHINode>(Op0I)) {
2946         if (Instruction *NV = FoldOpIntoPhi(I))
2947           return NV;
2948       }
2949
2950       // See if we can fold away this rem instruction.
2951       uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2952       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2953       if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2954                                KnownZero, KnownOne))
2955         return &I;
2956     }
2957   }
2958
2959   return 0;
2960 }
2961
2962 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2963   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
2965   if (Instruction *common = commonIRemTransforms(I))
2966     return common;
2967   
2968   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2969     // X urem C^2 -> X and C
2970     // Check to see if this is an unsigned remainder with an exact power of 2,
2971     // if so, convert to a bitwise and.
2972     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2973       if (C->getValue().isPowerOf2())
2974         return BinaryOperator::CreateAnd(Op0, SubOne(C));
2975   }
2976
2977   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2978     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2979     if (RHSI->getOpcode() == Instruction::Shl &&
2980         isa<ConstantInt>(RHSI->getOperand(0))) {
2981       if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2982         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2983         Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2984                                                                    "tmp"), I);
2985         return BinaryOperator::CreateAnd(Op0, Add);
2986       }
2987     }
2988   }
2989
2990   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2991   // where C1&C2 are powers of two.
2992   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2993     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2994       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2995         // STO == 0 and SFO == 0 handled above.
2996         if ((STO->getValue().isPowerOf2()) && 
2997             (SFO->getValue().isPowerOf2())) {
2998           Value *TrueAnd = InsertNewInstBefore(
2999             BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3000           Value *FalseAnd = InsertNewInstBefore(
3001             BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3002           return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3003         }
3004       }
3005   }
3006   
3007   return 0;
3008 }
3009
3010 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3011   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3012
3013   // Handle the integer rem common cases
3014   if (Instruction *common = commonIRemTransforms(I))
3015     return common;
3016   
3017   if (Value *RHSNeg = dyn_castNegVal(Op1))
3018     if (!isa<Constant>(RHSNeg) ||
3019         (isa<ConstantInt>(RHSNeg) &&
3020          cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3021       // X % -Y -> X % Y
3022       AddUsesToWorkList(I);
3023       I.setOperand(1, RHSNeg);
3024       return &I;
3025     }
3026  
3027   // If the sign bits of both operands are zero (i.e. we can prove they are
3028   // unsigned inputs), turn this into a urem.
3029   if (I.getType()->isInteger()) {
3030     APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3031     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3032       // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3033       return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3034     }
3035   }
3036
3037   return 0;
3038 }
3039
3040 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3041   return commonRemTransforms(I);
3042 }
3043
3044 // isOneBitSet - Return true if there is exactly one bit set in the specified
3045 // constant.
3046 static bool isOneBitSet(const ConstantInt *CI) {
3047   return CI->getValue().isPowerOf2();
3048 }
3049
3050 // isHighOnes - Return true if the constant is of the form 1+0+.
3051 // This is the same as lowones(~X).
3052 static bool isHighOnes(const ConstantInt *CI) {
3053   return (~CI->getValue() + 1).isPowerOf2();
3054 }
3055
3056 /// getICmpCode - Encode a icmp predicate into a three bit mask.  These bits
3057 /// are carefully arranged to allow folding of expressions such as:
3058 ///
3059 ///      (A < B) | (A > B) --> (A != B)
3060 ///
3061 /// Note that this is only valid if the first and second predicates have the
3062 /// same sign. Is illegal to do: (A u< B) | (A s> B) 
3063 ///
3064 /// Three bits are used to represent the condition, as follows:
3065 ///   0  A > B
3066 ///   1  A == B
3067 ///   2  A < B
3068 ///
3069 /// <=>  Value  Definition
3070 /// 000     0   Always false
3071 /// 001     1   A >  B
3072 /// 010     2   A == B
3073 /// 011     3   A >= B
3074 /// 100     4   A <  B
3075 /// 101     5   A != B
3076 /// 110     6   A <= B
3077 /// 111     7   Always true
3078 ///  
3079 static unsigned getICmpCode(const ICmpInst *ICI) {
3080   switch (ICI->getPredicate()) {
3081     // False -> 0
3082   case ICmpInst::ICMP_UGT: return 1;  // 001
3083   case ICmpInst::ICMP_SGT: return 1;  // 001
3084   case ICmpInst::ICMP_EQ:  return 2;  // 010
3085   case ICmpInst::ICMP_UGE: return 3;  // 011
3086   case ICmpInst::ICMP_SGE: return 3;  // 011
3087   case ICmpInst::ICMP_ULT: return 4;  // 100
3088   case ICmpInst::ICMP_SLT: return 4;  // 100
3089   case ICmpInst::ICMP_NE:  return 5;  // 101
3090   case ICmpInst::ICMP_ULE: return 6;  // 110
3091   case ICmpInst::ICMP_SLE: return 6;  // 110
3092     // True -> 7
3093   default:
3094     assert(0 && "Invalid ICmp predicate!");
3095     return 0;
3096   }
3097 }
3098
3099 /// getICmpValue - This is the complement of getICmpCode, which turns an
3100 /// opcode and two operands into either a constant true or false, or a brand 
3101 /// new ICmp instruction. The sign is passed in to determine which kind
3102 /// of predicate to use in new icmp instructions.
3103 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3104   switch (code) {
3105   default: assert(0 && "Illegal ICmp code!");
3106   case  0: return ConstantInt::getFalse();
3107   case  1: 
3108     if (sign)
3109       return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3110     else
3111       return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3112   case  2: return new ICmpInst(ICmpInst::ICMP_EQ,  LHS, RHS);
3113   case  3: 
3114     if (sign)
3115       return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3116     else
3117       return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3118   case  4: 
3119     if (sign)
3120       return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3121     else
3122       return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3123   case  5: return new ICmpInst(ICmpInst::ICMP_NE,  LHS, RHS);
3124   case  6: 
3125     if (sign)
3126       return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3127     else
3128       return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3129   case  7: return ConstantInt::getTrue();
3130   }
3131 }
3132
3133 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3134   return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3135     (ICmpInst::isSignedPredicate(p1) && 
3136      (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3137     (ICmpInst::isSignedPredicate(p2) && 
3138      (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3139 }
3140
3141 namespace { 
3142 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3143 struct FoldICmpLogical {
3144   InstCombiner &IC;
3145   Value *LHS, *RHS;
3146   ICmpInst::Predicate pred;
3147   FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3148     : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3149       pred(ICI->getPredicate()) {}
3150   bool shouldApply(Value *V) const {
3151     if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3152       if (PredicatesFoldable(pred, ICI->getPredicate()))
3153         return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3154                 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3155     return false;
3156   }
3157   Instruction *apply(Instruction &Log) const {
3158     ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3159     if (ICI->getOperand(0) != LHS) {
3160       assert(ICI->getOperand(1) == LHS);
3161       ICI->swapOperands();  // Swap the LHS and RHS of the ICmp
3162     }
3163
3164     ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3165     unsigned LHSCode = getICmpCode(ICI);
3166     unsigned RHSCode = getICmpCode(RHSICI);
3167     unsigned Code;
3168     switch (Log.getOpcode()) {
3169     case Instruction::And: Code = LHSCode & RHSCode; break;
3170     case Instruction::Or:  Code = LHSCode | RHSCode; break;
3171     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3172     default: assert(0 && "Illegal logical opcode!"); return 0;
3173     }
3174
3175     bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) || 
3176                     ICmpInst::isSignedPredicate(ICI->getPredicate());
3177       
3178     Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3179     if (Instruction *I = dyn_cast<Instruction>(RV))
3180       return I;
3181     // Otherwise, it's a constant boolean value...
3182     return IC.ReplaceInstUsesWith(Log, RV);
3183   }
3184 };
3185 } // end anonymous namespace
3186
3187 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
3188 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
3189 // guaranteed to be a binary operator.
3190 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3191                                     ConstantInt *OpRHS,
3192                                     ConstantInt *AndRHS,
3193                                     BinaryOperator &TheAnd) {
3194   Value *X = Op->getOperand(0);
3195   Constant *Together = 0;
3196   if (!Op->isShift())
3197     Together = And(AndRHS, OpRHS);
3198
3199   switch (Op->getOpcode()) {
3200   case Instruction::Xor:
3201     if (Op->hasOneUse()) {
3202       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3203       Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3204       InsertNewInstBefore(And, TheAnd);
3205       And->takeName(Op);
3206       return BinaryOperator::CreateXor(And, Together);
3207     }
3208     break;
3209   case Instruction::Or:
3210     if (Together == AndRHS) // (X | C) & C --> C
3211       return ReplaceInstUsesWith(TheAnd, AndRHS);
3212
3213     if (Op->hasOneUse() && Together != OpRHS) {
3214       // (X | C1) & C2 --> (X | (C1&C2)) & C2
3215       Instruction *Or = BinaryOperator::CreateOr(X, Together);
3216       InsertNewInstBefore(Or, TheAnd);
3217       Or->takeName(Op);
3218       return BinaryOperator::CreateAnd(Or, AndRHS);
3219     }
3220     break;
3221   case Instruction::Add:
3222     if (Op->hasOneUse()) {
3223       // Adding a one to a single bit bit-field should be turned into an XOR
3224       // of the bit.  First thing to check is to see if this AND is with a
3225       // single bit constant.
3226       const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3227
3228       // If there is only one bit set...
3229       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3230         // Ok, at this point, we know that we are masking the result of the
3231         // ADD down to exactly one bit.  If the constant we are adding has
3232         // no bits set below this bit, then we can eliminate the ADD.
3233         const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3234
3235         // Check to see if any bits below the one bit set in AndRHSV are set.
3236         if ((AddRHS & (AndRHSV-1)) == 0) {
3237           // If not, the only thing that can effect the output of the AND is
3238           // the bit specified by AndRHSV.  If that bit is set, the effect of
3239           // the XOR is to toggle the bit.  If it is clear, then the ADD has
3240           // no effect.
3241           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3242             TheAnd.setOperand(0, X);
3243             return &TheAnd;
3244           } else {
3245             // Pull the XOR out of the AND.
3246             Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3247             InsertNewInstBefore(NewAnd, TheAnd);
3248             NewAnd->takeName(Op);
3249             return BinaryOperator::CreateXor(NewAnd, AndRHS);
3250           }
3251         }
3252       }
3253     }
3254     break;
3255
3256   case Instruction::Shl: {
3257     // We know that the AND will not produce any of the bits shifted in, so if
3258     // the anded constant includes them, clear them now!
3259     //
3260     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3261     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3262     APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3263     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3264
3265     if (CI->getValue() == ShlMask) { 
3266     // Masking out bits that the shift already masks
3267       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
3268     } else if (CI != AndRHS) {                  // Reducing bits set in and.
3269       TheAnd.setOperand(1, CI);
3270       return &TheAnd;
3271     }
3272     break;
3273   }
3274   case Instruction::LShr:
3275   {
3276     // We know that the AND will not produce any of the bits shifted in, so if
3277     // the anded constant includes them, clear them now!  This only applies to
3278     // unsigned shifts, because a signed shr may bring in set bits!
3279     //
3280     uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3281     uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3282     APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3283     ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3284
3285     if (CI->getValue() == ShrMask) {   
3286     // Masking out bits that the shift already masks.
3287       return ReplaceInstUsesWith(TheAnd, Op);
3288     } else if (CI != AndRHS) {
3289       TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
3290       return &TheAnd;
3291     }
3292     break;
3293   }
3294   case Instruction::AShr:
3295     // Signed shr.
3296     // See if this is shifting in some sign extension, then masking it out
3297     // with an and.
3298     if (Op->hasOneUse()) {
3299       uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3300       uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3301       APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3302       Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3303       if (C == AndRHS) {          // Masking out bits shifted in.
3304         // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3305         // Make the argument unsigned.
3306         Value *ShVal = Op->getOperand(0);
3307         ShVal = InsertNewInstBefore(
3308             BinaryOperator::CreateLShr(ShVal, OpRHS, 
3309                                    Op->getName()), TheAnd);
3310         return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3311       }
3312     }
3313     break;
3314   }
3315   return 0;
3316 }
3317
3318
3319 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3320 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
3321 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi. isSigned indicates
3322 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3323 /// insert new instructions.
3324 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3325                                            bool isSigned, bool Inside, 
3326                                            Instruction &IB) {
3327   assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ? 
3328             ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3329          "Lo is not <= Hi in range emission code!");
3330     
3331   if (Inside) {
3332     if (Lo == Hi)  // Trivially false.
3333       return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3334
3335     // V >= Min && V < Hi --> V < Hi
3336     if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3337       ICmpInst::Predicate pred = (isSigned ? 
3338         ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3339       return new ICmpInst(pred, V, Hi);
3340     }
3341
3342     // Emit V-Lo <u Hi-Lo
3343     Constant *NegLo = ConstantExpr::getNeg(Lo);
3344     Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3345     InsertNewInstBefore(Add, IB);
3346     Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3347     return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3348   }
3349
3350   if (Lo == Hi)  // Trivially true.
3351     return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3352
3353   // V < Min || V >= Hi -> V > Hi-1
3354   Hi = SubOne(cast<ConstantInt>(Hi));
3355   if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3356     ICmpInst::Predicate pred = (isSigned ? 
3357         ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3358     return new ICmpInst(pred, V, Hi);
3359   }
3360
3361   // Emit V-Lo >u Hi-1-Lo
3362   // Note that Hi has already had one subtracted from it, above.
3363   ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3364   Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3365   InsertNewInstBefore(Add, IB);
3366   Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3367   return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3368 }
3369
3370 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3371 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
3372 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
3373 // not, since all 1s are not contiguous.
3374 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3375   const APInt& V = Val->getValue();
3376   uint32_t BitWidth = Val->getType()->getBitWidth();
3377   if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3378
3379   // look for the first zero bit after the run of ones
3380   MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3381   // look for the first non-zero bit
3382   ME = V.getActiveBits(); 
3383   return true;
3384 }
3385
3386 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3387 /// where isSub determines whether the operator is a sub.  If we can fold one of
3388 /// the following xforms:
3389 /// 
3390 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3391 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3392 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3393 ///
3394 /// return (A +/- B).
3395 ///
3396 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3397                                         ConstantInt *Mask, bool isSub,
3398                                         Instruction &I) {
3399   Instruction *LHSI = dyn_cast<Instruction>(LHS);
3400   if (!LHSI || LHSI->getNumOperands() != 2 ||
3401       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3402
3403   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3404
3405   switch (LHSI->getOpcode()) {
3406   default: return 0;
3407   case Instruction::And:
3408     if (And(N, Mask) == Mask) {
3409       // If the AndRHS is a power of two minus one (0+1+), this is simple.
3410       if ((Mask->getValue().countLeadingZeros() + 
3411            Mask->getValue().countPopulation()) == 
3412           Mask->getValue().getBitWidth())
3413         break;
3414
3415       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3416       // part, we don't need any explicit masks to take them out of A.  If that
3417       // is all N is, ignore it.
3418       uint32_t MB = 0, ME = 0;
3419       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
3420         uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3421         APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3422         if (MaskedValueIsZero(RHS, Mask))
3423           break;
3424       }
3425     }
3426     return 0;
3427   case Instruction::Or:
3428   case Instruction::Xor:
3429     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3430     if ((Mask->getValue().countLeadingZeros() + 
3431          Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3432         && And(N, Mask)->isZero())
3433       break;
3434     return 0;
3435   }
3436   
3437   Instruction *New;
3438   if (isSub)
3439     New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3440   else
3441     New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3442   return InsertNewInstBefore(New, I);
3443 }
3444
3445 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3446   bool Changed = SimplifyCommutative(I);
3447   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3448
3449   if (isa<UndefValue>(Op1))                         // X & undef -> 0
3450     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3451
3452   // and X, X = X
3453   if (Op0 == Op1)
3454     return ReplaceInstUsesWith(I, Op1);
3455
3456   // See if we can simplify any instructions used by the instruction whose sole 
3457   // purpose is to compute bits we don't care about.
3458   if (!isa<VectorType>(I.getType())) {
3459     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3460     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3461     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3462                              KnownZero, KnownOne))
3463       return &I;
3464   } else {
3465     if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3466       if (CP->isAllOnesValue())            // X & <-1,-1> -> X
3467         return ReplaceInstUsesWith(I, I.getOperand(0));
3468     } else if (isa<ConstantAggregateZero>(Op1)) {
3469       return ReplaceInstUsesWith(I, Op1);  // X & <0,0> -> <0,0>
3470     }
3471   }
3472   
3473   if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3474     const APInt& AndRHSMask = AndRHS->getValue();
3475     APInt NotAndRHS(~AndRHSMask);
3476
3477     // Optimize a variety of ((val OP C1) & C2) combinations...
3478     if (isa<BinaryOperator>(Op0)) {
3479       Instruction *Op0I = cast<Instruction>(Op0);
3480       Value *Op0LHS = Op0I->getOperand(0);
3481       Value *Op0RHS = Op0I->getOperand(1);
3482       switch (Op0I->getOpcode()) {
3483       case Instruction::Xor:
3484       case Instruction::Or:
3485         // If the mask is only needed on one incoming arm, push it up.
3486         if (Op0I->hasOneUse()) {
3487           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3488             // Not masking anything out for the LHS, move to RHS.
3489             Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3490                                                    Op0RHS->getName()+".masked");
3491             InsertNewInstBefore(NewRHS, I);
3492             return BinaryOperator::Create(
3493                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3494           }
3495           if (!isa<Constant>(Op0RHS) &&
3496               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3497             // Not masking anything out for the RHS, move to LHS.
3498             Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3499                                                    Op0LHS->getName()+".masked");
3500             InsertNewInstBefore(NewLHS, I);
3501             return BinaryOperator::Create(
3502                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3503           }
3504         }
3505
3506         break;
3507       case Instruction::Add:
3508         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3509         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3510         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3511         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3512           return BinaryOperator::CreateAnd(V, AndRHS);
3513         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3514           return BinaryOperator::CreateAnd(V, AndRHS);  // Add commutes
3515         break;
3516
3517       case Instruction::Sub:
3518         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3519         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3520         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3521         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3522           return BinaryOperator::CreateAnd(V, AndRHS);
3523
3524         // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3525         // has 1's for all bits that the subtraction with A might affect.
3526         if (Op0I->hasOneUse()) {
3527           uint32_t BitWidth = AndRHSMask.getBitWidth();
3528           uint32_t Zeros = AndRHSMask.countLeadingZeros();
3529           APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3530
3531           ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3532           if (!(A && A->isZero()) &&               // avoid infinite recursion.
3533               MaskedValueIsZero(Op0LHS, Mask)) {
3534             Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3535             InsertNewInstBefore(NewNeg, I);
3536             return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3537           }
3538         }
3539         break;
3540
3541       case Instruction::Shl:
3542       case Instruction::LShr:
3543         // (1 << x) & 1 --> zext(x == 0)
3544         // (1 >> x) & 1 --> zext(x == 0)
3545         if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3546           Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3547                                            Constant::getNullValue(I.getType()));
3548           InsertNewInstBefore(NewICmp, I);
3549           return new ZExtInst(NewICmp, I.getType());
3550         }
3551         break;
3552       }
3553
3554       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3555         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3556           return Res;
3557     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3558       // If this is an integer truncation or change from signed-to-unsigned, and
3559       // if the source is an and/or with immediate, transform it.  This
3560       // frequently occurs for bitfield accesses.
3561       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3562         if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3563             CastOp->getNumOperands() == 2)
3564           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3565             if (CastOp->getOpcode() == Instruction::And) {
3566               // Change: and (cast (and X, C1) to T), C2
3567               // into  : and (cast X to T), trunc_or_bitcast(C1)&C2
3568               // This will fold the two constants together, which may allow 
3569               // other simplifications.
3570               Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3571                 CastOp->getOperand(0), I.getType(), 
3572                 CastOp->getName()+".shrunk");
3573               NewCast = InsertNewInstBefore(NewCast, I);
3574               // trunc_or_bitcast(C1)&C2
3575               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3576               C3 = ConstantExpr::getAnd(C3, AndRHS);
3577               return BinaryOperator::CreateAnd(NewCast, C3);
3578             } else if (CastOp->getOpcode() == Instruction::Or) {
3579               // Change: and (cast (or X, C1) to T), C2
3580               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3581               Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3582               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3583                 return ReplaceInstUsesWith(I, AndRHS);
3584             }
3585           }
3586       }
3587     }
3588
3589     // Try to fold constant and into select arguments.
3590     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3591       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3592         return R;
3593     if (isa<PHINode>(Op0))
3594       if (Instruction *NV = FoldOpIntoPhi(I))
3595         return NV;
3596   }
3597
3598   Value *Op0NotVal = dyn_castNotVal(Op0);
3599   Value *Op1NotVal = dyn_castNotVal(Op1);
3600
3601   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3602     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3603
3604   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3605   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3606     Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3607                                                I.getName()+".demorgan");
3608     InsertNewInstBefore(Or, I);
3609     return BinaryOperator::CreateNot(Or);
3610   }
3611   
3612   {
3613     Value *A = 0, *B = 0, *C = 0, *D = 0;
3614     if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3615       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3616         return ReplaceInstUsesWith(I, Op1);
3617     
3618       // (A|B) & ~(A&B) -> A^B
3619       if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3620         if ((A == C && B == D) || (A == D && B == C))
3621           return BinaryOperator::CreateXor(A, B);
3622       }
3623     }
3624     
3625     if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3626       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3627         return ReplaceInstUsesWith(I, Op0);
3628
3629       // ~(A&B) & (A|B) -> A^B
3630       if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3631         if ((A == C && B == D) || (A == D && B == C))
3632           return BinaryOperator::CreateXor(A, B);
3633       }
3634     }
3635     
3636     if (Op0->hasOneUse() &&
3637         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3638       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3639         I.swapOperands();     // Simplify below
3640         std::swap(Op0, Op1);
3641       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3642         cast<BinaryOperator>(Op0)->swapOperands();
3643         I.swapOperands();     // Simplify below
3644         std::swap(Op0, Op1);
3645       }
3646     }
3647     if (Op1->hasOneUse() &&
3648         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3649       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3650         cast<BinaryOperator>(Op1)->swapOperands();
3651         std::swap(A, B);
3652       }
3653       if (A == Op0) {                                // A&(A^B) -> A & ~B
3654         Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3655         InsertNewInstBefore(NotB, I);
3656         return BinaryOperator::CreateAnd(A, NotB);
3657       }
3658     }
3659   }
3660   
3661   { // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3662     // where C is a power of 2
3663     Value *A, *B;
3664     ConstantInt *C1, *C2;
3665     ICmpInst::Predicate LHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3666     ICmpInst::Predicate RHSCC = ICmpInst::BAD_ICMP_PREDICATE;
3667     if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3668                         m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3669       if (C1 == C2 && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3670           C1->getValue().isPowerOf2()) {
3671         Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3672         InsertNewInstBefore(NewOr, I);
3673         return new ICmpInst(LHSCC, NewOr, C1);
3674       }
3675   }
3676   
3677   if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3678     // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3679     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3680       return R;
3681
3682     Value *LHSVal, *RHSVal;
3683     ConstantInt *LHSCst, *RHSCst;
3684     ICmpInst::Predicate LHSCC, RHSCC;
3685     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3686       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3687         if (LHSVal == RHSVal &&    // Found (X icmp C1) & (X icmp C2)
3688             // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3689             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3690             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3691             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3692             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3693             
3694             // Don't try to fold ICMP_SLT + ICMP_ULT.
3695             (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3696              ICmpInst::isSignedPredicate(LHSCC) == 
3697                  ICmpInst::isSignedPredicate(RHSCC))) {
3698           // Ensure that the larger constant is on the RHS.
3699           ICmpInst::Predicate GT;
3700           if (ICmpInst::isSignedPredicate(LHSCC) ||
3701               (ICmpInst::isEquality(LHSCC) && 
3702                ICmpInst::isSignedPredicate(RHSCC)))
3703             GT = ICmpInst::ICMP_SGT;
3704           else
3705             GT = ICmpInst::ICMP_UGT;
3706           
3707           Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3708           ICmpInst *LHS = cast<ICmpInst>(Op0);
3709           if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3710             std::swap(LHS, RHS);
3711             std::swap(LHSCst, RHSCst);
3712             std::swap(LHSCC, RHSCC);
3713           }
3714
3715           // At this point, we know we have have two icmp instructions
3716           // comparing a value against two constants and and'ing the result
3717           // together.  Because of the above check, we know that we only have
3718           // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know 
3719           // (from the FoldICmpLogical check above), that the two constants 
3720           // are not equal and that the larger constant is on the RHS
3721           assert(LHSCst != RHSCst && "Compares not folded above?");
3722
3723           switch (LHSCC) {
3724           default: assert(0 && "Unknown integer condition code!");
3725           case ICmpInst::ICMP_EQ:
3726             switch (RHSCC) {
3727             default: assert(0 && "Unknown integer condition code!");
3728             case ICmpInst::ICMP_EQ:         // (X == 13 & X == 15) -> false
3729             case ICmpInst::ICMP_UGT:        // (X == 13 & X >  15) -> false
3730             case ICmpInst::ICMP_SGT:        // (X == 13 & X >  15) -> false
3731               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3732             case ICmpInst::ICMP_NE:         // (X == 13 & X != 15) -> X == 13
3733             case ICmpInst::ICMP_ULT:        // (X == 13 & X <  15) -> X == 13
3734             case ICmpInst::ICMP_SLT:        // (X == 13 & X <  15) -> X == 13
3735               return ReplaceInstUsesWith(I, LHS);
3736             }
3737           case ICmpInst::ICMP_NE:
3738             switch (RHSCC) {
3739             default: assert(0 && "Unknown integer condition code!");
3740             case ICmpInst::ICMP_ULT:
3741               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3742                 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3743               break;                        // (X != 13 & X u< 15) -> no change
3744             case ICmpInst::ICMP_SLT:
3745               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3746                 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3747               break;                        // (X != 13 & X s< 15) -> no change
3748             case ICmpInst::ICMP_EQ:         // (X != 13 & X == 15) -> X == 15
3749             case ICmpInst::ICMP_UGT:        // (X != 13 & X u> 15) -> X u> 15
3750             case ICmpInst::ICMP_SGT:        // (X != 13 & X s> 15) -> X s> 15
3751               return ReplaceInstUsesWith(I, RHS);
3752             case ICmpInst::ICMP_NE:
3753               if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3754                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3755                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3756                                                       LHSVal->getName()+".off");
3757                 InsertNewInstBefore(Add, I);
3758                 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3759                                     ConstantInt::get(Add->getType(), 1));
3760               }
3761               break;                        // (X != 13 & X != 15) -> no change
3762             }
3763             break;
3764           case ICmpInst::ICMP_ULT:
3765             switch (RHSCC) {
3766             default: assert(0 && "Unknown integer condition code!");
3767             case ICmpInst::ICMP_EQ:         // (X u< 13 & X == 15) -> false
3768             case ICmpInst::ICMP_UGT:        // (X u< 13 & X u> 15) -> false
3769               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3770             case ICmpInst::ICMP_SGT:        // (X u< 13 & X s> 15) -> no change
3771               break;
3772             case ICmpInst::ICMP_NE:         // (X u< 13 & X != 15) -> X u< 13
3773             case ICmpInst::ICMP_ULT:        // (X u< 13 & X u< 15) -> X u< 13
3774               return ReplaceInstUsesWith(I, LHS);
3775             case ICmpInst::ICMP_SLT:        // (X u< 13 & X s< 15) -> no change
3776               break;
3777             }
3778             break;
3779           case ICmpInst::ICMP_SLT:
3780             switch (RHSCC) {
3781             default: assert(0 && "Unknown integer condition code!");
3782             case ICmpInst::ICMP_EQ:         // (X s< 13 & X == 15) -> false
3783             case ICmpInst::ICMP_SGT:        // (X s< 13 & X s> 15) -> false
3784               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3785             case ICmpInst::ICMP_UGT:        // (X s< 13 & X u> 15) -> no change
3786               break;
3787             case ICmpInst::ICMP_NE:         // (X s< 13 & X != 15) -> X < 13
3788             case ICmpInst::ICMP_SLT:        // (X s< 13 & X s< 15) -> X < 13
3789               return ReplaceInstUsesWith(I, LHS);
3790             case ICmpInst::ICMP_ULT:        // (X s< 13 & X u< 15) -> no change
3791               break;
3792             }
3793             break;
3794           case ICmpInst::ICMP_UGT:
3795             switch (RHSCC) {
3796             default: assert(0 && "Unknown integer condition code!");
3797             case ICmpInst::ICMP_EQ:         // (X u> 13 & X == 15) -> X == 15
3798             case ICmpInst::ICMP_UGT:        // (X u> 13 & X u> 15) -> X u> 15
3799               return ReplaceInstUsesWith(I, RHS);
3800             case ICmpInst::ICMP_SGT:        // (X u> 13 & X s> 15) -> no change
3801               break;
3802             case ICmpInst::ICMP_NE:
3803               if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3804                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3805               break;                        // (X u> 13 & X != 15) -> no change
3806             case ICmpInst::ICMP_ULT:        // (X u> 13 & X u< 15) ->(X-14) <u 1
3807               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false, 
3808                                      true, I);
3809             case ICmpInst::ICMP_SLT:        // (X u> 13 & X s< 15) -> no change
3810               break;
3811             }
3812             break;
3813           case ICmpInst::ICMP_SGT:
3814             switch (RHSCC) {
3815             default: assert(0 && "Unknown integer condition code!");
3816             case ICmpInst::ICMP_EQ:         // (X s> 13 & X == 15) -> X == 15
3817             case ICmpInst::ICMP_SGT:        // (X s> 13 & X s> 15) -> X s> 15
3818               return ReplaceInstUsesWith(I, RHS);
3819             case ICmpInst::ICMP_UGT:        // (X s> 13 & X u> 15) -> no change
3820               break;
3821             case ICmpInst::ICMP_NE:
3822               if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3823                 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3824               break;                        // (X s> 13 & X != 15) -> no change
3825             case ICmpInst::ICMP_SLT:        // (X s> 13 & X s< 15) ->(X-14) s< 1
3826               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, 
3827                                      true, I);
3828             case ICmpInst::ICMP_ULT:        // (X s> 13 & X u< 15) -> no change
3829               break;
3830             }
3831             break;
3832           }
3833         }
3834   }
3835
3836   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3837   if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3838     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3839       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3840         const Type *SrcTy = Op0C->getOperand(0)->getType();
3841         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3842             // Only do this if the casts both really cause code to be generated.
3843             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
3844                               I.getType(), TD) &&
3845             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
3846                               I.getType(), TD)) {
3847           Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3848                                                          Op1C->getOperand(0),
3849                                                          I.getName());
3850           InsertNewInstBefore(NewOp, I);
3851           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3852         }
3853       }
3854     
3855   // (X >> Z) & (Y >> Z)  -> (X&Y) >> Z  for all shifts.
3856   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3857     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3858       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
3859           SI0->getOperand(1) == SI1->getOperand(1) &&
3860           (SI0->hasOneUse() || SI1->hasOneUse())) {
3861         Instruction *NewOp =
3862           InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3863                                                         SI1->getOperand(0),
3864                                                         SI0->getName()), I);
3865         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
3866                                       SI1->getOperand(1));
3867       }
3868   }
3869
3870   // (fcmp ord x, c) & (fcmp ord y, c)  -> (fcmp ord x, y)
3871   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3872     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3873       if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3874           RHS->getPredicate() == FCmpInst::FCMP_ORD)
3875         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3876           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3877             // If either of the constants are nans, then the whole thing returns
3878             // false.
3879             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3880               return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3881             return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3882                                 RHS->getOperand(0));
3883           }
3884     }
3885   }
3886
3887   return Changed ? &I : 0;
3888 }
3889
3890 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3891 /// in the result.  If it does, and if the specified byte hasn't been filled in
3892 /// yet, fill it in and return false.
3893 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3894   Instruction *I = dyn_cast<Instruction>(V);
3895   if (I == 0) return true;
3896
3897   // If this is an or instruction, it is an inner node of the bswap.
3898   if (I->getOpcode() == Instruction::Or)
3899     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3900            CollectBSwapParts(I->getOperand(1), ByteValues);
3901   
3902   uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3903   // If this is a shift by a constant int, and it is "24", then its operand
3904   // defines a byte.  We only handle unsigned types here.
3905   if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3906     // Not shifting the entire input by N-1 bytes?
3907     if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3908         8*(ByteValues.size()-1))
3909       return true;
3910     
3911     unsigned DestNo;
3912     if (I->getOpcode() == Instruction::Shl) {
3913       // X << 24 defines the top byte with the lowest of the input bytes.
3914       DestNo = ByteValues.size()-1;
3915     } else {
3916       // X >>u 24 defines the low byte with the highest of the input bytes.
3917       DestNo = 0;
3918     }
3919     
3920     // If the destination byte value is already defined, the values are or'd
3921     // together, which isn't a bswap (unless it's an or of the same bits).
3922     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3923       return true;
3924     ByteValues[DestNo] = I->getOperand(0);
3925     return false;
3926   }
3927   
3928   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3929   // don't have this.
3930   Value *Shift = 0, *ShiftLHS = 0;
3931   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3932   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3933       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3934     return true;
3935   Instruction *SI = cast<Instruction>(Shift);
3936
3937   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3938   if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3939       ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3940     return true;
3941   
3942   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3943   unsigned DestByte;
3944   if (AndAmt->getValue().getActiveBits() > 64)
3945     return true;
3946   uint64_t AndAmtVal = AndAmt->getZExtValue();
3947   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3948     if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3949       break;
3950   // Unknown mask for bswap.
3951   if (DestByte == ByteValues.size()) return true;
3952   
3953   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3954   unsigned SrcByte;
3955   if (SI->getOpcode() == Instruction::Shl)
3956     SrcByte = DestByte - ShiftBytes;
3957   else
3958     SrcByte = DestByte + ShiftBytes;
3959   
3960   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3961   if (SrcByte != ByteValues.size()-DestByte-1)
3962     return true;
3963   
3964   // If the destination byte value is already defined, the values are or'd
3965   // together, which isn't a bswap (unless it's an or of the same bits).
3966   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3967     return true;
3968   ByteValues[DestByte] = SI->getOperand(0);
3969   return false;
3970 }
3971
3972 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3973 /// If so, insert the new bswap intrinsic and return it.
3974 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3975   const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3976   if (!ITy || ITy->getBitWidth() % 16) 
3977     return 0;   // Can only bswap pairs of bytes.  Can't do vectors.
3978   
3979   /// ByteValues - For each byte of the result, we keep track of which value
3980   /// defines each byte.
3981   SmallVector<Value*, 8> ByteValues;
3982   ByteValues.resize(ITy->getBitWidth()/8);
3983     
3984   // Try to find all the pieces corresponding to the bswap.
3985   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3986       CollectBSwapParts(I.getOperand(1), ByteValues))
3987     return 0;
3988   
3989   // Check to see if all of the bytes come from the same value.
3990   Value *V = ByteValues[0];
3991   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3992   
3993   // Check to make sure that all of the bytes come from the same value.
3994   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3995     if (ByteValues[i] != V)
3996       return 0;
3997   const Type *Tys[] = { ITy };
3998   Module *M = I.getParent()->getParent()->getParent();
3999   Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4000   return CallInst::Create(F, V);
4001 }
4002
4003
4004 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4005   bool Changed = SimplifyCommutative(I);
4006   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4007
4008   if (isa<UndefValue>(Op1))                       // X | undef -> -1
4009     return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4010
4011   // or X, X = X
4012   if (Op0 == Op1)
4013     return ReplaceInstUsesWith(I, Op0);
4014
4015   // See if we can simplify any instructions used by the instruction whose sole 
4016   // purpose is to compute bits we don't care about.
4017   if (!isa<VectorType>(I.getType())) {
4018     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4019     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4020     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4021                              KnownZero, KnownOne))
4022       return &I;
4023   } else if (isa<ConstantAggregateZero>(Op1)) {
4024     return ReplaceInstUsesWith(I, Op0);  // X | <0,0> -> X
4025   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4026     if (CP->isAllOnesValue())            // X | <-1,-1> -> <-1,-1>
4027       return ReplaceInstUsesWith(I, I.getOperand(1));
4028   }
4029     
4030
4031   
4032   // or X, -1 == -1
4033   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4034     ConstantInt *C1 = 0; Value *X = 0;
4035     // (X & C1) | C2 --> (X | C2) & (C1|C2)
4036     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4037       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4038       InsertNewInstBefore(Or, I);
4039       Or->takeName(Op0);
4040       return BinaryOperator::CreateAnd(Or, 
4041                ConstantInt::get(RHS->getValue() | C1->getValue()));
4042     }
4043
4044     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4045     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4046       Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4047       InsertNewInstBefore(Or, I);
4048       Or->takeName(Op0);
4049       return BinaryOperator::CreateXor(Or,
4050                  ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4051     }
4052
4053     // Try to fold constant and into select arguments.
4054     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4055       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4056         return R;
4057     if (isa<PHINode>(Op0))
4058       if (Instruction *NV = FoldOpIntoPhi(I))
4059         return NV;
4060   }
4061
4062   Value *A = 0, *B = 0;
4063   ConstantInt *C1 = 0, *C2 = 0;
4064
4065   if (match(Op0, m_And(m_Value(A), m_Value(B))))
4066     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
4067       return ReplaceInstUsesWith(I, Op1);
4068   if (match(Op1, m_And(m_Value(A), m_Value(B))))
4069     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
4070       return ReplaceInstUsesWith(I, Op0);
4071
4072   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
4073   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
4074   if (match(Op0, m_Or(m_Value(), m_Value())) ||
4075       match(Op1, m_Or(m_Value(), m_Value())) ||
4076       (match(Op0, m_Shift(m_Value(), m_Value())) &&
4077        match(Op1, m_Shift(m_Value(), m_Value())))) {
4078     if (Instruction *BSwap = MatchBSwap(I))
4079       return BSwap;
4080   }
4081   
4082   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4083   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4084       MaskedValueIsZero(Op1, C1->getValue())) {
4085     Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4086     InsertNewInstBefore(NOr, I);
4087     NOr->takeName(Op0);
4088     return BinaryOperator::CreateXor(NOr, C1);
4089   }
4090
4091   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4092   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4093       MaskedValueIsZero(Op0, C1->getValue())) {
4094     Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4095     InsertNewInstBefore(NOr, I);
4096     NOr->takeName(Op0);
4097     return BinaryOperator::CreateXor(NOr, C1);
4098   }
4099
4100   // (A & C)|(B & D)
4101   Value *C = 0, *D = 0;
4102   if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4103       match(Op1, m_And(m_Value(B), m_Value(D)))) {
4104     Value *V1 = 0, *V2 = 0, *V3 = 0;
4105     C1 = dyn_cast<ConstantInt>(C);
4106     C2 = dyn_cast<ConstantInt>(D);
4107     if (C1 && C2) {  // (A & C1)|(B & C2)
4108       // If we have: ((V + N) & C1) | (V & C2)
4109       // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4110       // replace with V+N.
4111       if (C1->getValue() == ~C2->getValue()) {
4112         if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4113             match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4114           // Add commutes, try both ways.
4115           if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4116             return ReplaceInstUsesWith(I, A);
4117           if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4118             return ReplaceInstUsesWith(I, A);
4119         }
4120         // Or commutes, try both ways.
4121         if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4122             match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4123           // Add commutes, try both ways.
4124           if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4125             return ReplaceInstUsesWith(I, B);
4126           if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4127             return ReplaceInstUsesWith(I, B);
4128         }
4129       }
4130       V1 = 0; V2 = 0; V3 = 0;
4131     }
4132     
4133     // Check to see if we have any common things being and'ed.  If so, find the
4134     // terms for V1 & (V2|V3).
4135     if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4136       if (A == B)      // (A & C)|(A & D) == A & (C|D)
4137         V1 = A, V2 = C, V3 = D;
4138       else if (A == D) // (A & C)|(B & A) == A & (B|C)
4139         V1 = A, V2 = B, V3 = C;
4140       else if (C == B) // (A & C)|(C & D) == C & (A|D)
4141         V1 = C, V2 = A, V3 = D;
4142       else if (C == D) // (A & C)|(B & C) == C & (A|B)
4143         V1 = C, V2 = A, V3 = B;
4144       
4145       if (V1) {
4146         Value *Or =
4147           InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4148         return BinaryOperator::CreateAnd(V1, Or);
4149       }
4150     }
4151   }
4152   
4153   // (X >> Z) | (Y >> Z)  -> (X|Y) >> Z  for all shifts.
4154   if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4155     if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4156       if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() && 
4157           SI0->getOperand(1) == SI1->getOperand(1) &&
4158           (SI0->hasOneUse() || SI1->hasOneUse())) {
4159         Instruction *NewOp =
4160         InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4161                                                      SI1->getOperand(0),
4162                                                      SI0->getName()), I);
4163         return BinaryOperator::Create(SI1->getOpcode(), NewOp, 
4164                                       SI1->getOperand(1));
4165       }
4166   }
4167
4168   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
4169     if (A == Op1)   // ~A | A == -1
4170       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4171   } else {
4172     A = 0;
4173   }
4174   // Note, A is still live here!
4175   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
4176     if (Op0 == B)
4177       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4178
4179     // (~A | ~B) == (~(A & B)) - De Morgan's Law
4180     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4181       Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4182                                               I.getName()+".demorgan"), I);
4183       return BinaryOperator::CreateNot(And);
4184     }
4185   }
4186
4187   // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4188   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4189     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4190       return R;
4191
4192     Value *LHSVal, *RHSVal;
4193     ConstantInt *LHSCst, *RHSCst;
4194     ICmpInst::Predicate LHSCC, RHSCC;
4195     if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4196       if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4197         if (LHSVal == RHSVal &&    // Found (X icmp C1) | (X icmp C2)
4198             // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4199             LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4200             RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4201             LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4202             RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4203             // We can't fold (ugt x, C) | (sgt x, C2).
4204             PredicatesFoldable(LHSCC, RHSCC)) {
4205           // Ensure that the larger constant is on the RHS.
4206           ICmpInst *LHS = cast<ICmpInst>(Op0);
4207           bool NeedsSwap;
4208           if (ICmpInst::isSignedPredicate(LHSCC))
4209             NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4210           else
4211             NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4212             
4213           if (NeedsSwap) {
4214             std::swap(LHS, RHS);
4215             std::swap(LHSCst, RHSCst);
4216             std::swap(LHSCC, RHSCC);
4217           }
4218
4219           // At this point, we know we have have two icmp instructions
4220           // comparing a value against two constants and or'ing the result
4221           // together.  Because of the above check, we know that we only have
4222           // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4223           // FoldICmpLogical check above), that the two constants are not
4224           // equal.
4225           assert(LHSCst != RHSCst && "Compares not folded above?");
4226
4227           switch (LHSCC) {
4228           default: assert(0 && "Unknown integer condition code!");
4229           case ICmpInst::ICMP_EQ:
4230             switch (RHSCC) {
4231             default: assert(0 && "Unknown integer condition code!");
4232             case ICmpInst::ICMP_EQ:
4233               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4234                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4235                 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4236                                                       LHSVal->getName()+".off");
4237                 InsertNewInstBefore(Add, I);
4238                 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4239                 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4240               }
4241               break;                         // (X == 13 | X == 15) -> no change
4242             case ICmpInst::ICMP_UGT:         // (X == 13 | X u> 14) -> no change
4243             case ICmpInst::ICMP_SGT:         // (X == 13 | X s> 14) -> no change
4244               break;
4245             case ICmpInst::ICMP_NE:          // (X == 13 | X != 15) -> X != 15
4246             case ICmpInst::ICMP_ULT:         // (X == 13 | X u< 15) -> X u< 15
4247             case ICmpInst::ICMP_SLT:         // (X == 13 | X s< 15) -> X s< 15
4248               return ReplaceInstUsesWith(I, RHS);
4249             }
4250             break;
4251           case ICmpInst::ICMP_NE:
4252             switch (RHSCC) {
4253             default: assert(0 && "Unknown integer condition code!");
4254             case ICmpInst::ICMP_EQ:          // (X != 13 | X == 15) -> X != 13
4255             case ICmpInst::ICMP_UGT:         // (X != 13 | X u> 15) -> X != 13
4256             case ICmpInst::ICMP_SGT:         // (X != 13 | X s> 15) -> X != 13
4257               return ReplaceInstUsesWith(I, LHS);
4258             case ICmpInst::ICMP_NE:          // (X != 13 | X != 15) -> true
4259             case ICmpInst::ICMP_ULT:         // (X != 13 | X u< 15) -> true
4260             case ICmpInst::ICMP_SLT:         // (X != 13 | X s< 15) -> true
4261               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4262             }
4263             break;
4264           case ICmpInst::ICMP_ULT:
4265             switch (RHSCC) {
4266             default: assert(0 && "Unknown integer condition code!");
4267             case ICmpInst::ICMP_EQ:         // (X u< 13 | X == 14) -> no change
4268               break;
4269             case ICmpInst::ICMP_UGT:        // (X u< 13 | X u> 15) ->(X-13) u> 2
4270               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4271               // this can cause overflow.
4272               if (RHSCst->isMaxValue(false))
4273                 return ReplaceInstUsesWith(I, LHS);
4274               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, 
4275                                      false, I);
4276             case ICmpInst::ICMP_SGT:        // (X u< 13 | X s> 15) -> no change
4277               break;
4278             case ICmpInst::ICMP_NE:         // (X u< 13 | X != 15) -> X != 15
4279             case ICmpInst::ICMP_ULT:        // (X u< 13 | X u< 15) -> X u< 15
4280               return ReplaceInstUsesWith(I, RHS);
4281             case ICmpInst::ICMP_SLT:        // (X u< 13 | X s< 15) -> no change
4282               break;
4283             }
4284             break;
4285           case ICmpInst::ICMP_SLT:
4286             switch (RHSCC) {
4287             default: assert(0 && "Unknown integer condition code!");
4288             case ICmpInst::ICMP_EQ:         // (X s< 13 | X == 14) -> no change
4289               break;
4290             case ICmpInst::ICMP_SGT:        // (X s< 13 | X s> 15) ->(X-13) s> 2
4291               // If RHSCst is [us]MAXINT, it is always false.  Not handling
4292               // this can cause overflow.
4293               if (RHSCst->isMaxValue(true))
4294                 return ReplaceInstUsesWith(I, LHS);
4295               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true, 
4296                                      false, I);
4297             case ICmpInst::ICMP_UGT:        // (X s< 13 | X u> 15) -> no change
4298               break;
4299             case ICmpInst::ICMP_NE:         // (X s< 13 | X != 15) -> X != 15
4300             case ICmpInst::ICMP_SLT:        // (X s< 13 | X s< 15) -> X s< 15
4301               return ReplaceInstUsesWith(I, RHS);
4302             case ICmpInst::ICMP_ULT:        // (X s< 13 | X u< 15) -> no change
4303               break;
4304             }
4305             break;
4306           case ICmpInst::ICMP_UGT:
4307             switch (RHSCC) {
4308             default: assert(0 && "Unknown integer condition code!");
4309             case ICmpInst::ICMP_EQ:         // (X u> 13 | X == 15) -> X u> 13
4310             case ICmpInst::ICMP_UGT:        // (X u> 13 | X u> 15) -> X u> 13
4311               return ReplaceInstUsesWith(I, LHS);
4312             case ICmpInst::ICMP_SGT:        // (X u> 13 | X s> 15) -> no change
4313               break;
4314             case ICmpInst::ICMP_NE:         // (X u> 13 | X != 15) -> true
4315             case ICmpInst::ICMP_ULT:        // (X u> 13 | X u< 15) -> true
4316               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4317             case ICmpInst::ICMP_SLT:        // (X u> 13 | X s< 15) -> no change
4318               break;
4319             }
4320             break;
4321           case ICmpInst::ICMP_SGT:
4322             switch (RHSCC) {
4323             default: assert(0 && "Unknown integer condition code!");
4324             case ICmpInst::ICMP_EQ:         // (X s> 13 | X == 15) -> X > 13
4325             case ICmpInst::ICMP_SGT:        // (X s> 13 | X s> 15) -> X > 13
4326               return ReplaceInstUsesWith(I, LHS);
4327             case ICmpInst::ICMP_UGT:        // (X s> 13 | X u> 15) -> no change
4328               break;
4329             case ICmpInst::ICMP_NE:         // (X s> 13 | X != 15) -> true
4330             case ICmpInst::ICMP_SLT:        // (X s> 13 | X s< 15) -> true
4331               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4332             case ICmpInst::ICMP_ULT:        // (X s> 13 | X u< 15) -> no change
4333               break;
4334             }
4335             break;
4336           }
4337         }
4338   }
4339     
4340   // fold (or (cast A), (cast B)) -> (cast (or A, B))
4341   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4342     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4343       if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4344         if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4345             !isa<ICmpInst>(Op1C->getOperand(0))) {
4346           const Type *SrcTy = Op0C->getOperand(0)->getType();
4347           if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4348               // Only do this if the casts both really cause code to be
4349               // generated.
4350               ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4351                                 I.getType(), TD) &&
4352               ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4353                                 I.getType(), TD)) {
4354             Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4355                                                           Op1C->getOperand(0),
4356                                                           I.getName());
4357             InsertNewInstBefore(NewOp, I);
4358             return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4359           }
4360         }
4361       }
4362   }
4363   
4364     
4365   // (fcmp uno x, c) | (fcmp uno y, c)  -> (fcmp uno x, y)
4366   if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4367     if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4368       if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4369           RHS->getPredicate() == FCmpInst::FCMP_UNO && 
4370           LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4371         if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4372           if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4373             // If either of the constants are nans, then the whole thing returns
4374             // true.
4375             if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4376               return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4377             
4378             // Otherwise, no need to compare the two constants, compare the
4379             // rest.
4380             return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4381                                 RHS->getOperand(0));
4382           }
4383     }
4384   }
4385
4386   return Changed ? &I : 0;
4387 }
4388
4389 namespace {
4390
4391 // XorSelf - Implements: X ^ X --> 0
4392 struct XorSelf {
4393   Value *RHS;
4394   XorSelf(Value *rhs) : RHS(rhs) {}
4395   bool shouldApply(Value *LHS) const { return LHS == RHS; }
4396   Instruction *apply(BinaryOperator &Xor) const {
4397     return &Xor;
4398   }
4399 };
4400
4401 }
4402
4403 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4404   bool Changed = SimplifyCommutative(I);
4405   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4406
4407   if (isa<UndefValue>(Op1)) {
4408     if (isa<UndefValue>(Op0))
4409       // Handle undef ^ undef -> 0 special case. This is a common
4410       // idiom (misuse).
4411       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4412     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
4413   }
4414
4415   // xor X, X = 0, even if X is nested in a sequence of Xor's.
4416   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4417     assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4418     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4419   }
4420   
4421   // See if we can simplify any instructions used by the instruction whose sole 
4422   // purpose is to compute bits we don't care about.
4423   if (!isa<VectorType>(I.getType())) {
4424     uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4425     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4426     if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4427                              KnownZero, KnownOne))
4428       return &I;
4429   } else if (isa<ConstantAggregateZero>(Op1)) {
4430     return ReplaceInstUsesWith(I, Op0);  // X ^ <0,0> -> X
4431   }
4432
4433   // Is this a ~ operation?
4434   if (Value *NotOp = dyn_castNotVal(&I)) {
4435     // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4436     // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4437     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4438       if (Op0I->getOpcode() == Instruction::And || 
4439           Op0I->getOpcode() == Instruction::Or) {
4440         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4441         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4442           Instruction *NotY =
4443             BinaryOperator::CreateNot(Op0I->getOperand(1),
4444                                       Op0I->getOperand(1)->getName()+".not");
4445           InsertNewInstBefore(NotY, I);
4446           if (Op0I->getOpcode() == Instruction::And)
4447             return BinaryOperator::CreateOr(Op0NotVal, NotY);
4448           else
4449             return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4450         }
4451       }
4452     }
4453   }
4454   
4455   
4456   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4457     // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4458     if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4459       if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4460         return new ICmpInst(ICI->getInversePredicate(),
4461                             ICI->getOperand(0), ICI->getOperand(1));
4462
4463       if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4464         return new FCmpInst(FCI->getInversePredicate(),
4465                             FCI->getOperand(0), FCI->getOperand(1));
4466     }
4467
4468     // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4469     if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4470       if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4471         if (CI->hasOneUse() && Op0C->hasOneUse()) {
4472           Instruction::CastOps Opcode = Op0C->getOpcode();
4473           if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4474             if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4475                                              Op0C->getDestTy())) {
4476               Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4477                                      CI->getOpcode(), CI->getInversePredicate(),
4478                                      CI->getOperand(0), CI->getOperand(1)), I);
4479               NewCI->takeName(CI);
4480               return CastInst::Create(Opcode, NewCI, Op0C->getType());
4481             }
4482           }
4483         }
4484       }
4485     }
4486
4487     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4488       // ~(c-X) == X-c-1 == X+(-c-1)
4489       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4490         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4491           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4492           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4493                                               ConstantInt::get(I.getType(), 1));
4494           return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4495         }
4496           
4497       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4498         if (Op0I->getOpcode() == Instruction::Add) {
4499           // ~(X-c) --> (-c-1)-X
4500           if (RHS->isAllOnesValue()) {
4501             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4502             return BinaryOperator::CreateSub(
4503                            ConstantExpr::getSub(NegOp0CI,
4504                                              ConstantInt::get(I.getType(), 1)),
4505                                           Op0I->getOperand(0));
4506           } else if (RHS->getValue().isSignBit()) {
4507             // (X + C) ^ signbit -> (X + C + signbit)
4508             Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4509             return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4510
4511           }
4512         } else if (Op0I->getOpcode() == Instruction::Or) {
4513           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4514           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4515             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4516             // Anything in both C1 and C2 is known to be zero, remove it from
4517             // NewRHS.
4518             Constant *CommonBits = And(Op0CI, RHS);
4519             NewRHS = ConstantExpr::getAnd(NewRHS, 
4520                                           ConstantExpr::getNot(CommonBits));
4521             AddToWorkList(Op0I);
4522             I.setOperand(0, Op0I->getOperand(0));
4523             I.setOperand(1, NewRHS);
4524             return &I;
4525           }
4526         }
4527       }
4528     }
4529
4530     // Try to fold constant and into select arguments.
4531     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4532       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4533         return R;
4534     if (isa<PHINode>(Op0))
4535       if (Instruction *NV = FoldOpIntoPhi(I))
4536         return NV;
4537   }
4538
4539   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
4540     if (X == Op1)
4541       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4542
4543   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
4544     if (X == Op0)
4545       return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4546
4547   
4548   BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4549   if (Op1I) {
4550     Value *A, *B;
4551     if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4552       if (A == Op0) {              // B^(B|A) == (A|B)^B
4553         Op1I->swapOperands();
4554         I.swapOperands();
4555         std::swap(Op0, Op1);
4556       } else if (B == Op0) {       // B^(A|B) == (A|B)^B
4557         I.swapOperands();     // Simplified below.
4558         std::swap(Op0, Op1);
4559       }
4560     } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4561       if (Op0 == A)                                          // A^(A^B) == B
4562         return ReplaceInstUsesWith(I, B);
4563       else if (Op0 == B)                                     // A^(B^A) == B
4564         return ReplaceInstUsesWith(I, A);
4565     } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4566       if (A == Op0) {                                      // A^(A&B) -> A^(B&A)
4567         Op1I->swapOperands();
4568         std::swap(A, B);
4569       }
4570       if (B == Op0) {                                      // A^(B&A) -> (B&A)^A
4571         I.swapOperands();     // Simplified below.
4572         std::swap(Op0, Op1);
4573       }
4574     }
4575   }
4576   
4577   BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4578   if (Op0I) {
4579     Value *A, *B;
4580     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4581       if (A == Op1)                                  // (B|A)^B == (A|B)^B
4582         std::swap(A, B);
4583       if (B == Op1) {                                // (A|B)^B == A & ~B
4584         Instruction *NotB =
4585           InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4586         return BinaryOperator::CreateAnd(A, NotB);
4587       }
4588     } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4589       if (Op1 == A)                                          // (A^B)^A == B
4590         return ReplaceInstUsesWith(I, B);
4591       else if (Op1 == B)                                     // (B^A)^A == B
4592         return ReplaceInstUsesWith(I, A);
4593     } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4594       if (A == Op1)                                        // (A&B)^A -> (B&A)^A
4595         std::swap(A, B);
4596       if (B == Op1 &&                                      // (B&A)^A == ~B & A
4597           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
4598         Instruction *N =
4599           InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4600         return BinaryOperator::CreateAnd(N, Op1);
4601       }
4602     }
4603   }
4604   
4605   // (X >> Z) ^ (Y >> Z)  -> (X^Y) >> Z  for all shifts.
4606   if (Op0I && Op1I && Op0I->isShift() && 
4607       Op0I->getOpcode() == Op1I->getOpcode() && 
4608       Op0I->getOperand(1) == Op1I->getOperand(1) &&
4609       (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4610     Instruction *NewOp =
4611       InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4612                                                     Op1I->getOperand(0),
4613                                                     Op0I->getName()), I);
4614     return BinaryOperator::Create(Op1I->getOpcode(), NewOp, 
4615                                   Op1I->getOperand(1));
4616   }
4617     
4618   if (Op0I && Op1I) {
4619     Value *A, *B, *C, *D;
4620     // (A & B)^(A | B) -> A ^ B
4621     if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4622         match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4623       if ((A == C && B == D) || (A == D && B == C)) 
4624         return BinaryOperator::CreateXor(A, B);
4625     }
4626     // (A | B)^(A & B) -> A ^ B
4627     if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4628         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4629       if ((A == C && B == D) || (A == D && B == C)) 
4630         return BinaryOperator::CreateXor(A, B);
4631     }
4632     
4633     // (A & B)^(C & D)
4634     if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4635         match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4636         match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4637       // (X & Y)^(X & Y) -> (Y^Z) & X
4638       Value *X = 0, *Y = 0, *Z = 0;
4639       if (A == C)
4640         X = A, Y = B, Z = D;
4641       else if (A == D)
4642         X = A, Y = B, Z = C;
4643       else if (B == C)
4644         X = B, Y = A, Z = D;
4645       else if (B == D)
4646         X = B, Y = A, Z = C;
4647       
4648       if (X) {
4649         Instruction *NewOp =
4650         InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4651         return BinaryOperator::CreateAnd(NewOp, X);
4652       }
4653     }
4654   }
4655     
4656   // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4657   if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4658     if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4659       return R;
4660
4661   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4662   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4663     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4664       if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4665         const Type *SrcTy = Op0C->getOperand(0)->getType();
4666         if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4667             // Only do this if the casts both really cause code to be generated.
4668             ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0), 
4669                               I.getType(), TD) &&
4670             ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0), 
4671                               I.getType(), TD)) {
4672           Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4673                                                          Op1C->getOperand(0),
4674                                                          I.getName());
4675           InsertNewInstBefore(NewOp, I);
4676           return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4677         }
4678       }
4679   }
4680
4681   return Changed ? &I : 0;
4682 }
4683
4684 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4685 /// overflowed for this type.
4686 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4687                             ConstantInt *In2, bool IsSigned = false) {
4688   Result = cast<ConstantInt>(Add(In1, In2));
4689
4690   if (IsSigned)
4691     if (In2->getValue().isNegative())
4692       return Result->getValue().sgt(In1->getValue());
4693     else
4694       return Result->getValue().slt(In1->getValue());
4695   else
4696     return Result->getValue().ult(In1->getValue());
4697 }
4698
4699 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
4700 /// overflowed for this type.
4701 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4702                             ConstantInt *In2, bool IsSigned = false) {
4703   Result = cast<ConstantInt>(Subtract(In1, In2));
4704
4705   if (IsSigned)
4706     if (In2->getValue().isNegative())
4707       return Result->getValue().slt(In1->getValue());
4708     else
4709       return Result->getValue().sgt(In1->getValue());
4710   else
4711     return Result->getValue().ugt(In1->getValue());
4712 }
4713
4714 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4715 /// code necessary to compute the offset from the base pointer (without adding
4716 /// in the base pointer).  Return the result as a signed integer of intptr size.
4717 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4718   TargetData &TD = IC.getTargetData();
4719   gep_type_iterator GTI = gep_type_begin(GEP);
4720   const Type *IntPtrTy = TD.getIntPtrType();
4721   Value *Result = Constant::getNullValue(IntPtrTy);
4722
4723   // Build a mask for high order bits.
4724   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4725   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4726
4727   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4728        ++i, ++GTI) {
4729     Value *Op = *i;
4730     uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4731     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4732       if (OpC->isZero()) continue;
4733       
4734       // Handle a struct index, which adds its field offset to the pointer.
4735       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4736         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4737         
4738         if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4739           Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4740         else
4741           Result = IC.InsertNewInstBefore(
4742                    BinaryOperator::CreateAdd(Result,
4743                                              ConstantInt::get(IntPtrTy, Size),
4744                                              GEP->getName()+".offs"), I);
4745         continue;
4746       }
4747       
4748       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4749       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4750       Scale = ConstantExpr::getMul(OC, Scale);
4751       if (Constant *RC = dyn_cast<Constant>(Result))
4752         Result = ConstantExpr::getAdd(RC, Scale);
4753       else {
4754         // Emit an add instruction.
4755         Result = IC.InsertNewInstBefore(
4756            BinaryOperator::CreateAdd(Result, Scale,
4757                                      GEP->getName()+".offs"), I);
4758       }
4759       continue;
4760     }
4761     // Convert to correct type.
4762     if (Op->getType() != IntPtrTy) {
4763       if (Constant *OpC = dyn_cast<Constant>(Op))
4764         Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4765       else
4766         Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4767                                                  Op->getName()+".c"), I);
4768     }
4769     if (Size != 1) {
4770       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4771       if (Constant *OpC = dyn_cast<Constant>(Op))
4772         Op = ConstantExpr::getMul(OpC, Scale);
4773       else    // We'll let instcombine(mul) convert this to a shl if possible.
4774         Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4775                                                   GEP->getName()+".idx"), I);
4776     }
4777
4778     // Emit an add instruction.
4779     if (isa<Constant>(Op) && isa<Constant>(Result))
4780       Result = ConstantExpr::getAdd(cast<Constant>(Op),
4781                                     cast<Constant>(Result));
4782     else
4783       Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4784                                                   GEP->getName()+".offs"), I);
4785   }
4786   return Result;
4787 }
4788
4789
4790 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4791 /// the *offset* implied by GEP to zero.  For example, if we have &A[i], we want
4792 /// to return 'i' for "icmp ne i, 0".  Note that, in general, indices can be
4793 /// complex, and scales are involved.  The above expression would also be legal
4794 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).  This
4795 /// later form is less amenable to optimization though, and we are allowed to
4796 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4797 ///
4798 /// If we can't emit an optimized form for this expression, this returns null.
4799 /// 
4800 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4801                                           InstCombiner &IC) {
4802   TargetData &TD = IC.getTargetData();
4803   gep_type_iterator GTI = gep_type_begin(GEP);
4804
4805   // Check to see if this gep only has a single variable index.  If so, and if
4806   // any constant indices are a multiple of its scale, then we can compute this
4807   // in terms of the scale of the variable index.  For example, if the GEP
4808   // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4809   // because the expression will cross zero at the same point.
4810   unsigned i, e = GEP->getNumOperands();
4811   int64_t Offset = 0;
4812   for (i = 1; i != e; ++i, ++GTI) {
4813     if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4814       // Compute the aggregate offset of constant indices.
4815       if (CI->isZero()) continue;
4816
4817       // Handle a struct index, which adds its field offset to the pointer.
4818       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4819         Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4820       } else {
4821         uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4822         Offset += Size*CI->getSExtValue();
4823       }
4824     } else {
4825       // Found our variable index.
4826       break;
4827     }
4828   }
4829   
4830   // If there are no variable indices, we must have a constant offset, just
4831   // evaluate it the general way.
4832   if (i == e) return 0;
4833   
4834   Value *VariableIdx = GEP->getOperand(i);
4835   // Determine the scale factor of the variable element.  For example, this is
4836   // 4 if the variable index is into an array of i32.
4837   uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4838   
4839   // Verify that there are no other variable indices.  If so, emit the hard way.
4840   for (++i, ++GTI; i != e; ++i, ++GTI) {
4841     ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4842     if (!CI) return 0;
4843    
4844     // Compute the aggregate offset of constant indices.
4845     if (CI->isZero()) continue;
4846     
4847     // Handle a struct index, which adds its field offset to the pointer.
4848     if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4849       Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4850     } else {
4851       uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4852       Offset += Size*CI->getSExtValue();
4853     }
4854   }
4855   
4856   // Okay, we know we have a single variable index, which must be a
4857   // pointer/array/vector index.  If there is no offset, life is simple, return
4858   // the index.
4859   unsigned IntPtrWidth = TD.getPointerSizeInBits();
4860   if (Offset == 0) {
4861     // Cast to intptrty in case a truncation occurs.  If an extension is needed,
4862     // we don't need to bother extending: the extension won't affect where the
4863     // computation crosses zero.
4864     if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4865       VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4866                                   VariableIdx->getNameStart(), &I);
4867     return VariableIdx;
4868   }
4869   
4870   // Otherwise, there is an index.  The computation we will do will be modulo
4871   // the pointer size, so get it.
4872   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4873   
4874   Offset &= PtrSizeMask;
4875   VariableScale &= PtrSizeMask;
4876
4877   // To do this transformation, any constant index must be a multiple of the
4878   // variable scale factor.  For example, we can evaluate "12 + 4*i" as "3 + i",
4879   // but we can't evaluate "10 + 3*i" in terms of i.  Check that the offset is a
4880   // multiple of the variable scale.
4881   int64_t NewOffs = Offset / (int64_t)VariableScale;
4882   if (Offset != NewOffs*(int64_t)VariableScale)
4883     return 0;
4884
4885   // Okay, we can do this evaluation.  Start by converting the index to intptr.
4886   const Type *IntPtrTy = TD.getIntPtrType();
4887   if (VariableIdx->getType() != IntPtrTy)
4888     VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4889                                               true /*SExt*/, 
4890                                               VariableIdx->getNameStart(), &I);
4891   Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4892   return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4893 }
4894
4895
4896 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4897 /// else.  At this point we know that the GEP is on the LHS of the comparison.
4898 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4899                                        ICmpInst::Predicate Cond,
4900                                        Instruction &I) {
4901   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4902
4903   // Look through bitcasts.
4904   if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4905     RHS = BCI->getOperand(0);
4906
4907   Value *PtrBase = GEPLHS->getOperand(0);
4908   if (PtrBase == RHS) {
4909     // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
4910     // This transformation (ignoring the base and scales) is valid because we
4911     // know pointers can't overflow.  See if we can output an optimized form.
4912     Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4913     
4914     // If not, synthesize the offset the hard way.
4915     if (Offset == 0)
4916       Offset = EmitGEPOffset(GEPLHS, I, *this);
4917     return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4918                         Constant::getNullValue(Offset->getType()));
4919   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4920     // If the base pointers are different, but the indices are the same, just
4921     // compare the base pointer.
4922     if (PtrBase != GEPRHS->getOperand(0)) {
4923       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4924       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4925                         GEPRHS->getOperand(0)->getType();
4926       if (IndicesTheSame)
4927         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4928           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4929             IndicesTheSame = false;
4930             break;
4931           }
4932
4933       // If all indices are the same, just compare the base pointers.
4934       if (IndicesTheSame)
4935         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), 
4936                             GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4937
4938       // Otherwise, the base pointers are different and the indices are
4939       // different, bail out.
4940       return 0;
4941     }
4942
4943     // If one of the GEPs has all zero indices, recurse.
4944     bool AllZeros = true;
4945     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4946       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4947           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4948         AllZeros = false;
4949         break;
4950       }
4951     if (AllZeros)
4952       return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4953                           ICmpInst::getSwappedPredicate(Cond), I);
4954
4955     // If the other GEP has all zero indices, recurse.
4956     AllZeros = true;
4957     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4958       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4959           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4960         AllZeros = false;
4961         break;
4962       }
4963     if (AllZeros)
4964       return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4965
4966     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4967       // If the GEPs only differ by one index, compare it.
4968       unsigned NumDifferences = 0;  // Keep track of # differences.
4969       unsigned DiffOperand = 0;     // The operand that differs.
4970       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4971         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4972           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4973                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4974             // Irreconcilable differences.
4975             NumDifferences = 2;
4976             break;
4977           } else {
4978             if (NumDifferences++) break;
4979             DiffOperand = i;
4980           }
4981         }
4982
4983       if (NumDifferences == 0)   // SAME GEP?
4984         return ReplaceInstUsesWith(I, // No comparison is needed here.
4985                                    ConstantInt::get(Type::Int1Ty,
4986                                              ICmpInst::isTrueWhenEqual(Cond)));
4987
4988       else if (NumDifferences == 1) {
4989         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4990         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4991         // Make sure we do a signed comparison here.
4992         return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4993       }
4994     }
4995
4996     // Only lower this if the icmp is the only user of the GEP or if we expect
4997     // the result to fold to a constant!
4998     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4999         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5000       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
5001       Value *L = EmitGEPOffset(GEPLHS, I, *this);
5002       Value *R = EmitGEPOffset(GEPRHS, I, *this);
5003       return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5004     }
5005   }
5006   return 0;
5007 }
5008
5009 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5010 ///
5011 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5012                                                 Instruction *LHSI,
5013                                                 Constant *RHSC) {
5014   if (!isa<ConstantFP>(RHSC)) return 0;
5015   const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5016   
5017   // Get the width of the mantissa.  We don't want to hack on conversions that
5018   // might lose information from the integer, e.g. "i64 -> float"
5019   int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5020   if (MantissaWidth == -1) return 0;  // Unknown.
5021   
5022   // Check to see that the input is converted from an integer type that is small
5023   // enough that preserves all bits.  TODO: check here for "known" sign bits.
5024   // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5025   unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5026   
5027   // If this is a uitofp instruction, we need an extra bit to hold the sign.
5028   if (isa<UIToFPInst>(LHSI))
5029     ++InputSize;
5030   
5031   // If the conversion would lose info, don't hack on this.
5032   if ((int)InputSize > MantissaWidth)
5033     return 0;
5034   
5035   // Otherwise, we can potentially simplify the comparison.  We know that it
5036   // will always come through as an integer value and we know the constant is
5037   // not a NAN (it would have been previously simplified).
5038   assert(!RHS.isNaN() && "NaN comparison not already folded!");
5039   
5040   ICmpInst::Predicate Pred;
5041   switch (I.getPredicate()) {
5042   default: assert(0 && "Unexpected predicate!");
5043   case FCmpInst::FCMP_UEQ:
5044   case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5045   case FCmpInst::FCMP_UGT:
5046   case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5047   case FCmpInst::FCMP_UGE:
5048   case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5049   case FCmpInst::FCMP_ULT:
5050   case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5051   case FCmpInst::FCMP_ULE:
5052   case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5053   case FCmpInst::FCMP_UNE:
5054   case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5055   case FCmpInst::FCMP_ORD:
5056     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5057   case FCmpInst::FCMP_UNO:
5058     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5059   }
5060   
5061   const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5062   
5063   // Now we know that the APFloat is a normal number, zero or inf.
5064   
5065   // See if the FP constant is too large for the integer.  For example,
5066   // comparing an i8 to 300.0.
5067   unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5068   
5069   // If the RHS value is > SignedMax, fold the comparison.  This handles +INF
5070   // and large values. 
5071   APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5072   SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5073                         APFloat::rmNearestTiesToEven);
5074   if (SMax.compare(RHS) == APFloat::cmpLessThan) {  // smax < 13123.0
5075     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5076         Pred == ICmpInst::ICMP_SLE)
5077       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5078     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5079   }
5080   
5081   // See if the RHS value is < SignedMin.
5082   APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5083   SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5084                         APFloat::rmNearestTiesToEven);
5085   if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5086     if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5087         Pred == ICmpInst::ICMP_SGE)
5088       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5089     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5090   }
5091
5092   // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5093   // it may still be fractional.  See if it is fractional by casting the FP
5094   // value to the integer value and back, checking for equality.  Don't do this
5095   // for zero, because -0.0 is not fractional.
5096   Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5097   if (!RHS.isZero() &&
5098       ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5099     // If we had a comparison against a fractional value, we have to adjust
5100     // the compare predicate and sometimes the value.  RHSC is rounded towards
5101     // zero at this point.
5102     switch (Pred) {
5103     default: assert(0 && "Unexpected integer comparison!");
5104     case ICmpInst::ICMP_NE:  // (float)int != 4.4   --> true
5105       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5106     case ICmpInst::ICMP_EQ:  // (float)int == 4.4   --> false
5107       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5108     case ICmpInst::ICMP_SLE:
5109       // (float)int <= 4.4   --> int <= 4
5110       // (float)int <= -4.4  --> int < -4
5111       if (RHS.isNegative())
5112         Pred = ICmpInst::ICMP_SLT;
5113       break;
5114     case ICmpInst::ICMP_SLT:
5115       // (float)int < -4.4   --> int < -4
5116       // (float)int < 4.4    --> int <= 4
5117       if (!RHS.isNegative())
5118         Pred = ICmpInst::ICMP_SLE;
5119       break;
5120     case ICmpInst::ICMP_SGT:
5121       // (float)int > 4.4    --> int > 4
5122       // (float)int > -4.4   --> int >= -4
5123       if (RHS.isNegative())
5124         Pred = ICmpInst::ICMP_SGE;
5125       break;
5126     case ICmpInst::ICMP_SGE:
5127       // (float)int >= -4.4   --> int >= -4
5128       // (float)int >= 4.4    --> int > 4
5129       if (!RHS.isNegative())
5130         Pred = ICmpInst::ICMP_SGT;
5131       break;
5132     }
5133   }
5134
5135   // Lower this FP comparison into an appropriate integer version of the
5136   // comparison.
5137   return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5138 }
5139
5140 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5141   bool Changed = SimplifyCompare(I);
5142   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5143
5144   // Fold trivial predicates.
5145   if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5146     return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5147   if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5148     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5149   
5150   // Simplify 'fcmp pred X, X'
5151   if (Op0 == Op1) {
5152     switch (I.getPredicate()) {
5153     default: assert(0 && "Unknown predicate!");
5154     case FCmpInst::FCMP_UEQ:    // True if unordered or equal
5155     case FCmpInst::FCMP_UGE:    // True if unordered, greater than, or equal
5156     case FCmpInst::FCMP_ULE:    // True if unordered, less than, or equal
5157       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5158     case FCmpInst::FCMP_OGT:    // True if ordered and greater than
5159     case FCmpInst::FCMP_OLT:    // True if ordered and less than
5160     case FCmpInst::FCMP_ONE:    // True if ordered and operands are unequal
5161       return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5162       
5163     case FCmpInst::FCMP_UNO:    // True if unordered: isnan(X) | isnan(Y)
5164     case FCmpInst::FCMP_ULT:    // True if unordered or less than
5165     case FCmpInst::FCMP_UGT:    // True if unordered or greater than
5166     case FCmpInst::FCMP_UNE:    // True if unordered or not equal
5167       // Canonicalize these to be 'fcmp uno %X, 0.0'.
5168       I.setPredicate(FCmpInst::FCMP_UNO);
5169       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5170       return &I;
5171       
5172     case FCmpInst::FCMP_ORD:    // True if ordered (no nans)
5173     case FCmpInst::FCMP_OEQ:    // True if ordered and equal
5174     case FCmpInst::FCMP_OGE:    // True if ordered and greater than or equal
5175     case FCmpInst::FCMP_OLE:    // True if ordered and less than or equal
5176       // Canonicalize these to be 'fcmp ord %X, 0.0'.
5177       I.setPredicate(FCmpInst::FCMP_ORD);
5178       I.setOperand(1, Constant::getNullValue(Op0->getType()));
5179       return &I;
5180     }
5181   }
5182     
5183   if (isa<UndefValue>(Op1))                  // fcmp pred X, undef -> undef
5184     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5185
5186   // Handle fcmp with constant RHS
5187   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5188     // If the constant is a nan, see if we can fold the comparison based on it.
5189     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5190       if (CFP->getValueAPF().isNaN()) {
5191         if (FCmpInst::isOrdered(I.getPredicate()))   // True if ordered and...
5192           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5193         assert(FCmpInst::isUnordered(I.getPredicate()) &&
5194                "Comparison must be either ordered or unordered!");
5195         // True if unordered.
5196         return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5197       }
5198     }
5199     
5200     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5201       switch (LHSI->getOpcode()) {
5202       case Instruction::PHI:
5203         // Only fold fcmp into the PHI if the phi and fcmp are in the same
5204         // block.  If in the same block, we're encouraging jump threading.  If
5205         // not, we are just pessimizing the code by making an i1 phi.
5206         if (LHSI->getParent() == I.getParent())
5207           if (Instruction *NV = FoldOpIntoPhi(I))
5208             return NV;
5209         break;
5210       case Instruction::SIToFP:
5211       case Instruction::UIToFP:
5212         if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5213           return NV;
5214         break;
5215       case Instruction::Select:
5216         // If either operand of the select is a constant, we can fold the
5217         // comparison into the select arms, which will cause one to be
5218         // constant folded and the select turned into a bitwise or.
5219         Value *Op1 = 0, *Op2 = 0;
5220         if (LHSI->hasOneUse()) {
5221           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5222             // Fold the known value into the constant operand.
5223             Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5224             // Insert a new FCmp of the other select operand.
5225             Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5226                                                       LHSI->getOperand(2), RHSC,
5227                                                       I.getName()), I);
5228           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5229             // Fold the known value into the constant operand.
5230             Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5231             // Insert a new FCmp of the other select operand.
5232             Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5233                                                       LHSI->getOperand(1), RHSC,
5234                                                       I.getName()), I);
5235           }
5236         }
5237
5238         if (Op1)
5239           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5240         break;
5241       }
5242   }
5243
5244   return Changed ? &I : 0;
5245 }
5246
5247 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5248   bool Changed = SimplifyCompare(I);
5249   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5250   const Type *Ty = Op0->getType();
5251
5252   // icmp X, X
5253   if (Op0 == Op1)
5254     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5255                                                    I.isTrueWhenEqual()));
5256
5257   if (isa<UndefValue>(Op1))                  // X icmp undef -> undef
5258     return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5259   
5260   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5261   // addresses never equal each other!  We already know that Op0 != Op1.
5262   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5263        isa<ConstantPointerNull>(Op0)) &&
5264       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5265        isa<ConstantPointerNull>(Op1)))
5266     return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 
5267                                                    !I.isTrueWhenEqual()));
5268
5269   // icmp's with boolean values can always be turned into bitwise operations
5270   if (Ty == Type::Int1Ty) {
5271     switch (I.getPredicate()) {
5272     default: assert(0 && "Invalid icmp instruction!");
5273     case ICmpInst::ICMP_EQ: {               // icmp eq i1 A, B -> ~(A^B)
5274       Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5275       InsertNewInstBefore(Xor, I);
5276       return BinaryOperator::CreateNot(Xor);
5277     }
5278     case ICmpInst::ICMP_NE:                  // icmp eq i1 A, B -> A^B
5279       return BinaryOperator::CreateXor(Op0, Op1);
5280
5281     case ICmpInst::ICMP_UGT:
5282       std::swap(Op0, Op1);                   // Change icmp ugt -> icmp ult
5283       // FALL THROUGH
5284     case ICmpInst::ICMP_ULT:{               // icmp ult i1 A, B -> ~A & B
5285       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5286       InsertNewInstBefore(Not, I);
5287       return BinaryOperator::CreateAnd(Not, Op1);
5288     }
5289     case ICmpInst::ICMP_SGT:
5290       std::swap(Op0, Op1);                   // Change icmp sgt -> icmp slt
5291       // FALL THROUGH
5292     case ICmpInst::ICMP_SLT: {               // icmp slt i1 A, B -> A & ~B
5293       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5294       InsertNewInstBefore(Not, I);
5295       return BinaryOperator::CreateAnd(Not, Op0);
5296     }
5297     case ICmpInst::ICMP_UGE:
5298       std::swap(Op0, Op1);                   // Change icmp uge -> icmp ule
5299       // FALL THROUGH
5300     case ICmpInst::ICMP_ULE: {               //  icmp ule i1 A, B -> ~A | B
5301       Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5302       InsertNewInstBefore(Not, I);
5303       return BinaryOperator::CreateOr(Not, Op1);
5304     }
5305     case ICmpInst::ICMP_SGE:
5306       std::swap(Op0, Op1);                   // Change icmp sge -> icmp sle
5307       // FALL THROUGH
5308     case ICmpInst::ICMP_SLE: {               //  icmp sle i1 A, B -> A | ~B
5309       Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5310       InsertNewInstBefore(Not, I);
5311       return BinaryOperator::CreateOr(Not, Op0);
5312     }
5313     }
5314   }
5315
5316   // See if we are doing a comparison with a constant.
5317   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5318     Value *A, *B;
5319     
5320     // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5321     if (I.isEquality() && CI->isNullValue() &&
5322         match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5323       // (icmp cond A B) if cond is equality
5324       return new ICmpInst(I.getPredicate(), A, B);
5325     }
5326     
5327     // If we have an icmp le or icmp ge instruction, turn it into the
5328     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
5329     // them being folded in the code below.
5330     switch (I.getPredicate()) {
5331     default: break;
5332     case ICmpInst::ICMP_ULE:
5333       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
5334         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5335       return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5336     case ICmpInst::ICMP_SLE:
5337       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
5338         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5339       return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5340     case ICmpInst::ICMP_UGE:
5341       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
5342         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5343       return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5344     case ICmpInst::ICMP_SGE:
5345       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
5346         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5347       return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5348     }
5349     
5350     // See if we can fold the comparison based on range information we can get
5351     // by checking whether bits are known to be zero or one in the input.
5352     uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5353     APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5354     
5355     // If this comparison is a normal comparison, it demands all
5356     // bits, if it is a sign bit comparison, it only demands the sign bit.
5357     bool UnusedBit;
5358     bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5359     
5360     if (SimplifyDemandedBits(Op0, 
5361                              isSignBit ? APInt::getSignBit(BitWidth)
5362                                        : APInt::getAllOnesValue(BitWidth),
5363                              KnownZero, KnownOne, 0))
5364       return &I;
5365         
5366     // Given the known and unknown bits, compute a range that the LHS could be
5367     // in.  Compute the Min, Max and RHS values based on the known bits. For the
5368     // EQ and NE we use unsigned values.
5369     APInt Min(BitWidth, 0), Max(BitWidth, 0);
5370     if (ICmpInst::isSignedPredicate(I.getPredicate()))
5371       ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5372     else
5373       ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5374     
5375     // If Min and Max are known to be the same, then SimplifyDemandedBits
5376     // figured out that the LHS is a constant.  Just constant fold this now so
5377     // that code below can assume that Min != Max.
5378     if (Min == Max)
5379       return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5380                                                           ConstantInt::get(Min),
5381                                                           CI));
5382     
5383     // Based on the range information we know about the LHS, see if we can
5384     // simplify this comparison.  For example, (x&4) < 8  is always true.
5385     const APInt &RHSVal = CI->getValue();
5386     switch (I.getPredicate()) {  // LE/GE have been folded already.
5387     default: assert(0 && "Unknown icmp opcode!");
5388     case ICmpInst::ICMP_EQ:
5389       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5390         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5391       break;
5392     case ICmpInst::ICMP_NE:
5393       if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5394         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5395       break;
5396     case ICmpInst::ICMP_ULT:
5397       if (Max.ult(RHSVal))                    // A <u C -> true iff max(A) < C
5398         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5399       if (Min.uge(RHSVal))                    // A <u C -> false iff min(A) >= C
5400         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5401       if (RHSVal == Max)                      // A <u MAX -> A != MAX
5402         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5403       if (RHSVal == Min+1)                    // A <u MIN+1 -> A == MIN
5404         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5405         
5406       // (x <u 2147483648) -> (x >s -1)  -> true if sign bit clear
5407       if (CI->isMinValue(true))
5408         return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5409                             ConstantInt::getAllOnesValue(Op0->getType()));
5410       break;
5411     case ICmpInst::ICMP_UGT:
5412       if (Min.ugt(RHSVal))                    // A >u C -> true iff min(A) > C
5413         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5414       if (Max.ule(RHSVal))                    // A >u C -> false iff max(A) <= C
5415         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5416         
5417       if (RHSVal == Min)                      // A >u MIN -> A != MIN
5418         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5419       if (RHSVal == Max-1)                    // A >u MAX-1 -> A == MAX
5420         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5421       
5422       // (x >u 2147483647) -> (x <s 0)  -> true if sign bit set
5423       if (CI->isMaxValue(true))
5424         return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5425                             ConstantInt::getNullValue(Op0->getType()));
5426       break;
5427     case ICmpInst::ICMP_SLT:
5428       if (Max.slt(RHSVal))                    // A <s C -> true iff max(A) < C
5429         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5430       if (Min.sge(RHSVal))                    // A <s C -> false iff min(A) >= C
5431         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5432       if (RHSVal == Max)                      // A <s MAX -> A != MAX
5433         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5434       if (RHSVal == Min+1)                    // A <s MIN+1 -> A == MIN
5435         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5436       break;
5437     case ICmpInst::ICMP_SGT: 
5438       if (Min.sgt(RHSVal))                    // A >s C -> true iff min(A) > C
5439         return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5440       if (Max.sle(RHSVal))                    // A >s C -> false iff max(A) <= C
5441         return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5442         
5443       if (RHSVal == Min)                      // A >s MIN -> A != MIN
5444         return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5445       if (RHSVal == Max-1)                    // A >s MAX-1 -> A == MAX
5446         return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5447       break;
5448     }
5449   }
5450
5451   // Test if the ICmpInst instruction is used exclusively by a select as
5452   // part of a minimum or maximum operation. If so, refrain from doing
5453   // any other folding. This helps out other analyses which understand
5454   // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5455   // and CodeGen. And in this case, at least one of the comparison
5456   // operands has at least one user besides the compare (the select),
5457   // which would often largely negate the benefit of folding anyway.
5458   if (I.hasOneUse())
5459     if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5460       if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5461           (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5462         return 0;
5463
5464   // See if we are doing a comparison between a constant and an instruction that
5465   // can be folded into the comparison.
5466   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5467     // Since the RHS is a ConstantInt (CI), if the left hand side is an 
5468     // instruction, see if that instruction also has constants so that the 
5469     // instruction can be folded into the icmp 
5470     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5471       if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5472         return Res;
5473   }
5474
5475   // Handle icmp with constant (but not simple integer constant) RHS
5476   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5477     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5478       switch (LHSI->getOpcode()) {
5479       case Instruction::GetElementPtr:
5480         if (RHSC->isNullValue()) {
5481           // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5482           bool isAllZeros = true;
5483           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5484             if (!isa<Constant>(LHSI->getOperand(i)) ||
5485                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5486               isAllZeros = false;
5487               break;
5488             }
5489           if (isAllZeros)
5490             return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5491                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
5492         }
5493         break;
5494
5495       case Instruction::PHI:
5496         // Only fold icmp into the PHI if the phi and fcmp are in the same
5497         // block.  If in the same block, we're encouraging jump threading.  If
5498         // not, we are just pessimizing the code by making an i1 phi.
5499         if (LHSI->getParent() == I.getParent())
5500           if (Instruction *NV = FoldOpIntoPhi(I))
5501             return NV;
5502         break;
5503       case Instruction::Select: {
5504         // If either operand of the select is a constant, we can fold the
5505         // comparison into the select arms, which will cause one to be
5506         // constant folded and the select turned into a bitwise or.
5507         Value *Op1 = 0, *Op2 = 0;
5508         if (LHSI->hasOneUse()) {
5509           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5510             // Fold the known value into the constant operand.
5511             Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5512             // Insert a new ICmp of the other select operand.
5513             Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5514                                                    LHSI->getOperand(2), RHSC,
5515                                                    I.getName()), I);
5516           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5517             // Fold the known value into the constant operand.
5518             Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5519             // Insert a new ICmp of the other select operand.
5520             Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5521                                                    LHSI->getOperand(1), RHSC,
5522                                                    I.getName()), I);
5523           }
5524         }
5525
5526         if (Op1)
5527           return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5528         break;
5529       }
5530       case Instruction::Malloc:
5531         // If we have (malloc != null), and if the malloc has a single use, we
5532         // can assume it is successful and remove the malloc.
5533         if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5534           AddToWorkList(LHSI);
5535           return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5536                                                          !I.isTrueWhenEqual()));
5537         }
5538         break;
5539       }
5540   }
5541
5542   // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5543   if (User *GEP = dyn_castGetElementPtr(Op0))
5544     if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5545       return NI;
5546   if (User *GEP = dyn_castGetElementPtr(Op1))
5547     if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5548                            ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5549       return NI;
5550
5551   // Test to see if the operands of the icmp are casted versions of other
5552   // values.  If the ptr->ptr cast can be stripped off both arguments, we do so
5553   // now.
5554   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5555     if (isa<PointerType>(Op0->getType()) && 
5556         (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) { 
5557       // We keep moving the cast from the left operand over to the right
5558       // operand, where it can often be eliminated completely.
5559       Op0 = CI->getOperand(0);
5560
5561       // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5562       // so eliminate it as well.
5563       if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5564         Op1 = CI2->getOperand(0);
5565
5566       // If Op1 is a constant, we can fold the cast into the constant.
5567       if (Op0->getType() != Op1->getType()) {
5568         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5569           Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5570         } else {
5571           // Otherwise, cast the RHS right before the icmp
5572           Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5573         }
5574       }
5575       return new ICmpInst(I.getPredicate(), Op0, Op1);
5576     }
5577   }
5578   
5579   if (isa<CastInst>(Op0)) {
5580     // Handle the special case of: icmp (cast bool to X), <cst>
5581     // This comes up when you have code like
5582     //   int X = A < B;
5583     //   if (X) ...
5584     // For generality, we handle any zero-extension of any operand comparison
5585     // with a constant or another cast from the same type.
5586     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5587       if (Instruction *R = visitICmpInstWithCastAndCast(I))
5588         return R;
5589   }
5590   
5591   // See if it's the same type of instruction on the left and right.
5592   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5593     if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5594       if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5595           Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5596           I.isEquality()) {
5597         switch (Op0I->getOpcode()) {
5598         default: break;
5599         case Instruction::Add:
5600         case Instruction::Sub:
5601         case Instruction::Xor:
5602           // a+x icmp eq/ne b+x --> a icmp b
5603           return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5604                               Op1I->getOperand(0));
5605           break;
5606         case Instruction::Mul:
5607           if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5608             // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5609             // Mask = -1 >> count-trailing-zeros(Cst).
5610             if (!CI->isZero() && !CI->isOne()) {
5611               const APInt &AP = CI->getValue();
5612               ConstantInt *Mask = ConstantInt::get(
5613                                       APInt::getLowBitsSet(AP.getBitWidth(),
5614                                                            AP.getBitWidth() -
5615                                                       AP.countTrailingZeros()));
5616               Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5617                                                             Mask);
5618               Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5619                                                             Mask);
5620               InsertNewInstBefore(And1, I);
5621               InsertNewInstBefore(And2, I);
5622               return new ICmpInst(I.getPredicate(), And1, And2);
5623             }
5624           }
5625           break;
5626         }
5627       }
5628     }
5629   }
5630   
5631   // ~x < ~y --> y < x
5632   { Value *A, *B;
5633     if (match(Op0, m_Not(m_Value(A))) &&
5634         match(Op1, m_Not(m_Value(B))))
5635       return new ICmpInst(I.getPredicate(), B, A);
5636   }
5637   
5638   if (I.isEquality()) {
5639     Value *A, *B, *C, *D;
5640     
5641     // -x == -y --> x == y
5642     if (match(Op0, m_Neg(m_Value(A))) &&
5643         match(Op1, m_Neg(m_Value(B))))
5644       return new ICmpInst(I.getPredicate(), A, B);
5645     
5646     if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5647       if (A == Op1 || B == Op1) {    // (A^B) == A  ->  B == 0
5648         Value *OtherVal = A == Op1 ? B : A;
5649         return new ICmpInst(I.getPredicate(), OtherVal,
5650                             Constant::getNullValue(A->getType()));
5651       }
5652
5653       if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5654         // A^c1 == C^c2 --> A == C^(c1^c2)
5655         if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5656           if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5657             if (Op1->hasOneUse()) {
5658               Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5659               Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5660               return new ICmpInst(I.getPredicate(), A,
5661                                   InsertNewInstBefore(Xor, I));
5662             }
5663         
5664         // A^B == A^D -> B == D
5665         if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5666         if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5667         if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5668         if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5669       }
5670     }
5671     
5672     if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5673         (A == Op0 || B == Op0)) {
5674       // A == (A^B)  ->  B == 0
5675       Value *OtherVal = A == Op0 ? B : A;
5676       return new ICmpInst(I.getPredicate(), OtherVal,
5677                           Constant::getNullValue(A->getType()));
5678     }
5679     if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5680       // (A-B) == A  ->  B == 0
5681       return new ICmpInst(I.getPredicate(), B,
5682                           Constant::getNullValue(B->getType()));
5683     }
5684     if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5685       // A == (A-B)  ->  B == 0
5686       return new ICmpInst(I.getPredicate(), B,
5687                           Constant::getNullValue(B->getType()));
5688     }
5689     
5690     // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5691     if (Op0->hasOneUse() && Op1->hasOneUse() &&
5692         match(Op0, m_And(m_Value(A), m_Value(B))) && 
5693         match(Op1, m_And(m_Value(C), m_Value(D)))) {
5694       Value *X = 0, *Y = 0, *Z = 0;
5695       
5696       if (A == C) {
5697         X = B; Y = D; Z = A;
5698       } else if (A == D) {
5699         X = B; Y = C; Z = A;
5700       } else if (B == C) {
5701         X = A; Y = D; Z = B;
5702       } else if (B == D) {
5703         X = A; Y = C; Z = B;
5704       }
5705       
5706       if (X) {   // Build (X^Y) & Z
5707         Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5708         Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5709         I.setOperand(0, Op1);
5710         I.setOperand(1, Constant::getNullValue(Op1->getType()));
5711         return &I;
5712       }
5713     }
5714   }
5715   return Changed ? &I : 0;
5716 }
5717
5718
5719 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5720 /// and CmpRHS are both known to be integer constants.
5721 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5722                                           ConstantInt *DivRHS) {
5723   ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5724   const APInt &CmpRHSV = CmpRHS->getValue();
5725   
5726   // FIXME: If the operand types don't match the type of the divide 
5727   // then don't attempt this transform. The code below doesn't have the
5728   // logic to deal with a signed divide and an unsigned compare (and
5729   // vice versa). This is because (x /s C1) <s C2  produces different 
5730   // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5731   // (x /u C1) <u C2.  Simply casting the operands and result won't 
5732   // work. :(  The if statement below tests that condition and bails 
5733   // if it finds it. 
5734   bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5735   if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5736     return 0;
5737   if (DivRHS->isZero())
5738     return 0; // The ProdOV computation fails on divide by zero.
5739
5740   // Compute Prod = CI * DivRHS. We are essentially solving an equation
5741   // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
5742   // C2 (CI). By solving for X we can turn this into a range check 
5743   // instead of computing a divide. 
5744   ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5745
5746   // Determine if the product overflows by seeing if the product is
5747   // not equal to the divide. Make sure we do the same kind of divide
5748   // as in the LHS instruction that we're folding. 
5749   bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5750                  ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5751
5752   // Get the ICmp opcode
5753   ICmpInst::Predicate Pred = ICI.getPredicate();
5754
5755   // Figure out the interval that is being checked.  For example, a comparison
5756   // like "X /u 5 == 0" is really checking that X is in the interval [0, 5). 
5757   // Compute this interval based on the constants involved and the signedness of
5758   // the compare/divide.  This computes a half-open interval, keeping track of
5759   // whether either value in the interval overflows.  After analysis each
5760   // overflow variable is set to 0 if it's corresponding bound variable is valid
5761   // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5762   int LoOverflow = 0, HiOverflow = 0;
5763   ConstantInt *LoBound = 0, *HiBound = 0;
5764   
5765   
5766   if (!DivIsSigned) {  // udiv
5767     // e.g. X/5 op 3  --> [15, 20)
5768     LoBound = Prod;
5769     HiOverflow = LoOverflow = ProdOV;
5770     if (!HiOverflow)
5771       HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5772   } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5773     if (CmpRHSV == 0) {       // (X / pos) op 0
5774       // Can't overflow.  e.g.  X/2 op 0 --> [-1, 2)
5775       LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5776       HiBound = DivRHS;
5777     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / pos) op pos
5778       LoBound = Prod;     // e.g.   X/5 op 3 --> [15, 20)
5779       HiOverflow = LoOverflow = ProdOV;
5780       if (!HiOverflow)
5781         HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5782     } else {                       // (X / pos) op neg
5783       // e.g. X/5 op -3  --> [-15-4, -15+1) --> [-19, -14)
5784       Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5785       LoOverflow = AddWithOverflow(LoBound, Prod,
5786                                    cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5787       HiBound = AddOne(Prod);
5788       HiOverflow = ProdOV ? -1 : 0;
5789     }
5790   } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5791     if (CmpRHSV == 0) {       // (X / neg) op 0
5792       // e.g. X/-5 op 0  --> [-4, 5)
5793       LoBound = AddOne(DivRHS);
5794       HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5795       if (HiBound == DivRHS) {     // -INTMIN = INTMIN
5796         HiOverflow = 1;            // [INTMIN+1, overflow)
5797         HiBound = 0;               // e.g. X/INTMIN = 0 --> X > INTMIN
5798       }
5799     } else if (CmpRHSV.isStrictlyPositive()) {   // (X / neg) op pos
5800       // e.g. X/-5 op 3  --> [-19, -14)
5801       HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5802       if (!LoOverflow)
5803         LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5804       HiBound = AddOne(Prod);
5805     } else {                       // (X / neg) op neg
5806       // e.g. X/-5 op -3  --> [15, 20)
5807       LoBound = Prod;
5808       LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5809       if (!HiOverflow)
5810         HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
5811     }
5812     
5813     // Dividing by a negative swaps the condition.  LT <-> GT
5814     Pred = ICmpInst::getSwappedPredicate(Pred);
5815   }
5816
5817   Value *X = DivI->getOperand(0);
5818   switch (Pred) {
5819   default: assert(0 && "Unhandled icmp opcode!");
5820   case ICmpInst::ICMP_EQ:
5821     if (LoOverflow && HiOverflow)
5822       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5823     else if (HiOverflow)
5824       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5825                           ICmpInst::ICMP_UGE, X, LoBound);
5826     else if (LoOverflow)
5827       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5828                           ICmpInst::ICMP_ULT, X, HiBound);
5829     else
5830       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5831   case ICmpInst::ICMP_NE:
5832     if (LoOverflow && HiOverflow)
5833       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5834     else if (HiOverflow)
5835       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : 
5836                           ICmpInst::ICMP_ULT, X, LoBound);
5837     else if (LoOverflow)
5838       return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : 
5839                           ICmpInst::ICMP_UGE, X, HiBound);
5840     else
5841       return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5842   case ICmpInst::ICMP_ULT:
5843   case ICmpInst::ICMP_SLT:
5844     if (LoOverflow == +1)   // Low bound is greater than input range.
5845       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5846     if (LoOverflow == -1)   // Low bound is less than input range.
5847       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5848     return new ICmpInst(Pred, X, LoBound);
5849   case ICmpInst::ICMP_UGT:
5850   case ICmpInst::ICMP_SGT:
5851     if (HiOverflow == +1)       // High bound greater than input range.
5852       return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5853     else if (HiOverflow == -1)  // High bound less than input range.
5854       return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5855     if (Pred == ICmpInst::ICMP_UGT)
5856       return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5857     else
5858       return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5859   }
5860 }
5861
5862
5863 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5864 ///
5865 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5866                                                           Instruction *LHSI,
5867                                                           ConstantInt *RHS) {
5868   const APInt &RHSV = RHS->getValue();
5869   
5870   switch (LHSI->getOpcode()) {
5871   case Instruction::Xor:         // (icmp pred (xor X, XorCST), CI)
5872     if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5873       // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5874       // fold the xor.
5875       if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5876           (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5877         Value *CompareVal = LHSI->getOperand(0);
5878         
5879         // If the sign bit of the XorCST is not set, there is no change to
5880         // the operation, just stop using the Xor.
5881         if (!XorCST->getValue().isNegative()) {
5882           ICI.setOperand(0, CompareVal);
5883           AddToWorkList(LHSI);
5884           return &ICI;
5885         }
5886         
5887         // Was the old condition true if the operand is positive?
5888         bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5889         
5890         // If so, the new one isn't.
5891         isTrueIfPositive ^= true;
5892         
5893         if (isTrueIfPositive)
5894           return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5895         else
5896           return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5897       }
5898     }
5899     break;
5900   case Instruction::And:         // (icmp pred (and X, AndCST), RHS)
5901     if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5902         LHSI->getOperand(0)->hasOneUse()) {
5903       ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5904       
5905       // If the LHS is an AND of a truncating cast, we can widen the
5906       // and/compare to be the input width without changing the value
5907       // produced, eliminating a cast.
5908       if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5909         // We can do this transformation if either the AND constant does not
5910         // have its sign bit set or if it is an equality comparison. 
5911         // Extending a relational comparison when we're checking the sign
5912         // bit would not work.
5913         if (Cast->hasOneUse() &&
5914             (ICI.isEquality() ||
5915              (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5916           uint32_t BitWidth = 
5917             cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5918           APInt NewCST = AndCST->getValue();
5919           NewCST.zext(BitWidth);
5920           APInt NewCI = RHSV;
5921           NewCI.zext(BitWidth);
5922           Instruction *NewAnd = 
5923             BinaryOperator::CreateAnd(Cast->getOperand(0),
5924                                       ConstantInt::get(NewCST),LHSI->getName());
5925           InsertNewInstBefore(NewAnd, ICI);
5926           return new ICmpInst(ICI.getPredicate(), NewAnd,
5927                               ConstantInt::get(NewCI));
5928         }
5929       }
5930       
5931       // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5932       // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
5933       // happens a LOT in code produced by the C front-end, for bitfield
5934       // access.
5935       BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5936       if (Shift && !Shift->isShift())
5937         Shift = 0;
5938       
5939       ConstantInt *ShAmt;
5940       ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5941       const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
5942       const Type *AndTy = AndCST->getType();          // Type of the and.
5943       
5944       // We can fold this as long as we can't shift unknown bits
5945       // into the mask.  This can only happen with signed shift
5946       // rights, as they sign-extend.
5947       if (ShAmt) {
5948         bool CanFold = Shift->isLogicalShift();
5949         if (!CanFold) {
5950           // To test for the bad case of the signed shr, see if any
5951           // of the bits shifted in could be tested after the mask.
5952           uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5953           int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5954           
5955           uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5956           if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) & 
5957                AndCST->getValue()) == 0)
5958             CanFold = true;
5959         }
5960         
5961         if (CanFold) {
5962           Constant *NewCst;
5963           if (Shift->getOpcode() == Instruction::Shl)
5964             NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5965           else
5966             NewCst = ConstantExpr::getShl(RHS, ShAmt);
5967           
5968           // Check to see if we are shifting out any of the bits being
5969           // compared.
5970           if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5971             // If we shifted bits out, the fold is not going to work out.
5972             // As a special case, check to see if this means that the
5973             // result is always true or false now.
5974             if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5975               return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5976             if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5977               return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5978           } else {
5979             ICI.setOperand(1, NewCst);
5980             Constant *NewAndCST;
5981             if (Shift->getOpcode() == Instruction::Shl)
5982               NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5983             else
5984               NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5985             LHSI->setOperand(1, NewAndCST);
5986             LHSI->setOperand(0, Shift->getOperand(0));
5987             AddToWorkList(Shift); // Shift is dead.
5988             AddUsesToWorkList(ICI);
5989             return &ICI;
5990           }
5991         }
5992       }
5993       
5994       // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
5995       // preferable because it allows the C<<Y expression to be hoisted out
5996       // of a loop if Y is invariant and X is not.
5997       if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5998           ICI.isEquality() && !Shift->isArithmeticShift() &&
5999           isa<Instruction>(Shift->getOperand(0))) {
6000         // Compute C << Y.
6001         Value *NS;
6002         if (Shift->getOpcode() == Instruction::LShr) {
6003           NS = BinaryOperator::CreateShl(AndCST, 
6004                                          Shift->getOperand(1), "tmp");
6005         } else {
6006           // Insert a logical shift.
6007           NS = BinaryOperator::CreateLShr(AndCST,
6008                                           Shift->getOperand(1), "tmp");
6009         }
6010         InsertNewInstBefore(cast<Instruction>(NS), ICI);
6011         
6012         // Compute X & (C << Y).
6013         Instruction *NewAnd = 
6014           BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6015         InsertNewInstBefore(NewAnd, ICI);
6016         
6017         ICI.setOperand(0, NewAnd);
6018         return &ICI;
6019       }
6020     }
6021     break;
6022     
6023   case Instruction::Shl: {       // (icmp pred (shl X, ShAmt), CI)
6024     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6025     if (!ShAmt) break;
6026     
6027     uint32_t TypeBits = RHSV.getBitWidth();
6028     
6029     // Check that the shift amount is in range.  If not, don't perform
6030     // undefined shifts.  When the shift is visited it will be
6031     // simplified.
6032     if (ShAmt->uge(TypeBits))
6033       break;
6034     
6035     if (ICI.isEquality()) {
6036       // If we are comparing against bits always shifted out, the
6037       // comparison cannot succeed.
6038       Constant *Comp =
6039         ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6040       if (Comp != RHS) {// Comparing against a bit that we know is zero.
6041         bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6042         Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6043         return ReplaceInstUsesWith(ICI, Cst);
6044       }
6045       
6046       if (LHSI->hasOneUse()) {
6047         // Otherwise strength reduce the shift into an and.
6048         uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6049         Constant *Mask =
6050           ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6051         
6052         Instruction *AndI =
6053           BinaryOperator::CreateAnd(LHSI->getOperand(0),
6054                                     Mask, LHSI->getName()+".mask");
6055         Value *And = InsertNewInstBefore(AndI, ICI);
6056         return new ICmpInst(ICI.getPredicate(), And,
6057                             ConstantInt::get(RHSV.lshr(ShAmtVal)));
6058       }
6059     }
6060     
6061     // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6062     bool TrueIfSigned = false;
6063     if (LHSI->hasOneUse() &&
6064         isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6065       // (X << 31) <s 0  --> (X&1) != 0
6066       Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6067                                            (TypeBits-ShAmt->getZExtValue()-1));
6068       Instruction *AndI =
6069         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6070                                   Mask, LHSI->getName()+".mask");
6071       Value *And = InsertNewInstBefore(AndI, ICI);
6072       
6073       return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6074                           And, Constant::getNullValue(And->getType()));
6075     }
6076     break;
6077   }
6078     
6079   case Instruction::LShr:         // (icmp pred (shr X, ShAmt), CI)
6080   case Instruction::AShr: {
6081     // Only handle equality comparisons of shift-by-constant.
6082     ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6083     if (!ShAmt || !ICI.isEquality()) break;
6084
6085     // Check that the shift amount is in range.  If not, don't perform
6086     // undefined shifts.  When the shift is visited it will be
6087     // simplified.
6088     uint32_t TypeBits = RHSV.getBitWidth();
6089     if (ShAmt->uge(TypeBits))
6090       break;
6091     
6092     uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6093       
6094     // If we are comparing against bits always shifted out, the
6095     // comparison cannot succeed.
6096     APInt Comp = RHSV << ShAmtVal;
6097     if (LHSI->getOpcode() == Instruction::LShr)
6098       Comp = Comp.lshr(ShAmtVal);
6099     else
6100       Comp = Comp.ashr(ShAmtVal);
6101     
6102     if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6103       bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6104       Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6105       return ReplaceInstUsesWith(ICI, Cst);
6106     }
6107     
6108     // Otherwise, check to see if the bits shifted out are known to be zero.
6109     // If so, we can compare against the unshifted value:
6110     //  (X & 4) >> 1 == 2  --> (X & 4) == 4.
6111     if (LHSI->hasOneUse() &&
6112         MaskedValueIsZero(LHSI->getOperand(0), 
6113                           APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6114       return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6115                           ConstantExpr::getShl(RHS, ShAmt));
6116     }
6117       
6118     if (LHSI->hasOneUse()) {
6119       // Otherwise strength reduce the shift into an and.
6120       APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6121       Constant *Mask = ConstantInt::get(Val);
6122       
6123       Instruction *AndI =
6124         BinaryOperator::CreateAnd(LHSI->getOperand(0),
6125                                   Mask, LHSI->getName()+".mask");
6126       Value *And = InsertNewInstBefore(AndI, ICI);
6127       return new ICmpInst(ICI.getPredicate(), And,
6128                           ConstantExpr::getShl(RHS, ShAmt));
6129     }
6130     break;
6131   }
6132     
6133   case Instruction::SDiv:
6134   case Instruction::UDiv:
6135     // Fold: icmp pred ([us]div X, C1), C2 -> range test
6136     // Fold this div into the comparison, producing a range check. 
6137     // Determine, based on the divide type, what the range is being 
6138     // checked.  If there is an overflow on the low or high side, remember 
6139     // it, otherwise compute the range [low, hi) bounding the new value.
6140     // See: InsertRangeTest above for the kinds of replacements possible.
6141     if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6142       if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6143                                           DivRHS))
6144         return R;
6145     break;
6146
6147   case Instruction::Add:
6148     // Fold: icmp pred (add, X, C1), C2
6149
6150     if (!ICI.isEquality()) {
6151       ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6152       if (!LHSC) break;
6153       const APInt &LHSV = LHSC->getValue();
6154
6155       ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6156                             .subtract(LHSV);
6157
6158       if (ICI.isSignedPredicate()) {
6159         if (CR.getLower().isSignBit()) {
6160           return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6161                               ConstantInt::get(CR.getUpper()));
6162         } else if (CR.getUpper().isSignBit()) {
6163           return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6164                               ConstantInt::get(CR.getLower()));
6165         }
6166       } else {
6167         if (CR.getLower().isMinValue()) {
6168           return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6169                               ConstantInt::get(CR.getUpper()));
6170         } else if (CR.getUpper().isMinValue()) {
6171           return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6172                               ConstantInt::get(CR.getLower()));
6173         }
6174       }
6175     }
6176     break;
6177   }
6178   
6179   // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6180   if (ICI.isEquality()) {
6181     bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6182     
6183     // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
6184     // the second operand is a constant, simplify a bit.
6185     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6186       switch (BO->getOpcode()) {
6187       case Instruction::SRem:
6188         // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6189         if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6190           const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6191           if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6192             Instruction *NewRem =
6193               BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6194                                          BO->getName());
6195             InsertNewInstBefore(NewRem, ICI);
6196             return new ICmpInst(ICI.getPredicate(), NewRem, 
6197                                 Constant::getNullValue(BO->getType()));
6198           }
6199         }
6200         break;
6201       case Instruction::Add:
6202         // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6203         if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6204           if (BO->hasOneUse())
6205             return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6206                                 Subtract(RHS, BOp1C));
6207         } else if (RHSV == 0) {
6208           // Replace ((add A, B) != 0) with (A != -B) if A or B is
6209           // efficiently invertible, or if the add has just this one use.
6210           Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6211           
6212           if (Value *NegVal = dyn_castNegVal(BOp1))
6213             return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6214           else if (Value *NegVal = dyn_castNegVal(BOp0))
6215             return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6216           else if (BO->hasOneUse()) {
6217             Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6218             InsertNewInstBefore(Neg, ICI);
6219             Neg->takeName(BO);
6220             return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6221           }
6222         }
6223         break;
6224       case Instruction::Xor:
6225         // For the xor case, we can xor two constants together, eliminating
6226         // the explicit xor.
6227         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6228           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0), 
6229                               ConstantExpr::getXor(RHS, BOC));
6230         
6231         // FALLTHROUGH
6232       case Instruction::Sub:
6233         // Replace (([sub|xor] A, B) != 0) with (A != B)
6234         if (RHSV == 0)
6235           return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6236                               BO->getOperand(1));
6237         break;
6238         
6239       case Instruction::Or:
6240         // If bits are being or'd in that are not present in the constant we
6241         // are comparing against, then the comparison could never succeed!
6242         if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6243           Constant *NotCI = ConstantExpr::getNot(RHS);
6244           if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6245             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty, 
6246                                                              isICMP_NE));
6247         }
6248         break;
6249         
6250       case Instruction::And:
6251         if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6252           // If bits are being compared against that are and'd out, then the
6253           // comparison can never succeed!
6254           if ((RHSV & ~BOC->getValue()) != 0)
6255             return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6256                                                              isICMP_NE));
6257           
6258           // If we have ((X & C) == C), turn it into ((X & C) != 0).
6259           if (RHS == BOC && RHSV.isPowerOf2())
6260             return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6261                                 ICmpInst::ICMP_NE, LHSI,
6262                                 Constant::getNullValue(RHS->getType()));
6263           
6264           // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6265           if (BOC->getValue().isSignBit()) {
6266             Value *X = BO->getOperand(0);
6267             Constant *Zero = Constant::getNullValue(X->getType());
6268             ICmpInst::Predicate pred = isICMP_NE ? 
6269               ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6270             return new ICmpInst(pred, X, Zero);
6271           }
6272           
6273           // ((X & ~7) == 0) --> X < 8
6274           if (RHSV == 0 && isHighOnes(BOC)) {
6275             Value *X = BO->getOperand(0);
6276             Constant *NegX = ConstantExpr::getNeg(BOC);
6277             ICmpInst::Predicate pred = isICMP_NE ? 
6278               ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6279             return new ICmpInst(pred, X, NegX);
6280           }
6281         }
6282       default: break;
6283       }
6284     } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6285       // Handle icmp {eq|ne} <intrinsic>, intcst.
6286       if (II->getIntrinsicID() == Intrinsic::bswap) {
6287         AddToWorkList(II);
6288         ICI.setOperand(0, II->getOperand(1));
6289         ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6290         return &ICI;
6291       }
6292     }
6293   } else {  // Not a ICMP_EQ/ICMP_NE
6294             // If the LHS is a cast from an integral value of the same size, 
6295             // then since we know the RHS is a constant, try to simlify.
6296     if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6297       Value *CastOp = Cast->getOperand(0);
6298       const Type *SrcTy = CastOp->getType();
6299       uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6300       if (SrcTy->isInteger() && 
6301           SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6302         // If this is an unsigned comparison, try to make the comparison use
6303         // smaller constant values.
6304         if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6305           // X u< 128 => X s> -1
6306           return new ICmpInst(ICmpInst::ICMP_SGT, CastOp, 
6307                            ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6308         } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6309                    RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6310           // X u> 127 => X s< 0
6311           return new ICmpInst(ICmpInst::ICMP_SLT, CastOp, 
6312                               Constant::getNullValue(SrcTy));
6313         }
6314       }
6315     }
6316   }
6317   return 0;
6318 }
6319
6320 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6321 /// We only handle extending casts so far.
6322 ///
6323 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6324   const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6325   Value *LHSCIOp        = LHSCI->getOperand(0);
6326   const Type *SrcTy     = LHSCIOp->getType();
6327   const Type *DestTy    = LHSCI->getType();
6328   Value *RHSCIOp;
6329
6330   // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the 
6331   // integer type is the same size as the pointer type.
6332   if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6333       getTargetData().getPointerSizeInBits() == 
6334          cast<IntegerType>(DestTy)->getBitWidth()) {
6335     Value *RHSOp = 0;
6336     if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6337       RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6338     } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6339       RHSOp = RHSC->getOperand(0);
6340       // If the pointer types don't match, insert a bitcast.
6341       if (LHSCIOp->getType() != RHSOp->getType())
6342         RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6343     }
6344
6345     if (RHSOp)
6346       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6347   }
6348   
6349   // The code below only handles extension cast instructions, so far.
6350   // Enforce this.
6351   if (LHSCI->getOpcode() != Instruction::ZExt &&
6352       LHSCI->getOpcode() != Instruction::SExt)
6353     return 0;
6354
6355   bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6356   bool isSignedCmp = ICI.isSignedPredicate();
6357
6358   if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6359     // Not an extension from the same type?
6360     RHSCIOp = CI->getOperand(0);
6361     if (RHSCIOp->getType() != LHSCIOp->getType()) 
6362       return 0;
6363     
6364     // If the signedness of the two casts doesn't agree (i.e. one is a sext
6365     // and the other is a zext), then we can't handle this.
6366     if (CI->getOpcode() != LHSCI->getOpcode())
6367       return 0;
6368
6369     // Deal with equality cases early.
6370     if (ICI.isEquality())
6371       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6372
6373     // A signed comparison of sign extended values simplifies into a
6374     // signed comparison.
6375     if (isSignedCmp && isSignedExt)
6376       return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6377
6378     // The other three cases all fold into an unsigned comparison.
6379     return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6380   }
6381
6382   // If we aren't dealing with a constant on the RHS, exit early
6383   ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6384   if (!CI)
6385     return 0;
6386
6387   // Compute the constant that would happen if we truncated to SrcTy then
6388   // reextended to DestTy.
6389   Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6390   Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6391
6392   // If the re-extended constant didn't change...
6393   if (Res2 == CI) {
6394     // Make sure that sign of the Cmp and the sign of the Cast are the same.
6395     // For example, we might have:
6396     //    %A = sext short %X to uint
6397     //    %B = icmp ugt uint %A, 1330
6398     // It is incorrect to transform this into 
6399     //    %B = icmp ugt short %X, 1330 
6400     // because %A may have negative value. 
6401     //
6402     // However, we allow this when the compare is EQ/NE, because they are
6403     // signless.
6404     if (isSignedExt == isSignedCmp || ICI.isEquality())
6405       return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6406     return 0;
6407   }
6408
6409   // The re-extended constant changed so the constant cannot be represented 
6410   // in the shorter type. Consequently, we cannot emit a simple comparison.
6411
6412   // First, handle some easy cases. We know the result cannot be equal at this
6413   // point so handle the ICI.isEquality() cases
6414   if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6415     return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6416   if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6417     return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6418
6419   // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6420   // should have been folded away previously and not enter in here.
6421   Value *Result;
6422   if (isSignedCmp) {
6423     // We're performing a signed comparison.
6424     if (cast<ConstantInt>(CI)->getValue().isNegative())
6425       Result = ConstantInt::getFalse();          // X < (small) --> false
6426     else
6427       Result = ConstantInt::getTrue();           // X < (large) --> true
6428   } else {
6429     // We're performing an unsigned comparison.
6430     if (isSignedExt) {
6431       // We're performing an unsigned comp with a sign extended value.
6432       // This is true if the input is >= 0. [aka >s -1]
6433       Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6434       Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6435                                    NegOne, ICI.getName()), ICI);
6436     } else {
6437       // Unsigned extend & unsigned compare -> always true.
6438       Result = ConstantInt::getTrue();
6439     }
6440   }
6441
6442   // Finally, return the value computed.
6443   if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6444       ICI.getPredicate() == ICmpInst::ICMP_SLT)
6445     return ReplaceInstUsesWith(ICI, Result);
6446
6447   assert((ICI.getPredicate()==ICmpInst::ICMP_UGT || 
6448           ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6449          "ICmp should be folded!");
6450   if (Constant *CI = dyn_cast<Constant>(Result))
6451     return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6452   return BinaryOperator::CreateNot(Result);
6453 }
6454
6455 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6456   return commonShiftTransforms(I);
6457 }
6458
6459 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6460   return commonShiftTransforms(I);
6461 }
6462
6463 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6464   if (Instruction *R = commonShiftTransforms(I))
6465     return R;
6466   
6467   Value *Op0 = I.getOperand(0);
6468   
6469   // ashr int -1, X = -1   (for any arithmetic shift rights of ~0)
6470   if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6471     if (CSI->isAllOnesValue())
6472       return ReplaceInstUsesWith(I, CSI);
6473   
6474   // See if we can turn a signed shr into an unsigned shr.
6475   if (!isa<VectorType>(I.getType()) &&
6476       MaskedValueIsZero(Op0,
6477                       APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6478     return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6479   
6480   return 0;
6481 }
6482
6483 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6484   assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6485   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6486
6487   // shl X, 0 == X and shr X, 0 == X
6488   // shl 0, X == 0 and shr 0, X == 0
6489   if (Op1 == Constant::getNullValue(Op1->getType()) ||
6490       Op0 == Constant::getNullValue(Op0->getType()))
6491     return ReplaceInstUsesWith(I, Op0);
6492   
6493   if (isa<UndefValue>(Op0)) {            
6494     if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6495       return ReplaceInstUsesWith(I, Op0);
6496     else                                    // undef << X -> 0, undef >>u X -> 0
6497       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6498   }
6499   if (isa<UndefValue>(Op1)) {
6500     if (I.getOpcode() == Instruction::AShr)  // X >>s undef -> X
6501       return ReplaceInstUsesWith(I, Op0);          
6502     else                                     // X << undef, X >>u undef -> 0
6503       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6504   }
6505
6506   // Try to fold constant and into select arguments.
6507   if (isa<Constant>(Op0))
6508     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6509       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6510         return R;
6511
6512   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6513     if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6514       return Res;
6515   return 0;
6516 }
6517
6518 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6519                                                BinaryOperator &I) {
6520   bool isLeftShift    = I.getOpcode() == Instruction::Shl;
6521
6522   // See if we can simplify any instructions used by the instruction whose sole 
6523   // purpose is to compute bits we don't care about.
6524   uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6525   APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6526   if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6527                            KnownZero, KnownOne))
6528     return &I;
6529   
6530   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6531   // of a signed value.
6532   //
6533   if (Op1->uge(TypeBits)) {
6534     if (I.getOpcode() != Instruction::AShr)
6535       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6536     else {
6537       I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6538       return &I;
6539     }
6540   }
6541   
6542   // ((X*C1) << C2) == (X * (C1 << C2))
6543   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6544     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6545       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6546         return BinaryOperator::CreateMul(BO->getOperand(0),
6547                                          ConstantExpr::getShl(BOOp, Op1));
6548   
6549   // Try to fold constant and into select arguments.
6550   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6551     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6552       return R;
6553   if (isa<PHINode>(Op0))
6554     if (Instruction *NV = FoldOpIntoPhi(I))
6555       return NV;
6556   
6557   // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6558   if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6559     Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6560     // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6561     // place.  Don't try to do this transformation in this case.  Also, we
6562     // require that the input operand is a shift-by-constant so that we have
6563     // confidence that the shifts will get folded together.  We could do this
6564     // xform in more cases, but it is unlikely to be profitable.
6565     if (TrOp && I.isLogicalShift() && TrOp->isShift() && 
6566         isa<ConstantInt>(TrOp->getOperand(1))) {
6567       // Okay, we'll do this xform.  Make the shift of shift.
6568       Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6569       Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6570                                                 I.getName());
6571       InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6572
6573       // For logical shifts, the truncation has the effect of making the high
6574       // part of the register be zeros.  Emulate this by inserting an AND to
6575       // clear the top bits as needed.  This 'and' will usually be zapped by
6576       // other xforms later if dead.
6577       unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6578       unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6579       APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6580       
6581       // The mask we constructed says what the trunc would do if occurring
6582       // between the shifts.  We want to know the effect *after* the second
6583       // shift.  We know that it is a logical shift by a constant, so adjust the
6584       // mask as appropriate.
6585       if (I.getOpcode() == Instruction::Shl)
6586         MaskV <<= Op1->getZExtValue();
6587       else {
6588         assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6589         MaskV = MaskV.lshr(Op1->getZExtValue());
6590       }
6591
6592       Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6593                                                    TI->getName());
6594       InsertNewInstBefore(And, I); // shift1 & 0x00FF
6595
6596       // Return the value truncated to the interesting size.
6597       return new TruncInst(And, I.getType());
6598     }
6599   }
6600   
6601   if (Op0->hasOneUse()) {
6602     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6603       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6604       Value *V1, *V2;
6605       ConstantInt *CC;
6606       switch (Op0BO->getOpcode()) {
6607         default: break;
6608         case Instruction::Add:
6609         case Instruction::And:
6610         case Instruction::Or:
6611         case Instruction::Xor: {
6612           // These operators commute.
6613           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
6614           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6615               match(Op0BO->getOperand(1),
6616                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6617             Instruction *YS = BinaryOperator::CreateShl(
6618                                             Op0BO->getOperand(0), Op1,
6619                                             Op0BO->getName());
6620             InsertNewInstBefore(YS, I); // (Y << C)
6621             Instruction *X = 
6622               BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6623                                      Op0BO->getOperand(1)->getName());
6624             InsertNewInstBefore(X, I);  // (X + (Y << C))
6625             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6626             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6627                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6628           }
6629           
6630           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
6631           Value *Op0BOOp1 = Op0BO->getOperand(1);
6632           if (isLeftShift && Op0BOOp1->hasOneUse() &&
6633               match(Op0BOOp1, 
6634                     m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6635               cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6636               V2 == Op1) {
6637             Instruction *YS = BinaryOperator::CreateShl(
6638                                                      Op0BO->getOperand(0), Op1,
6639                                                      Op0BO->getName());
6640             InsertNewInstBefore(YS, I); // (Y << C)
6641             Instruction *XM =
6642               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6643                                         V1->getName()+".mask");
6644             InsertNewInstBefore(XM, I); // X & (CC << C)
6645             
6646             return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6647           }
6648         }
6649           
6650         // FALL THROUGH.
6651         case Instruction::Sub: {
6652           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
6653           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6654               match(Op0BO->getOperand(0),
6655                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6656             Instruction *YS = BinaryOperator::CreateShl(
6657                                                      Op0BO->getOperand(1), Op1,
6658                                                      Op0BO->getName());
6659             InsertNewInstBefore(YS, I); // (Y << C)
6660             Instruction *X =
6661               BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6662                                      Op0BO->getOperand(0)->getName());
6663             InsertNewInstBefore(X, I);  // (X + (Y << C))
6664             uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6665             return BinaryOperator::CreateAnd(X, ConstantInt::get(
6666                        APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6667           }
6668           
6669           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
6670           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6671               match(Op0BO->getOperand(0),
6672                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
6673                           m_ConstantInt(CC))) && V2 == Op1 &&
6674               cast<BinaryOperator>(Op0BO->getOperand(0))
6675                   ->getOperand(0)->hasOneUse()) {
6676             Instruction *YS = BinaryOperator::CreateShl(
6677                                                      Op0BO->getOperand(1), Op1,
6678                                                      Op0BO->getName());
6679             InsertNewInstBefore(YS, I); // (Y << C)
6680             Instruction *XM =
6681               BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6682                                         V1->getName()+".mask");
6683             InsertNewInstBefore(XM, I); // X & (CC << C)
6684             
6685             return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6686           }
6687           
6688           break;
6689         }
6690       }
6691       
6692       
6693       // If the operand is an bitwise operator with a constant RHS, and the
6694       // shift is the only use, we can pull it out of the shift.
6695       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6696         bool isValid = true;     // Valid only for And, Or, Xor
6697         bool highBitSet = false; // Transform if high bit of constant set?
6698         
6699         switch (Op0BO->getOpcode()) {
6700           default: isValid = false; break;   // Do not perform transform!
6701           case Instruction::Add:
6702             isValid = isLeftShift;
6703             break;
6704           case Instruction::Or:
6705           case Instruction::Xor:
6706             highBitSet = false;
6707             break;
6708           case Instruction::And:
6709             highBitSet = true;
6710             break;
6711         }
6712         
6713         // If this is a signed shift right, and the high bit is modified
6714         // by the logical operation, do not perform the transformation.
6715         // The highBitSet boolean indicates the value of the high bit of
6716         // the constant which would cause it to be modified for this
6717         // operation.
6718         //
6719         if (isValid && I.getOpcode() == Instruction::AShr)
6720           isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6721         
6722         if (isValid) {
6723           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6724           
6725           Instruction *NewShift =
6726             BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6727           InsertNewInstBefore(NewShift, I);
6728           NewShift->takeName(Op0BO);
6729           
6730           return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6731                                         NewRHS);
6732         }
6733       }
6734     }
6735   }
6736   
6737   // Find out if this is a shift of a shift by a constant.
6738   BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6739   if (ShiftOp && !ShiftOp->isShift())
6740     ShiftOp = 0;
6741   
6742   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6743     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6744     uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6745     uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6746     assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6747     if (ShiftAmt1 == 0) return 0;  // Will be simplified in the future.
6748     Value *X = ShiftOp->getOperand(0);
6749     
6750     uint32_t AmtSum = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
6751     if (AmtSum > TypeBits)
6752       AmtSum = TypeBits;
6753     
6754     const IntegerType *Ty = cast<IntegerType>(I.getType());
6755     
6756     // Check for (X << c1) << c2  and  (X >> c1) >> c2
6757     if (I.getOpcode() == ShiftOp->getOpcode()) {
6758       return BinaryOperator::Create(I.getOpcode(), X,
6759                                     ConstantInt::get(Ty, AmtSum));
6760     } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6761                I.getOpcode() == Instruction::AShr) {
6762       // ((X >>u C1) >>s C2) -> (X >>u (C1+C2))  since C1 != 0.
6763       return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6764     } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6765                I.getOpcode() == Instruction::LShr) {
6766       // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6767       Instruction *Shift =
6768         BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6769       InsertNewInstBefore(Shift, I);
6770
6771       APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6772       return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6773     }
6774     
6775     // Okay, if we get here, one shift must be left, and the other shift must be
6776     // right.  See if the amounts are equal.
6777     if (ShiftAmt1 == ShiftAmt2) {
6778       // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6779       if (I.getOpcode() == Instruction::Shl) {
6780         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6781         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6782       }
6783       // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6784       if (I.getOpcode() == Instruction::LShr) {
6785         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6786         return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6787       }
6788       // We can simplify ((X << C) >>s C) into a trunc + sext.
6789       // NOTE: we could do this for any C, but that would make 'unusual' integer
6790       // types.  For now, just stick to ones well-supported by the code
6791       // generators.
6792       const Type *SExtType = 0;
6793       switch (Ty->getBitWidth() - ShiftAmt1) {
6794       case 1  :
6795       case 8  :
6796       case 16 :
6797       case 32 :
6798       case 64 :
6799       case 128:
6800         SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6801         break;
6802       default: break;
6803       }
6804       if (SExtType) {
6805         Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6806         InsertNewInstBefore(NewTrunc, I);
6807         return new SExtInst(NewTrunc, Ty);
6808       }
6809       // Otherwise, we can't handle it yet.
6810     } else if (ShiftAmt1 < ShiftAmt2) {
6811       uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6812       
6813       // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6814       if (I.getOpcode() == Instruction::Shl) {
6815         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6816                ShiftOp->getOpcode() == Instruction::AShr);
6817         Instruction *Shift =
6818           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6819         InsertNewInstBefore(Shift, I);
6820         
6821         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6822         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6823       }
6824       
6825       // (X << C1) >>u C2  --> X >>u (C2-C1) & (-1 >> C2)
6826       if (I.getOpcode() == Instruction::LShr) {
6827         assert(ShiftOp->getOpcode() == Instruction::Shl);
6828         Instruction *Shift =
6829           BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6830         InsertNewInstBefore(Shift, I);
6831         
6832         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6833         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6834       }
6835       
6836       // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6837     } else {
6838       assert(ShiftAmt2 < ShiftAmt1);
6839       uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6840
6841       // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6842       if (I.getOpcode() == Instruction::Shl) {
6843         assert(ShiftOp->getOpcode() == Instruction::LShr ||
6844                ShiftOp->getOpcode() == Instruction::AShr);
6845         Instruction *Shift =
6846           BinaryOperator::Create(ShiftOp->getOpcode(), X,
6847                                  ConstantInt::get(Ty, ShiftDiff));
6848         InsertNewInstBefore(Shift, I);
6849         
6850         APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6851         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6852       }
6853       
6854       // (X << C1) >>u C2  --> X << (C1-C2) & (-1 >> C2)
6855       if (I.getOpcode() == Instruction::LShr) {
6856         assert(ShiftOp->getOpcode() == Instruction::Shl);
6857         Instruction *Shift =
6858           BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6859         InsertNewInstBefore(Shift, I);
6860         
6861         APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6862         return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6863       }
6864       
6865       // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6866     }
6867   }
6868   return 0;
6869 }
6870
6871
6872 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6873 /// expression.  If so, decompose it, returning some value X, such that Val is
6874 /// X*Scale+Offset.
6875 ///
6876 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6877                                         int &Offset) {
6878   assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6879   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6880     Offset = CI->getZExtValue();
6881     Scale  = 0;
6882     return ConstantInt::get(Type::Int32Ty, 0);
6883   } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6884     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6885       if (I->getOpcode() == Instruction::Shl) {
6886         // This is a value scaled by '1 << the shift amt'.
6887         Scale = 1U << RHS->getZExtValue();
6888         Offset = 0;
6889         return I->getOperand(0);
6890       } else if (I->getOpcode() == Instruction::Mul) {
6891         // This value is scaled by 'RHS'.
6892         Scale = RHS->getZExtValue();
6893         Offset = 0;
6894         return I->getOperand(0);
6895       } else if (I->getOpcode() == Instruction::Add) {
6896         // We have X+C.  Check to see if we really have (X*C2)+C1, 
6897         // where C1 is divisible by C2.
6898         unsigned SubScale;
6899         Value *SubVal = 
6900           DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6901         Offset += RHS->getZExtValue();
6902         Scale = SubScale;
6903         return SubVal;
6904       }
6905     }
6906   }
6907
6908   // Otherwise, we can't look past this.
6909   Scale = 1;
6910   Offset = 0;
6911   return Val;
6912 }
6913
6914
6915 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6916 /// try to eliminate the cast by moving the type information into the alloc.
6917 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6918                                                    AllocationInst &AI) {
6919   const PointerType *PTy = cast<PointerType>(CI.getType());
6920   
6921   // Remove any uses of AI that are dead.
6922   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6923   
6924   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6925     Instruction *User = cast<Instruction>(*UI++);
6926     if (isInstructionTriviallyDead(User)) {
6927       while (UI != E && *UI == User)
6928         ++UI; // If this instruction uses AI more than once, don't break UI.
6929       
6930       ++NumDeadInst;
6931       DOUT << "IC: DCE: " << *User;
6932       EraseInstFromFunction(*User);
6933     }
6934   }
6935   
6936   // Get the type really allocated and the type casted to.
6937   const Type *AllocElTy = AI.getAllocatedType();
6938   const Type *CastElTy = PTy->getElementType();
6939   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6940
6941   unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6942   unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6943   if (CastElTyAlign < AllocElTyAlign) return 0;
6944
6945   // If the allocation has multiple uses, only promote it if we are strictly
6946   // increasing the alignment of the resultant allocation.  If we keep it the
6947   // same, we open the door to infinite loops of various kinds.
6948   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6949
6950   uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6951   uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6952   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6953
6954   // See if we can satisfy the modulus by pulling a scale out of the array
6955   // size argument.
6956   unsigned ArraySizeScale;
6957   int ArrayOffset;
6958   Value *NumElements = // See if the array size is a decomposable linear expr.
6959     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6960  
6961   // If we can now satisfy the modulus, by using a non-1 scale, we really can
6962   // do the xform.
6963   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6964       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
6965
6966   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6967   Value *Amt = 0;
6968   if (Scale == 1) {
6969     Amt = NumElements;
6970   } else {
6971     // If the allocation size is constant, form a constant mul expression
6972     Amt = ConstantInt::get(Type::Int32Ty, Scale);
6973     if (isa<ConstantInt>(NumElements))
6974       Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6975     // otherwise multiply the amount and the number of elements
6976     else if (Scale != 1) {
6977       Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6978       Amt = InsertNewInstBefore(Tmp, AI);
6979     }
6980   }
6981   
6982   if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6983     Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6984     Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6985     Amt = InsertNewInstBefore(Tmp, AI);
6986   }
6987   
6988   AllocationInst *New;
6989   if (isa<MallocInst>(AI))
6990     New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6991   else
6992     New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6993   InsertNewInstBefore(New, AI);
6994   New->takeName(&AI);
6995   
6996   // If the allocation has multiple uses, insert a cast and change all things
6997   // that used it to use the new cast.  This will also hack on CI, but it will
6998   // die soon.
6999   if (!AI.hasOneUse()) {
7000     AddUsesToWorkList(AI);
7001     // New is the allocation instruction, pointer typed. AI is the original
7002     // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7003     CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7004     InsertNewInstBefore(NewCast, AI);
7005     AI.replaceAllUsesWith(NewCast);
7006   }
7007   return ReplaceInstUsesWith(CI, New);
7008 }
7009
7010 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7011 /// and return it as type Ty without inserting any new casts and without
7012 /// changing the computed value.  This is used by code that tries to decide
7013 /// whether promoting or shrinking integer operations to wider or smaller types
7014 /// will allow us to eliminate a truncate or extend.
7015 ///
7016 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7017 /// extension operation if Ty is larger.
7018 ///
7019 /// If CastOpc is a truncation, then Ty will be a type smaller than V.  We
7020 /// should return true if trunc(V) can be computed by computing V in the smaller
7021 /// type.  If V is an instruction, then trunc(inst(x,y)) can be computed as
7022 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7023 /// efficiently truncated.
7024 ///
7025 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7026 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7027 /// the final result.
7028 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7029                                               unsigned CastOpc,
7030                                               int &NumCastsRemoved) {
7031   // We can always evaluate constants in another type.
7032   if (isa<ConstantInt>(V))
7033     return true;
7034   
7035   Instruction *I = dyn_cast<Instruction>(V);
7036   if (!I) return false;
7037   
7038   const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7039   
7040   // If this is an extension or truncate, we can often eliminate it.
7041   if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7042     // If this is a cast from the destination type, we can trivially eliminate
7043     // it, and this will remove a cast overall.
7044     if (I->getOperand(0)->getType() == Ty) {
7045       // If the first operand is itself a cast, and is eliminable, do not count
7046       // this as an eliminable cast.  We would prefer to eliminate those two
7047       // casts first.
7048       if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7049         ++NumCastsRemoved;
7050       return true;
7051     }
7052   }
7053
7054   // We can't extend or shrink something that has multiple uses: doing so would
7055   // require duplicating the instruction in general, which isn't profitable.
7056   if (!I->hasOneUse()) return false;
7057
7058   switch (I->getOpcode()) {
7059   case Instruction::Add:
7060   case Instruction::Sub:
7061   case Instruction::Mul:
7062   case Instruction::And:
7063   case Instruction::Or:
7064   case Instruction::Xor:
7065     // These operators can all arbitrarily be extended or truncated.
7066     return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7067                                       NumCastsRemoved) &&
7068            CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7069                                       NumCastsRemoved);
7070
7071   case Instruction::Shl:
7072     // If we are truncating the result of this SHL, and if it's a shift of a
7073     // constant amount, we can always perform a SHL in a smaller type.
7074     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7075       uint32_t BitWidth = Ty->getBitWidth();
7076       if (BitWidth < OrigTy->getBitWidth() && 
7077           CI->getLimitedValue(BitWidth) < BitWidth)
7078         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7079                                           NumCastsRemoved);
7080     }
7081     break;
7082   case Instruction::LShr:
7083     // If this is a truncate of a logical shr, we can truncate it to a smaller
7084     // lshr iff we know that the bits we would otherwise be shifting in are
7085     // already zeros.
7086     if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7087       uint32_t OrigBitWidth = OrigTy->getBitWidth();
7088       uint32_t BitWidth = Ty->getBitWidth();
7089       if (BitWidth < OrigBitWidth &&
7090           MaskedValueIsZero(I->getOperand(0),
7091             APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7092           CI->getLimitedValue(BitWidth) < BitWidth) {
7093         return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7094                                           NumCastsRemoved);
7095       }
7096     }
7097     break;
7098   case Instruction::ZExt:
7099   case Instruction::SExt:
7100   case Instruction::Trunc:
7101     // If this is the same kind of case as our original (e.g. zext+zext), we
7102     // can safely replace it.  Note that replacing it does not reduce the number
7103     // of casts in the input.
7104     if (I->getOpcode() == CastOpc)
7105       return true;
7106     break;
7107   case Instruction::Select: {
7108     SelectInst *SI = cast<SelectInst>(I);
7109     return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7110                                       NumCastsRemoved) &&
7111            CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7112                                       NumCastsRemoved);
7113   }
7114   case Instruction::PHI: {
7115     // We can change a phi if we can change all operands.
7116     PHINode *PN = cast<PHINode>(I);
7117     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7118       if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7119                                       NumCastsRemoved))
7120         return false;
7121     return true;
7122   }
7123   default:
7124     // TODO: Can handle more cases here.
7125     break;
7126   }
7127   
7128   return false;
7129 }
7130
7131 /// EvaluateInDifferentType - Given an expression that 
7132 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7133 /// evaluate the expression.
7134 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty, 
7135                                              bool isSigned) {
7136   if (Constant *C = dyn_cast<Constant>(V))
7137     return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7138
7139   // Otherwise, it must be an instruction.
7140   Instruction *I = cast<Instruction>(V);
7141   Instruction *Res = 0;
7142   switch (I->getOpcode()) {
7143   case Instruction::Add:
7144   case Instruction::Sub:
7145   case Instruction::Mul:
7146   case Instruction::And:
7147   case Instruction::Or:
7148   case Instruction::Xor:
7149   case Instruction::AShr:
7150   case Instruction::LShr:
7151   case Instruction::Shl: {
7152     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7153     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7154     Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7155                                  LHS, RHS);
7156     break;
7157   }    
7158   case Instruction::Trunc:
7159   case Instruction::ZExt:
7160   case Instruction::SExt:
7161     // If the source type of the cast is the type we're trying for then we can
7162     // just return the source.  There's no need to insert it because it is not
7163     // new.
7164     if (I->getOperand(0)->getType() == Ty)
7165       return I->getOperand(0);
7166     
7167     // Otherwise, must be the same type of cast, so just reinsert a new one.
7168     Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7169                            Ty);
7170     break;
7171   case Instruction::Select: {
7172     Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7173     Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7174     Res = SelectInst::Create(I->getOperand(0), True, False);
7175     break;
7176   }
7177   case Instruction::PHI: {
7178     PHINode *OPN = cast<PHINode>(I);
7179     PHINode *NPN = PHINode::Create(Ty);
7180     for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7181       Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7182       NPN->addIncoming(V, OPN->getIncomingBlock(i));
7183     }
7184     Res = NPN;
7185     break;
7186   }
7187   default: 
7188     // TODO: Can handle more cases here.
7189     assert(0 && "Unreachable!");
7190     break;
7191   }
7192   
7193   Res->takeName(I);
7194   return InsertNewInstBefore(Res, *I);
7195 }
7196
7197 /// @brief Implement the transforms common to all CastInst visitors.
7198 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7199   Value *Src = CI.getOperand(0);
7200
7201   // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7202   // eliminate it now.
7203   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7204     if (Instruction::CastOps opc = 
7205         isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7206       // The first cast (CSrc) is eliminable so we need to fix up or replace
7207       // the second cast (CI). CSrc will then have a good chance of being dead.
7208       return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7209     }
7210   }
7211
7212   // If we are casting a select then fold the cast into the select
7213   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7214     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7215       return NV;
7216
7217   // If we are casting a PHI then fold the cast into the PHI
7218   if (isa<PHINode>(Src))
7219     if (Instruction *NV = FoldOpIntoPhi(CI))
7220       return NV;
7221   
7222   return 0;
7223 }
7224
7225 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7226 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7227   Value *Src = CI.getOperand(0);
7228   
7229   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7230     // If casting the result of a getelementptr instruction with no offset, turn
7231     // this into a cast of the original pointer!
7232     if (GEP->hasAllZeroIndices()) {
7233       // Changing the cast operand is usually not a good idea but it is safe
7234       // here because the pointer operand is being replaced with another 
7235       // pointer operand so the opcode doesn't need to change.
7236       AddToWorkList(GEP);
7237       CI.setOperand(0, GEP->getOperand(0));
7238       return &CI;
7239     }
7240     
7241     // If the GEP has a single use, and the base pointer is a bitcast, and the
7242     // GEP computes a constant offset, see if we can convert these three
7243     // instructions into fewer.  This typically happens with unions and other
7244     // non-type-safe code.
7245     if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7246       if (GEP->hasAllConstantIndices()) {
7247         // We are guaranteed to get a constant from EmitGEPOffset.
7248         ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7249         int64_t Offset = OffsetV->getSExtValue();
7250         
7251         // Get the base pointer input of the bitcast, and the type it points to.
7252         Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7253         const Type *GEPIdxTy =
7254           cast<PointerType>(OrigBase->getType())->getElementType();
7255         if (GEPIdxTy->isSized()) {
7256           SmallVector<Value*, 8> NewIndices;
7257           
7258           // Start with the index over the outer type.  Note that the type size
7259           // might be zero (even if the offset isn't zero) if the indexed type
7260           // is something like [0 x {int, int}]
7261           const Type *IntPtrTy = TD->getIntPtrType();
7262           int64_t FirstIdx = 0;
7263           if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7264             FirstIdx = Offset/TySize;
7265             Offset %= TySize;
7266           
7267             // Handle silly modulus not returning values values [0..TySize).
7268             if (Offset < 0) {
7269               --FirstIdx;
7270               Offset += TySize;
7271               assert(Offset >= 0);
7272             }
7273             assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7274           }
7275           
7276           NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7277
7278           // Index into the types.  If we fail, set OrigBase to null.
7279           while (Offset) {
7280             if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7281               const StructLayout *SL = TD->getStructLayout(STy);
7282               if (Offset < (int64_t)SL->getSizeInBytes()) {
7283                 unsigned Elt = SL->getElementContainingOffset(Offset);
7284                 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7285               
7286                 Offset -= SL->getElementOffset(Elt);
7287                 GEPIdxTy = STy->getElementType(Elt);
7288               } else {
7289                 // Otherwise, we can't index into this, bail out.
7290                 Offset = 0;
7291                 OrigBase = 0;
7292               }
7293             } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7294               const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7295               if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7296                 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7297                 Offset %= EltSize;
7298               } else {
7299                 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7300               }
7301               GEPIdxTy = STy->getElementType();
7302             } else {
7303               // Otherwise, we can't index into this, bail out.
7304               Offset = 0;
7305               OrigBase = 0;
7306             }
7307           }
7308           if (OrigBase) {
7309             // If we were able to index down into an element, create the GEP
7310             // and bitcast the result.  This eliminates one bitcast, potentially
7311             // two.
7312             Instruction *NGEP = GetElementPtrInst::Create(OrigBase, 
7313                                                           NewIndices.begin(),
7314                                                           NewIndices.end(), "");
7315             InsertNewInstBefore(NGEP, CI);
7316             NGEP->takeName(GEP);
7317             
7318             if (isa<BitCastInst>(CI))
7319               return new BitCastInst(NGEP, CI.getType());
7320             assert(isa<PtrToIntInst>(CI));
7321             return new PtrToIntInst(NGEP, CI.getType());
7322           }
7323         }
7324       }      
7325     }
7326   }
7327     
7328   return commonCastTransforms(CI);
7329 }
7330
7331
7332
7333 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7334 /// integer types. This function implements the common transforms for all those
7335 /// cases.
7336 /// @brief Implement the transforms common to CastInst with integer operands
7337 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7338   if (Instruction *Result = commonCastTransforms(CI))
7339     return Result;
7340
7341   Value *Src = CI.getOperand(0);
7342   const Type *SrcTy = Src->getType();
7343   const Type *DestTy = CI.getType();
7344   uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7345   uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7346
7347   // See if we can simplify any instructions used by the LHS whose sole 
7348   // purpose is to compute bits we don't care about.
7349   APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7350   if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7351                            KnownZero, KnownOne))
7352     return &CI;
7353
7354   // If the source isn't an instruction or has more than one use then we
7355   // can't do anything more. 
7356   Instruction *SrcI = dyn_cast<Instruction>(Src);
7357   if (!SrcI || !Src->hasOneUse())
7358     return 0;
7359
7360   // Attempt to propagate the cast into the instruction for int->int casts.
7361   int NumCastsRemoved = 0;
7362   if (!isa<BitCastInst>(CI) &&
7363       CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7364                                  CI.getOpcode(), NumCastsRemoved)) {
7365     // If this cast is a truncate, evaluting in a different type always
7366     // eliminates the cast, so it is always a win.  If this is a zero-extension,
7367     // we need to do an AND to maintain the clear top-part of the computation,
7368     // so we require that the input have eliminated at least one cast.  If this
7369     // is a sign extension, we insert two new casts (to do the extension) so we
7370     // require that two casts have been eliminated.
7371     bool DoXForm;
7372     switch (CI.getOpcode()) {
7373     default:
7374       // All the others use floating point so we shouldn't actually 
7375       // get here because of the check above.
7376       assert(0 && "Unknown cast type");
7377     case Instruction::Trunc:
7378       DoXForm = true;
7379       break;
7380     case Instruction::ZExt:
7381       DoXForm = NumCastsRemoved >= 1;
7382       break;
7383     case Instruction::SExt:
7384       DoXForm = NumCastsRemoved >= 2;
7385       break;
7386     }
7387     
7388     if (DoXForm) {
7389       Value *Res = EvaluateInDifferentType(SrcI, DestTy, 
7390                                            CI.getOpcode() == Instruction::SExt);
7391       assert(Res->getType() == DestTy);
7392       switch (CI.getOpcode()) {
7393       default: assert(0 && "Unknown cast type!");
7394       case Instruction::Trunc:
7395       case Instruction::BitCast:
7396         // Just replace this cast with the result.
7397         return ReplaceInstUsesWith(CI, Res);
7398       case Instruction::ZExt: {
7399         // We need to emit an AND to clear the high bits.
7400         assert(SrcBitSize < DestBitSize && "Not a zext?");
7401         Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7402                                                             SrcBitSize));
7403         return BinaryOperator::CreateAnd(Res, C);
7404       }
7405       case Instruction::SExt:
7406         // We need to emit a cast to truncate, then a cast to sext.
7407         return CastInst::Create(Instruction::SExt,
7408             InsertCastBefore(Instruction::Trunc, Res, Src->getType(), 
7409                              CI), DestTy);
7410       }
7411     }
7412   }
7413   
7414   Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7415   Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7416
7417   switch (SrcI->getOpcode()) {
7418   case Instruction::Add:
7419   case Instruction::Mul:
7420   case Instruction::And:
7421   case Instruction::Or:
7422   case Instruction::Xor:
7423     // If we are discarding information, rewrite.
7424     if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7425       // Don't insert two casts if they cannot be eliminated.  We allow 
7426       // two casts to be inserted if the sizes are the same.  This could 
7427       // only be converting signedness, which is a noop.
7428       if (DestBitSize == SrcBitSize || 
7429           !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7430           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7431         Instruction::CastOps opcode = CI.getOpcode();
7432         Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7433         Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7434         return BinaryOperator::Create(
7435             cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7436       }
7437     }
7438
7439     // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
7440     if (isa<ZExtInst>(CI) && SrcBitSize == 1 && 
7441         SrcI->getOpcode() == Instruction::Xor &&
7442         Op1 == ConstantInt::getTrue() &&
7443         (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7444       Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7445       return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7446     }
7447     break;
7448   case Instruction::SDiv:
7449   case Instruction::UDiv:
7450   case Instruction::SRem:
7451   case Instruction::URem:
7452     // If we are just changing the sign, rewrite.
7453     if (DestBitSize == SrcBitSize) {
7454       // Don't insert two casts if they cannot be eliminated.  We allow 
7455       // two casts to be inserted if the sizes are the same.  This could 
7456       // only be converting signedness, which is a noop.
7457       if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) || 
7458           !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7459         Value *Op0c = InsertOperandCastBefore(Instruction::BitCast, 
7460                                               Op0, DestTy, SrcI);
7461         Value *Op1c = InsertOperandCastBefore(Instruction::BitCast, 
7462                                               Op1, DestTy, SrcI);
7463         return BinaryOperator::Create(
7464           cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7465       }
7466     }
7467     break;
7468
7469   case Instruction::Shl:
7470     // Allow changing the sign of the source operand.  Do not allow 
7471     // changing the size of the shift, UNLESS the shift amount is a 
7472     // constant.  We must not change variable sized shifts to a smaller 
7473     // size, because it is undefined to shift more bits out than exist 
7474     // in the value.
7475     if (DestBitSize == SrcBitSize ||
7476         (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7477       Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7478           Instruction::BitCast : Instruction::Trunc);
7479       Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7480       Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7481       return BinaryOperator::CreateShl(Op0c, Op1c);
7482     }
7483     break;
7484   case Instruction::AShr:
7485     // If this is a signed shr, and if all bits shifted in are about to be
7486     // truncated off, turn it into an unsigned shr to allow greater
7487     // simplifications.
7488     if (DestBitSize < SrcBitSize &&
7489         isa<ConstantInt>(Op1)) {
7490       uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7491       if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7492         // Insert the new logical shift right.
7493         return BinaryOperator::CreateLShr(Op0, Op1);
7494       }
7495     }
7496     break;
7497   }
7498   return 0;
7499 }
7500
7501 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7502   if (Instruction *Result = commonIntCastTransforms(CI))
7503     return Result;
7504   
7505   Value *Src = CI.getOperand(0);
7506   const Type *Ty = CI.getType();
7507   uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7508   uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7509   
7510   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7511     switch (SrcI->getOpcode()) {
7512     default: break;
7513     case Instruction::LShr:
7514       // We can shrink lshr to something smaller if we know the bits shifted in
7515       // are already zeros.
7516       if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7517         uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7518         
7519         // Get a mask for the bits shifting in.
7520         APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7521         Value* SrcIOp0 = SrcI->getOperand(0);
7522         if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7523           if (ShAmt >= DestBitWidth)        // All zeros.
7524             return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7525
7526           // Okay, we can shrink this.  Truncate the input, then return a new
7527           // shift.
7528           Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7529           Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7530                                        Ty, CI);
7531           return BinaryOperator::CreateLShr(V1, V2);
7532         }
7533       } else {     // This is a variable shr.
7534         
7535         // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'.  This is
7536         // more LLVM instructions, but allows '1 << Y' to be hoisted if
7537         // loop-invariant and CSE'd.
7538         if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7539           Value *One = ConstantInt::get(SrcI->getType(), 1);
7540
7541           Value *V = InsertNewInstBefore(
7542               BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7543                                      "tmp"), CI);
7544           V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7545                                                             SrcI->getOperand(0),
7546                                                             "tmp"), CI);
7547           Value *Zero = Constant::getNullValue(V->getType());
7548           return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7549         }
7550       }
7551       break;
7552     }
7553   }
7554   
7555   return 0;
7556 }
7557
7558 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7559 /// in order to eliminate the icmp.
7560 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7561                                              bool DoXform) {
7562   // If we are just checking for a icmp eq of a single bit and zext'ing it
7563   // to an integer, then shift the bit to the appropriate place and then
7564   // cast to integer to avoid the comparison.
7565   if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7566     const APInt &Op1CV = Op1C->getValue();
7567       
7568     // zext (x <s  0) to i32 --> x>>u31      true if signbit set.
7569     // zext (x >s -1) to i32 --> (x>>u31)^1  true if signbit clear.
7570     if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7571         (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7572       if (!DoXform) return ICI;
7573
7574       Value *In = ICI->getOperand(0);
7575       Value *Sh = ConstantInt::get(In->getType(),
7576                                    In->getType()->getPrimitiveSizeInBits()-1);
7577       In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7578                                                         In->getName()+".lobit"),
7579                                CI);
7580       if (In->getType() != CI.getType())
7581         In = CastInst::CreateIntegerCast(In, CI.getType(),
7582                                          false/*ZExt*/, "tmp", &CI);
7583
7584       if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7585         Constant *One = ConstantInt::get(In->getType(), 1);
7586         In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7587                                                          In->getName()+".not"),
7588                                  CI);
7589       }
7590
7591       return ReplaceInstUsesWith(CI, In);
7592     }
7593       
7594       
7595       
7596     // zext (X == 0) to i32 --> X^1      iff X has only the low bit set.
7597     // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7598     // zext (X == 1) to i32 --> X        iff X has only the low bit set.
7599     // zext (X == 2) to i32 --> X>>1     iff X has only the 2nd bit set.
7600     // zext (X != 0) to i32 --> X        iff X has only the low bit set.
7601     // zext (X != 0) to i32 --> X>>1     iff X has only the 2nd bit set.
7602     // zext (X != 1) to i32 --> X^1      iff X has only the low bit set.
7603     // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7604     if ((Op1CV == 0 || Op1CV.isPowerOf2()) && 
7605         // This only works for EQ and NE
7606         ICI->isEquality()) {
7607       // If Op1C some other power of two, convert:
7608       uint32_t BitWidth = Op1C->getType()->getBitWidth();
7609       APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7610       APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7611       ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7612         
7613       APInt KnownZeroMask(~KnownZero);
7614       if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7615         if (!DoXform) return ICI;
7616
7617         bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7618         if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7619           // (X&4) == 2 --> false
7620           // (X&4) != 2 --> true
7621           Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7622           Res = ConstantExpr::getZExt(Res, CI.getType());
7623           return ReplaceInstUsesWith(CI, Res);
7624         }
7625           
7626         uint32_t ShiftAmt = KnownZeroMask.logBase2();
7627         Value *In = ICI->getOperand(0);
7628         if (ShiftAmt) {
7629           // Perform a logical shr by shiftamt.
7630           // Insert the shift to put the result in the low bit.
7631           In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7632                                   ConstantInt::get(In->getType(), ShiftAmt),
7633                                                    In->getName()+".lobit"), CI);
7634         }
7635           
7636         if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7637           Constant *One = ConstantInt::get(In->getType(), 1);
7638           In = BinaryOperator::CreateXor(In, One, "tmp");
7639           InsertNewInstBefore(cast<Instruction>(In), CI);
7640         }
7641           
7642         if (CI.getType() == In->getType())
7643           return ReplaceInstUsesWith(CI, In);
7644         else
7645           return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7646       }
7647     }
7648   }
7649
7650   return 0;
7651 }
7652
7653 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7654   // If one of the common conversion will work ..
7655   if (Instruction *Result = commonIntCastTransforms(CI))
7656     return Result;
7657
7658   Value *Src = CI.getOperand(0);
7659
7660   // If this is a cast of a cast
7661   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
7662     // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7663     // types and if the sizes are just right we can convert this into a logical
7664     // 'and' which will be much cheaper than the pair of casts.
7665     if (isa<TruncInst>(CSrc)) {
7666       // Get the sizes of the types involved
7667       Value *A = CSrc->getOperand(0);
7668       uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7669       uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7670       uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7671       // If we're actually extending zero bits and the trunc is a no-op
7672       if (MidSize < DstSize && SrcSize == DstSize) {
7673         // Replace both of the casts with an And of the type mask.
7674         APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7675         Constant *AndConst = ConstantInt::get(AndValue);
7676         Instruction *And = 
7677           BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7678         // Unfortunately, if the type changed, we need to cast it back.
7679         if (And->getType() != CI.getType()) {
7680           And->setName(CSrc->getName()+".mask");
7681           InsertNewInstBefore(And, CI);
7682           And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7683         }
7684         return And;
7685       }
7686     }
7687   }
7688
7689   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7690     return transformZExtICmp(ICI, CI);
7691
7692   BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7693   if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7694     // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7695     // of the (zext icmp) will be transformed.
7696     ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7697     ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7698     if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7699         (transformZExtICmp(LHS, CI, false) ||
7700          transformZExtICmp(RHS, CI, false))) {
7701       Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7702       Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7703       return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7704     }
7705   }
7706
7707   return 0;
7708 }
7709
7710 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7711   if (Instruction *I = commonIntCastTransforms(CI))
7712     return I;
7713   
7714   Value *Src = CI.getOperand(0);
7715   
7716   // sext (x <s 0) -> ashr x, 31   -> all ones if signed
7717   // sext (x >s -1) -> ashr x, 31  -> all ones if not signed
7718   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7719     // If we are just checking for a icmp eq of a single bit and zext'ing it
7720     // to an integer, then shift the bit to the appropriate place and then
7721     // cast to integer to avoid the comparison.
7722     if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7723       const APInt &Op1CV = Op1C->getValue();
7724       
7725       // sext (x <s  0) to i32 --> x>>s31      true if signbit set.
7726       // sext (x >s -1) to i32 --> (x>>s31)^-1  true if signbit clear.
7727       if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7728           (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7729         Value *In = ICI->getOperand(0);
7730         Value *Sh = ConstantInt::get(In->getType(),
7731                                      In->getType()->getPrimitiveSizeInBits()-1);
7732         In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7733                                                         In->getName()+".lobit"),
7734                                  CI);
7735         if (In->getType() != CI.getType())
7736           In = CastInst::CreateIntegerCast(In, CI.getType(),
7737                                            true/*SExt*/, "tmp", &CI);
7738         
7739         if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7740           In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7741                                      In->getName()+".not"), CI);
7742         
7743         return ReplaceInstUsesWith(CI, In);
7744       }
7745     }
7746   }
7747
7748   // See if the value being truncated is already sign extended.  If so, just
7749   // eliminate the trunc/sext pair.
7750   if (getOpcode(Src) == Instruction::Trunc) {
7751     Value *Op = cast<User>(Src)->getOperand(0);
7752     unsigned OpBits   = cast<IntegerType>(Op->getType())->getBitWidth();
7753     unsigned MidBits  = cast<IntegerType>(Src->getType())->getBitWidth();
7754     unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7755     unsigned NumSignBits = ComputeNumSignBits(Op);
7756
7757     if (OpBits == DestBits) {
7758       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
7759       // bits, it is already ready.
7760       if (NumSignBits > DestBits-MidBits)
7761         return ReplaceInstUsesWith(CI, Op);
7762     } else if (OpBits < DestBits) {
7763       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
7764       // bits, just sext from i32.
7765       if (NumSignBits > OpBits-MidBits)
7766         return new SExtInst(Op, CI.getType(), "tmp");
7767     } else {
7768       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
7769       // bits, just truncate to i32.
7770       if (NumSignBits > OpBits-MidBits)
7771         return new TruncInst(Op, CI.getType(), "tmp");
7772     }
7773   }
7774
7775   // If the input is a shl/ashr pair of a same constant, then this is a sign
7776   // extension from a smaller value.  If we could trust arbitrary bitwidth
7777   // integers, we could turn this into a truncate to the smaller bit and then
7778   // use a sext for the whole extension.  Since we don't, look deeper and check
7779   // for a truncate.  If the source and dest are the same type, eliminate the
7780   // trunc and extend and just do shifts.  For example, turn:
7781   //   %a = trunc i32 %i to i8
7782   //   %b = shl i8 %a, 6
7783   //   %c = ashr i8 %b, 6
7784   //   %d = sext i8 %c to i32
7785   // into:
7786   //   %a = shl i32 %i, 30
7787   //   %d = ashr i32 %a, 30
7788   Value *A = 0;
7789   ConstantInt *BA = 0, *CA = 0;
7790   if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
7791                         m_ConstantInt(CA))) &&
7792       BA == CA && isa<TruncInst>(A)) {
7793     Value *I = cast<TruncInst>(A)->getOperand(0);
7794     if (I->getType() == CI.getType()) {
7795       unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
7796       unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
7797       unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
7798       Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
7799       I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
7800                                                         CI.getName()), CI);
7801       return BinaryOperator::CreateAShr(I, ShAmtV);
7802     }
7803   }
7804   
7805   return 0;
7806 }
7807
7808 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7809 /// in the specified FP type without changing its value.
7810 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7811   APFloat F = CFP->getValueAPF();
7812   if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7813     return ConstantFP::get(F);
7814   return 0;
7815 }
7816
7817 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7818 /// through it until we get the source value.
7819 static Value *LookThroughFPExtensions(Value *V) {
7820   if (Instruction *I = dyn_cast<Instruction>(V))
7821     if (I->getOpcode() == Instruction::FPExt)
7822       return LookThroughFPExtensions(I->getOperand(0));
7823   
7824   // If this value is a constant, return the constant in the smallest FP type
7825   // that can accurately represent it.  This allows us to turn
7826   // (float)((double)X+2.0) into x+2.0f.
7827   if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7828     if (CFP->getType() == Type::PPC_FP128Ty)
7829       return V;  // No constant folding of this.
7830     // See if the value can be truncated to float and then reextended.
7831     if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7832       return V;
7833     if (CFP->getType() == Type::DoubleTy)
7834       return V;  // Won't shrink.
7835     if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7836       return V;
7837     // Don't try to shrink to various long double types.
7838   }
7839   
7840   return V;
7841 }
7842
7843 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7844   if (Instruction *I = commonCastTransforms(CI))
7845     return I;
7846   
7847   // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7848   // smaller than the destination type, we can eliminate the truncate by doing
7849   // the add as the smaller type.  This applies to add/sub/mul/div as well as
7850   // many builtins (sqrt, etc).
7851   BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7852   if (OpI && OpI->hasOneUse()) {
7853     switch (OpI->getOpcode()) {
7854     default: break;
7855     case Instruction::Add:
7856     case Instruction::Sub:
7857     case Instruction::Mul:
7858     case Instruction::FDiv:
7859     case Instruction::FRem:
7860       const Type *SrcTy = OpI->getType();
7861       Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7862       Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7863       if (LHSTrunc->getType() != SrcTy && 
7864           RHSTrunc->getType() != SrcTy) {
7865         unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7866         // If the source types were both smaller than the destination type of
7867         // the cast, do this xform.
7868         if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7869             RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7870           LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7871                                       CI.getType(), CI);
7872           RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7873                                       CI.getType(), CI);
7874           return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7875         }
7876       }
7877       break;  
7878     }
7879   }
7880   return 0;
7881 }
7882
7883 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7884   return commonCastTransforms(CI);
7885 }
7886
7887 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7888   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7889   if (OpI == 0)
7890     return commonCastTransforms(FI);
7891
7892   // fptoui(uitofp(X)) --> X
7893   // fptoui(sitofp(X)) --> X
7894   // This is safe if the intermediate type has enough bits in its mantissa to
7895   // accurately represent all values of X.  For example, do not do this with
7896   // i64->float->i64.  This is also safe for sitofp case, because any negative
7897   // 'X' value would cause an undefined result for the fptoui. 
7898   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7899       OpI->getOperand(0)->getType() == FI.getType() &&
7900       (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7901                     OpI->getType()->getFPMantissaWidth())
7902     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7903
7904   return commonCastTransforms(FI);
7905 }
7906
7907 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7908   Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
7909   if (OpI == 0)
7910     return commonCastTransforms(FI);
7911   
7912   // fptosi(sitofp(X)) --> X
7913   // fptosi(uitofp(X)) --> X
7914   // This is safe if the intermediate type has enough bits in its mantissa to
7915   // accurately represent all values of X.  For example, do not do this with
7916   // i64->float->i64.  This is also safe for sitofp case, because any negative
7917   // 'X' value would cause an undefined result for the fptoui. 
7918   if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
7919       OpI->getOperand(0)->getType() == FI.getType() &&
7920       (int)FI.getType()->getPrimitiveSizeInBits() <= 
7921                     OpI->getType()->getFPMantissaWidth())
7922     return ReplaceInstUsesWith(FI, OpI->getOperand(0));
7923   
7924   return commonCastTransforms(FI);
7925 }
7926
7927 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7928   return commonCastTransforms(CI);
7929 }
7930
7931 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7932   return commonCastTransforms(CI);
7933 }
7934
7935 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7936   return commonPointerCastTransforms(CI);
7937 }
7938
7939 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7940   if (Instruction *I = commonCastTransforms(CI))
7941     return I;
7942   
7943   const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7944   if (!DestPointee->isSized()) return 0;
7945
7946   // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7947   ConstantInt *Cst;
7948   Value *X;
7949   if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7950                                     m_ConstantInt(Cst)))) {
7951     // If the source and destination operands have the same type, see if this
7952     // is a single-index GEP.
7953     if (X->getType() == CI.getType()) {
7954       // Get the size of the pointee type.
7955       uint64_t Size = TD->getABITypeSize(DestPointee);
7956
7957       // Convert the constant to intptr type.
7958       APInt Offset = Cst->getValue();
7959       Offset.sextOrTrunc(TD->getPointerSizeInBits());
7960
7961       // If Offset is evenly divisible by Size, we can do this xform.
7962       if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7963         Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7964         return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7965       }
7966     }
7967     // TODO: Could handle other cases, e.g. where add is indexing into field of
7968     // struct etc.
7969   } else if (CI.getOperand(0)->hasOneUse() &&
7970              match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7971     // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7972     // "inttoptr+GEP" instead of "add+intptr".
7973     
7974     // Get the size of the pointee type.
7975     uint64_t Size = TD->getABITypeSize(DestPointee);
7976     
7977     // Convert the constant to intptr type.
7978     APInt Offset = Cst->getValue();
7979     Offset.sextOrTrunc(TD->getPointerSizeInBits());
7980     
7981     // If Offset is evenly divisible by Size, we can do this xform.
7982     if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7983       Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7984       
7985       Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7986                                                             "tmp"), CI);
7987       return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7988     }
7989   }
7990   return 0;
7991 }
7992
7993 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7994   // If the operands are integer typed then apply the integer transforms,
7995   // otherwise just apply the common ones.
7996   Value *Src = CI.getOperand(0);
7997   const Type *SrcTy = Src->getType();
7998   const Type *DestTy = CI.getType();
7999
8000   if (SrcTy->isInteger() && DestTy->isInteger()) {
8001     if (Instruction *Result = commonIntCastTransforms(CI))
8002       return Result;
8003   } else if (isa<PointerType>(SrcTy)) {
8004     if (Instruction *I = commonPointerCastTransforms(CI))
8005       return I;
8006   } else {
8007     if (Instruction *Result = commonCastTransforms(CI))
8008       return Result;
8009   }
8010
8011
8012   // Get rid of casts from one type to the same type. These are useless and can
8013   // be replaced by the operand.
8014   if (DestTy == Src->getType())
8015     return ReplaceInstUsesWith(CI, Src);
8016
8017   if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8018     const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8019     const Type *DstElTy = DstPTy->getElementType();
8020     const Type *SrcElTy = SrcPTy->getElementType();
8021     
8022     // If the address spaces don't match, don't eliminate the bitcast, which is
8023     // required for changing types.
8024     if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8025       return 0;
8026     
8027     // If we are casting a malloc or alloca to a pointer to a type of the same
8028     // size, rewrite the allocation instruction to allocate the "right" type.
8029     if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8030       if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8031         return V;
8032     
8033     // If the source and destination are pointers, and this cast is equivalent
8034     // to a getelementptr X, 0, 0, 0...  turn it into the appropriate gep.
8035     // This can enhance SROA and other transforms that want type-safe pointers.
8036     Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8037     unsigned NumZeros = 0;
8038     while (SrcElTy != DstElTy && 
8039            isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8040            SrcElTy->getNumContainedTypes() /* not "{}" */) {
8041       SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8042       ++NumZeros;
8043     }
8044
8045     // If we found a path from the src to dest, create the getelementptr now.
8046     if (SrcElTy == DstElTy) {
8047       SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8048       return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "", 
8049                                        ((Instruction*) NULL));
8050     }
8051   }
8052
8053   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8054     if (SVI->hasOneUse()) {
8055       // Okay, we have (bitconvert (shuffle ..)).  Check to see if this is
8056       // a bitconvert to a vector with the same # elts.
8057       if (isa<VectorType>(DestTy) && 
8058           cast<VectorType>(DestTy)->getNumElements() == 
8059                 SVI->getType()->getNumElements()) {
8060         CastInst *Tmp;
8061         // If either of the operands is a cast from CI.getType(), then
8062         // evaluating the shuffle in the casted destination's type will allow
8063         // us to eliminate at least one cast.
8064         if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
8065              Tmp->getOperand(0)->getType() == DestTy) ||
8066             ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
8067              Tmp->getOperand(0)->getType() == DestTy)) {
8068           Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8069                                                SVI->getOperand(0), DestTy, &CI);
8070           Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8071                                                SVI->getOperand(1), DestTy, &CI);
8072           // Return a new shuffle vector.  Use the same element ID's, as we
8073           // know the vector types match #elts.
8074           return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8075         }
8076       }
8077     }
8078   }
8079   return 0;
8080 }
8081
8082 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8083 ///   %C = or %A, %B
8084 ///   %D = select %cond, %C, %A
8085 /// into:
8086 ///   %C = select %cond, %B, 0
8087 ///   %D = or %A, %C
8088 ///
8089 /// Assuming that the specified instruction is an operand to the select, return
8090 /// a bitmask indicating which operands of this instruction are foldable if they
8091 /// equal the other incoming value of the select.
8092 ///
8093 static unsigned GetSelectFoldableOperands(Instruction *I) {
8094   switch (I->getOpcode()) {
8095   case Instruction::Add:
8096   case Instruction::Mul:
8097   case Instruction::And:
8098   case Instruction::Or:
8099   case Instruction::Xor:
8100     return 3;              // Can fold through either operand.
8101   case Instruction::Sub:   // Can only fold on the amount subtracted.
8102   case Instruction::Shl:   // Can only fold on the shift amount.
8103   case Instruction::LShr:
8104   case Instruction::AShr:
8105     return 1;
8106   default:
8107     return 0;              // Cannot fold
8108   }
8109 }
8110
8111 /// GetSelectFoldableConstant - For the same transformation as the previous
8112 /// function, return the identity constant that goes into the select.
8113 static Constant *GetSelectFoldableConstant(Instruction *I) {
8114   switch (I->getOpcode()) {
8115   default: assert(0 && "This cannot happen!"); abort();
8116   case Instruction::Add:
8117   case Instruction::Sub:
8118   case Instruction::Or:
8119   case Instruction::Xor:
8120   case Instruction::Shl:
8121   case Instruction::LShr:
8122   case Instruction::AShr:
8123     return Constant::getNullValue(I->getType());
8124   case Instruction::And:
8125     return Constant::getAllOnesValue(I->getType());
8126   case Instruction::Mul:
8127     return ConstantInt::get(I->getType(), 1);
8128   }
8129 }
8130
8131 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8132 /// have the same opcode and only one use each.  Try to simplify this.
8133 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8134                                           Instruction *FI) {
8135   if (TI->getNumOperands() == 1) {
8136     // If this is a non-volatile load or a cast from the same type,
8137     // merge.
8138     if (TI->isCast()) {
8139       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8140         return 0;
8141     } else {
8142       return 0;  // unknown unary op.
8143     }
8144
8145     // Fold this by inserting a select from the input values.
8146     SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8147                                            FI->getOperand(0), SI.getName()+".v");
8148     InsertNewInstBefore(NewSI, SI);
8149     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 
8150                             TI->getType());
8151   }
8152
8153   // Only handle binary operators here.
8154   if (!isa<BinaryOperator>(TI))
8155     return 0;
8156
8157   // Figure out if the operations have any operands in common.
8158   Value *MatchOp, *OtherOpT, *OtherOpF;
8159   bool MatchIsOpZero;
8160   if (TI->getOperand(0) == FI->getOperand(0)) {
8161     MatchOp  = TI->getOperand(0);
8162     OtherOpT = TI->getOperand(1);
8163     OtherOpF = FI->getOperand(1);
8164     MatchIsOpZero = true;
8165   } else if (TI->getOperand(1) == FI->getOperand(1)) {
8166     MatchOp  = TI->getOperand(1);
8167     OtherOpT = TI->getOperand(0);
8168     OtherOpF = FI->getOperand(0);
8169     MatchIsOpZero = false;
8170   } else if (!TI->isCommutative()) {
8171     return 0;
8172   } else if (TI->getOperand(0) == FI->getOperand(1)) {
8173     MatchOp  = TI->getOperand(0);
8174     OtherOpT = TI->getOperand(1);
8175     OtherOpF = FI->getOperand(0);
8176     MatchIsOpZero = true;
8177   } else if (TI->getOperand(1) == FI->getOperand(0)) {
8178     MatchOp  = TI->getOperand(1);
8179     OtherOpT = TI->getOperand(0);
8180     OtherOpF = FI->getOperand(1);
8181     MatchIsOpZero = true;
8182   } else {
8183     return 0;
8184   }
8185
8186   // If we reach here, they do have operations in common.
8187   SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8188                                          OtherOpF, SI.getName()+".v");
8189   InsertNewInstBefore(NewSI, SI);
8190
8191   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8192     if (MatchIsOpZero)
8193       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8194     else
8195       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8196   }
8197   assert(0 && "Shouldn't get here");
8198   return 0;
8199 }
8200
8201 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8202 /// ICmpInst as its first operand.
8203 ///
8204 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8205                                                    ICmpInst *ICI) {
8206   bool Changed = false;
8207   ICmpInst::Predicate Pred = ICI->getPredicate();
8208   Value *CmpLHS = ICI->getOperand(0);
8209   Value *CmpRHS = ICI->getOperand(1);
8210   Value *TrueVal = SI.getTrueValue();
8211   Value *FalseVal = SI.getFalseValue();
8212
8213   // Check cases where the comparison is with a constant that
8214   // can be adjusted to fit the min/max idiom. We may edit ICI in
8215   // place here, so make sure the select is the only user.
8216   if (ICI->hasOneUse())
8217     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
8218       switch (Pred) {
8219       default: break;
8220       case ICmpInst::ICMP_ULT:
8221       case ICmpInst::ICMP_SLT: {
8222         // X < MIN ? T : F  -->  F
8223         if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8224           return ReplaceInstUsesWith(SI, FalseVal);
8225         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
8226         Constant *AdjustedRHS = SubOne(CI);
8227         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8228             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8229           Pred = ICmpInst::getSwappedPredicate(Pred);
8230           CmpRHS = AdjustedRHS;
8231           std::swap(FalseVal, TrueVal);
8232           ICI->setPredicate(Pred);
8233           ICI->setOperand(1, CmpRHS);
8234           SI.setOperand(1, TrueVal);
8235           SI.setOperand(2, FalseVal);
8236           Changed = true;
8237         }
8238         break;
8239       }
8240       case ICmpInst::ICMP_UGT:
8241       case ICmpInst::ICMP_SGT: {
8242         // X > MAX ? T : F  -->  F
8243         if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8244           return ReplaceInstUsesWith(SI, FalseVal);
8245         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
8246         Constant *AdjustedRHS = AddOne(CI);
8247         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8248             (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8249           Pred = ICmpInst::getSwappedPredicate(Pred);
8250           CmpRHS = AdjustedRHS;
8251           std::swap(FalseVal, TrueVal);
8252           ICI->setPredicate(Pred);
8253           ICI->setOperand(1, CmpRHS);
8254           SI.setOperand(1, TrueVal);
8255           SI.setOperand(2, FalseVal);
8256           Changed = true;
8257         }
8258         break;
8259       }
8260       }
8261
8262   if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8263     // Transform (X == Y) ? X : Y  -> Y
8264     if (Pred == ICmpInst::ICMP_EQ)
8265       return ReplaceInstUsesWith(SI, FalseVal);
8266     // Transform (X != Y) ? X : Y  -> X
8267     if (Pred == ICmpInst::ICMP_NE)
8268       return ReplaceInstUsesWith(SI, TrueVal);
8269     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8270
8271   } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8272     // Transform (X == Y) ? Y : X  -> X
8273     if (Pred == ICmpInst::ICMP_EQ)
8274       return ReplaceInstUsesWith(SI, FalseVal);
8275     // Transform (X != Y) ? Y : X  -> Y
8276     if (Pred == ICmpInst::ICMP_NE)
8277       return ReplaceInstUsesWith(SI, TrueVal);
8278     /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8279   }
8280
8281   /// NOTE: if we wanted to, this is where to detect integer ABS
8282
8283   return Changed ? &SI : 0;
8284 }
8285
8286 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8287   Value *CondVal = SI.getCondition();
8288   Value *TrueVal = SI.getTrueValue();
8289   Value *FalseVal = SI.getFalseValue();
8290
8291   // select true, X, Y  -> X
8292   // select false, X, Y -> Y
8293   if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8294     return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8295
8296   // select C, X, X -> X
8297   if (TrueVal == FalseVal)
8298     return ReplaceInstUsesWith(SI, TrueVal);
8299
8300   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
8301     return ReplaceInstUsesWith(SI, FalseVal);
8302   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
8303     return ReplaceInstUsesWith(SI, TrueVal);
8304   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
8305     if (isa<Constant>(TrueVal))
8306       return ReplaceInstUsesWith(SI, TrueVal);
8307     else
8308       return ReplaceInstUsesWith(SI, FalseVal);
8309   }
8310
8311   if (SI.getType() == Type::Int1Ty) {
8312     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8313       if (C->getZExtValue()) {
8314         // Change: A = select B, true, C --> A = or B, C
8315         return BinaryOperator::CreateOr(CondVal, FalseVal);
8316       } else {
8317         // Change: A = select B, false, C --> A = and !B, C
8318         Value *NotCond =
8319           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8320                                              "not."+CondVal->getName()), SI);
8321         return BinaryOperator::CreateAnd(NotCond, FalseVal);
8322       }
8323     } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8324       if (C->getZExtValue() == false) {
8325         // Change: A = select B, C, false --> A = and B, C
8326         return BinaryOperator::CreateAnd(CondVal, TrueVal);
8327       } else {
8328         // Change: A = select B, C, true --> A = or !B, C
8329         Value *NotCond =
8330           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8331                                              "not."+CondVal->getName()), SI);
8332         return BinaryOperator::CreateOr(NotCond, TrueVal);
8333       }
8334     }
8335     
8336     // select a, b, a  -> a&b
8337     // select a, a, b  -> a|b
8338     if (CondVal == TrueVal)
8339       return BinaryOperator::CreateOr(CondVal, FalseVal);
8340     else if (CondVal == FalseVal)
8341       return BinaryOperator::CreateAnd(CondVal, TrueVal);
8342   }
8343
8344   // Selecting between two integer constants?
8345   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8346     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8347       // select C, 1, 0 -> zext C to int
8348       if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8349         return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8350       } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8351         // select C, 0, 1 -> zext !C to int
8352         Value *NotCond =
8353           InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8354                                                "not."+CondVal->getName()), SI);
8355         return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8356       }
8357       
8358       // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8359
8360       if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8361
8362         // (x <s 0) ? -1 : 0 -> ashr x, 31
8363         if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8364           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8365             if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8366               // The comparison constant and the result are not neccessarily the
8367               // same width. Make an all-ones value by inserting a AShr.
8368               Value *X = IC->getOperand(0);
8369               uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8370               Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8371               Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8372                                                         ShAmt, "ones");
8373               InsertNewInstBefore(SRA, SI);
8374               
8375               // Finally, convert to the type of the select RHS.  We figure out
8376               // if this requires a SExt, Trunc or BitCast based on the sizes.
8377               Instruction::CastOps opc = Instruction::BitCast;
8378               uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8379               uint32_t SISize  = SI.getType()->getPrimitiveSizeInBits();
8380               if (SRASize < SISize)
8381                 opc = Instruction::SExt;
8382               else if (SRASize > SISize)
8383                 opc = Instruction::Trunc;
8384               return CastInst::Create(opc, SRA, SI.getType());
8385             }
8386           }
8387
8388
8389         // If one of the constants is zero (we know they can't both be) and we
8390         // have an icmp instruction with zero, and we have an 'and' with the
8391         // non-constant value, eliminate this whole mess.  This corresponds to
8392         // cases like this: ((X & 27) ? 27 : 0)
8393         if (TrueValC->isZero() || FalseValC->isZero())
8394           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8395               cast<Constant>(IC->getOperand(1))->isNullValue())
8396             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8397               if (ICA->getOpcode() == Instruction::And &&
8398                   isa<ConstantInt>(ICA->getOperand(1)) &&
8399                   (ICA->getOperand(1) == TrueValC ||
8400                    ICA->getOperand(1) == FalseValC) &&
8401                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8402                 // Okay, now we know that everything is set up, we just don't
8403                 // know whether we have a icmp_ne or icmp_eq and whether the 
8404                 // true or false val is the zero.
8405                 bool ShouldNotVal = !TrueValC->isZero();
8406                 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8407                 Value *V = ICA;
8408                 if (ShouldNotVal)
8409                   V = InsertNewInstBefore(BinaryOperator::Create(
8410                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
8411                 return ReplaceInstUsesWith(SI, V);
8412               }
8413       }
8414     }
8415
8416   // See if we are selecting two values based on a comparison of the two values.
8417   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8418     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8419       // Transform (X == Y) ? X : Y  -> Y
8420       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8421         // This is not safe in general for floating point:  
8422         // consider X== -0, Y== +0.
8423         // It becomes safe if either operand is a nonzero constant.
8424         ConstantFP *CFPt, *CFPf;
8425         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8426               !CFPt->getValueAPF().isZero()) ||
8427             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8428              !CFPf->getValueAPF().isZero()))
8429         return ReplaceInstUsesWith(SI, FalseVal);
8430       }
8431       // Transform (X != Y) ? X : Y  -> X
8432       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8433         return ReplaceInstUsesWith(SI, TrueVal);
8434       // NOTE: if we wanted to, this is where to detect MIN/MAX
8435
8436     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8437       // Transform (X == Y) ? Y : X  -> X
8438       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8439         // This is not safe in general for floating point:  
8440         // consider X== -0, Y== +0.
8441         // It becomes safe if either operand is a nonzero constant.
8442         ConstantFP *CFPt, *CFPf;
8443         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8444               !CFPt->getValueAPF().isZero()) ||
8445             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8446              !CFPf->getValueAPF().isZero()))
8447           return ReplaceInstUsesWith(SI, FalseVal);
8448       }
8449       // Transform (X != Y) ? Y : X  -> Y
8450       if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8451         return ReplaceInstUsesWith(SI, TrueVal);
8452       // NOTE: if we wanted to, this is where to detect MIN/MAX
8453     }
8454     // NOTE: if we wanted to, this is where to detect ABS
8455   }
8456
8457   // See if we are selecting two values based on a comparison of the two values.
8458   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8459     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8460       return Result;
8461
8462   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8463     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8464       if (TI->hasOneUse() && FI->hasOneUse()) {
8465         Instruction *AddOp = 0, *SubOp = 0;
8466
8467         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8468         if (TI->getOpcode() == FI->getOpcode())
8469           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8470             return IV;
8471
8472         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
8473         // even legal for FP.
8474         if (TI->getOpcode() == Instruction::Sub &&
8475             FI->getOpcode() == Instruction::Add) {
8476           AddOp = FI; SubOp = TI;
8477         } else if (FI->getOpcode() == Instruction::Sub &&
8478                    TI->getOpcode() == Instruction::Add) {
8479           AddOp = TI; SubOp = FI;
8480         }
8481
8482         if (AddOp) {
8483           Value *OtherAddOp = 0;
8484           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8485             OtherAddOp = AddOp->getOperand(1);
8486           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8487             OtherAddOp = AddOp->getOperand(0);
8488           }
8489
8490           if (OtherAddOp) {
8491             // So at this point we know we have (Y -> OtherAddOp):
8492             //        select C, (add X, Y), (sub X, Z)
8493             Value *NegVal;  // Compute -Z
8494             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8495               NegVal = ConstantExpr::getNeg(C);
8496             } else {
8497               NegVal = InsertNewInstBefore(
8498                     BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8499             }
8500
8501             Value *NewTrueOp = OtherAddOp;
8502             Value *NewFalseOp = NegVal;
8503             if (AddOp != TI)
8504               std::swap(NewTrueOp, NewFalseOp);
8505             Instruction *NewSel =
8506               SelectInst::Create(CondVal, NewTrueOp,
8507                                  NewFalseOp, SI.getName() + ".p");
8508
8509             NewSel = InsertNewInstBefore(NewSel, SI);
8510             return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8511           }
8512         }
8513       }
8514
8515   // See if we can fold the select into one of our operands.
8516   if (SI.getType()->isInteger()) {
8517     // See the comment above GetSelectFoldableOperands for a description of the
8518     // transformation we are doing here.
8519     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8520       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8521           !isa<Constant>(FalseVal))
8522         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8523           unsigned OpToFold = 0;
8524           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8525             OpToFold = 1;
8526           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8527             OpToFold = 2;
8528           }
8529
8530           if (OpToFold) {
8531             Constant *C = GetSelectFoldableConstant(TVI);
8532             Instruction *NewSel =
8533               SelectInst::Create(SI.getCondition(),
8534                                  TVI->getOperand(2-OpToFold), C);
8535             InsertNewInstBefore(NewSel, SI);
8536             NewSel->takeName(TVI);
8537             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8538               return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8539             else {
8540               assert(0 && "Unknown instruction!!");
8541             }
8542           }
8543         }
8544
8545     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8546       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8547           !isa<Constant>(TrueVal))
8548         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8549           unsigned OpToFold = 0;
8550           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8551             OpToFold = 1;
8552           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8553             OpToFold = 2;
8554           }
8555
8556           if (OpToFold) {
8557             Constant *C = GetSelectFoldableConstant(FVI);
8558             Instruction *NewSel =
8559               SelectInst::Create(SI.getCondition(), C,
8560                                  FVI->getOperand(2-OpToFold));
8561             InsertNewInstBefore(NewSel, SI);
8562             NewSel->takeName(FVI);
8563             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8564               return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8565             else
8566               assert(0 && "Unknown instruction!!");
8567           }
8568         }
8569   }
8570
8571   if (BinaryOperator::isNot(CondVal)) {
8572     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8573     SI.setOperand(1, FalseVal);
8574     SI.setOperand(2, TrueVal);
8575     return &SI;
8576   }
8577
8578   return 0;
8579 }
8580
8581 /// EnforceKnownAlignment - If the specified pointer points to an object that
8582 /// we control, modify the object's alignment to PrefAlign. This isn't
8583 /// often possible though. If alignment is important, a more reliable approach
8584 /// is to simply align all global variables and allocation instructions to
8585 /// their preferred alignment from the beginning.
8586 ///
8587 static unsigned EnforceKnownAlignment(Value *V,
8588                                       unsigned Align, unsigned PrefAlign) {
8589
8590   User *U = dyn_cast<User>(V);
8591   if (!U) return Align;
8592
8593   switch (getOpcode(U)) {
8594   default: break;
8595   case Instruction::BitCast:
8596     return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8597   case Instruction::GetElementPtr: {
8598     // If all indexes are zero, it is just the alignment of the base pointer.
8599     bool AllZeroOperands = true;
8600     for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8601       if (!isa<Constant>(*i) ||
8602           !cast<Constant>(*i)->isNullValue()) {
8603         AllZeroOperands = false;
8604         break;
8605       }
8606
8607     if (AllZeroOperands) {
8608       // Treat this like a bitcast.
8609       return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8610     }
8611     break;
8612   }
8613   }
8614
8615   if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8616     // If there is a large requested alignment and we can, bump up the alignment
8617     // of the global.
8618     if (!GV->isDeclaration()) {
8619       GV->setAlignment(PrefAlign);
8620       Align = PrefAlign;
8621     }
8622   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8623     // If there is a requested alignment and if this is an alloca, round up.  We
8624     // don't do this for malloc, because some systems can't respect the request.
8625     if (isa<AllocaInst>(AI)) {
8626       AI->setAlignment(PrefAlign);
8627       Align = PrefAlign;
8628     }
8629   }
8630
8631   return Align;
8632 }
8633
8634 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8635 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
8636 /// and it is more than the alignment of the ultimate object, see if we can
8637 /// increase the alignment of the ultimate object, making this check succeed.
8638 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8639                                                   unsigned PrefAlign) {
8640   unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8641                       sizeof(PrefAlign) * CHAR_BIT;
8642   APInt Mask = APInt::getAllOnesValue(BitWidth);
8643   APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8644   ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8645   unsigned TrailZ = KnownZero.countTrailingOnes();
8646   unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8647
8648   if (PrefAlign > Align)
8649     Align = EnforceKnownAlignment(V, Align, PrefAlign);
8650   
8651     // We don't need to make any adjustment.
8652   return Align;
8653 }
8654
8655 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8656   unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8657   unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8658   unsigned MinAlign = std::min(DstAlign, SrcAlign);
8659   unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8660
8661   if (CopyAlign < MinAlign) {
8662     MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8663     return MI;
8664   }
8665   
8666   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8667   // load/store.
8668   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8669   if (MemOpLength == 0) return 0;
8670   
8671   // Source and destination pointer types are always "i8*" for intrinsic.  See
8672   // if the size is something we can handle with a single primitive load/store.
8673   // A single load+store correctly handles overlapping memory in the memmove
8674   // case.
8675   unsigned Size = MemOpLength->getZExtValue();
8676   if (Size == 0) return MI;  // Delete this mem transfer.
8677   
8678   if (Size > 8 || (Size&(Size-1)))
8679     return 0;  // If not 1/2/4/8 bytes, exit.
8680   
8681   // Use an integer load+store unless we can find something better.
8682   Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8683   
8684   // Memcpy forces the use of i8* for the source and destination.  That means
8685   // that if you're using memcpy to move one double around, you'll get a cast
8686   // from double* to i8*.  We'd much rather use a double load+store rather than
8687   // an i64 load+store, here because this improves the odds that the source or
8688   // dest address will be promotable.  See if we can find a better type than the
8689   // integer datatype.
8690   if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8691     const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8692     if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8693       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
8694       // down through these levels if so.
8695       while (!SrcETy->isSingleValueType()) {
8696         if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8697           if (STy->getNumElements() == 1)
8698             SrcETy = STy->getElementType(0);
8699           else
8700             break;
8701         } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8702           if (ATy->getNumElements() == 1)
8703             SrcETy = ATy->getElementType();
8704           else
8705             break;
8706         } else
8707           break;
8708       }
8709       
8710       if (SrcETy->isSingleValueType())
8711         NewPtrTy = PointerType::getUnqual(SrcETy);
8712     }
8713   }
8714   
8715   
8716   // If the memcpy/memmove provides better alignment info than we can
8717   // infer, use it.
8718   SrcAlign = std::max(SrcAlign, CopyAlign);
8719   DstAlign = std::max(DstAlign, CopyAlign);
8720   
8721   Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8722   Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8723   Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8724   InsertNewInstBefore(L, *MI);
8725   InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8726
8727   // Set the size of the copy to 0, it will be deleted on the next iteration.
8728   MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8729   return MI;
8730 }
8731
8732 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8733   unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8734   if (MI->getAlignment()->getZExtValue() < Alignment) {
8735     MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8736     return MI;
8737   }
8738   
8739   // Extract the length and alignment and fill if they are constant.
8740   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8741   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8742   if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8743     return 0;
8744   uint64_t Len = LenC->getZExtValue();
8745   Alignment = MI->getAlignment()->getZExtValue();
8746   
8747   // If the length is zero, this is a no-op
8748   if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8749   
8750   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8751   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8752     const Type *ITy = IntegerType::get(Len*8);  // n=1 -> i8.
8753     
8754     Value *Dest = MI->getDest();
8755     Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8756
8757     // Alignment 0 is identity for alignment 1 for memset, but not store.
8758     if (Alignment == 0) Alignment = 1;
8759     
8760     // Extract the fill value and store.
8761     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8762     InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8763                                       Alignment), *MI);
8764     
8765     // Set the size of the copy to 0, it will be deleted on the next iteration.
8766     MI->setLength(Constant::getNullValue(LenC->getType()));
8767     return MI;
8768   }
8769
8770   return 0;
8771 }
8772
8773
8774 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
8775 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
8776 /// the heavy lifting.
8777 ///
8778 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8779   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8780   if (!II) return visitCallSite(&CI);
8781   
8782   // Intrinsics cannot occur in an invoke, so handle them here instead of in
8783   // visitCallSite.
8784   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8785     bool Changed = false;
8786
8787     // memmove/cpy/set of zero bytes is a noop.
8788     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8789       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8790
8791       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8792         if (CI->getZExtValue() == 1) {
8793           // Replace the instruction with just byte operations.  We would
8794           // transform other cases to loads/stores, but we don't know if
8795           // alignment is sufficient.
8796         }
8797     }
8798
8799     // If we have a memmove and the source operation is a constant global,
8800     // then the source and dest pointers can't alias, so we can change this
8801     // into a call to memcpy.
8802     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8803       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8804         if (GVSrc->isConstant()) {
8805           Module *M = CI.getParent()->getParent()->getParent();
8806           Intrinsic::ID MemCpyID;
8807           if (CI.getOperand(3)->getType() == Type::Int32Ty)
8808             MemCpyID = Intrinsic::memcpy_i32;
8809           else
8810             MemCpyID = Intrinsic::memcpy_i64;
8811           CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8812           Changed = true;
8813         }
8814
8815       // memmove(x,x,size) -> noop.
8816       if (MMI->getSource() == MMI->getDest())
8817         return EraseInstFromFunction(CI);
8818     }
8819
8820     // If we can determine a pointer alignment that is bigger than currently
8821     // set, update the alignment.
8822     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8823       if (Instruction *I = SimplifyMemTransfer(MI))
8824         return I;
8825     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8826       if (Instruction *I = SimplifyMemSet(MSI))
8827         return I;
8828     }
8829           
8830     if (Changed) return II;
8831   }
8832   
8833   switch (II->getIntrinsicID()) {
8834   default: break;
8835   case Intrinsic::bswap:
8836     // bswap(bswap(x)) -> x
8837     if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8838       if (Operand->getIntrinsicID() == Intrinsic::bswap)
8839         return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8840     break;
8841   case Intrinsic::ppc_altivec_lvx:
8842   case Intrinsic::ppc_altivec_lvxl:
8843   case Intrinsic::x86_sse_loadu_ps:
8844   case Intrinsic::x86_sse2_loadu_pd:
8845   case Intrinsic::x86_sse2_loadu_dq:
8846     // Turn PPC lvx     -> load if the pointer is known aligned.
8847     // Turn X86 loadups -> load if the pointer is known aligned.
8848     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8849       Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8850                                        PointerType::getUnqual(II->getType()),
8851                                        CI);
8852       return new LoadInst(Ptr);
8853     }
8854     break;
8855   case Intrinsic::ppc_altivec_stvx:
8856   case Intrinsic::ppc_altivec_stvxl:
8857     // Turn stvx -> store if the pointer is known aligned.
8858     if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8859       const Type *OpPtrTy = 
8860         PointerType::getUnqual(II->getOperand(1)->getType());
8861       Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8862       return new StoreInst(II->getOperand(1), Ptr);
8863     }
8864     break;
8865   case Intrinsic::x86_sse_storeu_ps:
8866   case Intrinsic::x86_sse2_storeu_pd:
8867   case Intrinsic::x86_sse2_storeu_dq:
8868     // Turn X86 storeu -> store if the pointer is known aligned.
8869     if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8870       const Type *OpPtrTy = 
8871         PointerType::getUnqual(II->getOperand(2)->getType());
8872       Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8873       return new StoreInst(II->getOperand(2), Ptr);
8874     }
8875     break;
8876     
8877   case Intrinsic::x86_sse_cvttss2si: {
8878     // These intrinsics only demands the 0th element of its input vector.  If
8879     // we can simplify the input based on that, do so now.
8880     uint64_t UndefElts;
8881     if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
8882                                               UndefElts)) {
8883       II->setOperand(1, V);
8884       return II;
8885     }
8886     break;
8887   }
8888     
8889   case Intrinsic::ppc_altivec_vperm:
8890     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8891     if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8892       assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8893       
8894       // Check that all of the elements are integer constants or undefs.
8895       bool AllEltsOk = true;
8896       for (unsigned i = 0; i != 16; ++i) {
8897         if (!isa<ConstantInt>(Mask->getOperand(i)) && 
8898             !isa<UndefValue>(Mask->getOperand(i))) {
8899           AllEltsOk = false;
8900           break;
8901         }
8902       }
8903       
8904       if (AllEltsOk) {
8905         // Cast the input vectors to byte vectors.
8906         Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8907         Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8908         Value *Result = UndefValue::get(Op0->getType());
8909         
8910         // Only extract each element once.
8911         Value *ExtractedElts[32];
8912         memset(ExtractedElts, 0, sizeof(ExtractedElts));
8913         
8914         for (unsigned i = 0; i != 16; ++i) {
8915           if (isa<UndefValue>(Mask->getOperand(i)))
8916             continue;
8917           unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8918           Idx &= 31;  // Match the hardware behavior.
8919           
8920           if (ExtractedElts[Idx] == 0) {
8921             Instruction *Elt = 
8922               new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8923             InsertNewInstBefore(Elt, CI);
8924             ExtractedElts[Idx] = Elt;
8925           }
8926         
8927           // Insert this value into the result vector.
8928           Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8929                                              i, "tmp");
8930           InsertNewInstBefore(cast<Instruction>(Result), CI);
8931         }
8932         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8933       }
8934     }
8935     break;
8936
8937   case Intrinsic::stackrestore: {
8938     // If the save is right next to the restore, remove the restore.  This can
8939     // happen when variable allocas are DCE'd.
8940     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8941       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8942         BasicBlock::iterator BI = SS;
8943         if (&*++BI == II)
8944           return EraseInstFromFunction(CI);
8945       }
8946     }
8947     
8948     // Scan down this block to see if there is another stack restore in the
8949     // same block without an intervening call/alloca.
8950     BasicBlock::iterator BI = II;
8951     TerminatorInst *TI = II->getParent()->getTerminator();
8952     bool CannotRemove = false;
8953     for (++BI; &*BI != TI; ++BI) {
8954       if (isa<AllocaInst>(BI)) {
8955         CannotRemove = true;
8956         break;
8957       }
8958       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8959         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8960           // If there is a stackrestore below this one, remove this one.
8961           if (II->getIntrinsicID() == Intrinsic::stackrestore)
8962             return EraseInstFromFunction(CI);
8963           // Otherwise, ignore the intrinsic.
8964         } else {
8965           // If we found a non-intrinsic call, we can't remove the stack
8966           // restore.
8967           CannotRemove = true;
8968           break;
8969         }
8970       }
8971     }
8972     
8973     // If the stack restore is in a return/unwind block and if there are no
8974     // allocas or calls between the restore and the return, nuke the restore.
8975     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8976       return EraseInstFromFunction(CI);
8977     break;
8978   }
8979   }
8980
8981   return visitCallSite(II);
8982 }
8983
8984 // InvokeInst simplification
8985 //
8986 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8987   return visitCallSite(&II);
8988 }
8989
8990 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 
8991 /// passed through the varargs area, we can eliminate the use of the cast.
8992 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8993                                          const CastInst * const CI,
8994                                          const TargetData * const TD,
8995                                          const int ix) {
8996   if (!CI->isLosslessCast())
8997     return false;
8998
8999   // The size of ByVal arguments is derived from the type, so we
9000   // can't change to a type with a different size.  If the size were
9001   // passed explicitly we could avoid this check.
9002   if (!CS.paramHasAttr(ix, Attribute::ByVal))
9003     return true;
9004
9005   const Type* SrcTy = 
9006             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9007   const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9008   if (!SrcTy->isSized() || !DstTy->isSized())
9009     return false;
9010   if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9011     return false;
9012   return true;
9013 }
9014
9015 // visitCallSite - Improvements for call and invoke instructions.
9016 //
9017 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9018   bool Changed = false;
9019
9020   // If the callee is a constexpr cast of a function, attempt to move the cast
9021   // to the arguments of the call/invoke.
9022   if (transformConstExprCastCall(CS)) return 0;
9023
9024   Value *Callee = CS.getCalledValue();
9025
9026   if (Function *CalleeF = dyn_cast<Function>(Callee))
9027     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9028       Instruction *OldCall = CS.getInstruction();
9029       // If the call and callee calling conventions don't match, this call must
9030       // be unreachable, as the call is undefined.
9031       new StoreInst(ConstantInt::getTrue(),
9032                     UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), 
9033                                     OldCall);
9034       if (!OldCall->use_empty())
9035         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9036       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
9037         return EraseInstFromFunction(*OldCall);
9038       return 0;
9039     }
9040
9041   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9042     // This instruction is not reachable, just remove it.  We insert a store to
9043     // undef so that we know that this code is not reachable, despite the fact
9044     // that we can't modify the CFG here.
9045     new StoreInst(ConstantInt::getTrue(),
9046                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9047                   CS.getInstruction());
9048
9049     if (!CS.getInstruction()->use_empty())
9050       CS.getInstruction()->
9051         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9052
9053     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9054       // Don't break the CFG, insert a dummy cond branch.
9055       BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9056                          ConstantInt::getTrue(), II);
9057     }
9058     return EraseInstFromFunction(*CS.getInstruction());
9059   }
9060
9061   if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9062     if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9063       if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9064         return transformCallThroughTrampoline(CS);
9065
9066   const PointerType *PTy = cast<PointerType>(Callee->getType());
9067   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9068   if (FTy->isVarArg()) {
9069     int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9070     // See if we can optimize any arguments passed through the varargs area of
9071     // the call.
9072     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9073            E = CS.arg_end(); I != E; ++I, ++ix) {
9074       CastInst *CI = dyn_cast<CastInst>(*I);
9075       if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9076         *I = CI->getOperand(0);
9077         Changed = true;
9078       }
9079     }
9080   }
9081
9082   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9083     // Inline asm calls cannot throw - mark them 'nounwind'.
9084     CS.setDoesNotThrow();
9085     Changed = true;
9086   }
9087
9088   return Changed ? CS.getInstruction() : 0;
9089 }
9090
9091 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9092 // attempt to move the cast to the arguments of the call/invoke.
9093 //
9094 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9095   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9096   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9097   if (CE->getOpcode() != Instruction::BitCast || 
9098       !isa<Function>(CE->getOperand(0)))
9099     return false;
9100   Function *Callee = cast<Function>(CE->getOperand(0));
9101   Instruction *Caller = CS.getInstruction();
9102   const AttrListPtr &CallerPAL = CS.getAttributes();
9103
9104   // Okay, this is a cast from a function to a different type.  Unless doing so
9105   // would cause a type conversion of one of our arguments, change this call to
9106   // be a direct call with arguments casted to the appropriate types.
9107   //
9108   const FunctionType *FT = Callee->getFunctionType();
9109   const Type *OldRetTy = Caller->getType();
9110   const Type *NewRetTy = FT->getReturnType();
9111
9112   if (isa<StructType>(NewRetTy))
9113     return false; // TODO: Handle multiple return values.
9114
9115   // Check to see if we are changing the return type...
9116   if (OldRetTy != NewRetTy) {
9117     if (Callee->isDeclaration() &&
9118         // Conversion is ok if changing from one pointer type to another or from
9119         // a pointer to an integer of the same size.
9120         !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9121           (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9122       return false;   // Cannot transform this return value.
9123
9124     if (!Caller->use_empty() &&
9125         // void -> non-void is handled specially
9126         NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9127       return false;   // Cannot transform this return value.
9128
9129     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9130       Attributes RAttrs = CallerPAL.getAttributes(0);
9131       if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9132         return false;   // Attribute not compatible with transformed value.
9133     }
9134
9135     // If the callsite is an invoke instruction, and the return value is used by
9136     // a PHI node in a successor, we cannot change the return type of the call
9137     // because there is no place to put the cast instruction (without breaking
9138     // the critical edge).  Bail out in this case.
9139     if (!Caller->use_empty())
9140       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9141         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9142              UI != E; ++UI)
9143           if (PHINode *PN = dyn_cast<PHINode>(*UI))
9144             if (PN->getParent() == II->getNormalDest() ||
9145                 PN->getParent() == II->getUnwindDest())
9146               return false;
9147   }
9148
9149   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9150   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9151
9152   CallSite::arg_iterator AI = CS.arg_begin();
9153   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9154     const Type *ParamTy = FT->getParamType(i);
9155     const Type *ActTy = (*AI)->getType();
9156
9157     if (!CastInst::isCastable(ActTy, ParamTy))
9158       return false;   // Cannot transform this parameter value.
9159
9160     if (CallerPAL.getAttributes(i + 1) & Attribute::typeIncompatible(ParamTy))
9161       return false;   // Attribute not compatible with transformed value.
9162
9163     // Converting from one pointer type to another or between a pointer and an
9164     // integer of the same size is safe even if we do not have a body.
9165     bool isConvertible = ActTy == ParamTy ||
9166       ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9167        (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9168     if (Callee->isDeclaration() && !isConvertible) return false;
9169   }
9170
9171   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9172       Callee->isDeclaration())
9173     return false;   // Do not delete arguments unless we have a function body.
9174
9175   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9176       !CallerPAL.isEmpty())
9177     // In this case we have more arguments than the new function type, but we
9178     // won't be dropping them.  Check that these extra arguments have attributes
9179     // that are compatible with being a vararg call argument.
9180     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9181       if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9182         break;
9183       Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9184       if (PAttrs & Attribute::VarArgsIncompatible)
9185         return false;
9186     }
9187
9188   // Okay, we decided that this is a safe thing to do: go ahead and start
9189   // inserting cast instructions as necessary...
9190   std::vector<Value*> Args;
9191   Args.reserve(NumActualArgs);
9192   SmallVector<AttributeWithIndex, 8> attrVec;
9193   attrVec.reserve(NumCommonArgs);
9194
9195   // Get any return attributes.
9196   Attributes RAttrs = CallerPAL.getAttributes(0);
9197
9198   // If the return value is not being used, the type may not be compatible
9199   // with the existing attributes.  Wipe out any problematic attributes.
9200   RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9201
9202   // Add the new return attributes.
9203   if (RAttrs)
9204     attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9205
9206   AI = CS.arg_begin();
9207   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9208     const Type *ParamTy = FT->getParamType(i);
9209     if ((*AI)->getType() == ParamTy) {
9210       Args.push_back(*AI);
9211     } else {
9212       Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9213           false, ParamTy, false);
9214       CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9215       Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9216     }
9217
9218     // Add any parameter attributes.
9219     if (Attributes PAttrs = CallerPAL.getAttributes(i + 1))
9220       attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9221   }
9222
9223   // If the function takes more arguments than the call was taking, add them
9224   // now...
9225   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9226     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9227
9228   // If we are removing arguments to the function, emit an obnoxious warning...
9229   if (FT->getNumParams() < NumActualArgs) {
9230     if (!FT->isVarArg()) {
9231       cerr << "WARNING: While resolving call to function '"
9232            << Callee->getName() << "' arguments were dropped!\n";
9233     } else {
9234       // Add all of the arguments in their promoted form to the arg list...
9235       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9236         const Type *PTy = getPromotedType((*AI)->getType());
9237         if (PTy != (*AI)->getType()) {
9238           // Must promote to pass through va_arg area!
9239           Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false, 
9240                                                                 PTy, false);
9241           Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9242           InsertNewInstBefore(Cast, *Caller);
9243           Args.push_back(Cast);
9244         } else {
9245           Args.push_back(*AI);
9246         }
9247
9248         // Add any parameter attributes.
9249         if (Attributes PAttrs = CallerPAL.getAttributes(i + 1))
9250           attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9251       }
9252     }
9253   }
9254
9255   if (NewRetTy == Type::VoidTy)
9256     Caller->setName("");   // Void type should not have a name.
9257
9258   const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9259
9260   Instruction *NC;
9261   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9262     NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9263                             Args.begin(), Args.end(),
9264                             Caller->getName(), Caller);
9265     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9266     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9267   } else {
9268     NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9269                           Caller->getName(), Caller);
9270     CallInst *CI = cast<CallInst>(Caller);
9271     if (CI->isTailCall())
9272       cast<CallInst>(NC)->setTailCall();
9273     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9274     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9275   }
9276
9277   // Insert a cast of the return type as necessary.
9278   Value *NV = NC;
9279   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9280     if (NV->getType() != Type::VoidTy) {
9281       Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false, 
9282                                                             OldRetTy, false);
9283       NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9284
9285       // If this is an invoke instruction, we should insert it after the first
9286       // non-phi, instruction in the normal successor block.
9287       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9288         BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9289         InsertNewInstBefore(NC, *I);
9290       } else {
9291         // Otherwise, it's a call, just insert cast right after the call instr
9292         InsertNewInstBefore(NC, *Caller);
9293       }
9294       AddUsersToWorkList(*Caller);
9295     } else {
9296       NV = UndefValue::get(Caller->getType());
9297     }
9298   }
9299
9300   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9301     Caller->replaceAllUsesWith(NV);
9302   Caller->eraseFromParent();
9303   RemoveFromWorkList(Caller);
9304   return true;
9305 }
9306
9307 // transformCallThroughTrampoline - Turn a call to a function created by the
9308 // init_trampoline intrinsic into a direct call to the underlying function.
9309 //
9310 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9311   Value *Callee = CS.getCalledValue();
9312   const PointerType *PTy = cast<PointerType>(Callee->getType());
9313   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9314   const AttrListPtr &Attrs = CS.getAttributes();
9315
9316   // If the call already has the 'nest' attribute somewhere then give up -
9317   // otherwise 'nest' would occur twice after splicing in the chain.
9318   if (Attrs.hasAttrSomewhere(Attribute::Nest))
9319     return 0;
9320
9321   IntrinsicInst *Tramp =
9322     cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9323
9324   Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9325   const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9326   const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9327
9328   const AttrListPtr &NestAttrs = NestF->getAttributes();
9329   if (!NestAttrs.isEmpty()) {
9330     unsigned NestIdx = 1;
9331     const Type *NestTy = 0;
9332     Attributes NestAttr = Attribute::None;
9333
9334     // Look for a parameter marked with the 'nest' attribute.
9335     for (FunctionType::param_iterator I = NestFTy->param_begin(),
9336          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9337       if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9338         // Record the parameter type and any other attributes.
9339         NestTy = *I;
9340         NestAttr = NestAttrs.getAttributes(NestIdx);
9341         break;
9342       }
9343
9344     if (NestTy) {
9345       Instruction *Caller = CS.getInstruction();
9346       std::vector<Value*> NewArgs;
9347       NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9348
9349       SmallVector<AttributeWithIndex, 8> NewAttrs;
9350       NewAttrs.reserve(Attrs.getNumSlots() + 1);
9351
9352       // Insert the nest argument into the call argument list, which may
9353       // mean appending it.  Likewise for attributes.
9354
9355       // Add any function result attributes.
9356       if (Attributes Attr = Attrs.getAttributes(0))
9357         NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9358
9359       {
9360         unsigned Idx = 1;
9361         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9362         do {
9363           if (Idx == NestIdx) {
9364             // Add the chain argument and attributes.
9365             Value *NestVal = Tramp->getOperand(3);
9366             if (NestVal->getType() != NestTy)
9367               NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9368             NewArgs.push_back(NestVal);
9369             NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9370           }
9371
9372           if (I == E)
9373             break;
9374
9375           // Add the original argument and attributes.
9376           NewArgs.push_back(*I);
9377           if (Attributes Attr = Attrs.getAttributes(Idx))
9378             NewAttrs.push_back
9379               (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9380
9381           ++Idx, ++I;
9382         } while (1);
9383       }
9384
9385       // The trampoline may have been bitcast to a bogus type (FTy).
9386       // Handle this by synthesizing a new function type, equal to FTy
9387       // with the chain parameter inserted.
9388
9389       std::vector<const Type*> NewTypes;
9390       NewTypes.reserve(FTy->getNumParams()+1);
9391
9392       // Insert the chain's type into the list of parameter types, which may
9393       // mean appending it.
9394       {
9395         unsigned Idx = 1;
9396         FunctionType::param_iterator I = FTy->param_begin(),
9397           E = FTy->param_end();
9398
9399         do {
9400           if (Idx == NestIdx)
9401             // Add the chain's type.
9402             NewTypes.push_back(NestTy);
9403
9404           if (I == E)
9405             break;
9406
9407           // Add the original type.
9408           NewTypes.push_back(*I);
9409
9410           ++Idx, ++I;
9411         } while (1);
9412       }
9413
9414       // Replace the trampoline call with a direct call.  Let the generic
9415       // code sort out any function type mismatches.
9416       FunctionType *NewFTy =
9417         FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9418       Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9419         NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9420       const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9421
9422       Instruction *NewCaller;
9423       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9424         NewCaller = InvokeInst::Create(NewCallee,
9425                                        II->getNormalDest(), II->getUnwindDest(),
9426                                        NewArgs.begin(), NewArgs.end(),
9427                                        Caller->getName(), Caller);
9428         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9429         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9430       } else {
9431         NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9432                                      Caller->getName(), Caller);
9433         if (cast<CallInst>(Caller)->isTailCall())
9434           cast<CallInst>(NewCaller)->setTailCall();
9435         cast<CallInst>(NewCaller)->
9436           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9437         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9438       }
9439       if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9440         Caller->replaceAllUsesWith(NewCaller);
9441       Caller->eraseFromParent();
9442       RemoveFromWorkList(Caller);
9443       return 0;
9444     }
9445   }
9446
9447   // Replace the trampoline call with a direct call.  Since there is no 'nest'
9448   // parameter, there is no need to adjust the argument list.  Let the generic
9449   // code sort out any function type mismatches.
9450   Constant *NewCallee =
9451     NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9452   CS.setCalledFunction(NewCallee);
9453   return CS.getInstruction();
9454 }
9455
9456 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9457 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9458 /// and a single binop.
9459 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9460   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9461   assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9462          isa<CmpInst>(FirstInst));
9463   unsigned Opc = FirstInst->getOpcode();
9464   Value *LHSVal = FirstInst->getOperand(0);
9465   Value *RHSVal = FirstInst->getOperand(1);
9466     
9467   const Type *LHSType = LHSVal->getType();
9468   const Type *RHSType = RHSVal->getType();
9469   
9470   // Scan to see if all operands are the same opcode, all have one use, and all
9471   // kill their operands (i.e. the operands have one use).
9472   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9473     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9474     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9475         // Verify type of the LHS matches so we don't fold cmp's of different
9476         // types or GEP's with different index types.
9477         I->getOperand(0)->getType() != LHSType ||
9478         I->getOperand(1)->getType() != RHSType)
9479       return 0;
9480
9481     // If they are CmpInst instructions, check their predicates
9482     if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9483       if (cast<CmpInst>(I)->getPredicate() !=
9484           cast<CmpInst>(FirstInst)->getPredicate())
9485         return 0;
9486     
9487     // Keep track of which operand needs a phi node.
9488     if (I->getOperand(0) != LHSVal) LHSVal = 0;
9489     if (I->getOperand(1) != RHSVal) RHSVal = 0;
9490   }
9491   
9492   // Otherwise, this is safe to transform, determine if it is profitable.
9493
9494   // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9495   // Indexes are often folded into load/store instructions, so we don't want to
9496   // hide them behind a phi.
9497   if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9498     return 0;
9499   
9500   Value *InLHS = FirstInst->getOperand(0);
9501   Value *InRHS = FirstInst->getOperand(1);
9502   PHINode *NewLHS = 0, *NewRHS = 0;
9503   if (LHSVal == 0) {
9504     NewLHS = PHINode::Create(LHSType,
9505                              FirstInst->getOperand(0)->getName() + ".pn");
9506     NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9507     NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9508     InsertNewInstBefore(NewLHS, PN);
9509     LHSVal = NewLHS;
9510   }
9511   
9512   if (RHSVal == 0) {
9513     NewRHS = PHINode::Create(RHSType,
9514                              FirstInst->getOperand(1)->getName() + ".pn");
9515     NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9516     NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9517     InsertNewInstBefore(NewRHS, PN);
9518     RHSVal = NewRHS;
9519   }
9520   
9521   // Add all operands to the new PHIs.
9522   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9523     if (NewLHS) {
9524       Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9525       NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9526     }
9527     if (NewRHS) {
9528       Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9529       NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9530     }
9531   }
9532     
9533   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9534     return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9535   else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9536     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal, 
9537                            RHSVal);
9538   else {
9539     assert(isa<GetElementPtrInst>(FirstInst));
9540     return GetElementPtrInst::Create(LHSVal, RHSVal);
9541   }
9542 }
9543
9544 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9545 /// of the block that defines it.  This means that it must be obvious the value
9546 /// of the load is not changed from the point of the load to the end of the
9547 /// block it is in.
9548 ///
9549 /// Finally, it is safe, but not profitable, to sink a load targetting a
9550 /// non-address-taken alloca.  Doing so will cause us to not promote the alloca
9551 /// to a register.
9552 static bool isSafeToSinkLoad(LoadInst *L) {
9553   BasicBlock::iterator BBI = L, E = L->getParent()->end();
9554   
9555   for (++BBI; BBI != E; ++BBI)
9556     if (BBI->mayWriteToMemory())
9557       return false;
9558   
9559   // Check for non-address taken alloca.  If not address-taken already, it isn't
9560   // profitable to do this xform.
9561   if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9562     bool isAddressTaken = false;
9563     for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9564          UI != E; ++UI) {
9565       if (isa<LoadInst>(UI)) continue;
9566       if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9567         // If storing TO the alloca, then the address isn't taken.
9568         if (SI->getOperand(1) == AI) continue;
9569       }
9570       isAddressTaken = true;
9571       break;
9572     }
9573     
9574     if (!isAddressTaken)
9575       return false;
9576   }
9577   
9578   return true;
9579 }
9580
9581
9582 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9583 // operator and they all are only used by the PHI, PHI together their
9584 // inputs, and do the operation once, to the result of the PHI.
9585 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9586   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9587
9588   // Scan the instruction, looking for input operations that can be folded away.
9589   // If all input operands to the phi are the same instruction (e.g. a cast from
9590   // the same type or "+42") we can pull the operation through the PHI, reducing
9591   // code size and simplifying code.
9592   Constant *ConstantOp = 0;
9593   const Type *CastSrcTy = 0;
9594   bool isVolatile = false;
9595   if (isa<CastInst>(FirstInst)) {
9596     CastSrcTy = FirstInst->getOperand(0)->getType();
9597   } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9598     // Can fold binop, compare or shift here if the RHS is a constant, 
9599     // otherwise call FoldPHIArgBinOpIntoPHI.
9600     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9601     if (ConstantOp == 0)
9602       return FoldPHIArgBinOpIntoPHI(PN);
9603   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9604     isVolatile = LI->isVolatile();
9605     // We can't sink the load if the loaded value could be modified between the
9606     // load and the PHI.
9607     if (LI->getParent() != PN.getIncomingBlock(0) ||
9608         !isSafeToSinkLoad(LI))
9609       return 0;
9610     
9611     // If the PHI is of volatile loads and the load block has multiple
9612     // successors, sinking it would remove a load of the volatile value from
9613     // the path through the other successor.
9614     if (isVolatile &&
9615         LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9616       return 0;
9617     
9618   } else if (isa<GetElementPtrInst>(FirstInst)) {
9619     if (FirstInst->getNumOperands() == 2)
9620       return FoldPHIArgBinOpIntoPHI(PN);
9621     // Can't handle general GEPs yet.
9622     return 0;
9623   } else {
9624     return 0;  // Cannot fold this operation.
9625   }
9626
9627   // Check to see if all arguments are the same operation.
9628   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9629     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9630     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9631     if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9632       return 0;
9633     if (CastSrcTy) {
9634       if (I->getOperand(0)->getType() != CastSrcTy)
9635         return 0;  // Cast operation must match.
9636     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9637       // We can't sink the load if the loaded value could be modified between 
9638       // the load and the PHI.
9639       if (LI->isVolatile() != isVolatile ||
9640           LI->getParent() != PN.getIncomingBlock(i) ||
9641           !isSafeToSinkLoad(LI))
9642         return 0;
9643       
9644       // If the PHI is of volatile loads and the load block has multiple
9645       // successors, sinking it would remove a load of the volatile value from
9646       // the path through the other successor.
9647       if (isVolatile &&
9648           LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9649         return 0;
9650
9651       
9652     } else if (I->getOperand(1) != ConstantOp) {
9653       return 0;
9654     }
9655   }
9656
9657   // Okay, they are all the same operation.  Create a new PHI node of the
9658   // correct type, and PHI together all of the LHS's of the instructions.
9659   PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9660                                    PN.getName()+".in");
9661   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9662
9663   Value *InVal = FirstInst->getOperand(0);
9664   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9665
9666   // Add all operands to the new PHI.
9667   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9668     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9669     if (NewInVal != InVal)
9670       InVal = 0;
9671     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9672   }
9673
9674   Value *PhiVal;
9675   if (InVal) {
9676     // The new PHI unions all of the same values together.  This is really
9677     // common, so we handle it intelligently here for compile-time speed.
9678     PhiVal = InVal;
9679     delete NewPN;
9680   } else {
9681     InsertNewInstBefore(NewPN, PN);
9682     PhiVal = NewPN;
9683   }
9684
9685   // Insert and return the new operation.
9686   if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9687     return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9688   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9689     return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9690   if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9691     return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), 
9692                            PhiVal, ConstantOp);
9693   assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9694   
9695   // If this was a volatile load that we are merging, make sure to loop through
9696   // and mark all the input loads as non-volatile.  If we don't do this, we will
9697   // insert a new volatile load and the old ones will not be deletable.
9698   if (isVolatile)
9699     for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9700       cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9701   
9702   return new LoadInst(PhiVal, "", isVolatile);
9703 }
9704
9705 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9706 /// that is dead.
9707 static bool DeadPHICycle(PHINode *PN,
9708                          SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9709   if (PN->use_empty()) return true;
9710   if (!PN->hasOneUse()) return false;
9711
9712   // Remember this node, and if we find the cycle, return.
9713   if (!PotentiallyDeadPHIs.insert(PN))
9714     return true;
9715   
9716   // Don't scan crazily complex things.
9717   if (PotentiallyDeadPHIs.size() == 16)
9718     return false;
9719
9720   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9721     return DeadPHICycle(PU, PotentiallyDeadPHIs);
9722
9723   return false;
9724 }
9725
9726 /// PHIsEqualValue - Return true if this phi node is always equal to
9727 /// NonPhiInVal.  This happens with mutually cyclic phi nodes like:
9728 ///   z = some value; x = phi (y, z); y = phi (x, z)
9729 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal, 
9730                            SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9731   // See if we already saw this PHI node.
9732   if (!ValueEqualPHIs.insert(PN))
9733     return true;
9734   
9735   // Don't scan crazily complex things.
9736   if (ValueEqualPHIs.size() == 16)
9737     return false;
9738  
9739   // Scan the operands to see if they are either phi nodes or are equal to
9740   // the value.
9741   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9742     Value *Op = PN->getIncomingValue(i);
9743     if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9744       if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9745         return false;
9746     } else if (Op != NonPhiInVal)
9747       return false;
9748   }
9749   
9750   return true;
9751 }
9752
9753
9754 // PHINode simplification
9755 //
9756 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9757   // If LCSSA is around, don't mess with Phi nodes
9758   if (MustPreserveLCSSA) return 0;
9759   
9760   if (Value *V = PN.hasConstantValue())
9761     return ReplaceInstUsesWith(PN, V);
9762
9763   // If all PHI operands are the same operation, pull them through the PHI,
9764   // reducing code size.
9765   if (isa<Instruction>(PN.getIncomingValue(0)) &&
9766       PN.getIncomingValue(0)->hasOneUse())
9767     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9768       return Result;
9769
9770   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
9771   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9772   // PHI)... break the cycle.
9773   if (PN.hasOneUse()) {
9774     Instruction *PHIUser = cast<Instruction>(PN.use_back());
9775     if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9776       SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9777       PotentiallyDeadPHIs.insert(&PN);
9778       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9779         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9780     }
9781    
9782     // If this phi has a single use, and if that use just computes a value for
9783     // the next iteration of a loop, delete the phi.  This occurs with unused
9784     // induction variables, e.g. "for (int j = 0; ; ++j);".  Detecting this
9785     // common case here is good because the only other things that catch this
9786     // are induction variable analysis (sometimes) and ADCE, which is only run
9787     // late.
9788     if (PHIUser->hasOneUse() &&
9789         (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9790         PHIUser->use_back() == &PN) {
9791       return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9792     }
9793   }
9794
9795   // We sometimes end up with phi cycles that non-obviously end up being the
9796   // same value, for example:
9797   //   z = some value; x = phi (y, z); y = phi (x, z)
9798   // where the phi nodes don't necessarily need to be in the same block.  Do a
9799   // quick check to see if the PHI node only contains a single non-phi value, if
9800   // so, scan to see if the phi cycle is actually equal to that value.
9801   {
9802     unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9803     // Scan for the first non-phi operand.
9804     while (InValNo != NumOperandVals && 
9805            isa<PHINode>(PN.getIncomingValue(InValNo)))
9806       ++InValNo;
9807
9808     if (InValNo != NumOperandVals) {
9809       Value *NonPhiInVal = PN.getOperand(InValNo);
9810       
9811       // Scan the rest of the operands to see if there are any conflicts, if so
9812       // there is no need to recursively scan other phis.
9813       for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9814         Value *OpVal = PN.getIncomingValue(InValNo);
9815         if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9816           break;
9817       }
9818       
9819       // If we scanned over all operands, then we have one unique value plus
9820       // phi values.  Scan PHI nodes to see if they all merge in each other or
9821       // the value.
9822       if (InValNo == NumOperandVals) {
9823         SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9824         if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9825           return ReplaceInstUsesWith(PN, NonPhiInVal);
9826       }
9827     }
9828   }
9829   return 0;
9830 }
9831
9832 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9833                                    Instruction *InsertPoint,
9834                                    InstCombiner *IC) {
9835   unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9836   unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9837   // We must cast correctly to the pointer type. Ensure that we
9838   // sign extend the integer value if it is smaller as this is
9839   // used for address computation.
9840   Instruction::CastOps opcode = 
9841      (VTySize < PtrSize ? Instruction::SExt :
9842       (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9843   return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9844 }
9845
9846
9847 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9848   Value *PtrOp = GEP.getOperand(0);
9849   // Is it 'getelementptr %P, i32 0'  or 'getelementptr %P'
9850   // If so, eliminate the noop.
9851   if (GEP.getNumOperands() == 1)
9852     return ReplaceInstUsesWith(GEP, PtrOp);
9853
9854   if (isa<UndefValue>(GEP.getOperand(0)))
9855     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9856
9857   bool HasZeroPointerIndex = false;
9858   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9859     HasZeroPointerIndex = C->isNullValue();
9860
9861   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9862     return ReplaceInstUsesWith(GEP, PtrOp);
9863
9864   // Eliminate unneeded casts for indices.
9865   bool MadeChange = false;
9866   
9867   gep_type_iterator GTI = gep_type_begin(GEP);
9868   for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9869        i != e; ++i, ++GTI) {
9870     if (isa<SequentialType>(*GTI)) {
9871       if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9872         if (CI->getOpcode() == Instruction::ZExt ||
9873             CI->getOpcode() == Instruction::SExt) {
9874           const Type *SrcTy = CI->getOperand(0)->getType();
9875           // We can eliminate a cast from i32 to i64 iff the target 
9876           // is a 32-bit pointer target.
9877           if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9878             MadeChange = true;
9879             *i = CI->getOperand(0);
9880           }
9881         }
9882       }
9883       // If we are using a wider index than needed for this platform, shrink it
9884       // to what we need.  If narrower, sign-extend it to what we need.
9885       // If the incoming value needs a cast instruction,
9886       // insert it.  This explicit cast can make subsequent optimizations more
9887       // obvious.
9888       Value *Op = *i;
9889       if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9890         if (Constant *C = dyn_cast<Constant>(Op)) {
9891           *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9892           MadeChange = true;
9893         } else {
9894           Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9895                                 GEP);
9896           *i = Op;
9897           MadeChange = true;
9898         }
9899       } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
9900         if (Constant *C = dyn_cast<Constant>(Op)) {
9901           *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
9902           MadeChange = true;
9903         } else {
9904           Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
9905                                 GEP);
9906           *i = Op;
9907           MadeChange = true;
9908         }
9909       }
9910     }
9911   }
9912   if (MadeChange) return &GEP;
9913
9914   // If this GEP instruction doesn't move the pointer, and if the input operand
9915   // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9916   // real input to the dest type.
9917   if (GEP.hasAllZeroIndices()) {
9918     if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9919       // If the bitcast is of an allocation, and the allocation will be
9920       // converted to match the type of the cast, don't touch this.
9921       if (isa<AllocationInst>(BCI->getOperand(0))) {
9922         // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9923         if (Instruction *I = visitBitCast(*BCI)) {
9924           if (I != BCI) {
9925             I->takeName(BCI);
9926             BCI->getParent()->getInstList().insert(BCI, I);
9927             ReplaceInstUsesWith(*BCI, I);
9928           }
9929           return &GEP;
9930         }
9931       }
9932       return new BitCastInst(BCI->getOperand(0), GEP.getType());
9933     }
9934   }
9935   
9936   // Combine Indices - If the source pointer to this getelementptr instruction
9937   // is a getelementptr instruction, combine the indices of the two
9938   // getelementptr instructions into a single instruction.
9939   //
9940   SmallVector<Value*, 8> SrcGEPOperands;
9941   if (User *Src = dyn_castGetElementPtr(PtrOp))
9942     SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9943
9944   if (!SrcGEPOperands.empty()) {
9945     // Note that if our source is a gep chain itself that we wait for that
9946     // chain to be resolved before we perform this transformation.  This
9947     // avoids us creating a TON of code in some cases.
9948     //
9949     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9950         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9951       return 0;   // Wait until our source is folded to completion.
9952
9953     SmallVector<Value*, 8> Indices;
9954
9955     // Find out whether the last index in the source GEP is a sequential idx.
9956     bool EndsWithSequential = false;
9957     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9958            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9959       EndsWithSequential = !isa<StructType>(*I);
9960
9961     // Can we combine the two pointer arithmetics offsets?
9962     if (EndsWithSequential) {
9963       // Replace: gep (gep %P, long B), long A, ...
9964       // With:    T = long A+B; gep %P, T, ...
9965       //
9966       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9967       if (SO1 == Constant::getNullValue(SO1->getType())) {
9968         Sum = GO1;
9969       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9970         Sum = SO1;
9971       } else {
9972         // If they aren't the same type, convert both to an integer of the
9973         // target's pointer size.
9974         if (SO1->getType() != GO1->getType()) {
9975           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9976             SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9977           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9978             GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9979           } else {
9980             unsigned PS = TD->getPointerSizeInBits();
9981             if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9982               // Convert GO1 to SO1's type.
9983               GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9984
9985             } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9986               // Convert SO1 to GO1's type.
9987               SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9988             } else {
9989               const Type *PT = TD->getIntPtrType();
9990               SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9991               GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9992             }
9993           }
9994         }
9995         if (isa<Constant>(SO1) && isa<Constant>(GO1))
9996           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9997         else {
9998           Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9999           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10000         }
10001       }
10002
10003       // Recycle the GEP we already have if possible.
10004       if (SrcGEPOperands.size() == 2) {
10005         GEP.setOperand(0, SrcGEPOperands[0]);
10006         GEP.setOperand(1, Sum);
10007         return &GEP;
10008       } else {
10009         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10010                        SrcGEPOperands.end()-1);
10011         Indices.push_back(Sum);
10012         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10013       }
10014     } else if (isa<Constant>(*GEP.idx_begin()) &&
10015                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10016                SrcGEPOperands.size() != 1) {
10017       // Otherwise we can do the fold if the first index of the GEP is a zero
10018       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10019                      SrcGEPOperands.end());
10020       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10021     }
10022
10023     if (!Indices.empty())
10024       return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10025                                        Indices.end(), GEP.getName());
10026
10027   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10028     // GEP of global variable.  If all of the indices for this GEP are
10029     // constants, we can promote this to a constexpr instead of an instruction.
10030
10031     // Scan for nonconstants...
10032     SmallVector<Constant*, 8> Indices;
10033     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10034     for (; I != E && isa<Constant>(*I); ++I)
10035       Indices.push_back(cast<Constant>(*I));
10036
10037     if (I == E) {  // If they are all constants...
10038       Constant *CE = ConstantExpr::getGetElementPtr(GV,
10039                                                     &Indices[0],Indices.size());
10040
10041       // Replace all uses of the GEP with the new constexpr...
10042       return ReplaceInstUsesWith(GEP, CE);
10043     }
10044   } else if (Value *X = getBitCastOperand(PtrOp)) {  // Is the operand a cast?
10045     if (!isa<PointerType>(X->getType())) {
10046       // Not interesting.  Source pointer must be a cast from pointer.
10047     } else if (HasZeroPointerIndex) {
10048       // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10049       // into     : GEP [10 x i8]* X, i32 0, ...
10050       //
10051       // This occurs when the program declares an array extern like "int X[];"
10052       //
10053       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10054       const PointerType *XTy = cast<PointerType>(X->getType());
10055       if (const ArrayType *XATy =
10056           dyn_cast<ArrayType>(XTy->getElementType()))
10057         if (const ArrayType *CATy =
10058             dyn_cast<ArrayType>(CPTy->getElementType()))
10059           if (CATy->getElementType() == XATy->getElementType()) {
10060             // At this point, we know that the cast source type is a pointer
10061             // to an array of the same type as the destination pointer
10062             // array.  Because the array type is never stepped over (there
10063             // is a leading zero) we can fold the cast into this GEP.
10064             GEP.setOperand(0, X);
10065             return &GEP;
10066           }
10067     } else if (GEP.getNumOperands() == 2) {
10068       // Transform things like:
10069       // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10070       // into:  %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10071       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10072       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10073       if (isa<ArrayType>(SrcElTy) &&
10074           TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10075           TD->getABITypeSize(ResElTy)) {
10076         Value *Idx[2];
10077         Idx[0] = Constant::getNullValue(Type::Int32Ty);
10078         Idx[1] = GEP.getOperand(1);
10079         Value *V = InsertNewInstBefore(
10080                GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10081         // V and GEP are both pointer types --> BitCast
10082         return new BitCastInst(V, GEP.getType());
10083       }
10084       
10085       // Transform things like:
10086       // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10087       //   (where tmp = 8*tmp2) into:
10088       // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10089       
10090       if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10091         uint64_t ArrayEltSize =
10092             TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10093         
10094         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
10095         // allow either a mul, shift, or constant here.
10096         Value *NewIdx = 0;
10097         ConstantInt *Scale = 0;
10098         if (ArrayEltSize == 1) {
10099           NewIdx = GEP.getOperand(1);
10100           Scale = ConstantInt::get(NewIdx->getType(), 1);
10101         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10102           NewIdx = ConstantInt::get(CI->getType(), 1);
10103           Scale = CI;
10104         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10105           if (Inst->getOpcode() == Instruction::Shl &&
10106               isa<ConstantInt>(Inst->getOperand(1))) {
10107             ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10108             uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10109             Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10110             NewIdx = Inst->getOperand(0);
10111           } else if (Inst->getOpcode() == Instruction::Mul &&
10112                      isa<ConstantInt>(Inst->getOperand(1))) {
10113             Scale = cast<ConstantInt>(Inst->getOperand(1));
10114             NewIdx = Inst->getOperand(0);
10115           }
10116         }
10117         
10118         // If the index will be to exactly the right offset with the scale taken
10119         // out, perform the transformation. Note, we don't know whether Scale is
10120         // signed or not. We'll use unsigned version of division/modulo
10121         // operation after making sure Scale doesn't have the sign bit set.
10122         if (Scale && Scale->getSExtValue() >= 0LL &&
10123             Scale->getZExtValue() % ArrayEltSize == 0) {
10124           Scale = ConstantInt::get(Scale->getType(),
10125                                    Scale->getZExtValue() / ArrayEltSize);
10126           if (Scale->getZExtValue() != 1) {
10127             Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10128                                                        false /*ZExt*/);
10129             Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10130             NewIdx = InsertNewInstBefore(Sc, GEP);
10131           }
10132
10133           // Insert the new GEP instruction.
10134           Value *Idx[2];
10135           Idx[0] = Constant::getNullValue(Type::Int32Ty);
10136           Idx[1] = NewIdx;
10137           Instruction *NewGEP =
10138             GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10139           NewGEP = InsertNewInstBefore(NewGEP, GEP);
10140           // The NewGEP must be pointer typed, so must the old one -> BitCast
10141           return new BitCastInst(NewGEP, GEP.getType());
10142         }
10143       }
10144     }
10145   }
10146
10147   return 0;
10148 }
10149
10150 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10151   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10152   if (AI.isArrayAllocation()) {  // Check C != 1
10153     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10154       const Type *NewTy = 
10155         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10156       AllocationInst *New = 0;
10157
10158       // Create and insert the replacement instruction...
10159       if (isa<MallocInst>(AI))
10160         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10161       else {
10162         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10163         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10164       }
10165
10166       InsertNewInstBefore(New, AI);
10167
10168       // Scan to the end of the allocation instructions, to skip over a block of
10169       // allocas if possible...
10170       //
10171       BasicBlock::iterator It = New;
10172       while (isa<AllocationInst>(*It)) ++It;
10173
10174       // Now that I is pointing to the first non-allocation-inst in the block,
10175       // insert our getelementptr instruction...
10176       //
10177       Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10178       Value *Idx[2];
10179       Idx[0] = NullIdx;
10180       Idx[1] = NullIdx;
10181       Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10182                                            New->getName()+".sub", It);
10183
10184       // Now make everything use the getelementptr instead of the original
10185       // allocation.
10186       return ReplaceInstUsesWith(AI, V);
10187     } else if (isa<UndefValue>(AI.getArraySize())) {
10188       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10189     }
10190   }
10191
10192   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10193   // Note that we only do this for alloca's, because malloc should allocate and
10194   // return a unique pointer, even for a zero byte allocation.
10195   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10196       TD->getABITypeSize(AI.getAllocatedType()) == 0)
10197     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10198
10199   return 0;
10200 }
10201
10202 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10203   Value *Op = FI.getOperand(0);
10204
10205   // free undef -> unreachable.
10206   if (isa<UndefValue>(Op)) {
10207     // Insert a new store to null because we cannot modify the CFG here.
10208     new StoreInst(ConstantInt::getTrue(),
10209                   UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10210     return EraseInstFromFunction(FI);
10211   }
10212   
10213   // If we have 'free null' delete the instruction.  This can happen in stl code
10214   // when lots of inlining happens.
10215   if (isa<ConstantPointerNull>(Op))
10216     return EraseInstFromFunction(FI);
10217   
10218   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10219   if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10220     FI.setOperand(0, CI->getOperand(0));
10221     return &FI;
10222   }
10223   
10224   // Change free (gep X, 0,0,0,0) into free(X)
10225   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10226     if (GEPI->hasAllZeroIndices()) {
10227       AddToWorkList(GEPI);
10228       FI.setOperand(0, GEPI->getOperand(0));
10229       return &FI;
10230     }
10231   }
10232   
10233   // Change free(malloc) into nothing, if the malloc has a single use.
10234   if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10235     if (MI->hasOneUse()) {
10236       EraseInstFromFunction(FI);
10237       return EraseInstFromFunction(*MI);
10238     }
10239
10240   return 0;
10241 }
10242
10243
10244 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10245 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10246                                         const TargetData *TD) {
10247   User *CI = cast<User>(LI.getOperand(0));
10248   Value *CastOp = CI->getOperand(0);
10249
10250   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10251     // Instead of loading constant c string, use corresponding integer value
10252     // directly if string length is small enough.
10253     std::string Str;
10254     if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10255       unsigned len = Str.length();
10256       const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10257       unsigned numBits = Ty->getPrimitiveSizeInBits();
10258       // Replace LI with immediate integer store.
10259       if ((numBits >> 3) == len + 1) {
10260         APInt StrVal(numBits, 0);
10261         APInt SingleChar(numBits, 0);
10262         if (TD->isLittleEndian()) {
10263           for (signed i = len-1; i >= 0; i--) {
10264             SingleChar = (uint64_t) Str[i];
10265             StrVal = (StrVal << 8) | SingleChar;
10266           }
10267         } else {
10268           for (unsigned i = 0; i < len; i++) {
10269             SingleChar = (uint64_t) Str[i];
10270             StrVal = (StrVal << 8) | SingleChar;
10271           }
10272           // Append NULL at the end.
10273           SingleChar = 0;
10274           StrVal = (StrVal << 8) | SingleChar;
10275         }
10276         Value *NL = ConstantInt::get(StrVal);
10277         return IC.ReplaceInstUsesWith(LI, NL);
10278       }
10279     }
10280   }
10281
10282   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10283   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10284     const Type *SrcPTy = SrcTy->getElementType();
10285
10286     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
10287          isa<VectorType>(DestPTy)) {
10288       // If the source is an array, the code below will not succeed.  Check to
10289       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10290       // constants.
10291       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10292         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10293           if (ASrcTy->getNumElements() != 0) {
10294             Value *Idxs[2];
10295             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10296             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10297             SrcTy = cast<PointerType>(CastOp->getType());
10298             SrcPTy = SrcTy->getElementType();
10299           }
10300
10301       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
10302             isa<VectorType>(SrcPTy)) &&
10303           // Do not allow turning this into a load of an integer, which is then
10304           // casted to a pointer, this pessimizes pointer analysis a lot.
10305           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10306           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10307                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10308
10309         // Okay, we are casting from one integer or pointer type to another of
10310         // the same size.  Instead of casting the pointer before the load, cast
10311         // the result of the loaded value.
10312         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10313                                                              CI->getName(),
10314                                                          LI.isVolatile()),LI);
10315         // Now cast the result of the load.
10316         return new BitCastInst(NewLoad, LI.getType());
10317       }
10318     }
10319   }
10320   return 0;
10321 }
10322
10323 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10324 /// from this value cannot trap.  If it is not obviously safe to load from the
10325 /// specified pointer, we do a quick local scan of the basic block containing
10326 /// ScanFrom, to determine if the address is already accessed.
10327 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10328   // If it is an alloca it is always safe to load from.
10329   if (isa<AllocaInst>(V)) return true;
10330
10331   // If it is a global variable it is mostly safe to load from.
10332   if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10333     // Don't try to evaluate aliases.  External weak GV can be null.
10334     return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10335
10336   // Otherwise, be a little bit agressive by scanning the local block where we
10337   // want to check to see if the pointer is already being loaded or stored
10338   // from/to.  If so, the previous load or store would have already trapped,
10339   // so there is no harm doing an extra load (also, CSE will later eliminate
10340   // the load entirely).
10341   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10342
10343   while (BBI != E) {
10344     --BBI;
10345
10346     // If we see a free or a call (which might do a free) the pointer could be
10347     // marked invalid.
10348     if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10349       return false;
10350     
10351     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10352       if (LI->getOperand(0) == V) return true;
10353     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10354       if (SI->getOperand(1) == V) return true;
10355     }
10356
10357   }
10358   return false;
10359 }
10360
10361 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10362 /// until we find the underlying object a pointer is referring to or something
10363 /// we don't understand.  Note that the returned pointer may be offset from the
10364 /// input, because we ignore GEP indices.
10365 static Value *GetUnderlyingObject(Value *Ptr) {
10366   while (1) {
10367     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10368       if (CE->getOpcode() == Instruction::BitCast ||
10369           CE->getOpcode() == Instruction::GetElementPtr)
10370         Ptr = CE->getOperand(0);
10371       else
10372         return Ptr;
10373     } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10374       Ptr = BCI->getOperand(0);
10375     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10376       Ptr = GEP->getOperand(0);
10377     } else {
10378       return Ptr;
10379     }
10380   }
10381 }
10382
10383 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10384   Value *Op = LI.getOperand(0);
10385
10386   // Attempt to improve the alignment.
10387   unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10388   if (KnownAlign >
10389       (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10390                                 LI.getAlignment()))
10391     LI.setAlignment(KnownAlign);
10392
10393   // load (cast X) --> cast (load X) iff safe
10394   if (isa<CastInst>(Op))
10395     if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10396       return Res;
10397
10398   // None of the following transforms are legal for volatile loads.
10399   if (LI.isVolatile()) return 0;
10400   
10401   if (&LI.getParent()->front() != &LI) {
10402     BasicBlock::iterator BBI = &LI; --BBI;
10403     // If the instruction immediately before this is a store to the same
10404     // address, do a simple form of store->load forwarding.
10405     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10406       if (SI->getOperand(1) == LI.getOperand(0))
10407         return ReplaceInstUsesWith(LI, SI->getOperand(0));
10408     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10409       if (LIB->getOperand(0) == LI.getOperand(0))
10410         return ReplaceInstUsesWith(LI, LIB);
10411   }
10412
10413   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10414     const Value *GEPI0 = GEPI->getOperand(0);
10415     // TODO: Consider a target hook for valid address spaces for this xform.
10416     if (isa<ConstantPointerNull>(GEPI0) &&
10417         cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10418       // Insert a new store to null instruction before the load to indicate
10419       // that this code is not reachable.  We do this instead of inserting
10420       // an unreachable instruction directly because we cannot modify the
10421       // CFG.
10422       new StoreInst(UndefValue::get(LI.getType()),
10423                     Constant::getNullValue(Op->getType()), &LI);
10424       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10425     }
10426   } 
10427
10428   if (Constant *C = dyn_cast<Constant>(Op)) {
10429     // load null/undef -> undef
10430     // TODO: Consider a target hook for valid address spaces for this xform.
10431     if (isa<UndefValue>(C) || (C->isNullValue() && 
10432         cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10433       // Insert a new store to null instruction before the load to indicate that
10434       // this code is not reachable.  We do this instead of inserting an
10435       // unreachable instruction directly because we cannot modify the CFG.
10436       new StoreInst(UndefValue::get(LI.getType()),
10437                     Constant::getNullValue(Op->getType()), &LI);
10438       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10439     }
10440
10441     // Instcombine load (constant global) into the value loaded.
10442     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10443       if (GV->isConstant() && !GV->isDeclaration())
10444         return ReplaceInstUsesWith(LI, GV->getInitializer());
10445
10446     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10447     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10448       if (CE->getOpcode() == Instruction::GetElementPtr) {
10449         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10450           if (GV->isConstant() && !GV->isDeclaration())
10451             if (Constant *V = 
10452                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10453               return ReplaceInstUsesWith(LI, V);
10454         if (CE->getOperand(0)->isNullValue()) {
10455           // Insert a new store to null instruction before the load to indicate
10456           // that this code is not reachable.  We do this instead of inserting
10457           // an unreachable instruction directly because we cannot modify the
10458           // CFG.
10459           new StoreInst(UndefValue::get(LI.getType()),
10460                         Constant::getNullValue(Op->getType()), &LI);
10461           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10462         }
10463
10464       } else if (CE->isCast()) {
10465         if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10466           return Res;
10467       }
10468     }
10469   }
10470     
10471   // If this load comes from anywhere in a constant global, and if the global
10472   // is all undef or zero, we know what it loads.
10473   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10474     if (GV->isConstant() && GV->hasInitializer()) {
10475       if (GV->getInitializer()->isNullValue())
10476         return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10477       else if (isa<UndefValue>(GV->getInitializer()))
10478         return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10479     }
10480   }
10481
10482   if (Op->hasOneUse()) {
10483     // Change select and PHI nodes to select values instead of addresses: this
10484     // helps alias analysis out a lot, allows many others simplifications, and
10485     // exposes redundancy in the code.
10486     //
10487     // Note that we cannot do the transformation unless we know that the
10488     // introduced loads cannot trap!  Something like this is valid as long as
10489     // the condition is always false: load (select bool %C, int* null, int* %G),
10490     // but it would not be valid if we transformed it to load from null
10491     // unconditionally.
10492     //
10493     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10494       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
10495       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10496           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10497         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10498                                      SI->getOperand(1)->getName()+".val"), LI);
10499         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10500                                      SI->getOperand(2)->getName()+".val"), LI);
10501         return SelectInst::Create(SI->getCondition(), V1, V2);
10502       }
10503
10504       // load (select (cond, null, P)) -> load P
10505       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10506         if (C->isNullValue()) {
10507           LI.setOperand(0, SI->getOperand(2));
10508           return &LI;
10509         }
10510
10511       // load (select (cond, P, null)) -> load P
10512       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10513         if (C->isNullValue()) {
10514           LI.setOperand(0, SI->getOperand(1));
10515           return &LI;
10516         }
10517     }
10518   }
10519   return 0;
10520 }
10521
10522 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10523 /// when possible.
10524 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10525   User *CI = cast<User>(SI.getOperand(1));
10526   Value *CastOp = CI->getOperand(0);
10527
10528   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10529   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10530     const Type *SrcPTy = SrcTy->getElementType();
10531
10532     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10533       // If the source is an array, the code below will not succeed.  Check to
10534       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
10535       // constants.
10536       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10537         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10538           if (ASrcTy->getNumElements() != 0) {
10539             Value* Idxs[2];
10540             Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10541             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10542             SrcTy = cast<PointerType>(CastOp->getType());
10543             SrcPTy = SrcTy->getElementType();
10544           }
10545
10546       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10547           IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10548                IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10549
10550         // Okay, we are casting from one integer or pointer type to another of
10551         // the same size.  Instead of casting the pointer before 
10552         // the store, cast the value to be stored.
10553         Value *NewCast;
10554         Value *SIOp0 = SI.getOperand(0);
10555         Instruction::CastOps opcode = Instruction::BitCast;
10556         const Type* CastSrcTy = SIOp0->getType();
10557         const Type* CastDstTy = SrcPTy;
10558         if (isa<PointerType>(CastDstTy)) {
10559           if (CastSrcTy->isInteger())
10560             opcode = Instruction::IntToPtr;
10561         } else if (isa<IntegerType>(CastDstTy)) {
10562           if (isa<PointerType>(SIOp0->getType()))
10563             opcode = Instruction::PtrToInt;
10564         }
10565         if (Constant *C = dyn_cast<Constant>(SIOp0))
10566           NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10567         else
10568           NewCast = IC.InsertNewInstBefore(
10569             CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"), 
10570             SI);
10571         return new StoreInst(NewCast, CastOp);
10572       }
10573     }
10574   }
10575   return 0;
10576 }
10577
10578 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10579   Value *Val = SI.getOperand(0);
10580   Value *Ptr = SI.getOperand(1);
10581
10582   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
10583     EraseInstFromFunction(SI);
10584     ++NumCombined;
10585     return 0;
10586   }
10587   
10588   // If the RHS is an alloca with a single use, zapify the store, making the
10589   // alloca dead.
10590   if (Ptr->hasOneUse() && !SI.isVolatile()) {
10591     if (isa<AllocaInst>(Ptr)) {
10592       EraseInstFromFunction(SI);
10593       ++NumCombined;
10594       return 0;
10595     }
10596     
10597     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10598       if (isa<AllocaInst>(GEP->getOperand(0)) &&
10599           GEP->getOperand(0)->hasOneUse()) {
10600         EraseInstFromFunction(SI);
10601         ++NumCombined;
10602         return 0;
10603       }
10604   }
10605
10606   // Attempt to improve the alignment.
10607   unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10608   if (KnownAlign >
10609       (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10610                                 SI.getAlignment()))
10611     SI.setAlignment(KnownAlign);
10612
10613   // Do really simple DSE, to catch cases where there are several consequtive
10614   // stores to the same location, separated by a few arithmetic operations. This
10615   // situation often occurs with bitfield accesses.
10616   BasicBlock::iterator BBI = &SI;
10617   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10618        --ScanInsts) {
10619     --BBI;
10620     
10621     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10622       // Prev store isn't volatile, and stores to the same location?
10623       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10624         ++NumDeadStore;
10625         ++BBI;
10626         EraseInstFromFunction(*PrevSI);
10627         continue;
10628       }
10629       break;
10630     }
10631     
10632     // If this is a load, we have to stop.  However, if the loaded value is from
10633     // the pointer we're loading and is producing the pointer we're storing,
10634     // then *this* store is dead (X = load P; store X -> P).
10635     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10636       if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10637         EraseInstFromFunction(SI);
10638         ++NumCombined;
10639         return 0;
10640       }
10641       // Otherwise, this is a load from some other location.  Stores before it
10642       // may not be dead.
10643       break;
10644     }
10645     
10646     // Don't skip over loads or things that can modify memory.
10647     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10648       break;
10649   }
10650   
10651   
10652   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
10653
10654   // store X, null    -> turns into 'unreachable' in SimplifyCFG
10655   if (isa<ConstantPointerNull>(Ptr)) {
10656     if (!isa<UndefValue>(Val)) {
10657       SI.setOperand(0, UndefValue::get(Val->getType()));
10658       if (Instruction *U = dyn_cast<Instruction>(Val))
10659         AddToWorkList(U);  // Dropped a use.
10660       ++NumCombined;
10661     }
10662     return 0;  // Do not modify these!
10663   }
10664
10665   // store undef, Ptr -> noop
10666   if (isa<UndefValue>(Val)) {
10667     EraseInstFromFunction(SI);
10668     ++NumCombined;
10669     return 0;
10670   }
10671
10672   // If the pointer destination is a cast, see if we can fold the cast into the
10673   // source instead.
10674   if (isa<CastInst>(Ptr))
10675     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10676       return Res;
10677   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10678     if (CE->isCast())
10679       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10680         return Res;
10681
10682   
10683   // If this store is the last instruction in the basic block, and if the block
10684   // ends with an unconditional branch, try to move it to the successor block.
10685   BBI = &SI; ++BBI;
10686   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10687     if (BI->isUnconditional())
10688       if (SimplifyStoreAtEndOfBlock(SI))
10689         return 0;  // xform done!
10690   
10691   return 0;
10692 }
10693
10694 /// SimplifyStoreAtEndOfBlock - Turn things like:
10695 ///   if () { *P = v1; } else { *P = v2 }
10696 /// into a phi node with a store in the successor.
10697 ///
10698 /// Simplify things like:
10699 ///   *P = v1; if () { *P = v2; }
10700 /// into a phi node with a store in the successor.
10701 ///
10702 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10703   BasicBlock *StoreBB = SI.getParent();
10704   
10705   // Check to see if the successor block has exactly two incoming edges.  If
10706   // so, see if the other predecessor contains a store to the same location.
10707   // if so, insert a PHI node (if needed) and move the stores down.
10708   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10709   
10710   // Determine whether Dest has exactly two predecessors and, if so, compute
10711   // the other predecessor.
10712   pred_iterator PI = pred_begin(DestBB);
10713   BasicBlock *OtherBB = 0;
10714   if (*PI != StoreBB)
10715     OtherBB = *PI;
10716   ++PI;
10717   if (PI == pred_end(DestBB))
10718     return false;
10719   
10720   if (*PI != StoreBB) {
10721     if (OtherBB)
10722       return false;
10723     OtherBB = *PI;
10724   }
10725   if (++PI != pred_end(DestBB))
10726     return false;
10727
10728   // Bail out if all the relevant blocks aren't distinct (this can happen,
10729   // for example, if SI is in an infinite loop)
10730   if (StoreBB == DestBB || OtherBB == DestBB)
10731     return false;
10732
10733   // Verify that the other block ends in a branch and is not otherwise empty.
10734   BasicBlock::iterator BBI = OtherBB->getTerminator();
10735   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10736   if (!OtherBr || BBI == OtherBB->begin())
10737     return false;
10738   
10739   // If the other block ends in an unconditional branch, check for the 'if then
10740   // else' case.  there is an instruction before the branch.
10741   StoreInst *OtherStore = 0;
10742   if (OtherBr->isUnconditional()) {
10743     // If this isn't a store, or isn't a store to the same location, bail out.
10744     --BBI;
10745     OtherStore = dyn_cast<StoreInst>(BBI);
10746     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10747       return false;
10748   } else {
10749     // Otherwise, the other block ended with a conditional branch. If one of the
10750     // destinations is StoreBB, then we have the if/then case.
10751     if (OtherBr->getSuccessor(0) != StoreBB && 
10752         OtherBr->getSuccessor(1) != StoreBB)
10753       return false;
10754     
10755     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10756     // if/then triangle.  See if there is a store to the same ptr as SI that
10757     // lives in OtherBB.
10758     for (;; --BBI) {
10759       // Check to see if we find the matching store.
10760       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10761         if (OtherStore->getOperand(1) != SI.getOperand(1))
10762           return false;
10763         break;
10764       }
10765       // If we find something that may be using or overwriting the stored
10766       // value, or if we run out of instructions, we can't do the xform.
10767       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10768           BBI == OtherBB->begin())
10769         return false;
10770     }
10771     
10772     // In order to eliminate the store in OtherBr, we have to
10773     // make sure nothing reads or overwrites the stored value in
10774     // StoreBB.
10775     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10776       // FIXME: This should really be AA driven.
10777       if (I->mayReadFromMemory() || I->mayWriteToMemory())
10778         return false;
10779     }
10780   }
10781   
10782   // Insert a PHI node now if we need it.
10783   Value *MergedVal = OtherStore->getOperand(0);
10784   if (MergedVal != SI.getOperand(0)) {
10785     PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10786     PN->reserveOperandSpace(2);
10787     PN->addIncoming(SI.getOperand(0), SI.getParent());
10788     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10789     MergedVal = InsertNewInstBefore(PN, DestBB->front());
10790   }
10791   
10792   // Advance to a place where it is safe to insert the new store and
10793   // insert it.
10794   BBI = DestBB->getFirstNonPHI();
10795   InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10796                                     OtherStore->isVolatile()), *BBI);
10797   
10798   // Nuke the old stores.
10799   EraseInstFromFunction(SI);
10800   EraseInstFromFunction(*OtherStore);
10801   ++NumCombined;
10802   return true;
10803 }
10804
10805
10806 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10807   // Change br (not X), label True, label False to: br X, label False, True
10808   Value *X = 0;
10809   BasicBlock *TrueDest;
10810   BasicBlock *FalseDest;
10811   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10812       !isa<Constant>(X)) {
10813     // Swap Destinations and condition...
10814     BI.setCondition(X);
10815     BI.setSuccessor(0, FalseDest);
10816     BI.setSuccessor(1, TrueDest);
10817     return &BI;
10818   }
10819
10820   // Cannonicalize fcmp_one -> fcmp_oeq
10821   FCmpInst::Predicate FPred; Value *Y;
10822   if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)), 
10823                              TrueDest, FalseDest)))
10824     if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10825          FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10826       FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10827       FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10828       Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10829       NewSCC->takeName(I);
10830       // Swap Destinations and condition...
10831       BI.setCondition(NewSCC);
10832       BI.setSuccessor(0, FalseDest);
10833       BI.setSuccessor(1, TrueDest);
10834       RemoveFromWorkList(I);
10835       I->eraseFromParent();
10836       AddToWorkList(NewSCC);
10837       return &BI;
10838     }
10839
10840   // Cannonicalize icmp_ne -> icmp_eq
10841   ICmpInst::Predicate IPred;
10842   if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10843                       TrueDest, FalseDest)))
10844     if ((IPred == ICmpInst::ICMP_NE  || IPred == ICmpInst::ICMP_ULE ||
10845          IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10846          IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10847       ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10848       ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10849       Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10850       NewSCC->takeName(I);
10851       // Swap Destinations and condition...
10852       BI.setCondition(NewSCC);
10853       BI.setSuccessor(0, FalseDest);
10854       BI.setSuccessor(1, TrueDest);
10855       RemoveFromWorkList(I);
10856       I->eraseFromParent();;
10857       AddToWorkList(NewSCC);
10858       return &BI;
10859     }
10860
10861   return 0;
10862 }
10863
10864 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10865   Value *Cond = SI.getCondition();
10866   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10867     if (I->getOpcode() == Instruction::Add)
10868       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10869         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10870         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10871           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10872                                                 AddRHS));
10873         SI.setOperand(0, I->getOperand(0));
10874         AddToWorkList(I);
10875         return &SI;
10876       }
10877   }
10878   return 0;
10879 }
10880
10881 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10882   Value *Agg = EV.getAggregateOperand();
10883
10884   if (!EV.hasIndices())
10885     return ReplaceInstUsesWith(EV, Agg);
10886
10887   if (Constant *C = dyn_cast<Constant>(Agg)) {
10888     if (isa<UndefValue>(C))
10889       return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
10890       
10891     if (isa<ConstantAggregateZero>(C))
10892       return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
10893
10894     if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
10895       // Extract the element indexed by the first index out of the constant
10896       Value *V = C->getOperand(*EV.idx_begin());
10897       if (EV.getNumIndices() > 1)
10898         // Extract the remaining indices out of the constant indexed by the
10899         // first index
10900         return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
10901       else
10902         return ReplaceInstUsesWith(EV, V);
10903     }
10904     return 0; // Can't handle other constants
10905   } 
10906   if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
10907     // We're extracting from an insertvalue instruction, compare the indices
10908     const unsigned *exti, *exte, *insi, *inse;
10909     for (exti = EV.idx_begin(), insi = IV->idx_begin(),
10910          exte = EV.idx_end(), inse = IV->idx_end();
10911          exti != exte && insi != inse;
10912          ++exti, ++insi) {
10913       if (*insi != *exti)
10914         // The insert and extract both reference distinctly different elements.
10915         // This means the extract is not influenced by the insert, and we can
10916         // replace the aggregate operand of the extract with the aggregate
10917         // operand of the insert. i.e., replace
10918         // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10919         // %E = extractvalue { i32, { i32 } } %I, 0
10920         // with
10921         // %E = extractvalue { i32, { i32 } } %A, 0
10922         return ExtractValueInst::Create(IV->getAggregateOperand(),
10923                                         EV.idx_begin(), EV.idx_end());
10924     }
10925     if (exti == exte && insi == inse)
10926       // Both iterators are at the end: Index lists are identical. Replace
10927       // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10928       // %C = extractvalue { i32, { i32 } } %B, 1, 0
10929       // with "i32 42"
10930       return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
10931     if (exti == exte) {
10932       // The extract list is a prefix of the insert list. i.e. replace
10933       // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
10934       // %E = extractvalue { i32, { i32 } } %I, 1
10935       // with
10936       // %X = extractvalue { i32, { i32 } } %A, 1
10937       // %E = insertvalue { i32 } %X, i32 42, 0
10938       // by switching the order of the insert and extract (though the
10939       // insertvalue should be left in, since it may have other uses).
10940       Value *NewEV = InsertNewInstBefore(
10941         ExtractValueInst::Create(IV->getAggregateOperand(),
10942                                  EV.idx_begin(), EV.idx_end()),
10943         EV);
10944       return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
10945                                      insi, inse);
10946     }
10947     if (insi == inse)
10948       // The insert list is a prefix of the extract list
10949       // We can simply remove the common indices from the extract and make it
10950       // operate on the inserted value instead of the insertvalue result.
10951       // i.e., replace
10952       // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
10953       // %E = extractvalue { i32, { i32 } } %I, 1, 0
10954       // with
10955       // %E extractvalue { i32 } { i32 42 }, 0
10956       return ExtractValueInst::Create(IV->getInsertedValueOperand(), 
10957                                       exti, exte);
10958   }
10959   // Can't simplify extracts from other values. Note that nested extracts are
10960   // already simplified implicitely by the above (extract ( extract (insert) )
10961   // will be translated into extract ( insert ( extract ) ) first and then just
10962   // the value inserted, if appropriate).
10963   return 0;
10964 }
10965
10966 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10967 /// is to leave as a vector operation.
10968 static bool CheapToScalarize(Value *V, bool isConstant) {
10969   if (isa<ConstantAggregateZero>(V)) 
10970     return true;
10971   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10972     if (isConstant) return true;
10973     // If all elts are the same, we can extract.
10974     Constant *Op0 = C->getOperand(0);
10975     for (unsigned i = 1; i < C->getNumOperands(); ++i)
10976       if (C->getOperand(i) != Op0)
10977         return false;
10978     return true;
10979   }
10980   Instruction *I = dyn_cast<Instruction>(V);
10981   if (!I) return false;
10982   
10983   // Insert element gets simplified to the inserted element or is deleted if
10984   // this is constant idx extract element and its a constant idx insertelt.
10985   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10986       isa<ConstantInt>(I->getOperand(2)))
10987     return true;
10988   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10989     return true;
10990   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10991     if (BO->hasOneUse() &&
10992         (CheapToScalarize(BO->getOperand(0), isConstant) ||
10993          CheapToScalarize(BO->getOperand(1), isConstant)))
10994       return true;
10995   if (CmpInst *CI = dyn_cast<CmpInst>(I))
10996     if (CI->hasOneUse() &&
10997         (CheapToScalarize(CI->getOperand(0), isConstant) ||
10998          CheapToScalarize(CI->getOperand(1), isConstant)))
10999       return true;
11000   
11001   return false;
11002 }
11003
11004 /// Read and decode a shufflevector mask.
11005 ///
11006 /// It turns undef elements into values that are larger than the number of
11007 /// elements in the input.
11008 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11009   unsigned NElts = SVI->getType()->getNumElements();
11010   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11011     return std::vector<unsigned>(NElts, 0);
11012   if (isa<UndefValue>(SVI->getOperand(2)))
11013     return std::vector<unsigned>(NElts, 2*NElts);
11014
11015   std::vector<unsigned> Result;
11016   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11017   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11018     if (isa<UndefValue>(*i))
11019       Result.push_back(NElts*2);  // undef -> 8
11020     else
11021       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11022   return Result;
11023 }
11024
11025 /// FindScalarElement - Given a vector and an element number, see if the scalar
11026 /// value is already around as a register, for example if it were inserted then
11027 /// extracted from the vector.
11028 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11029   assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11030   const VectorType *PTy = cast<VectorType>(V->getType());
11031   unsigned Width = PTy->getNumElements();
11032   if (EltNo >= Width)  // Out of range access.
11033     return UndefValue::get(PTy->getElementType());
11034   
11035   if (isa<UndefValue>(V))
11036     return UndefValue::get(PTy->getElementType());
11037   else if (isa<ConstantAggregateZero>(V))
11038     return Constant::getNullValue(PTy->getElementType());
11039   else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11040     return CP->getOperand(EltNo);
11041   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11042     // If this is an insert to a variable element, we don't know what it is.
11043     if (!isa<ConstantInt>(III->getOperand(2))) 
11044       return 0;
11045     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11046     
11047     // If this is an insert to the element we are looking for, return the
11048     // inserted value.
11049     if (EltNo == IIElt) 
11050       return III->getOperand(1);
11051     
11052     // Otherwise, the insertelement doesn't modify the value, recurse on its
11053     // vector input.
11054     return FindScalarElement(III->getOperand(0), EltNo);
11055   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11056     unsigned InEl = getShuffleMask(SVI)[EltNo];
11057     if (InEl < Width)
11058       return FindScalarElement(SVI->getOperand(0), InEl);
11059     else if (InEl < Width*2)
11060       return FindScalarElement(SVI->getOperand(1), InEl - Width);
11061     else
11062       return UndefValue::get(PTy->getElementType());
11063   }
11064   
11065   // Otherwise, we don't know.
11066   return 0;
11067 }
11068
11069 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11070   // If vector val is undef, replace extract with scalar undef.
11071   if (isa<UndefValue>(EI.getOperand(0)))
11072     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11073
11074   // If vector val is constant 0, replace extract with scalar 0.
11075   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11076     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11077   
11078   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11079     // If vector val is constant with all elements the same, replace EI with
11080     // that element. When the elements are not identical, we cannot replace yet
11081     // (we do that below, but only when the index is constant).
11082     Constant *op0 = C->getOperand(0);
11083     for (unsigned i = 1; i < C->getNumOperands(); ++i)
11084       if (C->getOperand(i) != op0) {
11085         op0 = 0; 
11086         break;
11087       }
11088     if (op0)
11089       return ReplaceInstUsesWith(EI, op0);
11090   }
11091   
11092   // If extracting a specified index from the vector, see if we can recursively
11093   // find a previously computed scalar that was inserted into the vector.
11094   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11095     unsigned IndexVal = IdxC->getZExtValue();
11096     unsigned VectorWidth = 
11097       cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11098       
11099     // If this is extracting an invalid index, turn this into undef, to avoid
11100     // crashing the code below.
11101     if (IndexVal >= VectorWidth)
11102       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11103     
11104     // This instruction only demands the single element from the input vector.
11105     // If the input vector has a single use, simplify it based on this use
11106     // property.
11107     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11108       uint64_t UndefElts;
11109       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11110                                                 1 << IndexVal,
11111                                                 UndefElts)) {
11112         EI.setOperand(0, V);
11113         return &EI;
11114       }
11115     }
11116     
11117     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11118       return ReplaceInstUsesWith(EI, Elt);
11119     
11120     // If the this extractelement is directly using a bitcast from a vector of
11121     // the same number of elements, see if we can find the source element from
11122     // it.  In this case, we will end up needing to bitcast the scalars.
11123     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11124       if (const VectorType *VT = 
11125               dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11126         if (VT->getNumElements() == VectorWidth)
11127           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11128             return new BitCastInst(Elt, EI.getType());
11129     }
11130   }
11131   
11132   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11133     if (I->hasOneUse()) {
11134       // Push extractelement into predecessor operation if legal and
11135       // profitable to do so
11136       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11137         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11138         if (CheapToScalarize(BO, isConstantElt)) {
11139           ExtractElementInst *newEI0 = 
11140             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11141                                    EI.getName()+".lhs");
11142           ExtractElementInst *newEI1 =
11143             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11144                                    EI.getName()+".rhs");
11145           InsertNewInstBefore(newEI0, EI);
11146           InsertNewInstBefore(newEI1, EI);
11147           return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11148         }
11149       } else if (isa<LoadInst>(I)) {
11150         unsigned AS = 
11151           cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11152         Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11153                                          PointerType::get(EI.getType(), AS),EI);
11154         GetElementPtrInst *GEP =
11155           GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11156         InsertNewInstBefore(GEP, EI);
11157         return new LoadInst(GEP);
11158       }
11159     }
11160     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11161       // Extracting the inserted element?
11162       if (IE->getOperand(2) == EI.getOperand(1))
11163         return ReplaceInstUsesWith(EI, IE->getOperand(1));
11164       // If the inserted and extracted elements are constants, they must not
11165       // be the same value, extract from the pre-inserted value instead.
11166       if (isa<Constant>(IE->getOperand(2)) &&
11167           isa<Constant>(EI.getOperand(1))) {
11168         AddUsesToWorkList(EI);
11169         EI.setOperand(0, IE->getOperand(0));
11170         return &EI;
11171       }
11172     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11173       // If this is extracting an element from a shufflevector, figure out where
11174       // it came from and extract from the appropriate input element instead.
11175       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11176         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11177         Value *Src;
11178         if (SrcIdx < SVI->getType()->getNumElements())
11179           Src = SVI->getOperand(0);
11180         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11181           SrcIdx -= SVI->getType()->getNumElements();
11182           Src = SVI->getOperand(1);
11183         } else {
11184           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11185         }
11186         return new ExtractElementInst(Src, SrcIdx);
11187       }
11188     }
11189   }
11190   return 0;
11191 }
11192
11193 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11194 /// elements from either LHS or RHS, return the shuffle mask and true. 
11195 /// Otherwise, return false.
11196 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11197                                          std::vector<Constant*> &Mask) {
11198   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11199          "Invalid CollectSingleShuffleElements");
11200   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11201
11202   if (isa<UndefValue>(V)) {
11203     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11204     return true;
11205   } else if (V == LHS) {
11206     for (unsigned i = 0; i != NumElts; ++i)
11207       Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11208     return true;
11209   } else if (V == RHS) {
11210     for (unsigned i = 0; i != NumElts; ++i)
11211       Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11212     return true;
11213   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11214     // If this is an insert of an extract from some other vector, include it.
11215     Value *VecOp    = IEI->getOperand(0);
11216     Value *ScalarOp = IEI->getOperand(1);
11217     Value *IdxOp    = IEI->getOperand(2);
11218     
11219     if (!isa<ConstantInt>(IdxOp))
11220       return false;
11221     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11222     
11223     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
11224       // Okay, we can handle this if the vector we are insertinting into is
11225       // transitively ok.
11226       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11227         // If so, update the mask to reflect the inserted undef.
11228         Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11229         return true;
11230       }      
11231     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11232       if (isa<ConstantInt>(EI->getOperand(1)) &&
11233           EI->getOperand(0)->getType() == V->getType()) {
11234         unsigned ExtractedIdx =
11235           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11236         
11237         // This must be extracting from either LHS or RHS.
11238         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11239           // Okay, we can handle this if the vector we are insertinting into is
11240           // transitively ok.
11241           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11242             // If so, update the mask to reflect the inserted value.
11243             if (EI->getOperand(0) == LHS) {
11244               Mask[InsertedIdx % NumElts] = 
11245                  ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11246             } else {
11247               assert(EI->getOperand(0) == RHS);
11248               Mask[InsertedIdx % NumElts] = 
11249                 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11250               
11251             }
11252             return true;
11253           }
11254         }
11255       }
11256     }
11257   }
11258   // TODO: Handle shufflevector here!
11259   
11260   return false;
11261 }
11262
11263 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11264 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
11265 /// that computes V and the LHS value of the shuffle.
11266 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11267                                      Value *&RHS) {
11268   assert(isa<VectorType>(V->getType()) && 
11269          (RHS == 0 || V->getType() == RHS->getType()) &&
11270          "Invalid shuffle!");
11271   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11272
11273   if (isa<UndefValue>(V)) {
11274     Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11275     return V;
11276   } else if (isa<ConstantAggregateZero>(V)) {
11277     Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11278     return V;
11279   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11280     // If this is an insert of an extract from some other vector, include it.
11281     Value *VecOp    = IEI->getOperand(0);
11282     Value *ScalarOp = IEI->getOperand(1);
11283     Value *IdxOp    = IEI->getOperand(2);
11284     
11285     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11286       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11287           EI->getOperand(0)->getType() == V->getType()) {
11288         unsigned ExtractedIdx =
11289           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11290         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11291         
11292         // Either the extracted from or inserted into vector must be RHSVec,
11293         // otherwise we'd end up with a shuffle of three inputs.
11294         if (EI->getOperand(0) == RHS || RHS == 0) {
11295           RHS = EI->getOperand(0);
11296           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11297           Mask[InsertedIdx % NumElts] = 
11298             ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11299           return V;
11300         }
11301         
11302         if (VecOp == RHS) {
11303           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11304           // Everything but the extracted element is replaced with the RHS.
11305           for (unsigned i = 0; i != NumElts; ++i) {
11306             if (i != InsertedIdx)
11307               Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11308           }
11309           return V;
11310         }
11311         
11312         // If this insertelement is a chain that comes from exactly these two
11313         // vectors, return the vector and the effective shuffle.
11314         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11315           return EI->getOperand(0);
11316         
11317       }
11318     }
11319   }
11320   // TODO: Handle shufflevector here!
11321   
11322   // Otherwise, can't do anything fancy.  Return an identity vector.
11323   for (unsigned i = 0; i != NumElts; ++i)
11324     Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11325   return V;
11326 }
11327
11328 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11329   Value *VecOp    = IE.getOperand(0);
11330   Value *ScalarOp = IE.getOperand(1);
11331   Value *IdxOp    = IE.getOperand(2);
11332   
11333   // Inserting an undef or into an undefined place, remove this.
11334   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11335     ReplaceInstUsesWith(IE, VecOp);
11336   
11337   // If the inserted element was extracted from some other vector, and if the 
11338   // indexes are constant, try to turn this into a shufflevector operation.
11339   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11340     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11341         EI->getOperand(0)->getType() == IE.getType()) {
11342       unsigned NumVectorElts = IE.getType()->getNumElements();
11343       unsigned ExtractedIdx =
11344         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11345       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11346       
11347       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11348         return ReplaceInstUsesWith(IE, VecOp);
11349       
11350       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
11351         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11352       
11353       // If we are extracting a value from a vector, then inserting it right
11354       // back into the same place, just use the input vector.
11355       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11356         return ReplaceInstUsesWith(IE, VecOp);      
11357       
11358       // We could theoretically do this for ANY input.  However, doing so could
11359       // turn chains of insertelement instructions into a chain of shufflevector
11360       // instructions, and right now we do not merge shufflevectors.  As such,
11361       // only do this in a situation where it is clear that there is benefit.
11362       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11363         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
11364         // the values of VecOp, except then one read from EIOp0.
11365         // Build a new shuffle mask.
11366         std::vector<Constant*> Mask;
11367         if (isa<UndefValue>(VecOp))
11368           Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11369         else {
11370           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11371           Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11372                                                        NumVectorElts));
11373         } 
11374         Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11375         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11376                                      ConstantVector::get(Mask));
11377       }
11378       
11379       // If this insertelement isn't used by some other insertelement, turn it
11380       // (and any insertelements it points to), into one big shuffle.
11381       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11382         std::vector<Constant*> Mask;
11383         Value *RHS = 0;
11384         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11385         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11386         // We now have a shuffle of LHS, RHS, Mask.
11387         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11388       }
11389     }
11390   }
11391
11392   return 0;
11393 }
11394
11395
11396 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11397   Value *LHS = SVI.getOperand(0);
11398   Value *RHS = SVI.getOperand(1);
11399   std::vector<unsigned> Mask = getShuffleMask(&SVI);
11400
11401   bool MadeChange = false;
11402   
11403   // Undefined shuffle mask -> undefined value.
11404   if (isa<UndefValue>(SVI.getOperand(2)))
11405     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11406
11407   uint64_t UndefElts;
11408   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11409   uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11410   if (VWidth <= 64 &&
11411       SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11412     LHS = SVI.getOperand(0);
11413     RHS = SVI.getOperand(1);
11414     MadeChange = true;
11415   }
11416   
11417   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
11418   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11419   if (LHS == RHS || isa<UndefValue>(LHS)) {
11420     if (isa<UndefValue>(LHS) && LHS == RHS) {
11421       // shuffle(undef,undef,mask) -> undef.
11422       return ReplaceInstUsesWith(SVI, LHS);
11423     }
11424     
11425     // Remap any references to RHS to use LHS.
11426     std::vector<Constant*> Elts;
11427     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11428       if (Mask[i] >= 2*e)
11429         Elts.push_back(UndefValue::get(Type::Int32Ty));
11430       else {
11431         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11432             (Mask[i] <  e && isa<UndefValue>(LHS))) {
11433           Mask[i] = 2*e;     // Turn into undef.
11434           Elts.push_back(UndefValue::get(Type::Int32Ty));
11435         } else {
11436           Mask[i] = Mask[i] % e;  // Force to LHS.
11437           Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11438         }
11439       }
11440     }
11441     SVI.setOperand(0, SVI.getOperand(1));
11442     SVI.setOperand(1, UndefValue::get(RHS->getType()));
11443     SVI.setOperand(2, ConstantVector::get(Elts));
11444     LHS = SVI.getOperand(0);
11445     RHS = SVI.getOperand(1);
11446     MadeChange = true;
11447   }
11448   
11449   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11450   bool isLHSID = true, isRHSID = true;
11451     
11452   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11453     if (Mask[i] >= e*2) continue;  // Ignore undef values.
11454     // Is this an identity shuffle of the LHS value?
11455     isLHSID &= (Mask[i] == i);
11456       
11457     // Is this an identity shuffle of the RHS value?
11458     isRHSID &= (Mask[i]-e == i);
11459   }
11460
11461   // Eliminate identity shuffles.
11462   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11463   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11464   
11465   // If the LHS is a shufflevector itself, see if we can combine it with this
11466   // one without producing an unusual shuffle.  Here we are really conservative:
11467   // we are absolutely afraid of producing a shuffle mask not in the input
11468   // program, because the code gen may not be smart enough to turn a merged
11469   // shuffle into two specific shuffles: it may produce worse code.  As such,
11470   // we only merge two shuffles if the result is one of the two input shuffle
11471   // masks.  In this case, merging the shuffles just removes one instruction,
11472   // which we know is safe.  This is good for things like turning:
11473   // (splat(splat)) -> splat.
11474   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11475     if (isa<UndefValue>(RHS)) {
11476       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11477
11478       std::vector<unsigned> NewMask;
11479       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11480         if (Mask[i] >= 2*e)
11481           NewMask.push_back(2*e);
11482         else
11483           NewMask.push_back(LHSMask[Mask[i]]);
11484       
11485       // If the result mask is equal to the src shuffle or this shuffle mask, do
11486       // the replacement.
11487       if (NewMask == LHSMask || NewMask == Mask) {
11488         std::vector<Constant*> Elts;
11489         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11490           if (NewMask[i] >= e*2) {
11491             Elts.push_back(UndefValue::get(Type::Int32Ty));
11492           } else {
11493             Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11494           }
11495         }
11496         return new ShuffleVectorInst(LHSSVI->getOperand(0),
11497                                      LHSSVI->getOperand(1),
11498                                      ConstantVector::get(Elts));
11499       }
11500     }
11501   }
11502
11503   return MadeChange ? &SVI : 0;
11504 }
11505
11506
11507
11508
11509 /// TryToSinkInstruction - Try to move the specified instruction from its
11510 /// current block into the beginning of DestBlock, which can only happen if it's
11511 /// safe to move the instruction past all of the instructions between it and the
11512 /// end of its block.
11513 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11514   assert(I->hasOneUse() && "Invariants didn't hold!");
11515
11516   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11517   if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11518     return false;
11519
11520   // Do not sink alloca instructions out of the entry block.
11521   if (isa<AllocaInst>(I) && I->getParent() ==
11522         &DestBlock->getParent()->getEntryBlock())
11523     return false;
11524
11525   // We can only sink load instructions if there is nothing between the load and
11526   // the end of block that could change the value.
11527   if (I->mayReadFromMemory()) {
11528     for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11529          Scan != E; ++Scan)
11530       if (Scan->mayWriteToMemory())
11531         return false;
11532   }
11533
11534   BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11535
11536   I->moveBefore(InsertPos);
11537   ++NumSunkInst;
11538   return true;
11539 }
11540
11541
11542 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11543 /// all reachable code to the worklist.
11544 ///
11545 /// This has a couple of tricks to make the code faster and more powerful.  In
11546 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11547 /// them to the worklist (this significantly speeds up instcombine on code where
11548 /// many instructions are dead or constant).  Additionally, if we find a branch
11549 /// whose condition is a known constant, we only visit the reachable successors.
11550 ///
11551 static void AddReachableCodeToWorklist(BasicBlock *BB, 
11552                                        SmallPtrSet<BasicBlock*, 64> &Visited,
11553                                        InstCombiner &IC,
11554                                        const TargetData *TD) {
11555   SmallVector<BasicBlock*, 256> Worklist;
11556   Worklist.push_back(BB);
11557
11558   while (!Worklist.empty()) {
11559     BB = Worklist.back();
11560     Worklist.pop_back();
11561     
11562     // We have now visited this block!  If we've already been here, ignore it.
11563     if (!Visited.insert(BB)) continue;
11564     
11565     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11566       Instruction *Inst = BBI++;
11567       
11568       // DCE instruction if trivially dead.
11569       if (isInstructionTriviallyDead(Inst)) {
11570         ++NumDeadInst;
11571         DOUT << "IC: DCE: " << *Inst;
11572         Inst->eraseFromParent();
11573         continue;
11574       }
11575       
11576       // ConstantProp instruction if trivially constant.
11577       if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11578         DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11579         Inst->replaceAllUsesWith(C);
11580         ++NumConstProp;
11581         Inst->eraseFromParent();
11582         continue;
11583       }
11584      
11585       IC.AddToWorkList(Inst);
11586     }
11587
11588     // Recursively visit successors.  If this is a branch or switch on a
11589     // constant, only visit the reachable successor.
11590     TerminatorInst *TI = BB->getTerminator();
11591     if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11592       if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11593         bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11594         BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11595         Worklist.push_back(ReachableBB);
11596         continue;
11597       }
11598     } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11599       if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11600         // See if this is an explicit destination.
11601         for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11602           if (SI->getCaseValue(i) == Cond) {
11603             BasicBlock *ReachableBB = SI->getSuccessor(i);
11604             Worklist.push_back(ReachableBB);
11605             continue;
11606           }
11607         
11608         // Otherwise it is the default destination.
11609         Worklist.push_back(SI->getSuccessor(0));
11610         continue;
11611       }
11612     }
11613     
11614     for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11615       Worklist.push_back(TI->getSuccessor(i));
11616   }
11617 }
11618
11619 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11620   bool Changed = false;
11621   TD = &getAnalysis<TargetData>();
11622   
11623   DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11624              << F.getNameStr() << "\n");
11625
11626   {
11627     // Do a depth-first traversal of the function, populate the worklist with
11628     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
11629     // track of which blocks we visit.
11630     SmallPtrSet<BasicBlock*, 64> Visited;
11631     AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11632
11633     // Do a quick scan over the function.  If we find any blocks that are
11634     // unreachable, remove any instructions inside of them.  This prevents
11635     // the instcombine code from having to deal with some bad special cases.
11636     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11637       if (!Visited.count(BB)) {
11638         Instruction *Term = BB->getTerminator();
11639         while (Term != BB->begin()) {   // Remove instrs bottom-up
11640           BasicBlock::iterator I = Term; --I;
11641
11642           DOUT << "IC: DCE: " << *I;
11643           ++NumDeadInst;
11644
11645           if (!I->use_empty())
11646             I->replaceAllUsesWith(UndefValue::get(I->getType()));
11647           I->eraseFromParent();
11648         }
11649       }
11650   }
11651
11652   while (!Worklist.empty()) {
11653     Instruction *I = RemoveOneFromWorkList();
11654     if (I == 0) continue;  // skip null values.
11655
11656     // Check to see if we can DCE the instruction.
11657     if (isInstructionTriviallyDead(I)) {
11658       // Add operands to the worklist.
11659       if (I->getNumOperands() < 4)
11660         AddUsesToWorkList(*I);
11661       ++NumDeadInst;
11662
11663       DOUT << "IC: DCE: " << *I;
11664
11665       I->eraseFromParent();
11666       RemoveFromWorkList(I);
11667       continue;
11668     }
11669
11670     // Instruction isn't dead, see if we can constant propagate it.
11671     if (Constant *C = ConstantFoldInstruction(I, TD)) {
11672       DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11673
11674       // Add operands to the worklist.
11675       AddUsesToWorkList(*I);
11676       ReplaceInstUsesWith(*I, C);
11677
11678       ++NumConstProp;
11679       I->eraseFromParent();
11680       RemoveFromWorkList(I);
11681       continue;
11682     }
11683
11684     if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11685       // See if we can constant fold its operands.
11686       for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11687         if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11688           if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11689             i->set(NewC);
11690         }
11691       }
11692     }
11693
11694     // See if we can trivially sink this instruction to a successor basic block.
11695     if (I->hasOneUse()) {
11696       BasicBlock *BB = I->getParent();
11697       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11698       if (UserParent != BB) {
11699         bool UserIsSuccessor = false;
11700         // See if the user is one of our successors.
11701         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11702           if (*SI == UserParent) {
11703             UserIsSuccessor = true;
11704             break;
11705           }
11706
11707         // If the user is one of our immediate successors, and if that successor
11708         // only has us as a predecessors (we'd have to split the critical edge
11709         // otherwise), we can keep going.
11710         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11711             next(pred_begin(UserParent)) == pred_end(UserParent))
11712           // Okay, the CFG is simple enough, try to sink this instruction.
11713           Changed |= TryToSinkInstruction(I, UserParent);
11714       }
11715     }
11716
11717     // Now that we have an instruction, try combining it to simplify it...
11718 #ifndef NDEBUG
11719     std::string OrigI;
11720 #endif
11721     DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11722     if (Instruction *Result = visit(*I)) {
11723       ++NumCombined;
11724       // Should we replace the old instruction with a new one?
11725       if (Result != I) {
11726         DOUT << "IC: Old = " << *I
11727              << "    New = " << *Result;
11728
11729         // Everything uses the new instruction now.
11730         I->replaceAllUsesWith(Result);
11731
11732         // Push the new instruction and any users onto the worklist.
11733         AddToWorkList(Result);
11734         AddUsersToWorkList(*Result);
11735
11736         // Move the name to the new instruction first.
11737         Result->takeName(I);
11738
11739         // Insert the new instruction into the basic block...
11740         BasicBlock *InstParent = I->getParent();
11741         BasicBlock::iterator InsertPos = I;
11742
11743         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
11744           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11745             ++InsertPos;
11746
11747         InstParent->getInstList().insert(InsertPos, Result);
11748
11749         // Make sure that we reprocess all operands now that we reduced their
11750         // use counts.
11751         AddUsesToWorkList(*I);
11752
11753         // Instructions can end up on the worklist more than once.  Make sure
11754         // we do not process an instruction that has been deleted.
11755         RemoveFromWorkList(I);
11756
11757         // Erase the old instruction.
11758         InstParent->getInstList().erase(I);
11759       } else {
11760 #ifndef NDEBUG
11761         DOUT << "IC: Mod = " << OrigI
11762              << "    New = " << *I;
11763 #endif
11764
11765         // If the instruction was modified, it's possible that it is now dead.
11766         // if so, remove it.
11767         if (isInstructionTriviallyDead(I)) {
11768           // Make sure we process all operands now that we are reducing their
11769           // use counts.
11770           AddUsesToWorkList(*I);
11771
11772           // Instructions may end up in the worklist more than once.  Erase all
11773           // occurrences of this instruction.
11774           RemoveFromWorkList(I);
11775           I->eraseFromParent();
11776         } else {
11777           AddToWorkList(I);
11778           AddUsersToWorkList(*I);
11779         }
11780       }
11781       Changed = true;
11782     }
11783   }
11784
11785   assert(WorklistMap.empty() && "Worklist empty, but map not?");
11786     
11787   // Do an explicit clear, this shrinks the map if needed.
11788   WorklistMap.clear();
11789   return Changed;
11790 }
11791
11792
11793 bool InstCombiner::runOnFunction(Function &F) {
11794   MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11795   
11796   bool EverMadeChange = false;
11797
11798   // Iterate while there is work to do.
11799   unsigned Iteration = 0;
11800   while (DoOneIteration(F, Iteration++))
11801     EverMadeChange = true;
11802   return EverMadeChange;
11803 }
11804
11805 FunctionPass *llvm::createInstructionCombiningPass() {
11806   return new InstCombiner();
11807 }
11808
11809