d3a625b8bc113cd2f527b56f9cd5eb13ede0b7f2
[oota-llvm.git] / lib / Transforms / Scalar / InstructionCombining.cpp
1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions.  This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
13 //
14 // This pass combines things like:
15 //    %Y = add int %X, 1
16 //    %Z = add int %Y, 1
17 // into:
18 //    %Z = add int %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. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 //    4. All SetCC 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/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 #include <iostream>
56 using namespace llvm;
57 using namespace llvm::PatternMatch;
58
59 namespace {
60   Statistic<> NumCombined ("instcombine", "Number of insts combined");
61   Statistic<> NumConstProp("instcombine", "Number of constant folds");
62   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63   Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64   Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
65
66   class VISIBILITY_HIDDEN InstCombiner
67     : public FunctionPass,
68       public InstVisitor<InstCombiner, Instruction*> {
69     // Worklist of all of the instructions that need to be simplified.
70     std::vector<Instruction*> WorkList;
71     TargetData *TD;
72
73     /// AddUsersToWorkList - When an instruction is simplified, add all users of
74     /// the instruction to the work lists because they might get more simplified
75     /// now.
76     ///
77     void AddUsersToWorkList(Value &I) {
78       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79            UI != UE; ++UI)
80         WorkList.push_back(cast<Instruction>(*UI));
81     }
82
83     /// AddUsesToWorkList - When an instruction is simplified, add operands to
84     /// the work lists because they might get more simplified now.
85     ///
86     void AddUsesToWorkList(Instruction &I) {
87       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89           WorkList.push_back(Op);
90     }
91     
92     /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93     /// dead.  Add all of its operands to the worklist, turning them into
94     /// undef's to reduce the number of uses of those instructions.
95     ///
96     /// Return the specified operand before it is turned into an undef.
97     ///
98     Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99       Value *R = I.getOperand(op);
100       
101       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103           WorkList.push_back(Op);
104           // Set the operand to undef to drop the use.
105           I.setOperand(i, UndefValue::get(Op->getType()));
106         }
107       
108       return R;
109     }
110
111     // removeFromWorkList - remove all instances of I from the worklist.
112     void removeFromWorkList(Instruction *I);
113   public:
114     virtual bool runOnFunction(Function &F);
115
116     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117       AU.addRequired<TargetData>();
118       AU.addPreservedID(LCSSAID);
119       AU.setPreservesCFG();
120     }
121
122     TargetData &getTargetData() const { return *TD; }
123
124     // Visitation implementation - Implement instruction combining for different
125     // instruction types.  The semantics are as follows:
126     // Return Value:
127     //    null        - No change was made
128     //     I          - Change was made, I is still valid, I may be dead though
129     //   otherwise    - Change was made, replace I with returned instruction
130     //
131     Instruction *visitAdd(BinaryOperator &I);
132     Instruction *visitSub(BinaryOperator &I);
133     Instruction *visitMul(BinaryOperator &I);
134     Instruction *visitURem(BinaryOperator &I);
135     Instruction *visitSRem(BinaryOperator &I);
136     Instruction *visitFRem(BinaryOperator &I);
137     Instruction *commonRemTransforms(BinaryOperator &I);
138     Instruction *commonIRemTransforms(BinaryOperator &I);
139     Instruction *commonDivTransforms(BinaryOperator &I);
140     Instruction *commonIDivTransforms(BinaryOperator &I);
141     Instruction *visitUDiv(BinaryOperator &I);
142     Instruction *visitSDiv(BinaryOperator &I);
143     Instruction *visitFDiv(BinaryOperator &I);
144     Instruction *visitAnd(BinaryOperator &I);
145     Instruction *visitOr (BinaryOperator &I);
146     Instruction *visitXor(BinaryOperator &I);
147     Instruction *visitSetCondInst(SetCondInst &I);
148     Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
149
150     Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
151                               Instruction::BinaryOps Cond, Instruction &I);
152     Instruction *visitShiftInst(ShiftInst &I);
153     Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
154                                      ShiftInst &I);
155     Instruction *visitCastInst(CastInst &CI);
156     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
157                                 Instruction *FI);
158     Instruction *visitSelectInst(SelectInst &CI);
159     Instruction *visitCallInst(CallInst &CI);
160     Instruction *visitInvokeInst(InvokeInst &II);
161     Instruction *visitPHINode(PHINode &PN);
162     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
163     Instruction *visitAllocationInst(AllocationInst &AI);
164     Instruction *visitFreeInst(FreeInst &FI);
165     Instruction *visitLoadInst(LoadInst &LI);
166     Instruction *visitStoreInst(StoreInst &SI);
167     Instruction *visitBranchInst(BranchInst &BI);
168     Instruction *visitSwitchInst(SwitchInst &SI);
169     Instruction *visitInsertElementInst(InsertElementInst &IE);
170     Instruction *visitExtractElementInst(ExtractElementInst &EI);
171     Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
172
173     // visitInstruction - Specify what to return for unhandled instructions...
174     Instruction *visitInstruction(Instruction &I) { return 0; }
175
176   private:
177     Instruction *visitCallSite(CallSite CS);
178     bool transformConstExprCastCall(CallSite CS);
179
180   public:
181     // InsertNewInstBefore - insert an instruction New before instruction Old
182     // in the program.  Add the new instruction to the worklist.
183     //
184     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
185       assert(New && New->getParent() == 0 &&
186              "New instruction already inserted into a basic block!");
187       BasicBlock *BB = Old.getParent();
188       BB->getInstList().insert(&Old, New);  // Insert inst
189       WorkList.push_back(New);              // Add to worklist
190       return New;
191     }
192
193     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
194     /// This also adds the cast to the worklist.  Finally, this returns the
195     /// cast.
196     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
197       if (V->getType() == Ty) return V;
198
199       if (Constant *CV = dyn_cast<Constant>(V))
200         return ConstantExpr::getCast(CV, Ty);
201       
202       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
203       WorkList.push_back(C);
204       return C;
205     }
206
207     // ReplaceInstUsesWith - This method is to be used when an instruction is
208     // found to be dead, replacable with another preexisting expression.  Here
209     // we add all uses of I to the worklist, replace all uses of I with the new
210     // value, then return I, so that the inst combiner will know that I was
211     // modified.
212     //
213     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
214       AddUsersToWorkList(I);         // Add all modified instrs to worklist
215       if (&I != V) {
216         I.replaceAllUsesWith(V);
217         return &I;
218       } else {
219         // If we are replacing the instruction with itself, this must be in a
220         // segment of unreachable code, so just clobber the instruction.
221         I.replaceAllUsesWith(UndefValue::get(I.getType()));
222         return &I;
223       }
224     }
225
226     // UpdateValueUsesWith - This method is to be used when an value is
227     // found to be replacable with another preexisting expression or was
228     // updated.  Here we add all uses of I to the worklist, replace all uses of
229     // I with the new value (unless the instruction was just updated), then
230     // return true, so that the inst combiner will know that I was modified.
231     //
232     bool UpdateValueUsesWith(Value *Old, Value *New) {
233       AddUsersToWorkList(*Old);         // Add all modified instrs to worklist
234       if (Old != New)
235         Old->replaceAllUsesWith(New);
236       if (Instruction *I = dyn_cast<Instruction>(Old))
237         WorkList.push_back(I);
238       if (Instruction *I = dyn_cast<Instruction>(New))
239         WorkList.push_back(I);
240       return true;
241     }
242     
243     // EraseInstFromFunction - When dealing with an instruction that has side
244     // effects or produces a void value, we can't rely on DCE to delete the
245     // instruction.  Instead, visit methods should return the value returned by
246     // this function.
247     Instruction *EraseInstFromFunction(Instruction &I) {
248       assert(I.use_empty() && "Cannot erase instruction that is used!");
249       AddUsesToWorkList(I);
250       removeFromWorkList(&I);
251       I.eraseFromParent();
252       return 0;  // Don't do anything with FI
253     }
254
255   private:
256     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
257     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
258     /// casts that are known to not do anything...
259     ///
260     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
261                                    Instruction *InsertBefore);
262
263     // SimplifyCommutative - This performs a few simplifications for commutative
264     // operators.
265     bool SimplifyCommutative(BinaryOperator &I);
266
267     bool SimplifyDemandedBits(Value *V, uint64_t Mask, 
268                               uint64_t &KnownZero, uint64_t &KnownOne,
269                               unsigned Depth = 0);
270
271     Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
272                                       uint64_t &UndefElts, unsigned Depth = 0);
273       
274     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
275     // PHI node as operand #0, see if we can fold the instruction into the PHI
276     // (which is only possible if all operands to the PHI are constants).
277     Instruction *FoldOpIntoPhi(Instruction &I);
278
279     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
280     // operator and they all are only used by the PHI, PHI together their
281     // inputs, and do the operation once, to the result of the PHI.
282     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
283     Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
284     
285     
286     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
287                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
288     
289     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
290                               bool isSub, Instruction &I);
291     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
292                                  bool Inside, Instruction &IB);
293     Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
294     Instruction *MatchBSwap(BinaryOperator &I);
295
296     Value *EvaluateInDifferentType(Value *V, const Type *Ty);
297   };
298
299   RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
300 }
301
302 // getComplexity:  Assign a complexity or rank value to LLVM Values...
303 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
304 static unsigned getComplexity(Value *V) {
305   if (isa<Instruction>(V)) {
306     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
307       return 3;
308     return 4;
309   }
310   if (isa<Argument>(V)) return 3;
311   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
312 }
313
314 // isOnlyUse - Return true if this instruction will be deleted if we stop using
315 // it.
316 static bool isOnlyUse(Value *V) {
317   return V->hasOneUse() || isa<Constant>(V);
318 }
319
320 // getPromotedType - Return the specified type promoted as it would be to pass
321 // though a va_arg area...
322 static const Type *getPromotedType(const Type *Ty) {
323   switch (Ty->getTypeID()) {
324   case Type::SByteTyID:
325   case Type::ShortTyID:  return Type::IntTy;
326   case Type::UByteTyID:
327   case Type::UShortTyID: return Type::UIntTy;
328   case Type::FloatTyID:  return Type::DoubleTy;
329   default:               return Ty;
330   }
331 }
332
333 /// isCast - If the specified operand is a CastInst or a constant expr cast,
334 /// return the operand value, otherwise return null.
335 static Value *isCast(Value *V) {
336   if (CastInst *I = dyn_cast<CastInst>(V))
337     return I->getOperand(0);
338   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
339     if (CE->getOpcode() == Instruction::Cast)
340       return CE->getOperand(0);
341   return 0;
342 }
343
344 enum CastType {
345   Noop     = 0,
346   Truncate = 1,
347   Signext  = 2,
348   Zeroext  = 3
349 };
350
351 /// getCastType - In the future, we will split the cast instruction into these
352 /// various types.  Until then, we have to do the analysis here.
353 static CastType getCastType(const Type *Src, const Type *Dest) {
354   assert(Src->isIntegral() && Dest->isIntegral() &&
355          "Only works on integral types!");
356   unsigned SrcSize = Src->getPrimitiveSizeInBits();
357   unsigned DestSize = Dest->getPrimitiveSizeInBits();
358   
359   if (SrcSize == DestSize) return Noop;
360   if (SrcSize > DestSize)  return Truncate;
361   if (Src->isSigned()) return Signext;
362   return Zeroext;
363 }
364
365
366 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
367 // instruction.
368 //
369 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
370                                    const Type *DstTy, TargetData *TD) {
371   
372   // It is legal to eliminate the instruction if casting A->B->A if the sizes
373   // are identical and the bits don't get reinterpreted (for example
374   // int->float->int would not be allowed).
375   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
376     return true;
377   
378   // If we are casting between pointer and integer types, treat pointers as
379   // integers of the appropriate size for the code below.
380   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
381   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
382   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
383   
384   // Allow free casting and conversion of sizes as long as the sign doesn't
385   // change...
386   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
387     CastType FirstCast = getCastType(SrcTy, MidTy);
388     CastType SecondCast = getCastType(MidTy, DstTy);
389     
390     // Capture the effect of these two casts.  If the result is a legal cast,
391     // the CastType is stored here, otherwise a special code is used.
392     static const unsigned CastResult[] = {
393       // First cast is noop
394       0, 1, 2, 3,
395       // First cast is a truncate
396       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
397                           // First cast is a sign ext
398       2, 5, 2, 4,         // signext->zeroext never ok
399                           // First cast is a zero ext
400       3, 5, 3, 3,
401     };
402     
403     unsigned Result = CastResult[FirstCast*4+SecondCast];
404     switch (Result) {
405     default: assert(0 && "Illegal table value!");
406     case 0:
407     case 1:
408     case 2:
409     case 3:
410       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
411       // truncates, we could eliminate more casts.
412       return (unsigned)getCastType(SrcTy, DstTy) == Result;
413     case 4:
414       return false;  // Not possible to eliminate this here.
415     case 5:
416       // Sign or zero extend followed by truncate is always ok if the result
417       // is a truncate or noop.
418       CastType ResultCast = getCastType(SrcTy, DstTy);
419       if (ResultCast == Noop || ResultCast == Truncate)
420         return true;
421         // Otherwise we are still growing the value, we are only safe if the
422         // result will match the sign/zeroextendness of the result.
423         return ResultCast == FirstCast;
424     }
425   }
426   
427   // If this is a cast from 'float -> double -> integer', cast from
428   // 'float -> integer' directly, as the value isn't changed by the 
429   // float->double conversion.
430   if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
431       DstTy->isIntegral() && 
432       SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
433     return true;
434   
435   // Packed type conversions don't modify bits.
436   if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
437     return true;
438   
439   return false;
440 }
441
442 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443 /// in any code being generated.  It does not require codegen if V is simple
444 /// enough or if the cast can be folded into other casts.
445 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
446   if (V->getType() == Ty || isa<Constant>(V)) return false;
447   
448   // If this is a noop cast, it isn't real codegen.
449   if (V->getType()->isLosslesslyConvertibleTo(Ty))
450     return false;
451
452   // If this is another cast that can be eliminated, it isn't codegen either.
453   if (const CastInst *CI = dyn_cast<CastInst>(V))
454     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
455                                TD))
456       return false;
457   return true;
458 }
459
460 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
461 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
462 /// casts that are known to not do anything...
463 ///
464 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
465                                              Instruction *InsertBefore) {
466   if (V->getType() == DestTy) return V;
467   if (Constant *C = dyn_cast<Constant>(V))
468     return ConstantExpr::getCast(C, DestTy);
469   
470   return InsertCastBefore(V, DestTy, *InsertBefore);
471 }
472
473 // SimplifyCommutative - This performs a few simplifications for commutative
474 // operators:
475 //
476 //  1. Order operands such that they are listed from right (least complex) to
477 //     left (most complex).  This puts constants before unary operators before
478 //     binary operators.
479 //
480 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
481 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
482 //
483 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
484   bool Changed = false;
485   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
486     Changed = !I.swapOperands();
487
488   if (!I.isAssociative()) return Changed;
489   Instruction::BinaryOps Opcode = I.getOpcode();
490   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
491     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
492       if (isa<Constant>(I.getOperand(1))) {
493         Constant *Folded = ConstantExpr::get(I.getOpcode(),
494                                              cast<Constant>(I.getOperand(1)),
495                                              cast<Constant>(Op->getOperand(1)));
496         I.setOperand(0, Op->getOperand(0));
497         I.setOperand(1, Folded);
498         return true;
499       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
500         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
501             isOnlyUse(Op) && isOnlyUse(Op1)) {
502           Constant *C1 = cast<Constant>(Op->getOperand(1));
503           Constant *C2 = cast<Constant>(Op1->getOperand(1));
504
505           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
506           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
507           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
508                                                     Op1->getOperand(0),
509                                                     Op1->getName(), &I);
510           WorkList.push_back(New);
511           I.setOperand(0, New);
512           I.setOperand(1, Folded);
513           return true;
514         }
515     }
516   return Changed;
517 }
518
519 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
520 // if the LHS is a constant zero (which is the 'negate' form).
521 //
522 static inline Value *dyn_castNegVal(Value *V) {
523   if (BinaryOperator::isNeg(V))
524     return BinaryOperator::getNegArgument(V);
525
526   // Constants can be considered to be negated values if they can be folded.
527   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
528     return ConstantExpr::getNeg(C);
529   return 0;
530 }
531
532 static inline Value *dyn_castNotVal(Value *V) {
533   if (BinaryOperator::isNot(V))
534     return BinaryOperator::getNotArgument(V);
535
536   // Constants can be considered to be not'ed values...
537   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
538     return ConstantExpr::getNot(C);
539   return 0;
540 }
541
542 // dyn_castFoldableMul - If this value is a multiply that can be folded into
543 // other computations (because it has a constant operand), return the
544 // non-constant operand of the multiply, and set CST to point to the multiplier.
545 // Otherwise, return null.
546 //
547 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
548   if (V->hasOneUse() && V->getType()->isInteger())
549     if (Instruction *I = dyn_cast<Instruction>(V)) {
550       if (I->getOpcode() == Instruction::Mul)
551         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
552           return I->getOperand(0);
553       if (I->getOpcode() == Instruction::Shl)
554         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
555           // The multiplier is really 1 << CST.
556           Constant *One = ConstantInt::get(V->getType(), 1);
557           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
558           return I->getOperand(0);
559         }
560     }
561   return 0;
562 }
563
564 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
565 /// expression, return it.
566 static User *dyn_castGetElementPtr(Value *V) {
567   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
568   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
569     if (CE->getOpcode() == Instruction::GetElementPtr)
570       return cast<User>(V);
571   return false;
572 }
573
574 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
575 static ConstantInt *AddOne(ConstantInt *C) {
576   return cast<ConstantInt>(ConstantExpr::getAdd(C,
577                                          ConstantInt::get(C->getType(), 1)));
578 }
579 static ConstantInt *SubOne(ConstantInt *C) {
580   return cast<ConstantInt>(ConstantExpr::getSub(C,
581                                          ConstantInt::get(C->getType(), 1)));
582 }
583
584 /// GetConstantInType - Return a ConstantInt with the specified type and value.
585 ///
586 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
587   if (Ty->isUnsigned()) 
588     return ConstantInt::get(Ty, Val);
589   else if (Ty->getTypeID() == Type::BoolTyID)
590     return ConstantBool::get(Val);
591   int64_t SVal = Val;
592   SVal <<= 64-Ty->getPrimitiveSizeInBits();
593   SVal >>= 64-Ty->getPrimitiveSizeInBits();
594   return ConstantInt::get(Ty, SVal);
595 }
596
597
598 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
599 /// known to be either zero or one and return them in the KnownZero/KnownOne
600 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
601 /// processing.
602 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
603                               uint64_t &KnownOne, unsigned Depth = 0) {
604   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
605   // we cannot optimize based on the assumption that it is zero without changing
606   // it to be an explicit zero.  If we don't change it to zero, other code could
607   // optimized based on the contradictory assumption that it is non-zero.
608   // Because instcombine aggressively folds operations with undef args anyway,
609   // this won't lose us code quality.
610   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
611     // We know all of the bits for a constant!
612     KnownOne = CI->getZExtValue() & Mask;
613     KnownZero = ~KnownOne & Mask;
614     return;
615   }
616
617   KnownZero = KnownOne = 0;   // Don't know anything.
618   if (Depth == 6 || Mask == 0)
619     return;  // Limit search depth.
620
621   uint64_t KnownZero2, KnownOne2;
622   Instruction *I = dyn_cast<Instruction>(V);
623   if (!I) return;
624
625   Mask &= V->getType()->getIntegralTypeMask();
626   
627   switch (I->getOpcode()) {
628   case Instruction::And:
629     // If either the LHS or the RHS are Zero, the result is zero.
630     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
631     Mask &= ~KnownZero;
632     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
633     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
634     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
635     
636     // Output known-1 bits are only known if set in both the LHS & RHS.
637     KnownOne &= KnownOne2;
638     // Output known-0 are known to be clear if zero in either the LHS | RHS.
639     KnownZero |= KnownZero2;
640     return;
641   case Instruction::Or:
642     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
643     Mask &= ~KnownOne;
644     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
645     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
646     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
647     
648     // Output known-0 bits are only known if clear in both the LHS & RHS.
649     KnownZero &= KnownZero2;
650     // Output known-1 are known to be set if set in either the LHS | RHS.
651     KnownOne |= KnownOne2;
652     return;
653   case Instruction::Xor: {
654     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
655     ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
656     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
657     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
658     
659     // Output known-0 bits are known if clear or set in both the LHS & RHS.
660     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
661     // Output known-1 are known to be set if set in only one of the LHS, RHS.
662     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
663     KnownZero = KnownZeroOut;
664     return;
665   }
666   case Instruction::Select:
667     ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
668     ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
669     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
670     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
671
672     // Only known if known in both the LHS and RHS.
673     KnownOne &= KnownOne2;
674     KnownZero &= KnownZero2;
675     return;
676   case Instruction::Cast: {
677     const Type *SrcTy = I->getOperand(0)->getType();
678     if (!SrcTy->isIntegral()) return;
679     
680     // If this is an integer truncate or noop, just look in the input.
681     if (SrcTy->getPrimitiveSizeInBits() >= 
682            I->getType()->getPrimitiveSizeInBits()) {
683       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
684       return;
685     }
686
687     // Sign or Zero extension.  Compute the bits in the result that are not
688     // present in the input.
689     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
690     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
691       
692     // Handle zero extension.
693     if (!SrcTy->isSigned()) {
694       Mask &= SrcTy->getIntegralTypeMask();
695       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
697       // The top bits are known to be zero.
698       KnownZero |= NewBits;
699     } else {
700       // Sign extension.
701       Mask &= SrcTy->getIntegralTypeMask();
702       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
703       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
704
705       // If the sign bit of the input is known set or clear, then we know the
706       // top bits of the result.
707       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
708       if (KnownZero & InSignBit) {          // Input sign bit known zero
709         KnownZero |= NewBits;
710         KnownOne &= ~NewBits;
711       } else if (KnownOne & InSignBit) {    // Input sign bit known set
712         KnownOne |= NewBits;
713         KnownZero &= ~NewBits;
714       } else {                              // Input sign bit unknown
715         KnownZero &= ~NewBits;
716         KnownOne &= ~NewBits;
717       }
718     }
719     return;
720   }
721   case Instruction::Shl:
722     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
723     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
724       uint64_t ShiftAmt = SA->getZExtValue();
725       Mask >>= ShiftAmt;
726       ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
727       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
728       KnownZero <<= ShiftAmt;
729       KnownOne  <<= ShiftAmt;
730       KnownZero |= (1ULL << ShiftAmt)-1;  // low bits known zero.
731       return;
732     }
733     break;
734   case Instruction::Shr:
735     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
736     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
737       // Compute the new bits that are at the top now.
738       uint64_t ShiftAmt = SA->getZExtValue();
739       uint64_t HighBits = (1ULL << ShiftAmt)-1;
740       HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
741       
742       if (I->getType()->isUnsigned()) {   // Unsigned shift right.
743         Mask <<= ShiftAmt;
744         ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
745         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
746         KnownZero >>= ShiftAmt;
747         KnownOne  >>= ShiftAmt;
748         KnownZero |= HighBits;  // high bits known zero.
749       } else {
750         Mask <<= ShiftAmt;
751         ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
752         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?"); 
753         KnownZero >>= ShiftAmt;
754         KnownOne  >>= ShiftAmt;
755         
756         // Handle the sign bits.
757         uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
758         SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
759         
760         if (KnownZero & SignBit) {       // New bits are known zero.
761           KnownZero |= HighBits;
762         } else if (KnownOne & SignBit) { // New bits are known one.
763           KnownOne |= HighBits;
764         }
765       }
766       return;
767     }
768     break;
769   }
770 }
771
772 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
773 /// this predicate to simplify operations downstream.  Mask is known to be zero
774 /// for bits that V cannot have.
775 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
776   uint64_t KnownZero, KnownOne;
777   ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
778   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
779   return (KnownZero & Mask) == Mask;
780 }
781
782 /// ShrinkDemandedConstant - Check to see if the specified operand of the 
783 /// specified instruction is a constant integer.  If so, check to see if there
784 /// are any bits set in the constant that are not demanded.  If so, shrink the
785 /// constant and return true.
786 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo, 
787                                    uint64_t Demanded) {
788   ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
789   if (!OpC) return false;
790
791   // If there are no bits set that aren't demanded, nothing to do.
792   if ((~Demanded & OpC->getZExtValue()) == 0)
793     return false;
794
795   // This is producing any bits that are not needed, shrink the RHS.
796   uint64_t Val = Demanded & OpC->getZExtValue();
797   I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
798   return true;
799 }
800
801 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a 
802 // set of known zero and one bits, compute the maximum and minimum values that
803 // could have the specified known zero and known one bits, returning them in
804 // min/max.
805 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
806                                                    uint64_t KnownZero,
807                                                    uint64_t KnownOne,
808                                                    int64_t &Min, int64_t &Max) {
809   uint64_t TypeBits = Ty->getIntegralTypeMask();
810   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
811
812   uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
813   
814   // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
815   // bit if it is unknown.
816   Min = KnownOne;
817   Max = KnownOne|UnknownBits;
818   
819   if (SignBit & UnknownBits) { // Sign bit is unknown
820     Min |= SignBit;
821     Max &= ~SignBit;
822   }
823   
824   // Sign extend the min/max values.
825   int ShAmt = 64-Ty->getPrimitiveSizeInBits();
826   Min = (Min << ShAmt) >> ShAmt;
827   Max = (Max << ShAmt) >> ShAmt;
828 }
829
830 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
831 // a set of known zero and one bits, compute the maximum and minimum values that
832 // could have the specified known zero and known one bits, returning them in
833 // min/max.
834 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
835                                                      uint64_t KnownZero,
836                                                      uint64_t KnownOne,
837                                                      uint64_t &Min,
838                                                      uint64_t &Max) {
839   uint64_t TypeBits = Ty->getIntegralTypeMask();
840   uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
841   
842   // The minimum value is when the unknown bits are all zeros.
843   Min = KnownOne;
844   // The maximum value is when the unknown bits are all ones.
845   Max = KnownOne|UnknownBits;
846 }
847
848
849 /// SimplifyDemandedBits - Look at V.  At this point, we know that only the
850 /// DemandedMask bits of the result of V are ever used downstream.  If we can
851 /// use this information to simplify V, do so and return true.  Otherwise,
852 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
853 /// the expression (used to simplify the caller).  The KnownZero/One bits may
854 /// only be accurate for those bits in the DemandedMask.
855 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
856                                         uint64_t &KnownZero, uint64_t &KnownOne,
857                                         unsigned Depth) {
858   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
859     // We know all of the bits for a constant!
860     KnownOne = CI->getZExtValue() & DemandedMask;
861     KnownZero = ~KnownOne & DemandedMask;
862     return false;
863   }
864   
865   KnownZero = KnownOne = 0;
866   if (!V->hasOneUse()) {    // Other users may use these bits.
867     if (Depth != 0) {       // Not at the root.
868       // Just compute the KnownZero/KnownOne bits to simplify things downstream.
869       ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
870       return false;
871     }
872     // If this is the root being simplified, allow it to have multiple uses,
873     // just set the DemandedMask to all bits.
874     DemandedMask = V->getType()->getIntegralTypeMask();
875   } else if (DemandedMask == 0) {   // Not demanding any bits from V.
876     if (V != UndefValue::get(V->getType()))
877       return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
878     return false;
879   } else if (Depth == 6) {        // Limit search depth.
880     return false;
881   }
882   
883   Instruction *I = dyn_cast<Instruction>(V);
884   if (!I) return false;        // Only analyze instructions.
885
886   DemandedMask &= V->getType()->getIntegralTypeMask();
887   
888   uint64_t KnownZero2, KnownOne2;
889   switch (I->getOpcode()) {
890   default: break;
891   case Instruction::And:
892     // If either the LHS or the RHS are Zero, the result is zero.
893     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
894                              KnownZero, KnownOne, Depth+1))
895       return true;
896     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
897
898     // If something is known zero on the RHS, the bits aren't demanded on the
899     // LHS.
900     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
901                              KnownZero2, KnownOne2, Depth+1))
902       return true;
903     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
904
905     // If all of the demanded bits are known one on one side, return the other.
906     // These bits cannot contribute to the result of the 'and'.
907     if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
908       return UpdateValueUsesWith(I, I->getOperand(0));
909     if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
910       return UpdateValueUsesWith(I, I->getOperand(1));
911     
912     // If all of the demanded bits in the inputs are known zeros, return zero.
913     if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
914       return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
915       
916     // If the RHS is a constant, see if we can simplify it.
917     if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
918       return UpdateValueUsesWith(I, I);
919       
920     // Output known-1 bits are only known if set in both the LHS & RHS.
921     KnownOne &= KnownOne2;
922     // Output known-0 are known to be clear if zero in either the LHS | RHS.
923     KnownZero |= KnownZero2;
924     break;
925   case Instruction::Or:
926     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
927                              KnownZero, KnownOne, Depth+1))
928       return true;
929     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
930     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne, 
931                              KnownZero2, KnownOne2, Depth+1))
932       return true;
933     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
934     
935     // If all of the demanded bits are known zero on one side, return the other.
936     // These bits cannot contribute to the result of the 'or'.
937     if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
938       return UpdateValueUsesWith(I, I->getOperand(0));
939     if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
940       return UpdateValueUsesWith(I, I->getOperand(1));
941
942     // If all of the potentially set bits on one side are known to be set on
943     // the other side, just use the 'other' side.
944     if ((DemandedMask & (~KnownZero) & KnownOne2) == 
945         (DemandedMask & (~KnownZero)))
946       return UpdateValueUsesWith(I, I->getOperand(0));
947     if ((DemandedMask & (~KnownZero2) & KnownOne) == 
948         (DemandedMask & (~KnownZero2)))
949       return UpdateValueUsesWith(I, I->getOperand(1));
950         
951     // If the RHS is a constant, see if we can simplify it.
952     if (ShrinkDemandedConstant(I, 1, DemandedMask))
953       return UpdateValueUsesWith(I, I);
954           
955     // Output known-0 bits are only known if clear in both the LHS & RHS.
956     KnownZero &= KnownZero2;
957     // Output known-1 are known to be set if set in either the LHS | RHS.
958     KnownOne |= KnownOne2;
959     break;
960   case Instruction::Xor: {
961     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962                              KnownZero, KnownOne, Depth+1))
963       return true;
964     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
965     if (SimplifyDemandedBits(I->getOperand(0), DemandedMask, 
966                              KnownZero2, KnownOne2, Depth+1))
967       return true;
968     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
969     
970     // If all of the demanded bits are known zero on one side, return the other.
971     // These bits cannot contribute to the result of the 'xor'.
972     if ((DemandedMask & KnownZero) == DemandedMask)
973       return UpdateValueUsesWith(I, I->getOperand(0));
974     if ((DemandedMask & KnownZero2) == DemandedMask)
975       return UpdateValueUsesWith(I, I->getOperand(1));
976     
977     // Output known-0 bits are known if clear or set in both the LHS & RHS.
978     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
979     // Output known-1 are known to be set if set in only one of the LHS, RHS.
980     uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
981     
982     // If all of the unknown bits are known to be zero on one side or the other
983     // (but not both) turn this into an *inclusive* or.
984     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
985     if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
986       if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
987         Instruction *Or =
988           BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
989                                    I->getName());
990         InsertNewInstBefore(Or, *I);
991         return UpdateValueUsesWith(I, Or);
992       }
993     }
994     
995     // If all of the demanded bits on one side are known, and all of the set
996     // bits on that side are also known to be set on the other side, turn this
997     // into an AND, as we know the bits will be cleared.
998     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
999     if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
1000       if ((KnownOne & KnownOne2) == KnownOne) {
1001         Constant *AndC = GetConstantInType(I->getType(), 
1002                                            ~KnownOne & DemandedMask);
1003         Instruction *And = 
1004           BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1005         InsertNewInstBefore(And, *I);
1006         return UpdateValueUsesWith(I, And);
1007       }
1008     }
1009     
1010     // If the RHS is a constant, see if we can simplify it.
1011     // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1012     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1013       return UpdateValueUsesWith(I, I);
1014     
1015     KnownZero = KnownZeroOut;
1016     KnownOne  = KnownOneOut;
1017     break;
1018   }
1019   case Instruction::Select:
1020     if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1021                              KnownZero, KnownOne, Depth+1))
1022       return true;
1023     if (SimplifyDemandedBits(I->getOperand(1), DemandedMask, 
1024                              KnownZero2, KnownOne2, Depth+1))
1025       return true;
1026     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1027     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1028     
1029     // If the operands are constants, see if we can simplify them.
1030     if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031       return UpdateValueUsesWith(I, I);
1032     if (ShrinkDemandedConstant(I, 2, DemandedMask))
1033       return UpdateValueUsesWith(I, I);
1034     
1035     // Only known if known in both the LHS and RHS.
1036     KnownOne &= KnownOne2;
1037     KnownZero &= KnownZero2;
1038     break;
1039   case Instruction::Cast: {
1040     const Type *SrcTy = I->getOperand(0)->getType();
1041     if (!SrcTy->isIntegral()) return false;
1042     
1043     // If this is an integer truncate or noop, just look in the input.
1044     if (SrcTy->getPrimitiveSizeInBits() >= 
1045         I->getType()->getPrimitiveSizeInBits()) {
1046       // Cast to bool is a comparison against 0, which demands all bits.  We
1047       // can't propagate anything useful up.
1048       if (I->getType() == Type::BoolTy)
1049         break;
1050       
1051       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1052                                KnownZero, KnownOne, Depth+1))
1053         return true;
1054       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1055       break;
1056     }
1057     
1058     // Sign or Zero extension.  Compute the bits in the result that are not
1059     // present in the input.
1060     uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1061     uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1062     
1063     // Handle zero extension.
1064     if (!SrcTy->isSigned()) {
1065       DemandedMask &= SrcTy->getIntegralTypeMask();
1066       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1067                                KnownZero, KnownOne, Depth+1))
1068         return true;
1069       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1070       // The top bits are known to be zero.
1071       KnownZero |= NewBits;
1072     } else {
1073       // Sign extension.
1074       uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1075       int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1076
1077       // If any of the sign extended bits are demanded, we know that the sign
1078       // bit is demanded.
1079       if (NewBits & DemandedMask)
1080         InputDemandedBits |= InSignBit;
1081       
1082       if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1083                                KnownZero, KnownOne, Depth+1))
1084         return true;
1085       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1086       
1087       // If the sign bit of the input is known set or clear, then we know the
1088       // top bits of the result.
1089
1090       // If the input sign bit is known zero, or if the NewBits are not demanded
1091       // convert this into a zero extension.
1092       if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1093         // Convert to unsigned first.
1094         Value *NewVal = 
1095           InsertCastBefore(I->getOperand(0), SrcTy->getUnsignedVersion(), *I);
1096         // Then cast that to the destination type.
1097         NewVal = new CastInst(NewVal, I->getType(), I->getName());
1098         InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1099         return UpdateValueUsesWith(I, NewVal);
1100       } else if (KnownOne & InSignBit) {    // Input sign bit known set
1101         KnownOne |= NewBits;
1102         KnownZero &= ~NewBits;
1103       } else {                              // Input sign bit unknown
1104         KnownZero &= ~NewBits;
1105         KnownOne &= ~NewBits;
1106       }
1107     }
1108     break;
1109   }
1110   case Instruction::Shl:
1111     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1112       uint64_t ShiftAmt = SA->getZExtValue();
1113       if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt, 
1114                                KnownZero, KnownOne, Depth+1))
1115         return true;
1116       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1117       KnownZero <<= ShiftAmt;
1118       KnownOne  <<= ShiftAmt;
1119       KnownZero |= (1ULL << ShiftAmt) - 1;  // low bits known zero.
1120     }
1121     break;
1122   case Instruction::Shr:
1123     // If this is an arithmetic shift right and only the low-bit is set, we can
1124     // always convert this into a logical shr, even if the shift amount is
1125     // variable.  The low bit of the shift cannot be an input sign bit unless
1126     // the shift amount is >= the size of the datatype, which is undefined.
1127     if (DemandedMask == 1 && I->getType()->isSigned()) {
1128       // Convert the input to unsigned.
1129       Value *NewVal = InsertCastBefore(I->getOperand(0), 
1130                                        I->getType()->getUnsignedVersion(), *I);
1131       // Perform the unsigned shift right.
1132       NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1133                              I->getName());
1134       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1135       // Then cast that to the destination type.
1136       NewVal = new CastInst(NewVal, I->getType(), I->getName());
1137       InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1138       return UpdateValueUsesWith(I, NewVal);
1139     }    
1140     
1141     if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1142       unsigned ShiftAmt = SA->getZExtValue();
1143       
1144       // Compute the new bits that are at the top now.
1145       uint64_t HighBits = (1ULL << ShiftAmt)-1;
1146       HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1147       uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1148       if (I->getType()->isUnsigned()) {   // Unsigned shift right.
1149         if (SimplifyDemandedBits(I->getOperand(0),
1150                                  (DemandedMask << ShiftAmt) & TypeMask,
1151                                  KnownZero, KnownOne, Depth+1))
1152           return true;
1153         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1154         KnownZero &= TypeMask;
1155         KnownOne  &= TypeMask;
1156         KnownZero >>= ShiftAmt;
1157         KnownOne  >>= ShiftAmt;
1158         KnownZero |= HighBits;  // high bits known zero.
1159       } else {                            // Signed shift right.
1160         if (SimplifyDemandedBits(I->getOperand(0),
1161                                  (DemandedMask << ShiftAmt) & TypeMask,
1162                                  KnownZero, KnownOne, Depth+1))
1163           return true;
1164         assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1165         KnownZero &= TypeMask;
1166         KnownOne  &= TypeMask;
1167         KnownZero >>= ShiftAmt;
1168         KnownOne  >>= ShiftAmt;
1169         
1170         // Handle the sign bits.
1171         uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1172         SignBit >>= ShiftAmt;  // Adjust to where it is now in the mask.
1173         
1174         // If the input sign bit is known to be zero, or if none of the top bits
1175         // are demanded, turn this into an unsigned shift right.
1176         if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1177           // Convert the input to unsigned.
1178           Value *NewVal = InsertCastBefore(I->getOperand(0), 
1179                              I->getType()->getUnsignedVersion(), *I);
1180           // Perform the unsigned shift right.
1181           NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1182           InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1183           // Then cast that to the destination type.
1184           NewVal = new CastInst(NewVal, I->getType(), I->getName());
1185           InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1186           return UpdateValueUsesWith(I, NewVal);
1187         } else if (KnownOne & SignBit) { // New bits are known one.
1188           KnownOne |= HighBits;
1189         }
1190       }
1191     }
1192     break;
1193   }
1194   
1195   // If the client is only demanding bits that we know, return the known
1196   // constant.
1197   if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1198     return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1199   return false;
1200 }  
1201
1202
1203 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1204 /// 64 or fewer elements.  DemandedElts contains the set of elements that are
1205 /// actually used by the caller.  This method analyzes which elements of the
1206 /// operand are undef and returns that information in UndefElts.
1207 ///
1208 /// If the information about demanded elements can be used to simplify the
1209 /// operation, the operation is simplified, then the resultant value is
1210 /// returned.  This returns null if no change was made.
1211 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1212                                                 uint64_t &UndefElts,
1213                                                 unsigned Depth) {
1214   unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1215   assert(VWidth <= 64 && "Vector too wide to analyze!");
1216   uint64_t EltMask = ~0ULL >> (64-VWidth);
1217   assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1218          "Invalid DemandedElts!");
1219
1220   if (isa<UndefValue>(V)) {
1221     // If the entire vector is undefined, just return this info.
1222     UndefElts = EltMask;
1223     return 0;
1224   } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1225     UndefElts = EltMask;
1226     return UndefValue::get(V->getType());
1227   }
1228   
1229   UndefElts = 0;
1230   if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1231     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1232     Constant *Undef = UndefValue::get(EltTy);
1233
1234     std::vector<Constant*> Elts;
1235     for (unsigned i = 0; i != VWidth; ++i)
1236       if (!(DemandedElts & (1ULL << i))) {   // If not demanded, set to undef.
1237         Elts.push_back(Undef);
1238         UndefElts |= (1ULL << i);
1239       } else if (isa<UndefValue>(CP->getOperand(i))) {   // Already undef.
1240         Elts.push_back(Undef);
1241         UndefElts |= (1ULL << i);
1242       } else {                               // Otherwise, defined.
1243         Elts.push_back(CP->getOperand(i));
1244       }
1245         
1246     // If we changed the constant, return it.
1247     Constant *NewCP = ConstantPacked::get(Elts);
1248     return NewCP != CP ? NewCP : 0;
1249   } else if (isa<ConstantAggregateZero>(V)) {
1250     // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1251     // set to undef.
1252     const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1253     Constant *Zero = Constant::getNullValue(EltTy);
1254     Constant *Undef = UndefValue::get(EltTy);
1255     std::vector<Constant*> Elts;
1256     for (unsigned i = 0; i != VWidth; ++i)
1257       Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1258     UndefElts = DemandedElts ^ EltMask;
1259     return ConstantPacked::get(Elts);
1260   }
1261   
1262   if (!V->hasOneUse()) {    // Other users may use these bits.
1263     if (Depth != 0) {       // Not at the root.
1264       // TODO: Just compute the UndefElts information recursively.
1265       return false;
1266     }
1267     return false;
1268   } else if (Depth == 10) {        // Limit search depth.
1269     return false;
1270   }
1271   
1272   Instruction *I = dyn_cast<Instruction>(V);
1273   if (!I) return false;        // Only analyze instructions.
1274   
1275   bool MadeChange = false;
1276   uint64_t UndefElts2;
1277   Value *TmpV;
1278   switch (I->getOpcode()) {
1279   default: break;
1280     
1281   case Instruction::InsertElement: {
1282     // If this is a variable index, we don't know which element it overwrites.
1283     // demand exactly the same input as we produce.
1284     ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1285     if (Idx == 0) {
1286       // Note that we can't propagate undef elt info, because we don't know
1287       // which elt is getting updated.
1288       TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1289                                         UndefElts2, Depth+1);
1290       if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1291       break;
1292     }
1293     
1294     // If this is inserting an element that isn't demanded, remove this
1295     // insertelement.
1296     unsigned IdxNo = Idx->getZExtValue();
1297     if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1298       return AddSoonDeadInstToWorklist(*I, 0);
1299     
1300     // Otherwise, the element inserted overwrites whatever was there, so the
1301     // input demanded set is simpler than the output set.
1302     TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1303                                       DemandedElts & ~(1ULL << IdxNo),
1304                                       UndefElts, Depth+1);
1305     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1306
1307     // The inserted element is defined.
1308     UndefElts |= 1ULL << IdxNo;
1309     break;
1310   }
1311     
1312   case Instruction::And:
1313   case Instruction::Or:
1314   case Instruction::Xor:
1315   case Instruction::Add:
1316   case Instruction::Sub:
1317   case Instruction::Mul:
1318     // div/rem demand all inputs, because they don't want divide by zero.
1319     TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1320                                       UndefElts, Depth+1);
1321     if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1322     TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1323                                       UndefElts2, Depth+1);
1324     if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1325       
1326     // Output elements are undefined if both are undefined.  Consider things
1327     // like undef&0.  The result is known zero, not undef.
1328     UndefElts &= UndefElts2;
1329     break;
1330     
1331   case Instruction::Call: {
1332     IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1333     if (!II) break;
1334     switch (II->getIntrinsicID()) {
1335     default: break;
1336       
1337     // Binary vector operations that work column-wise.  A dest element is a
1338     // function of the corresponding input elements from the two inputs.
1339     case Intrinsic::x86_sse_sub_ss:
1340     case Intrinsic::x86_sse_mul_ss:
1341     case Intrinsic::x86_sse_min_ss:
1342     case Intrinsic::x86_sse_max_ss:
1343     case Intrinsic::x86_sse2_sub_sd:
1344     case Intrinsic::x86_sse2_mul_sd:
1345     case Intrinsic::x86_sse2_min_sd:
1346     case Intrinsic::x86_sse2_max_sd:
1347       TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1348                                         UndefElts, Depth+1);
1349       if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1350       TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1351                                         UndefElts2, Depth+1);
1352       if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1353
1354       // If only the low elt is demanded and this is a scalarizable intrinsic,
1355       // scalarize it now.
1356       if (DemandedElts == 1) {
1357         switch (II->getIntrinsicID()) {
1358         default: break;
1359         case Intrinsic::x86_sse_sub_ss:
1360         case Intrinsic::x86_sse_mul_ss:
1361         case Intrinsic::x86_sse2_sub_sd:
1362         case Intrinsic::x86_sse2_mul_sd:
1363           // TODO: Lower MIN/MAX/ABS/etc
1364           Value *LHS = II->getOperand(1);
1365           Value *RHS = II->getOperand(2);
1366           // Extract the element as scalars.
1367           LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1368           RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1369           
1370           switch (II->getIntrinsicID()) {
1371           default: assert(0 && "Case stmts out of sync!");
1372           case Intrinsic::x86_sse_sub_ss:
1373           case Intrinsic::x86_sse2_sub_sd:
1374             TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1375                                                         II->getName()), *II);
1376             break;
1377           case Intrinsic::x86_sse_mul_ss:
1378           case Intrinsic::x86_sse2_mul_sd:
1379             TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1380                                                          II->getName()), *II);
1381             break;
1382           }
1383           
1384           Instruction *New =
1385             new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1386                                   II->getName());
1387           InsertNewInstBefore(New, *II);
1388           AddSoonDeadInstToWorklist(*II, 0);
1389           return New;
1390         }            
1391       }
1392         
1393       // Output elements are undefined if both are undefined.  Consider things
1394       // like undef&0.  The result is known zero, not undef.
1395       UndefElts &= UndefElts2;
1396       break;
1397     }
1398     break;
1399   }
1400   }
1401   return MadeChange ? I : 0;
1402 }
1403
1404 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1405 // true when both operands are equal...
1406 //
1407 static bool isTrueWhenEqual(Instruction &I) {
1408   return I.getOpcode() == Instruction::SetEQ ||
1409          I.getOpcode() == Instruction::SetGE ||
1410          I.getOpcode() == Instruction::SetLE;
1411 }
1412
1413 /// AssociativeOpt - Perform an optimization on an associative operator.  This
1414 /// function is designed to check a chain of associative operators for a
1415 /// potential to apply a certain optimization.  Since the optimization may be
1416 /// applicable if the expression was reassociated, this checks the chain, then
1417 /// reassociates the expression as necessary to expose the optimization
1418 /// opportunity.  This makes use of a special Functor, which must define
1419 /// 'shouldApply' and 'apply' methods.
1420 ///
1421 template<typename Functor>
1422 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1423   unsigned Opcode = Root.getOpcode();
1424   Value *LHS = Root.getOperand(0);
1425
1426   // Quick check, see if the immediate LHS matches...
1427   if (F.shouldApply(LHS))
1428     return F.apply(Root);
1429
1430   // Otherwise, if the LHS is not of the same opcode as the root, return.
1431   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1432   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1433     // Should we apply this transform to the RHS?
1434     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1435
1436     // If not to the RHS, check to see if we should apply to the LHS...
1437     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1438       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
1439       ShouldApply = true;
1440     }
1441
1442     // If the functor wants to apply the optimization to the RHS of LHSI,
1443     // reassociate the expression from ((? op A) op B) to (? op (A op B))
1444     if (ShouldApply) {
1445       BasicBlock *BB = Root.getParent();
1446
1447       // Now all of the instructions are in the current basic block, go ahead
1448       // and perform the reassociation.
1449       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1450
1451       // First move the selected RHS to the LHS of the root...
1452       Root.setOperand(0, LHSI->getOperand(1));
1453
1454       // Make what used to be the LHS of the root be the user of the root...
1455       Value *ExtraOperand = TmpLHSI->getOperand(1);
1456       if (&Root == TmpLHSI) {
1457         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1458         return 0;
1459       }
1460       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
1461       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
1462       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1463       BasicBlock::iterator ARI = &Root; ++ARI;
1464       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
1465       ARI = Root;
1466
1467       // Now propagate the ExtraOperand down the chain of instructions until we
1468       // get to LHSI.
1469       while (TmpLHSI != LHSI) {
1470         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1471         // Move the instruction to immediately before the chain we are
1472         // constructing to avoid breaking dominance properties.
1473         NextLHSI->getParent()->getInstList().remove(NextLHSI);
1474         BB->getInstList().insert(ARI, NextLHSI);
1475         ARI = NextLHSI;
1476
1477         Value *NextOp = NextLHSI->getOperand(1);
1478         NextLHSI->setOperand(1, ExtraOperand);
1479         TmpLHSI = NextLHSI;
1480         ExtraOperand = NextOp;
1481       }
1482
1483       // Now that the instructions are reassociated, have the functor perform
1484       // the transformation...
1485       return F.apply(Root);
1486     }
1487
1488     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1489   }
1490   return 0;
1491 }
1492
1493
1494 // AddRHS - Implements: X + X --> X << 1
1495 struct AddRHS {
1496   Value *RHS;
1497   AddRHS(Value *rhs) : RHS(rhs) {}
1498   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1499   Instruction *apply(BinaryOperator &Add) const {
1500     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1501                          ConstantInt::get(Type::UByteTy, 1));
1502   }
1503 };
1504
1505 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1506 //                 iff C1&C2 == 0
1507 struct AddMaskingAnd {
1508   Constant *C2;
1509   AddMaskingAnd(Constant *c) : C2(c) {}
1510   bool shouldApply(Value *LHS) const {
1511     ConstantInt *C1;
1512     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1513            ConstantExpr::getAnd(C1, C2)->isNullValue();
1514   }
1515   Instruction *apply(BinaryOperator &Add) const {
1516     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1517   }
1518 };
1519
1520 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1521                                              InstCombiner *IC) {
1522   if (isa<CastInst>(I)) {
1523     if (Constant *SOC = dyn_cast<Constant>(SO))
1524       return ConstantExpr::getCast(SOC, I.getType());
1525
1526     return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1527                                                 SO->getName() + ".cast"), I);
1528   }
1529
1530   // Figure out if the constant is the left or the right argument.
1531   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1532   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1533
1534   if (Constant *SOC = dyn_cast<Constant>(SO)) {
1535     if (ConstIsRHS)
1536       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1537     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1538   }
1539
1540   Value *Op0 = SO, *Op1 = ConstOperand;
1541   if (!ConstIsRHS)
1542     std::swap(Op0, Op1);
1543   Instruction *New;
1544   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1545     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1546   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1547     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1548   else {
1549     assert(0 && "Unknown binary instruction type!");
1550     abort();
1551   }
1552   return IC->InsertNewInstBefore(New, I);
1553 }
1554
1555 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1556 // constant as the other operand, try to fold the binary operator into the
1557 // select arguments.  This also works for Cast instructions, which obviously do
1558 // not have a second operand.
1559 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1560                                      InstCombiner *IC) {
1561   // Don't modify shared select instructions
1562   if (!SI->hasOneUse()) return 0;
1563   Value *TV = SI->getOperand(1);
1564   Value *FV = SI->getOperand(2);
1565
1566   if (isa<Constant>(TV) || isa<Constant>(FV)) {
1567     // Bool selects with constant operands can be folded to logical ops.
1568     if (SI->getType() == Type::BoolTy) return 0;
1569
1570     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1571     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1572
1573     return new SelectInst(SI->getCondition(), SelectTrueVal,
1574                           SelectFalseVal);
1575   }
1576   return 0;
1577 }
1578
1579
1580 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1581 /// node as operand #0, see if we can fold the instruction into the PHI (which
1582 /// is only possible if all operands to the PHI are constants).
1583 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1584   PHINode *PN = cast<PHINode>(I.getOperand(0));
1585   unsigned NumPHIValues = PN->getNumIncomingValues();
1586   if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1587
1588   // Check to see if all of the operands of the PHI are constants.  If there is
1589   // one non-constant value, remember the BB it is.  If there is more than one
1590   // bail out.
1591   BasicBlock *NonConstBB = 0;
1592   for (unsigned i = 0; i != NumPHIValues; ++i)
1593     if (!isa<Constant>(PN->getIncomingValue(i))) {
1594       if (NonConstBB) return 0;  // More than one non-const value.
1595       NonConstBB = PN->getIncomingBlock(i);
1596       
1597       // If the incoming non-constant value is in I's block, we have an infinite
1598       // loop.
1599       if (NonConstBB == I.getParent())
1600         return 0;
1601     }
1602   
1603   // If there is exactly one non-constant value, we can insert a copy of the
1604   // operation in that block.  However, if this is a critical edge, we would be
1605   // inserting the computation one some other paths (e.g. inside a loop).  Only
1606   // do this if the pred block is unconditionally branching into the phi block.
1607   if (NonConstBB) {
1608     BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1609     if (!BI || !BI->isUnconditional()) return 0;
1610   }
1611
1612   // Okay, we can do the transformation: create the new PHI node.
1613   PHINode *NewPN = new PHINode(I.getType(), I.getName());
1614   I.setName("");
1615   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1616   InsertNewInstBefore(NewPN, *PN);
1617
1618   // Next, add all of the operands to the PHI.
1619   if (I.getNumOperands() == 2) {
1620     Constant *C = cast<Constant>(I.getOperand(1));
1621     for (unsigned i = 0; i != NumPHIValues; ++i) {
1622       Value *InV;
1623       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1624         InV = ConstantExpr::get(I.getOpcode(), InC, C);
1625       } else {
1626         assert(PN->getIncomingBlock(i) == NonConstBB);
1627         if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I)) 
1628           InV = BinaryOperator::create(BO->getOpcode(),
1629                                        PN->getIncomingValue(i), C, "phitmp",
1630                                        NonConstBB->getTerminator());
1631         else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1632           InV = new ShiftInst(SI->getOpcode(),
1633                               PN->getIncomingValue(i), C, "phitmp",
1634                               NonConstBB->getTerminator());
1635         else
1636           assert(0 && "Unknown binop!");
1637         
1638         WorkList.push_back(cast<Instruction>(InV));
1639       }
1640       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1641     }
1642   } else {
1643     assert(isa<CastInst>(I) && "Unary op should be a cast!");
1644     const Type *RetTy = I.getType();
1645     for (unsigned i = 0; i != NumPHIValues; ++i) {
1646       Value *InV;
1647       if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1648         InV = ConstantExpr::getCast(InC, RetTy);
1649       } else {
1650         assert(PN->getIncomingBlock(i) == NonConstBB);
1651         InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1652                            NonConstBB->getTerminator());
1653         WorkList.push_back(cast<Instruction>(InV));
1654       }
1655       NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1656     }
1657   }
1658   return ReplaceInstUsesWith(I, NewPN);
1659 }
1660
1661 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1662   bool Changed = SimplifyCommutative(I);
1663   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1664
1665   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1666     // X + undef -> undef
1667     if (isa<UndefValue>(RHS))
1668       return ReplaceInstUsesWith(I, RHS);
1669
1670     // X + 0 --> X
1671     if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1672       if (RHSC->isNullValue())
1673         return ReplaceInstUsesWith(I, LHS);
1674     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1675       if (CFP->isExactlyValue(-0.0))
1676         return ReplaceInstUsesWith(I, LHS);
1677     }
1678
1679     // X + (signbit) --> X ^ signbit
1680     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1681       uint64_t Val = CI->getZExtValue();
1682       if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1683         return BinaryOperator::createXor(LHS, RHS);
1684     }
1685
1686     if (isa<PHINode>(LHS))
1687       if (Instruction *NV = FoldOpIntoPhi(I))
1688         return NV;
1689     
1690     ConstantInt *XorRHS = 0;
1691     Value *XorLHS = 0;
1692     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1693       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1694       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1695       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1696       
1697       uint64_t C0080Val = 1ULL << 31;
1698       int64_t CFF80Val = -C0080Val;
1699       unsigned Size = 32;
1700       do {
1701         if (TySizeBits > Size) {
1702           bool Found = false;
1703           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1704           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1705           if (RHSSExt == CFF80Val) {
1706             if (XorRHS->getZExtValue() == C0080Val)
1707               Found = true;
1708           } else if (RHSZExt == C0080Val) {
1709             if (XorRHS->getSExtValue() == CFF80Val)
1710               Found = true;
1711           }
1712           if (Found) {
1713             // This is a sign extend if the top bits are known zero.
1714             uint64_t Mask = ~0ULL;
1715             Mask <<= 64-(TySizeBits-Size);
1716             Mask &= XorLHS->getType()->getIntegralTypeMask();
1717             if (!MaskedValueIsZero(XorLHS, Mask))
1718               Size = 0;  // Not a sign ext, but can't be any others either.
1719             goto FoundSExt;
1720           }
1721         }
1722         Size >>= 1;
1723         C0080Val >>= Size;
1724         CFF80Val >>= Size;
1725       } while (Size >= 8);
1726       
1727 FoundSExt:
1728       const Type *MiddleType = 0;
1729       switch (Size) {
1730       default: break;
1731       case 32: MiddleType = Type::IntTy; break;
1732       case 16: MiddleType = Type::ShortTy; break;
1733       case 8:  MiddleType = Type::SByteTy; break;
1734       }
1735       if (MiddleType) {
1736         Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1737         InsertNewInstBefore(NewTrunc, I);
1738         return new CastInst(NewTrunc, I.getType());
1739       }
1740     }
1741   }
1742
1743   // X + X --> X << 1
1744   if (I.getType()->isInteger()) {
1745     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1746
1747     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1748       if (RHSI->getOpcode() == Instruction::Sub)
1749         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
1750           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1751     }
1752     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1753       if (LHSI->getOpcode() == Instruction::Sub)
1754         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
1755           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1756     }
1757   }
1758
1759   // -A + B  -->  B - A
1760   if (Value *V = dyn_castNegVal(LHS))
1761     return BinaryOperator::createSub(RHS, V);
1762
1763   // A + -B  -->  A - B
1764   if (!isa<Constant>(RHS))
1765     if (Value *V = dyn_castNegVal(RHS))
1766       return BinaryOperator::createSub(LHS, V);
1767
1768
1769   ConstantInt *C2;
1770   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1771     if (X == RHS)   // X*C + X --> X * (C+1)
1772       return BinaryOperator::createMul(RHS, AddOne(C2));
1773
1774     // X*C1 + X*C2 --> X * (C1+C2)
1775     ConstantInt *C1;
1776     if (X == dyn_castFoldableMul(RHS, C1))
1777       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1778   }
1779
1780   // X + X*C --> X * (C+1)
1781   if (dyn_castFoldableMul(RHS, C2) == LHS)
1782     return BinaryOperator::createMul(LHS, AddOne(C2));
1783
1784
1785   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1786   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1787     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1788
1789   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1790     Value *X = 0;
1791     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
1792       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1793       return BinaryOperator::createSub(C, X);
1794     }
1795
1796     // (X & FF00) + xx00  -> (X+xx00) & FF00
1797     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1798       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1799       if (Anded == CRHS) {
1800         // See if all bits from the first bit set in the Add RHS up are included
1801         // in the mask.  First, get the rightmost bit.
1802         uint64_t AddRHSV = CRHS->getZExtValue();
1803
1804         // Form a mask of all bits from the lowest bit added through the top.
1805         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1806         AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1807
1808         // See if the and mask includes all of these bits.
1809         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1810
1811         if (AddRHSHighBits == AddRHSHighBitsAnd) {
1812           // Okay, the xform is safe.  Insert the new add pronto.
1813           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1814                                                             LHS->getName()), I);
1815           return BinaryOperator::createAnd(NewAdd, C2);
1816         }
1817       }
1818     }
1819
1820     // Try to fold constant add into select arguments.
1821     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1822       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1823         return R;
1824   }
1825
1826   // add (cast *A to intptrtype) B -> 
1827   //   cast (GEP (cast *A to sbyte*) B) -> 
1828   //     intptrtype
1829   {
1830     CastInst* CI = dyn_cast<CastInst>(LHS);
1831     Value* Other = RHS;
1832     if (!CI) {
1833       CI = dyn_cast<CastInst>(RHS);
1834       Other = LHS;
1835     }
1836     if (CI && CI->getType()->isSized() && 
1837         (CI->getType()->getPrimitiveSize() == 
1838          TD->getIntPtrType()->getPrimitiveSize()) 
1839         && isa<PointerType>(CI->getOperand(0)->getType())) {
1840       Value* I2 = InsertCastBefore(CI->getOperand(0),
1841                                    PointerType::get(Type::SByteTy), I);
1842       I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1843       return new CastInst(I2, CI->getType());
1844     }
1845   }
1846
1847   return Changed ? &I : 0;
1848 }
1849
1850 // isSignBit - Return true if the value represented by the constant only has the
1851 // highest order bit set.
1852 static bool isSignBit(ConstantInt *CI) {
1853   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1854   return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1855 }
1856
1857 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1858 ///
1859 static Value *RemoveNoopCast(Value *V) {
1860   if (CastInst *CI = dyn_cast<CastInst>(V)) {
1861     const Type *CTy = CI->getType();
1862     const Type *OpTy = CI->getOperand(0)->getType();
1863     if (CTy->isInteger() && OpTy->isInteger()) {
1864       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1865         return RemoveNoopCast(CI->getOperand(0));
1866     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1867       return RemoveNoopCast(CI->getOperand(0));
1868   }
1869   return V;
1870 }
1871
1872 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1873   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1874
1875   if (Op0 == Op1)         // sub X, X  -> 0
1876     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1877
1878   // If this is a 'B = x-(-A)', change to B = x+A...
1879   if (Value *V = dyn_castNegVal(Op1))
1880     return BinaryOperator::createAdd(Op0, V);
1881
1882   if (isa<UndefValue>(Op0))
1883     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
1884   if (isa<UndefValue>(Op1))
1885     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
1886
1887   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1888     // Replace (-1 - A) with (~A)...
1889     if (C->isAllOnesValue())
1890       return BinaryOperator::createNot(Op1);
1891
1892     // C - ~X == X + (1+C)
1893     Value *X = 0;
1894     if (match(Op1, m_Not(m_Value(X))))
1895       return BinaryOperator::createAdd(X,
1896                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1897     // -((uint)X >> 31) -> ((int)X >> 31)
1898     // -((int)X >> 31) -> ((uint)X >> 31)
1899     if (C->isNullValue()) {
1900       Value *NoopCastedRHS = RemoveNoopCast(Op1);
1901       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1902         if (SI->getOpcode() == Instruction::Shr)
1903           if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1904             const Type *NewTy;
1905             if (SI->getType()->isSigned())
1906               NewTy = SI->getType()->getUnsignedVersion();
1907             else
1908               NewTy = SI->getType()->getSignedVersion();
1909             // Check to see if we are shifting out everything but the sign bit.
1910             if (CU->getZExtValue() == 
1911                 SI->getType()->getPrimitiveSizeInBits()-1) {
1912               // Ok, the transformation is safe.  Insert a cast of the incoming
1913               // value, then the new shift, then the new cast.
1914               Value *InV = InsertCastBefore(SI->getOperand(0), NewTy, I);
1915               Instruction *NewShift = new ShiftInst(Instruction::Shr, InV,
1916                                                     CU, SI->getName());
1917               if (NewShift->getType() == I.getType())
1918                 return NewShift;
1919               else {
1920                 InsertNewInstBefore(NewShift, I);
1921                 return new CastInst(NewShift, I.getType());
1922               }
1923             }
1924           }
1925     }
1926
1927     // Try to fold constant sub into select arguments.
1928     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1929       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1930         return R;
1931
1932     if (isa<PHINode>(Op0))
1933       if (Instruction *NV = FoldOpIntoPhi(I))
1934         return NV;
1935   }
1936
1937   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1938     if (Op1I->getOpcode() == Instruction::Add &&
1939         !Op0->getType()->isFloatingPoint()) {
1940       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
1941         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1942       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
1943         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1944       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1945         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1946           // C1-(X+C2) --> (C1-C2)-X
1947           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1948                                            Op1I->getOperand(0));
1949       }
1950     }
1951
1952     if (Op1I->hasOneUse()) {
1953       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1954       // is not used by anyone else...
1955       //
1956       if (Op1I->getOpcode() == Instruction::Sub &&
1957           !Op1I->getType()->isFloatingPoint()) {
1958         // Swap the two operands of the subexpr...
1959         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1960         Op1I->setOperand(0, IIOp1);
1961         Op1I->setOperand(1, IIOp0);
1962
1963         // Create the new top level add instruction...
1964         return BinaryOperator::createAdd(Op0, Op1);
1965       }
1966
1967       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1968       //
1969       if (Op1I->getOpcode() == Instruction::And &&
1970           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1971         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1972
1973         Value *NewNot =
1974           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1975         return BinaryOperator::createAnd(Op0, NewNot);
1976       }
1977
1978       // 0 - (X sdiv C)  -> (X sdiv -C)
1979       if (Op1I->getOpcode() == Instruction::SDiv)
1980         if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
1981           if (CSI->isNullValue())
1982             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1983               return BinaryOperator::createSDiv(Op1I->getOperand(0),
1984                                                ConstantExpr::getNeg(DivRHS));
1985
1986       // X - X*C --> X * (1-C)
1987       ConstantInt *C2 = 0;
1988       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1989         Constant *CP1 =
1990           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1991         return BinaryOperator::createMul(Op0, CP1);
1992       }
1993     }
1994   }
1995
1996   if (!Op0->getType()->isFloatingPoint())
1997     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1998       if (Op0I->getOpcode() == Instruction::Add) {
1999         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
2000           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2001         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
2002           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2003       } else if (Op0I->getOpcode() == Instruction::Sub) {
2004         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
2005           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2006       }
2007
2008   ConstantInt *C1;
2009   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2010     if (X == Op1) { // X*C - X --> X * (C-1)
2011       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2012       return BinaryOperator::createMul(Op1, CP1);
2013     }
2014
2015     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
2016     if (X == dyn_castFoldableMul(Op1, C2))
2017       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2018   }
2019   return 0;
2020 }
2021
2022 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2023 /// really just returns true if the most significant (sign) bit is set.
2024 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2025   if (RHS->getType()->isSigned()) {
2026     // True if source is LHS < 0 or LHS <= -1
2027     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2028            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2029   } else {
2030     ConstantInt *RHSC = cast<ConstantInt>(RHS);
2031     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2032     // the size of the integer type.
2033     if (Opcode == Instruction::SetGE)
2034       return RHSC->getZExtValue() ==
2035         1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2036     if (Opcode == Instruction::SetGT)
2037       return RHSC->getZExtValue() ==
2038         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2039   }
2040   return false;
2041 }
2042
2043 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2044   bool Changed = SimplifyCommutative(I);
2045   Value *Op0 = I.getOperand(0);
2046
2047   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
2048     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2049
2050   // Simplify mul instructions with a constant RHS...
2051   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2052     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2053
2054       // ((X << C1)*C2) == (X * (C2 << C1))
2055       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2056         if (SI->getOpcode() == Instruction::Shl)
2057           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2058             return BinaryOperator::createMul(SI->getOperand(0),
2059                                              ConstantExpr::getShl(CI, ShOp));
2060
2061       if (CI->isNullValue())
2062         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
2063       if (CI->equalsInt(1))                  // X * 1  == X
2064         return ReplaceInstUsesWith(I, Op0);
2065       if (CI->isAllOnesValue())              // X * -1 == 0 - X
2066         return BinaryOperator::createNeg(Op0, I.getName());
2067
2068       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2069       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
2070         uint64_t C = Log2_64(Val);
2071         return new ShiftInst(Instruction::Shl, Op0,
2072                              ConstantInt::get(Type::UByteTy, C));
2073       }
2074     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2075       if (Op1F->isNullValue())
2076         return ReplaceInstUsesWith(I, Op1);
2077
2078       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
2079       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2080       if (Op1F->getValue() == 1.0)
2081         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
2082     }
2083     
2084     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2085       if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2086           isa<ConstantInt>(Op0I->getOperand(1))) {
2087         // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2088         Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2089                                                      Op1, "tmp");
2090         InsertNewInstBefore(Add, I);
2091         Value *C1C2 = ConstantExpr::getMul(Op1, 
2092                                            cast<Constant>(Op0I->getOperand(1)));
2093         return BinaryOperator::createAdd(Add, C1C2);
2094         
2095       }
2096
2097     // Try to fold constant mul into select arguments.
2098     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2099       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2100         return R;
2101
2102     if (isa<PHINode>(Op0))
2103       if (Instruction *NV = FoldOpIntoPhi(I))
2104         return NV;
2105   }
2106
2107   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
2108     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2109       return BinaryOperator::createMul(Op0v, Op1v);
2110
2111   // If one of the operands of the multiply is a cast from a boolean value, then
2112   // we know the bool is either zero or one, so this is a 'masking' multiply.
2113   // See if we can simplify things based on how the boolean was originally
2114   // formed.
2115   CastInst *BoolCast = 0;
2116   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2117     if (CI->getOperand(0)->getType() == Type::BoolTy)
2118       BoolCast = CI;
2119   if (!BoolCast)
2120     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2121       if (CI->getOperand(0)->getType() == Type::BoolTy)
2122         BoolCast = CI;
2123   if (BoolCast) {
2124     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2125       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2126       const Type *SCOpTy = SCIOp0->getType();
2127
2128       // If the setcc is true iff the sign bit of X is set, then convert this
2129       // multiply into a shift/and combination.
2130       if (isa<ConstantInt>(SCIOp1) &&
2131           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2132         // Shift the X value right to turn it into "all signbits".
2133         Constant *Amt = ConstantInt::get(Type::UByteTy,
2134                                           SCOpTy->getPrimitiveSizeInBits()-1);
2135         if (SCIOp0->getType()->isUnsigned()) {
2136           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2137           SCIOp0 = InsertCastBefore(SCIOp0, NewTy, I);
2138         }
2139
2140         Value *V =
2141           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2142                                             BoolCast->getOperand(0)->getName()+
2143                                             ".mask"), I);
2144
2145         // If the multiply type is not the same as the source type, sign extend
2146         // or truncate to the multiply type.
2147         if (I.getType() != V->getType())
2148           V = InsertCastBefore(V, I.getType(), I);
2149
2150         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2151         return BinaryOperator::createAnd(V, OtherOp);
2152       }
2153     }
2154   }
2155
2156   return Changed ? &I : 0;
2157 }
2158
2159 /// This function implements the transforms on div instructions that work
2160 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2161 /// used by the visitors to those instructions.
2162 /// @brief Transforms common to all three div instructions
2163 Instruction* InstCombiner::commonDivTransforms(BinaryOperator &I) {
2164   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2165
2166   // undef / X -> 0
2167   if (isa<UndefValue>(Op0))
2168     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2169
2170   // X / undef -> undef
2171   if (isa<UndefValue>(Op1))
2172     return ReplaceInstUsesWith(I, Op1);
2173
2174   // Handle cases involving: div X, (select Cond, Y, Z)
2175   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2176     // div X, (Cond ? 0 : Y) -> div X, Y.  If the div and the select are in the
2177     // same basic block, then we replace the select with Y, and the condition 
2178     // of the select with false (if the cond value is in the same BB).  If the
2179     // select has uses other than the div, this allows them to be simplified
2180     // also. Note that div X, Y is just as good as div X, 0 (undef)
2181     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2182       if (ST->isNullValue()) {
2183         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2184         if (CondI && CondI->getParent() == I.getParent())
2185           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2186         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2187           I.setOperand(1, SI->getOperand(2));
2188         else
2189           UpdateValueUsesWith(SI, SI->getOperand(2));
2190         return &I;
2191       }
2192
2193     // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2194     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2195       if (ST->isNullValue()) {
2196         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2197         if (CondI && CondI->getParent() == I.getParent())
2198           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2199         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2200           I.setOperand(1, SI->getOperand(1));
2201         else
2202           UpdateValueUsesWith(SI, SI->getOperand(1));
2203         return &I;
2204       }
2205   }
2206
2207   return 0;
2208 }
2209
2210 /// This function implements the transforms common to both integer division
2211 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2212 /// division instructions.
2213 /// @brief Common integer divide transforms
2214 Instruction* InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2215   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2216
2217   if (Instruction *Common = commonDivTransforms(I))
2218     return Common;
2219
2220   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2221     // div X, 1 == X
2222     if (RHS->equalsInt(1))
2223       return ReplaceInstUsesWith(I, Op0);
2224
2225     // (X / C1) / C2  -> X / (C1*C2)
2226     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2227       if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2228         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2229           return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2230                                         ConstantExpr::getMul(RHS, LHSRHS));
2231         }
2232
2233     if (!RHS->isNullValue()) { // avoid X udiv 0
2234       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2235         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2236           return R;
2237       if (isa<PHINode>(Op0))
2238         if (Instruction *NV = FoldOpIntoPhi(I))
2239           return NV;
2240     }
2241   }
2242
2243   // 0 / X == 0, we don't need to preserve faults!
2244   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2245     if (LHS->equalsInt(0))
2246       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2247
2248   return 0;
2249 }
2250
2251 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2252   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2253
2254   // Handle the integer div common cases
2255   if (Instruction *Common = commonIDivTransforms(I))
2256     return Common;
2257
2258   // X udiv C^2 -> X >> C
2259   // Check to see if this is an unsigned division with an exact power of 2,
2260   // if so, convert to a right shift.
2261   if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2262     if (uint64_t Val = C->getZExtValue())    // Don't break X / 0
2263       if (isPowerOf2_64(Val)) {
2264         uint64_t ShiftAmt = Log2_64(Val);
2265         Value* X = Op0;
2266         const Type* XTy = X->getType();
2267         bool isSigned = XTy->isSigned();
2268         if (isSigned)
2269           X = InsertCastBefore(X, XTy->getUnsignedVersion(), I);
2270         Instruction* Result = 
2271           new ShiftInst(Instruction::Shr, X, 
2272                         ConstantInt::get(Type::UByteTy, ShiftAmt));
2273         if (!isSigned)
2274           return Result;
2275         InsertNewInstBefore(Result, I);
2276         return new CastInst(Result, XTy->getSignedVersion(), I.getName());
2277       }
2278   }
2279
2280   // X udiv (C1 << N), where C1 is "1<<C2"  -->  X >> (N+C2)
2281   if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2282     if (RHSI->getOpcode() == Instruction::Shl &&
2283         isa<ConstantInt>(RHSI->getOperand(0))) {
2284       uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2285       if (isPowerOf2_64(C1)) {
2286         Value *N = RHSI->getOperand(1);
2287         const Type* NTy = N->getType();
2288         bool isSigned = NTy->isSigned();
2289         if (uint64_t C2 = Log2_64(C1)) {
2290           if (isSigned) {
2291             NTy = NTy->getUnsignedVersion();
2292             N = InsertCastBefore(N, NTy, I);
2293           }
2294           Constant *C2V = ConstantInt::get(NTy, C2);
2295           N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2296         }
2297         Instruction* Result = new ShiftInst(Instruction::Shr, Op0, N);
2298         if (!isSigned)
2299           return Result;
2300         InsertNewInstBefore(Result, I);
2301         return new CastInst(Result, NTy->getSignedVersion(), I.getName());
2302       }
2303     }
2304   }
2305   
2306   // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2307   // where C1&C2 are powers of two.
2308   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2309     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2310       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) 
2311         if (!STO->isNullValue() && !STO->isNullValue()) {
2312           uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2313           if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2314             // Compute the shift amounts
2315             unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2316             // Make sure we get the unsigned version of X
2317             Value* X = Op0;
2318             const Type* origXTy = X->getType();
2319             bool isSigned = origXTy->isSigned();
2320             if (isSigned)
2321               X = InsertCastBefore(X, X->getType()->getUnsignedVersion(), I);
2322             // Construct the "on true" case of the select
2323             Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2324             Instruction *TSI = 
2325               new ShiftInst(Instruction::Shr, X, TC, SI->getName()+".t");
2326             TSI = InsertNewInstBefore(TSI, I);
2327     
2328             // Construct the "on false" case of the select
2329             Constant *FC = ConstantInt::get(Type::UByteTy, FSA); 
2330             Instruction *FSI = 
2331               new ShiftInst(Instruction::Shr, X, FC, SI->getName()+".f");
2332             FSI = InsertNewInstBefore(FSI, I);
2333
2334             // construct the select instruction and return it.
2335             SelectInst* NewSI = 
2336               new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2337             if (!isSigned)
2338               return NewSI;
2339             InsertNewInstBefore(NewSI, I);
2340             return new CastInst(NewSI, origXTy, NewSI->getName());
2341           }
2342         }
2343   }
2344   return 0;
2345 }
2346
2347 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2348   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2349
2350   // Handle the integer div common cases
2351   if (Instruction *Common = commonIDivTransforms(I))
2352     return Common;
2353
2354   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2355     // sdiv X, -1 == -X
2356     if (RHS->isAllOnesValue())
2357       return BinaryOperator::createNeg(Op0);
2358
2359     // -X/C -> X/-C
2360     if (Value *LHSNeg = dyn_castNegVal(Op0))
2361       return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2362   }
2363
2364   // If the sign bits of both operands are zero (i.e. we can prove they are
2365   // unsigned inputs), turn this into a udiv.
2366   if (I.getType()->isInteger()) {
2367     uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2368     if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2369       return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2370     }
2371   }      
2372   
2373   return 0;
2374 }
2375
2376 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2377   return commonDivTransforms(I);
2378 }
2379
2380 /// GetFactor - If we can prove that the specified value is at least a multiple
2381 /// of some factor, return that factor.
2382 static Constant *GetFactor(Value *V) {
2383   if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2384     return CI;
2385   
2386   // Unless we can be tricky, we know this is a multiple of 1.
2387   Constant *Result = ConstantInt::get(V->getType(), 1);
2388   
2389   Instruction *I = dyn_cast<Instruction>(V);
2390   if (!I) return Result;
2391   
2392   if (I->getOpcode() == Instruction::Mul) {
2393     // Handle multiplies by a constant, etc.
2394     return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2395                                 GetFactor(I->getOperand(1)));
2396   } else if (I->getOpcode() == Instruction::Shl) {
2397     // (X<<C) -> X * (1 << C)
2398     if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2399       ShRHS = ConstantExpr::getShl(Result, ShRHS);
2400       return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2401     }
2402   } else if (I->getOpcode() == Instruction::And) {
2403     if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2404       // X & 0xFFF0 is known to be a multiple of 16.
2405       unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2406       if (Zeros != V->getType()->getPrimitiveSizeInBits())
2407         return ConstantExpr::getShl(Result, 
2408                                     ConstantInt::get(Type::UByteTy, Zeros));
2409     }
2410   } else if (I->getOpcode() == Instruction::Cast) {
2411     Value *Op = I->getOperand(0);
2412     // Only handle int->int casts.
2413     if (!Op->getType()->isInteger()) return Result;
2414     return ConstantExpr::getCast(GetFactor(Op), V->getType());
2415   }    
2416   return Result;
2417 }
2418
2419 /// This function implements the transforms on rem instructions that work
2420 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It 
2421 /// is used by the visitors to those instructions.
2422 /// @brief Transforms common to all three rem instructions
2423 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2424   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2425
2426   // 0 % X == 0, we don't need to preserve faults!
2427   if (Constant *LHS = dyn_cast<Constant>(Op0))
2428     if (LHS->isNullValue())
2429       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2430
2431   if (isa<UndefValue>(Op0))              // undef % X -> 0
2432     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2433   if (isa<UndefValue>(Op1))
2434     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
2435
2436   // Handle cases involving: rem X, (select Cond, Y, Z)
2437   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2438     // rem X, (Cond ? 0 : Y) -> rem X, Y.  If the rem and the select are in
2439     // the same basic block, then we replace the select with Y, and the
2440     // condition of the select with false (if the cond value is in the same
2441     // BB).  If the select has uses other than the div, this allows them to be
2442     // simplified also.
2443     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2444       if (ST->isNullValue()) {
2445         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2446         if (CondI && CondI->getParent() == I.getParent())
2447           UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2448         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2449           I.setOperand(1, SI->getOperand(2));
2450         else
2451           UpdateValueUsesWith(SI, SI->getOperand(2));
2452         return &I;
2453       }
2454     // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2455     if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2456       if (ST->isNullValue()) {
2457         Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2458         if (CondI && CondI->getParent() == I.getParent())
2459           UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2460         else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2461           I.setOperand(1, SI->getOperand(1));
2462         else
2463           UpdateValueUsesWith(SI, SI->getOperand(1));
2464         return &I;
2465       }
2466   }
2467
2468   return 0;
2469 }
2470
2471 /// This function implements the transforms common to both integer remainder
2472 /// instructions (urem and srem). It is called by the visitors to those integer
2473 /// remainder instructions.
2474 /// @brief Common integer remainder transforms
2475 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2476   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2477
2478   if (Instruction *common = commonRemTransforms(I))
2479     return common;
2480
2481   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2482     // X % 0 == undef, we don't need to preserve faults!
2483     if (RHS->equalsInt(0))
2484       return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2485     
2486     if (RHS->equalsInt(1))  // X % 1 == 0
2487       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2488
2489     if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2490       if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2491         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2492           return R;
2493       } else if (isa<PHINode>(Op0I)) {
2494         if (Instruction *NV = FoldOpIntoPhi(I))
2495           return NV;
2496       }
2497       // (X * C1) % C2 --> 0  iff  C1 % C2 == 0
2498       if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2499         return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2500     }
2501   }
2502
2503   return 0;
2504 }
2505
2506 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2507   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2508
2509   if (Instruction *common = commonIRemTransforms(I))
2510     return common;
2511   
2512   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2513     // X urem C^2 -> X and C
2514     // Check to see if this is an unsigned remainder with an exact power of 2,
2515     // if so, convert to a bitwise and.
2516     if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2517       if (isPowerOf2_64(C->getZExtValue()))
2518         return BinaryOperator::createAnd(Op0, SubOne(C));
2519   }
2520
2521   if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2522     // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)  
2523     if (RHSI->getOpcode() == Instruction::Shl &&
2524         isa<ConstantInt>(RHSI->getOperand(0))) {
2525       unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2526       if (isPowerOf2_64(C1)) {
2527         Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2528         Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2529                                                                    "tmp"), I);
2530         return BinaryOperator::createAnd(Op0, Add);
2531       }
2532     }
2533   }
2534
2535   // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2536   // where C1&C2 are powers of two.
2537   if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2538     if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2539       if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2540         // STO == 0 and SFO == 0 handled above.
2541         if (isPowerOf2_64(STO->getZExtValue()) && 
2542             isPowerOf2_64(SFO->getZExtValue())) {
2543           Value *TrueAnd = InsertNewInstBefore(
2544             BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2545           Value *FalseAnd = InsertNewInstBefore(
2546             BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2547           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2548         }
2549       }
2550   }
2551   
2552   return 0;
2553 }
2554
2555 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2556   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2557
2558   if (Instruction *common = commonIRemTransforms(I))
2559     return common;
2560   
2561   if (Value *RHSNeg = dyn_castNegVal(Op1))
2562     if (!isa<ConstantInt>(RHSNeg) || 
2563         cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2564       // X % -Y -> X % Y
2565       AddUsesToWorkList(I);
2566       I.setOperand(1, RHSNeg);
2567       return &I;
2568     }
2569  
2570   // If the top bits of both operands are zero (i.e. we can prove they are
2571   // unsigned inputs), turn this into a urem.
2572   uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2573   if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2574     // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2575     return BinaryOperator::createURem(Op0, Op1, I.getName());
2576   }
2577
2578   return 0;
2579 }
2580
2581 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2582   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2583
2584   return commonRemTransforms(I);
2585 }
2586
2587 // isMaxValueMinusOne - return true if this is Max-1
2588 static bool isMaxValueMinusOne(const ConstantInt *C) {
2589   if (C->getType()->isUnsigned()) 
2590     return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
2591
2592   // Calculate 0111111111..11111
2593   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2594   int64_t Val = INT64_MAX;             // All ones
2595   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
2596   return C->getSExtValue() == Val-1;
2597 }
2598
2599 // isMinValuePlusOne - return true if this is Min+1
2600 static bool isMinValuePlusOne(const ConstantInt *C) {
2601   if (C->getType()->isUnsigned())
2602     return C->getZExtValue() == 1;
2603
2604   // Calculate 1111111111000000000000
2605   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2606   int64_t Val = -1;                    // All ones
2607   Val <<= TypeBits-1;                  // Shift over to the right spot
2608   return C->getSExtValue() == Val+1;
2609 }
2610
2611 // isOneBitSet - Return true if there is exactly one bit set in the specified
2612 // constant.
2613 static bool isOneBitSet(const ConstantInt *CI) {
2614   uint64_t V = CI->getZExtValue();
2615   return V && (V & (V-1)) == 0;
2616 }
2617
2618 #if 0   // Currently unused
2619 // isLowOnes - Return true if the constant is of the form 0+1+.
2620 static bool isLowOnes(const ConstantInt *CI) {
2621   uint64_t V = CI->getZExtValue();
2622
2623   // There won't be bits set in parts that the type doesn't contain.
2624   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2625
2626   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2627   return U && V && (U & V) == 0;
2628 }
2629 #endif
2630
2631 // isHighOnes - Return true if the constant is of the form 1+0+.
2632 // This is the same as lowones(~X).
2633 static bool isHighOnes(const ConstantInt *CI) {
2634   uint64_t V = ~CI->getZExtValue();
2635   if (~V == 0) return false;  // 0's does not match "1+"
2636
2637   // There won't be bits set in parts that the type doesn't contain.
2638   V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2639
2640   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
2641   return U && V && (U & V) == 0;
2642 }
2643
2644
2645 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
2646 /// are carefully arranged to allow folding of expressions such as:
2647 ///
2648 ///      (A < B) | (A > B) --> (A != B)
2649 ///
2650 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2651 /// represents that the comparison is true if A == B, and bit value '1' is true
2652 /// if A < B.
2653 ///
2654 static unsigned getSetCondCode(const SetCondInst *SCI) {
2655   switch (SCI->getOpcode()) {
2656     // False -> 0
2657   case Instruction::SetGT: return 1;
2658   case Instruction::SetEQ: return 2;
2659   case Instruction::SetGE: return 3;
2660   case Instruction::SetLT: return 4;
2661   case Instruction::SetNE: return 5;
2662   case Instruction::SetLE: return 6;
2663     // True -> 7
2664   default:
2665     assert(0 && "Invalid SetCC opcode!");
2666     return 0;
2667   }
2668 }
2669
2670 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2671 /// opcode and two operands into either a constant true or false, or a brand new
2672 /// SetCC instruction.
2673 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2674   switch (Opcode) {
2675   case 0: return ConstantBool::getFalse();
2676   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2677   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2678   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2679   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2680   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2681   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2682   case 7: return ConstantBool::getTrue();
2683   default: assert(0 && "Illegal SetCCCode!"); return 0;
2684   }
2685 }
2686
2687 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2688 struct FoldSetCCLogical {
2689   InstCombiner &IC;
2690   Value *LHS, *RHS;
2691   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2692     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2693   bool shouldApply(Value *V) const {
2694     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2695       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2696               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2697     return false;
2698   }
2699   Instruction *apply(BinaryOperator &Log) const {
2700     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2701     if (SCI->getOperand(0) != LHS) {
2702       assert(SCI->getOperand(1) == LHS);
2703       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
2704     }
2705
2706     unsigned LHSCode = getSetCondCode(SCI);
2707     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2708     unsigned Code;
2709     switch (Log.getOpcode()) {
2710     case Instruction::And: Code = LHSCode & RHSCode; break;
2711     case Instruction::Or:  Code = LHSCode | RHSCode; break;
2712     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2713     default: assert(0 && "Illegal logical opcode!"); return 0;
2714     }
2715
2716     Value *RV = getSetCCValue(Code, LHS, RHS);
2717     if (Instruction *I = dyn_cast<Instruction>(RV))
2718       return I;
2719     // Otherwise, it's a constant boolean value...
2720     return IC.ReplaceInstUsesWith(Log, RV);
2721   }
2722 };
2723
2724 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
2725 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
2726 // guaranteed to be either a shift instruction or a binary operator.
2727 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2728                                     ConstantIntegral *OpRHS,
2729                                     ConstantIntegral *AndRHS,
2730                                     BinaryOperator &TheAnd) {
2731   Value *X = Op->getOperand(0);
2732   Constant *Together = 0;
2733   if (!isa<ShiftInst>(Op))
2734     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2735
2736   switch (Op->getOpcode()) {
2737   case Instruction::Xor:
2738     if (Op->hasOneUse()) {
2739       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2740       std::string OpName = Op->getName(); Op->setName("");
2741       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2742       InsertNewInstBefore(And, TheAnd);
2743       return BinaryOperator::createXor(And, Together);
2744     }
2745     break;
2746   case Instruction::Or:
2747     if (Together == AndRHS) // (X | C) & C --> C
2748       return ReplaceInstUsesWith(TheAnd, AndRHS);
2749
2750     if (Op->hasOneUse() && Together != OpRHS) {
2751       // (X | C1) & C2 --> (X | (C1&C2)) & C2
2752       std::string Op0Name = Op->getName(); Op->setName("");
2753       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2754       InsertNewInstBefore(Or, TheAnd);
2755       return BinaryOperator::createAnd(Or, AndRHS);
2756     }
2757     break;
2758   case Instruction::Add:
2759     if (Op->hasOneUse()) {
2760       // Adding a one to a single bit bit-field should be turned into an XOR
2761       // of the bit.  First thing to check is to see if this AND is with a
2762       // single bit constant.
2763       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2764
2765       // Clear bits that are not part of the constant.
2766       AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2767
2768       // If there is only one bit set...
2769       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2770         // Ok, at this point, we know that we are masking the result of the
2771         // ADD down to exactly one bit.  If the constant we are adding has
2772         // no bits set below this bit, then we can eliminate the ADD.
2773         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2774
2775         // Check to see if any bits below the one bit set in AndRHSV are set.
2776         if ((AddRHS & (AndRHSV-1)) == 0) {
2777           // If not, the only thing that can effect the output of the AND is
2778           // the bit specified by AndRHSV.  If that bit is set, the effect of
2779           // the XOR is to toggle the bit.  If it is clear, then the ADD has
2780           // no effect.
2781           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2782             TheAnd.setOperand(0, X);
2783             return &TheAnd;
2784           } else {
2785             std::string Name = Op->getName(); Op->setName("");
2786             // Pull the XOR out of the AND.
2787             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2788             InsertNewInstBefore(NewAnd, TheAnd);
2789             return BinaryOperator::createXor(NewAnd, AndRHS);
2790           }
2791         }
2792       }
2793     }
2794     break;
2795
2796   case Instruction::Shl: {
2797     // We know that the AND will not produce any of the bits shifted in, so if
2798     // the anded constant includes them, clear them now!
2799     //
2800     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2801     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2802     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2803
2804     if (CI == ShlMask) {   // Masking out bits that the shift already masks
2805       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
2806     } else if (CI != AndRHS) {                  // Reducing bits set in and.
2807       TheAnd.setOperand(1, CI);
2808       return &TheAnd;
2809     }
2810     break;
2811   }
2812   case Instruction::Shr:
2813     // We know that the AND will not produce any of the bits shifted in, so if
2814     // the anded constant includes them, clear them now!  This only applies to
2815     // unsigned shifts, because a signed shr may bring in set bits!
2816     //
2817     if (AndRHS->getType()->isUnsigned()) {
2818       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2819       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2820       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2821
2822       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
2823         return ReplaceInstUsesWith(TheAnd, Op);
2824       } else if (CI != AndRHS) {
2825         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
2826         return &TheAnd;
2827       }
2828     } else {   // Signed shr.
2829       // See if this is shifting in some sign extension, then masking it out
2830       // with an and.
2831       if (Op->hasOneUse()) {
2832         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2833         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2834         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2835         if (CI == AndRHS) {          // Masking out bits shifted in.
2836           // Make the argument unsigned.
2837           Value *ShVal = Op->getOperand(0);
2838           ShVal = InsertCastBefore(ShVal,
2839                                    ShVal->getType()->getUnsignedVersion(),
2840                                    TheAnd);
2841           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2842                                                     OpRHS, Op->getName()),
2843                                       TheAnd);
2844           Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2845           ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2846                                                              TheAnd.getName()),
2847                                       TheAnd);
2848           return new CastInst(ShVal, Op->getType());
2849         }
2850       }
2851     }
2852     break;
2853   }
2854   return 0;
2855 }
2856
2857
2858 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2859 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
2860 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
2861 /// insert new instructions.
2862 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2863                                            bool Inside, Instruction &IB) {
2864   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2865          "Lo is not <= Hi in range emission code!");
2866   if (Inside) {
2867     if (Lo == Hi)  // Trivially false.
2868       return new SetCondInst(Instruction::SetNE, V, V);
2869     if (cast<ConstantIntegral>(Lo)->isMinValue())
2870       return new SetCondInst(Instruction::SetLT, V, Hi);
2871
2872     Constant *AddCST = ConstantExpr::getNeg(Lo);
2873     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2874     InsertNewInstBefore(Add, IB);
2875     // Convert to unsigned for the comparison.
2876     const Type *UnsType = Add->getType()->getUnsignedVersion();
2877     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2878     AddCST = ConstantExpr::getAdd(AddCST, Hi);
2879     AddCST = ConstantExpr::getCast(AddCST, UnsType);
2880     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2881   }
2882
2883   if (Lo == Hi)  // Trivially true.
2884     return new SetCondInst(Instruction::SetEQ, V, V);
2885
2886   Hi = SubOne(cast<ConstantInt>(Hi));
2887
2888   // V < 0 || V >= Hi ->'V > Hi-1'
2889   if (cast<ConstantIntegral>(Lo)->isMinValue())
2890     return new SetCondInst(Instruction::SetGT, V, Hi);
2891
2892   // Emit X-Lo > Hi-Lo-1
2893   Constant *AddCST = ConstantExpr::getNeg(Lo);
2894   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2895   InsertNewInstBefore(Add, IB);
2896   // Convert to unsigned for the comparison.
2897   const Type *UnsType = Add->getType()->getUnsignedVersion();
2898   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2899   AddCST = ConstantExpr::getAdd(AddCST, Hi);
2900   AddCST = ConstantExpr::getCast(AddCST, UnsType);
2901   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2902 }
2903
2904 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2905 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
2906 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
2907 // not, since all 1s are not contiguous.
2908 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2909   uint64_t V = Val->getZExtValue();
2910   if (!isShiftedMask_64(V)) return false;
2911
2912   // look for the first zero bit after the run of ones
2913   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2914   // look for the first non-zero bit
2915   ME = 64-CountLeadingZeros_64(V);
2916   return true;
2917 }
2918
2919
2920
2921 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2922 /// where isSub determines whether the operator is a sub.  If we can fold one of
2923 /// the following xforms:
2924 /// 
2925 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2926 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2927 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2928 ///
2929 /// return (A +/- B).
2930 ///
2931 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2932                                         ConstantIntegral *Mask, bool isSub,
2933                                         Instruction &I) {
2934   Instruction *LHSI = dyn_cast<Instruction>(LHS);
2935   if (!LHSI || LHSI->getNumOperands() != 2 ||
2936       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2937
2938   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2939
2940   switch (LHSI->getOpcode()) {
2941   default: return 0;
2942   case Instruction::And:
2943     if (ConstantExpr::getAnd(N, Mask) == Mask) {
2944       // If the AndRHS is a power of two minus one (0+1+), this is simple.
2945       if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
2946         break;
2947
2948       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2949       // part, we don't need any explicit masks to take them out of A.  If that
2950       // is all N is, ignore it.
2951       unsigned MB, ME;
2952       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
2953         uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2954         Mask >>= 64-MB+1;
2955         if (MaskedValueIsZero(RHS, Mask))
2956           break;
2957       }
2958     }
2959     return 0;
2960   case Instruction::Or:
2961   case Instruction::Xor:
2962     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2963     if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
2964         ConstantExpr::getAnd(N, Mask)->isNullValue())
2965       break;
2966     return 0;
2967   }
2968   
2969   Instruction *New;
2970   if (isSub)
2971     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2972   else
2973     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2974   return InsertNewInstBefore(New, I);
2975 }
2976
2977 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2978   bool Changed = SimplifyCommutative(I);
2979   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2980
2981   if (isa<UndefValue>(Op1))                         // X & undef -> 0
2982     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2983
2984   // and X, X = X
2985   if (Op0 == Op1)
2986     return ReplaceInstUsesWith(I, Op1);
2987
2988   // See if we can simplify any instructions used by the instruction whose sole 
2989   // purpose is to compute bits we don't care about.
2990   uint64_t KnownZero, KnownOne;
2991   if (!isa<PackedType>(I.getType()) &&
2992       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2993                            KnownZero, KnownOne))
2994     return &I;
2995   
2996   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2997     uint64_t AndRHSMask = AndRHS->getZExtValue();
2998     uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2999     uint64_t NotAndRHS = AndRHSMask^TypeMask;
3000
3001     // Optimize a variety of ((val OP C1) & C2) combinations...
3002     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3003       Instruction *Op0I = cast<Instruction>(Op0);
3004       Value *Op0LHS = Op0I->getOperand(0);
3005       Value *Op0RHS = Op0I->getOperand(1);
3006       switch (Op0I->getOpcode()) {
3007       case Instruction::Xor:
3008       case Instruction::Or:
3009         // If the mask is only needed on one incoming arm, push it up.
3010         if (Op0I->hasOneUse()) {
3011           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3012             // Not masking anything out for the LHS, move to RHS.
3013             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3014                                                    Op0RHS->getName()+".masked");
3015             InsertNewInstBefore(NewRHS, I);
3016             return BinaryOperator::create(
3017                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3018           }
3019           if (!isa<Constant>(Op0RHS) &&
3020               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3021             // Not masking anything out for the RHS, move to LHS.
3022             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3023                                                    Op0LHS->getName()+".masked");
3024             InsertNewInstBefore(NewLHS, I);
3025             return BinaryOperator::create(
3026                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3027           }
3028         }
3029
3030         break;
3031       case Instruction::Add:
3032         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3033         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3034         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3035         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3036           return BinaryOperator::createAnd(V, AndRHS);
3037         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3038           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
3039         break;
3040
3041       case Instruction::Sub:
3042         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3043         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3044         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3045         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3046           return BinaryOperator::createAnd(V, AndRHS);
3047         break;
3048       }
3049
3050       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3051         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3052           return Res;
3053     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3054       const Type *SrcTy = CI->getOperand(0)->getType();
3055
3056       // If this is an integer truncation or change from signed-to-unsigned, and
3057       // if the source is an and/or with immediate, transform it.  This
3058       // frequently occurs for bitfield accesses.
3059       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3060         if (SrcTy->getPrimitiveSizeInBits() >= 
3061               I.getType()->getPrimitiveSizeInBits() &&
3062             CastOp->getNumOperands() == 2)
3063           if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3064             if (CastOp->getOpcode() == Instruction::And) {
3065               // Change: and (cast (and X, C1) to T), C2
3066               // into  : and (cast X to T), trunc(C1)&C2
3067               // This will folds the two ands together, which may allow other
3068               // simplifications.
3069               Instruction *NewCast =
3070                 new CastInst(CastOp->getOperand(0), I.getType(),
3071                              CastOp->getName()+".shrunk");
3072               NewCast = InsertNewInstBefore(NewCast, I);
3073               
3074               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3075               C3 = ConstantExpr::getAnd(C3, AndRHS);            // trunc(C1)&C2
3076               return BinaryOperator::createAnd(NewCast, C3);
3077             } else if (CastOp->getOpcode() == Instruction::Or) {
3078               // Change: and (cast (or X, C1) to T), C2
3079               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3080               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
3081               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
3082                 return ReplaceInstUsesWith(I, AndRHS);
3083             }
3084       }
3085     }
3086
3087     // Try to fold constant and into select arguments.
3088     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3089       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3090         return R;
3091     if (isa<PHINode>(Op0))
3092       if (Instruction *NV = FoldOpIntoPhi(I))
3093         return NV;
3094   }
3095
3096   Value *Op0NotVal = dyn_castNotVal(Op0);
3097   Value *Op1NotVal = dyn_castNotVal(Op1);
3098
3099   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
3100     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3101
3102   // (~A & ~B) == (~(A | B)) - De Morgan's Law
3103   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3104     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3105                                                I.getName()+".demorgan");
3106     InsertNewInstBefore(Or, I);
3107     return BinaryOperator::createNot(Or);
3108   }
3109   
3110   {
3111     Value *A = 0, *B = 0;
3112     ConstantInt *C1 = 0, *C2 = 0;
3113     if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3114       if (A == Op1 || B == Op1)    // (A | ?) & A  --> A
3115         return ReplaceInstUsesWith(I, Op1);
3116     if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3117       if (A == Op0 || B == Op0)    // A & (A | ?)  --> A
3118         return ReplaceInstUsesWith(I, Op0);
3119     
3120     if (Op0->hasOneUse() &&
3121         match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3122       if (A == Op1) {                                // (A^B)&A -> A&(A^B)
3123         I.swapOperands();     // Simplify below
3124         std::swap(Op0, Op1);
3125       } else if (B == Op1) {                         // (A^B)&B -> B&(B^A)
3126         cast<BinaryOperator>(Op0)->swapOperands();
3127         I.swapOperands();     // Simplify below
3128         std::swap(Op0, Op1);
3129       }
3130     }
3131     if (Op1->hasOneUse() &&
3132         match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3133       if (B == Op0) {                                // B&(A^B) -> B&(B^A)
3134         cast<BinaryOperator>(Op1)->swapOperands();
3135         std::swap(A, B);
3136       }
3137       if (A == Op0) {                                // A&(A^B) -> A & ~B
3138         Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3139         InsertNewInstBefore(NotB, I);
3140         return BinaryOperator::createAnd(A, NotB);
3141       }
3142     }
3143   }
3144   
3145
3146   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3147     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3148     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3149       return R;
3150
3151     Value *LHSVal, *RHSVal;
3152     ConstantInt *LHSCst, *RHSCst;
3153     Instruction::BinaryOps LHSCC, RHSCC;
3154     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3155       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3156         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
3157             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3158             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3159             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3160           // Ensure that the larger constant is on the RHS.
3161           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3162           SetCondInst *LHS = cast<SetCondInst>(Op0);
3163           if (cast<ConstantBool>(Cmp)->getValue()) {
3164             std::swap(LHS, RHS);
3165             std::swap(LHSCst, RHSCst);
3166             std::swap(LHSCC, RHSCC);
3167           }
3168
3169           // At this point, we know we have have two setcc instructions
3170           // comparing a value against two constants and and'ing the result
3171           // together.  Because of the above check, we know that we only have
3172           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3173           // FoldSetCCLogical check above), that the two constants are not
3174           // equal.
3175           assert(LHSCst != RHSCst && "Compares not folded above?");
3176
3177           switch (LHSCC) {
3178           default: assert(0 && "Unknown integer condition code!");
3179           case Instruction::SetEQ:
3180             switch (RHSCC) {
3181             default: assert(0 && "Unknown integer condition code!");
3182             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
3183             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
3184               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3185             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
3186             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
3187               return ReplaceInstUsesWith(I, LHS);
3188             }
3189           case Instruction::SetNE:
3190             switch (RHSCC) {
3191             default: assert(0 && "Unknown integer condition code!");
3192             case Instruction::SetLT:
3193               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3194                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3195               break;                        // (X != 13 & X < 15) -> no change
3196             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
3197             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
3198               return ReplaceInstUsesWith(I, RHS);
3199             case Instruction::SetNE:
3200               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3201                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3202                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3203                                                       LHSVal->getName()+".off");
3204                 InsertNewInstBefore(Add, I);
3205                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3206                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3207                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3208                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3209                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3210               }
3211               break;                        // (X != 13 & X != 15) -> no change
3212             }
3213             break;
3214           case Instruction::SetLT:
3215             switch (RHSCC) {
3216             default: assert(0 && "Unknown integer condition code!");
3217             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
3218             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
3219               return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3220             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
3221             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
3222               return ReplaceInstUsesWith(I, LHS);
3223             }
3224           case Instruction::SetGT:
3225             switch (RHSCC) {
3226             default: assert(0 && "Unknown integer condition code!");
3227             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
3228               return ReplaceInstUsesWith(I, LHS);
3229             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
3230               return ReplaceInstUsesWith(I, RHS);
3231             case Instruction::SetNE:
3232               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3233                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3234               break;                        // (X > 13 & X != 15) -> no change
3235             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
3236               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3237             }
3238           }
3239         }
3240   }
3241
3242   // fold (and (cast A), (cast B)) -> (cast (and A, B))
3243   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3244     const Type *SrcTy = Op0C->getOperand(0)->getType();
3245     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3246       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3247           // Only do this if the casts both really cause code to be generated.
3248           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3249           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3250         Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3251                                                        Op1C->getOperand(0),
3252                                                        I.getName());
3253         InsertNewInstBefore(NewOp, I);
3254         return new CastInst(NewOp, I.getType());
3255       }
3256   }
3257
3258   return Changed ? &I : 0;
3259 }
3260
3261 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3262 /// in the result.  If it does, and if the specified byte hasn't been filled in
3263 /// yet, fill it in and return false.
3264 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3265   Instruction *I = dyn_cast<Instruction>(V);
3266   if (I == 0) return true;
3267
3268   // If this is an or instruction, it is an inner node of the bswap.
3269   if (I->getOpcode() == Instruction::Or)
3270     return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3271            CollectBSwapParts(I->getOperand(1), ByteValues);
3272   
3273   // If this is a shift by a constant int, and it is "24", then its operand
3274   // defines a byte.  We only handle unsigned types here.
3275   if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3276     // Not shifting the entire input by N-1 bytes?
3277     if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3278         8*(ByteValues.size()-1))
3279       return true;
3280     
3281     unsigned DestNo;
3282     if (I->getOpcode() == Instruction::Shl) {
3283       // X << 24 defines the top byte with the lowest of the input bytes.
3284       DestNo = ByteValues.size()-1;
3285     } else {
3286       // X >>u 24 defines the low byte with the highest of the input bytes.
3287       DestNo = 0;
3288     }
3289     
3290     // If the destination byte value is already defined, the values are or'd
3291     // together, which isn't a bswap (unless it's an or of the same bits).
3292     if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3293       return true;
3294     ByteValues[DestNo] = I->getOperand(0);
3295     return false;
3296   }
3297   
3298   // Otherwise, we can only handle and(shift X, imm), imm).  Bail out of if we
3299   // don't have this.
3300   Value *Shift = 0, *ShiftLHS = 0;
3301   ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3302   if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3303       !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3304     return true;
3305   Instruction *SI = cast<Instruction>(Shift);
3306
3307   // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3308   if (ShiftAmt->getZExtValue() & 7 ||
3309       ShiftAmt->getZExtValue() > 8*ByteValues.size())
3310     return true;
3311   
3312   // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3313   unsigned DestByte;
3314   for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3315     if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3316       break;
3317   // Unknown mask for bswap.
3318   if (DestByte == ByteValues.size()) return true;
3319   
3320   unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3321   unsigned SrcByte;
3322   if (SI->getOpcode() == Instruction::Shl)
3323     SrcByte = DestByte - ShiftBytes;
3324   else
3325     SrcByte = DestByte + ShiftBytes;
3326   
3327   // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3328   if (SrcByte != ByteValues.size()-DestByte-1)
3329     return true;
3330   
3331   // If the destination byte value is already defined, the values are or'd
3332   // together, which isn't a bswap (unless it's an or of the same bits).
3333   if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3334     return true;
3335   ByteValues[DestByte] = SI->getOperand(0);
3336   return false;
3337 }
3338
3339 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3340 /// If so, insert the new bswap intrinsic and return it.
3341 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3342   // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3343   if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3344     return 0;
3345   
3346   /// ByteValues - For each byte of the result, we keep track of which value
3347   /// defines each byte.
3348   std::vector<Value*> ByteValues;
3349   ByteValues.resize(I.getType()->getPrimitiveSize());
3350     
3351   // Try to find all the pieces corresponding to the bswap.
3352   if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3353       CollectBSwapParts(I.getOperand(1), ByteValues))
3354     return 0;
3355   
3356   // Check to see if all of the bytes come from the same value.
3357   Value *V = ByteValues[0];
3358   if (V == 0) return 0;  // Didn't find a byte?  Must be zero.
3359   
3360   // Check to make sure that all of the bytes come from the same value.
3361   for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3362     if (ByteValues[i] != V)
3363       return 0;
3364     
3365   // If they do then *success* we can turn this into a bswap.  Figure out what
3366   // bswap to make it into.
3367   Module *M = I.getParent()->getParent()->getParent();
3368   const char *FnName = 0;
3369   if (I.getType() == Type::UShortTy)
3370     FnName = "llvm.bswap.i16";
3371   else if (I.getType() == Type::UIntTy)
3372     FnName = "llvm.bswap.i32";
3373   else if (I.getType() == Type::ULongTy)
3374     FnName = "llvm.bswap.i64";
3375   else
3376     assert(0 && "Unknown integer type!");
3377   Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3378   
3379   return new CallInst(F, V);
3380 }
3381
3382
3383 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3384   bool Changed = SimplifyCommutative(I);
3385   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3386
3387   if (isa<UndefValue>(Op1))
3388     return ReplaceInstUsesWith(I,                         // X | undef -> -1
3389                                ConstantIntegral::getAllOnesValue(I.getType()));
3390
3391   // or X, X = X
3392   if (Op0 == Op1)
3393     return ReplaceInstUsesWith(I, Op0);
3394
3395   // See if we can simplify any instructions used by the instruction whose sole 
3396   // purpose is to compute bits we don't care about.
3397   uint64_t KnownZero, KnownOne;
3398   if (!isa<PackedType>(I.getType()) &&
3399       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3400                            KnownZero, KnownOne))
3401     return &I;
3402   
3403   // or X, -1 == -1
3404   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3405     ConstantInt *C1 = 0; Value *X = 0;
3406     // (X & C1) | C2 --> (X | C2) & (C1|C2)
3407     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3408       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3409       Op0->setName("");
3410       InsertNewInstBefore(Or, I);
3411       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3412     }
3413
3414     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3415     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3416       std::string Op0Name = Op0->getName(); Op0->setName("");
3417       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3418       InsertNewInstBefore(Or, I);
3419       return BinaryOperator::createXor(Or,
3420                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3421     }
3422
3423     // Try to fold constant and into select arguments.
3424     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3425       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3426         return R;
3427     if (isa<PHINode>(Op0))
3428       if (Instruction *NV = FoldOpIntoPhi(I))
3429         return NV;
3430   }
3431
3432   Value *A = 0, *B = 0;
3433   ConstantInt *C1 = 0, *C2 = 0;
3434
3435   if (match(Op0, m_And(m_Value(A), m_Value(B))))
3436     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
3437       return ReplaceInstUsesWith(I, Op1);
3438   if (match(Op1, m_And(m_Value(A), m_Value(B))))
3439     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
3440       return ReplaceInstUsesWith(I, Op0);
3441
3442   // (A | B) | C  and  A | (B | C)                  -> bswap if possible.
3443   // (A >> B) | (C << D)  and  (A << B) | (B >> C)  -> bswap if possible.
3444   if (match(Op0, m_Or(m_Value(), m_Value())) ||
3445       match(Op1, m_Or(m_Value(), m_Value())) ||
3446       (match(Op0, m_Shift(m_Value(), m_Value())) &&
3447        match(Op1, m_Shift(m_Value(), m_Value())))) {
3448     if (Instruction *BSwap = MatchBSwap(I))
3449       return BSwap;
3450   }
3451   
3452   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3453   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3454       MaskedValueIsZero(Op1, C1->getZExtValue())) {
3455     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3456     Op0->setName("");
3457     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3458   }
3459
3460   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3461   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3462       MaskedValueIsZero(Op0, C1->getZExtValue())) {
3463     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3464     Op0->setName("");
3465     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3466   }
3467
3468   // (A & C1)|(B & C2)
3469   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3470       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3471
3472     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
3473       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3474
3475
3476     // If we have: ((V + N) & C1) | (V & C2)
3477     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3478     // replace with V+N.
3479     if (C1 == ConstantExpr::getNot(C2)) {
3480       Value *V1 = 0, *V2 = 0;
3481       if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3482           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3483         // Add commutes, try both ways.
3484         if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3485           return ReplaceInstUsesWith(I, A);
3486         if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3487           return ReplaceInstUsesWith(I, A);
3488       }
3489       // Or commutes, try both ways.
3490       if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3491           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3492         // Add commutes, try both ways.
3493         if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3494           return ReplaceInstUsesWith(I, B);
3495         if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3496           return ReplaceInstUsesWith(I, B);
3497       }
3498     }
3499   }
3500
3501   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
3502     if (A == Op1)   // ~A | A == -1
3503       return ReplaceInstUsesWith(I,
3504                                 ConstantIntegral::getAllOnesValue(I.getType()));
3505   } else {
3506     A = 0;
3507   }
3508   // Note, A is still live here!
3509   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
3510     if (Op0 == B)
3511       return ReplaceInstUsesWith(I,
3512                                 ConstantIntegral::getAllOnesValue(I.getType()));
3513
3514     // (~A | ~B) == (~(A & B)) - De Morgan's Law
3515     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3516       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3517                                               I.getName()+".demorgan"), I);
3518       return BinaryOperator::createNot(And);
3519     }
3520   }
3521
3522   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3523   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3524     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3525       return R;
3526
3527     Value *LHSVal, *RHSVal;
3528     ConstantInt *LHSCst, *RHSCst;
3529     Instruction::BinaryOps LHSCC, RHSCC;
3530     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3531       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3532         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
3533             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3534             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3535             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3536           // Ensure that the larger constant is on the RHS.
3537           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3538           SetCondInst *LHS = cast<SetCondInst>(Op0);
3539           if (cast<ConstantBool>(Cmp)->getValue()) {
3540             std::swap(LHS, RHS);
3541             std::swap(LHSCst, RHSCst);
3542             std::swap(LHSCC, RHSCC);
3543           }
3544
3545           // At this point, we know we have have two setcc instructions
3546           // comparing a value against two constants and or'ing the result
3547           // together.  Because of the above check, we know that we only have
3548           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
3549           // FoldSetCCLogical check above), that the two constants are not
3550           // equal.
3551           assert(LHSCst != RHSCst && "Compares not folded above?");
3552
3553           switch (LHSCC) {
3554           default: assert(0 && "Unknown integer condition code!");
3555           case Instruction::SetEQ:
3556             switch (RHSCC) {
3557             default: assert(0 && "Unknown integer condition code!");
3558             case Instruction::SetEQ:
3559               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3560                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3561                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3562                                                       LHSVal->getName()+".off");
3563                 InsertNewInstBefore(Add, I);
3564                 const Type *UnsType = Add->getType()->getUnsignedVersion();
3565                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3566                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3567                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3568                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3569               }
3570               break;                  // (X == 13 | X == 15) -> no change
3571
3572             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
3573               break;
3574             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
3575             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
3576               return ReplaceInstUsesWith(I, RHS);
3577             }
3578             break;
3579           case Instruction::SetNE:
3580             switch (RHSCC) {
3581             default: assert(0 && "Unknown integer condition code!");
3582             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
3583             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
3584               return ReplaceInstUsesWith(I, LHS);
3585             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
3586             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
3587               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3588             }
3589             break;
3590           case Instruction::SetLT:
3591             switch (RHSCC) {
3592             default: assert(0 && "Unknown integer condition code!");
3593             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
3594               break;
3595             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
3596               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3597             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
3598             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
3599               return ReplaceInstUsesWith(I, RHS);
3600             }
3601             break;
3602           case Instruction::SetGT:
3603             switch (RHSCC) {
3604             default: assert(0 && "Unknown integer condition code!");
3605             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
3606             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
3607               return ReplaceInstUsesWith(I, LHS);
3608             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
3609             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
3610               return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3611             }
3612           }
3613         }
3614   }
3615     
3616   // fold (or (cast A), (cast B)) -> (cast (or A, B))
3617   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3618     const Type *SrcTy = Op0C->getOperand(0)->getType();
3619     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3620       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3621           // Only do this if the casts both really cause code to be generated.
3622           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3623           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3624         Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3625                                                       Op1C->getOperand(0),
3626                                                       I.getName());
3627         InsertNewInstBefore(NewOp, I);
3628         return new CastInst(NewOp, I.getType());
3629       }
3630   }
3631       
3632
3633   return Changed ? &I : 0;
3634 }
3635
3636 // XorSelf - Implements: X ^ X --> 0
3637 struct XorSelf {
3638   Value *RHS;
3639   XorSelf(Value *rhs) : RHS(rhs) {}
3640   bool shouldApply(Value *LHS) const { return LHS == RHS; }
3641   Instruction *apply(BinaryOperator &Xor) const {
3642     return &Xor;
3643   }
3644 };
3645
3646
3647 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3648   bool Changed = SimplifyCommutative(I);
3649   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3650
3651   if (isa<UndefValue>(Op1))
3652     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
3653
3654   // xor X, X = 0, even if X is nested in a sequence of Xor's.
3655   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3656     assert(Result == &I && "AssociativeOpt didn't work?");
3657     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3658   }
3659   
3660   // See if we can simplify any instructions used by the instruction whose sole 
3661   // purpose is to compute bits we don't care about.
3662   uint64_t KnownZero, KnownOne;
3663   if (!isa<PackedType>(I.getType()) &&
3664       SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3665                            KnownZero, KnownOne))
3666     return &I;
3667
3668   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3669     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3670       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3671       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3672         if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3673           return new SetCondInst(SCI->getInverseCondition(),
3674                                  SCI->getOperand(0), SCI->getOperand(1));
3675
3676       // ~(c-X) == X-c-1 == X+(-c-1)
3677       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3678         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3679           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3680           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3681                                               ConstantInt::get(I.getType(), 1));
3682           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3683         }
3684
3685       // ~(~X & Y) --> (X | ~Y)
3686       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3687         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3688         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3689           Instruction *NotY =
3690             BinaryOperator::createNot(Op0I->getOperand(1),
3691                                       Op0I->getOperand(1)->getName()+".not");
3692           InsertNewInstBefore(NotY, I);
3693           return BinaryOperator::createOr(Op0NotVal, NotY);
3694         }
3695       }
3696
3697       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3698         if (Op0I->getOpcode() == Instruction::Add) {
3699           // ~(X-c) --> (-c-1)-X
3700           if (RHS->isAllOnesValue()) {
3701             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3702             return BinaryOperator::createSub(
3703                            ConstantExpr::getSub(NegOp0CI,
3704                                              ConstantInt::get(I.getType(), 1)),
3705                                           Op0I->getOperand(0));
3706           }
3707         } else if (Op0I->getOpcode() == Instruction::Or) {
3708           // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3709           if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3710             Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3711             // Anything in both C1 and C2 is known to be zero, remove it from
3712             // NewRHS.
3713             Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3714             NewRHS = ConstantExpr::getAnd(NewRHS, 
3715                                           ConstantExpr::getNot(CommonBits));
3716             WorkList.push_back(Op0I);
3717             I.setOperand(0, Op0I->getOperand(0));
3718             I.setOperand(1, NewRHS);
3719             return &I;
3720           }
3721         }
3722     }
3723
3724     // Try to fold constant and into select arguments.
3725     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3726       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3727         return R;
3728     if (isa<PHINode>(Op0))
3729       if (Instruction *NV = FoldOpIntoPhi(I))
3730         return NV;
3731   }
3732
3733   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
3734     if (X == Op1)
3735       return ReplaceInstUsesWith(I,
3736                                 ConstantIntegral::getAllOnesValue(I.getType()));
3737
3738   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
3739     if (X == Op0)
3740       return ReplaceInstUsesWith(I,
3741                                 ConstantIntegral::getAllOnesValue(I.getType()));
3742
3743   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3744     if (Op1I->getOpcode() == Instruction::Or) {
3745       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
3746         Op1I->swapOperands();
3747         I.swapOperands();
3748         std::swap(Op0, Op1);
3749       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
3750         I.swapOperands();     // Simplified below.
3751         std::swap(Op0, Op1);
3752       }
3753     } else if (Op1I->getOpcode() == Instruction::Xor) {
3754       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
3755         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3756       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
3757         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3758     } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3759       if (Op1I->getOperand(0) == Op0)                      // A^(A&B) -> A^(B&A)
3760         Op1I->swapOperands();
3761       if (Op0 == Op1I->getOperand(1)) {                    // A^(B&A) -> (B&A)^A
3762         I.swapOperands();     // Simplified below.
3763         std::swap(Op0, Op1);
3764       }
3765     }
3766
3767   if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3768     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3769       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
3770         Op0I->swapOperands();
3771       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
3772         Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3773         InsertNewInstBefore(NotB, I);
3774         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3775       }
3776     } else if (Op0I->getOpcode() == Instruction::Xor) {
3777       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
3778         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3779       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
3780         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3781     } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3782       if (Op0I->getOperand(0) == Op1)                      // (A&B)^A -> (B&A)^A
3783         Op0I->swapOperands();
3784       if (Op0I->getOperand(1) == Op1 &&                    // (B&A)^A == ~B & A
3785           !isa<ConstantInt>(Op1)) {  // Canonical form is (B&C)^C
3786         Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3787         InsertNewInstBefore(N, I);
3788         return BinaryOperator::createAnd(N, Op1);
3789       }
3790     }
3791
3792   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3793   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3794     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3795       return R;
3796
3797   // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3798   if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3799     const Type *SrcTy = Op0C->getOperand(0)->getType();
3800     if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3801       if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3802           // Only do this if the casts both really cause code to be generated.
3803           ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3804           ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3805         Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3806                                                        Op1C->getOperand(0),
3807                                                        I.getName());
3808         InsertNewInstBefore(NewOp, I);
3809         return new CastInst(NewOp, I.getType());
3810       }
3811   }
3812     
3813   return Changed ? &I : 0;
3814 }
3815
3816 static bool isPositive(ConstantInt *C) {
3817   return C->getSExtValue() >= 0;
3818 }
3819
3820 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3821 /// overflowed for this type.
3822 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3823                             ConstantInt *In2) {
3824   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3825
3826   if (In1->getType()->isUnsigned())
3827     return cast<ConstantInt>(Result)->getZExtValue() <
3828            cast<ConstantInt>(In1)->getZExtValue();
3829   if (isPositive(In1) != isPositive(In2))
3830     return false;
3831   if (isPositive(In1))
3832     return cast<ConstantInt>(Result)->getSExtValue() <
3833            cast<ConstantInt>(In1)->getSExtValue();
3834   return cast<ConstantInt>(Result)->getSExtValue() >
3835          cast<ConstantInt>(In1)->getSExtValue();
3836 }
3837
3838 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3839 /// code necessary to compute the offset from the base pointer (without adding
3840 /// in the base pointer).  Return the result as a signed integer of intptr size.
3841 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3842   TargetData &TD = IC.getTargetData();
3843   gep_type_iterator GTI = gep_type_begin(GEP);
3844   const Type *UIntPtrTy = TD.getIntPtrType();
3845   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3846   Value *Result = Constant::getNullValue(SIntPtrTy);
3847
3848   // Build a mask for high order bits.
3849   uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3850
3851   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3852     Value *Op = GEP->getOperand(i);
3853     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3854     Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
3855                                             SIntPtrTy);
3856     if (Constant *OpC = dyn_cast<Constant>(Op)) {
3857       if (!OpC->isNullValue()) {
3858         OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3859         Scale = ConstantExpr::getMul(OpC, Scale);
3860         if (Constant *RC = dyn_cast<Constant>(Result))
3861           Result = ConstantExpr::getAdd(RC, Scale);
3862         else {
3863           // Emit an add instruction.
3864           Result = IC.InsertNewInstBefore(
3865              BinaryOperator::createAdd(Result, Scale,
3866                                        GEP->getName()+".offs"), I);
3867         }
3868       }
3869     } else {
3870       // Convert to correct type.
3871       Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3872                                                Op->getName()+".c"), I);
3873       if (Size != 1)
3874         // We'll let instcombine(mul) convert this to a shl if possible.
3875         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3876                                                     GEP->getName()+".idx"), I);
3877
3878       // Emit an add instruction.
3879       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3880                                                     GEP->getName()+".offs"), I);
3881     }
3882   }
3883   return Result;
3884 }
3885
3886 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3887 /// else.  At this point we know that the GEP is on the LHS of the comparison.
3888 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3889                                         Instruction::BinaryOps Cond,
3890                                         Instruction &I) {
3891   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3892
3893   if (CastInst *CI = dyn_cast<CastInst>(RHS))
3894     if (isa<PointerType>(CI->getOperand(0)->getType()))
3895       RHS = CI->getOperand(0);
3896
3897   Value *PtrBase = GEPLHS->getOperand(0);
3898   if (PtrBase == RHS) {
3899     // As an optimization, we don't actually have to compute the actual value of
3900     // OFFSET if this is a seteq or setne comparison, just return whether each
3901     // index is zero or not.
3902     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3903       Instruction *InVal = 0;
3904       gep_type_iterator GTI = gep_type_begin(GEPLHS);
3905       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3906         bool EmitIt = true;
3907         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3908           if (isa<UndefValue>(C))  // undef index -> undef.
3909             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3910           if (C->isNullValue())
3911             EmitIt = false;
3912           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3913             EmitIt = false;  // This is indexing into a zero sized array?
3914           } else if (isa<ConstantInt>(C))
3915             return ReplaceInstUsesWith(I, // No comparison is needed here.
3916                                  ConstantBool::get(Cond == Instruction::SetNE));
3917         }
3918
3919         if (EmitIt) {
3920           Instruction *Comp =
3921             new SetCondInst(Cond, GEPLHS->getOperand(i),
3922                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3923           if (InVal == 0)
3924             InVal = Comp;
3925           else {
3926             InVal = InsertNewInstBefore(InVal, I);
3927             InsertNewInstBefore(Comp, I);
3928             if (Cond == Instruction::SetNE)   // True if any are unequal
3929               InVal = BinaryOperator::createOr(InVal, Comp);
3930             else                              // True if all are equal
3931               InVal = BinaryOperator::createAnd(InVal, Comp);
3932           }
3933         }
3934       }
3935
3936       if (InVal)
3937         return InVal;
3938       else
3939         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3940                             ConstantBool::get(Cond == Instruction::SetEQ));
3941     }
3942
3943     // Only lower this if the setcc is the only user of the GEP or if we expect
3944     // the result to fold to a constant!
3945     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3946       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
3947       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3948       return new SetCondInst(Cond, Offset,
3949                              Constant::getNullValue(Offset->getType()));
3950     }
3951   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3952     // If the base pointers are different, but the indices are the same, just
3953     // compare the base pointer.
3954     if (PtrBase != GEPRHS->getOperand(0)) {
3955       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3956       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3957                         GEPRHS->getOperand(0)->getType();
3958       if (IndicesTheSame)
3959         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3960           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3961             IndicesTheSame = false;
3962             break;
3963           }
3964
3965       // If all indices are the same, just compare the base pointers.
3966       if (IndicesTheSame)
3967         return new SetCondInst(Cond, GEPLHS->getOperand(0),
3968                                GEPRHS->getOperand(0));
3969
3970       // Otherwise, the base pointers are different and the indices are
3971       // different, bail out.
3972       return 0;
3973     }
3974
3975     // If one of the GEPs has all zero indices, recurse.
3976     bool AllZeros = true;
3977     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3978       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3979           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3980         AllZeros = false;
3981         break;
3982       }
3983     if (AllZeros)
3984       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3985                           SetCondInst::getSwappedCondition(Cond), I);
3986
3987     // If the other GEP has all zero indices, recurse.
3988     AllZeros = true;
3989     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3990       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3991           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3992         AllZeros = false;
3993         break;
3994       }
3995     if (AllZeros)
3996       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3997
3998     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3999       // If the GEPs only differ by one index, compare it.
4000       unsigned NumDifferences = 0;  // Keep track of # differences.
4001       unsigned DiffOperand = 0;     // The operand that differs.
4002       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4003         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4004           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4005                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4006             // Irreconcilable differences.
4007             NumDifferences = 2;
4008             break;
4009           } else {
4010             if (NumDifferences++) break;
4011             DiffOperand = i;
4012           }
4013         }
4014
4015       if (NumDifferences == 0)   // SAME GEP?
4016         return ReplaceInstUsesWith(I, // No comparison is needed here.
4017                                  ConstantBool::get(Cond == Instruction::SetEQ));
4018       else if (NumDifferences == 1) {
4019         Value *LHSV = GEPLHS->getOperand(DiffOperand);
4020         Value *RHSV = GEPRHS->getOperand(DiffOperand);
4021
4022         // Convert the operands to signed values to make sure to perform a
4023         // signed comparison.
4024         const Type *NewTy = LHSV->getType()->getSignedVersion();
4025         if (LHSV->getType() != NewTy)
4026           LHSV = InsertCastBefore(LHSV, NewTy, I);
4027         if (RHSV->getType() != NewTy)
4028           RHSV = InsertCastBefore(RHSV, NewTy, I);
4029         return new SetCondInst(Cond, LHSV, RHSV);
4030       }
4031     }
4032
4033     // Only lower this if the setcc is the only user of the GEP or if we expect
4034     // the result to fold to a constant!
4035     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4036         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4037       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
4038       Value *L = EmitGEPOffset(GEPLHS, I, *this);
4039       Value *R = EmitGEPOffset(GEPRHS, I, *this);
4040       return new SetCondInst(Cond, L, R);
4041     }
4042   }
4043   return 0;
4044 }
4045
4046
4047 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
4048   bool Changed = SimplifyCommutative(I);
4049   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4050   const Type *Ty = Op0->getType();
4051
4052   // setcc X, X
4053   if (Op0 == Op1)
4054     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
4055
4056   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
4057     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
4058
4059   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4060   // addresses never equal each other!  We already know that Op0 != Op1.
4061   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4062        isa<ConstantPointerNull>(Op0)) &&
4063       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4064        isa<ConstantPointerNull>(Op1)))
4065     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
4066
4067   // setcc's with boolean values can always be turned into bitwise operations
4068   if (Ty == Type::BoolTy) {
4069     switch (I.getOpcode()) {
4070     default: assert(0 && "Invalid setcc instruction!");
4071     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
4072       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4073       InsertNewInstBefore(Xor, I);
4074       return BinaryOperator::createNot(Xor);
4075     }
4076     case Instruction::SetNE:
4077       return BinaryOperator::createXor(Op0, Op1);
4078
4079     case Instruction::SetGT:
4080       std::swap(Op0, Op1);                   // Change setgt -> setlt
4081       // FALL THROUGH
4082     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
4083       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4084       InsertNewInstBefore(Not, I);
4085       return BinaryOperator::createAnd(Not, Op1);
4086     }
4087     case Instruction::SetGE:
4088       std::swap(Op0, Op1);                   // Change setge -> setle
4089       // FALL THROUGH
4090     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
4091       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4092       InsertNewInstBefore(Not, I);
4093       return BinaryOperator::createOr(Not, Op1);
4094     }
4095     }
4096   }
4097
4098   // See if we are doing a comparison between a constant and an instruction that
4099   // can be folded into the comparison.
4100   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4101     // Check to see if we are comparing against the minimum or maximum value...
4102     if (CI->isMinValue()) {
4103       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
4104         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4105       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
4106         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4107       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
4108         return BinaryOperator::createSetEQ(Op0, Op1);
4109       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
4110         return BinaryOperator::createSetNE(Op0, Op1);
4111
4112     } else if (CI->isMaxValue()) {
4113       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
4114         return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4115       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
4116         return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4117       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
4118         return BinaryOperator::createSetEQ(Op0, Op1);
4119       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
4120         return BinaryOperator::createSetNE(Op0, Op1);
4121
4122       // Comparing against a value really close to min or max?
4123     } else if (isMinValuePlusOne(CI)) {
4124       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
4125         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4126       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
4127         return BinaryOperator::createSetNE(Op0, SubOne(CI));
4128
4129     } else if (isMaxValueMinusOne(CI)) {
4130       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
4131         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4132       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
4133         return BinaryOperator::createSetNE(Op0, AddOne(CI));
4134     }
4135
4136     // If we still have a setle or setge instruction, turn it into the
4137     // appropriate setlt or setgt instruction.  Since the border cases have
4138     // already been handled above, this requires little checking.
4139     //
4140     if (I.getOpcode() == Instruction::SetLE)
4141       return BinaryOperator::createSetLT(Op0, AddOne(CI));
4142     if (I.getOpcode() == Instruction::SetGE)
4143       return BinaryOperator::createSetGT(Op0, SubOne(CI));
4144
4145     
4146     // See if we can fold the comparison based on bits known to be zero or one
4147     // in the input.
4148     uint64_t KnownZero, KnownOne;
4149     if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4150                              KnownZero, KnownOne, 0))
4151       return &I;
4152         
4153     // Given the known and unknown bits, compute a range that the LHS could be
4154     // in.
4155     if (KnownOne | KnownZero) {
4156       if (Ty->isUnsigned()) {   // Unsigned comparison.
4157         uint64_t Min, Max;
4158         uint64_t RHSVal = CI->getZExtValue();
4159         ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4160                                                  Min, Max);
4161         switch (I.getOpcode()) {  // LE/GE have been folded already.
4162         default: assert(0 && "Unknown setcc opcode!");
4163         case Instruction::SetEQ:
4164           if (Max < RHSVal || Min > RHSVal)
4165             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4166           break;
4167         case Instruction::SetNE:
4168           if (Max < RHSVal || Min > RHSVal)
4169             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4170           break;
4171         case Instruction::SetLT:
4172           if (Max < RHSVal)
4173             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4174           if (Min > RHSVal)
4175             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4176           break;
4177         case Instruction::SetGT:
4178           if (Min > RHSVal)
4179             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4180           if (Max < RHSVal)
4181             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4182           break;
4183         }
4184       } else {              // Signed comparison.
4185         int64_t Min, Max;
4186         int64_t RHSVal = CI->getSExtValue();
4187         ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4188                                                Min, Max);
4189         switch (I.getOpcode()) {  // LE/GE have been folded already.
4190         default: assert(0 && "Unknown setcc opcode!");
4191         case Instruction::SetEQ:
4192           if (Max < RHSVal || Min > RHSVal)
4193             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4194           break;
4195         case Instruction::SetNE:
4196           if (Max < RHSVal || Min > RHSVal)
4197             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4198           break;
4199         case Instruction::SetLT:
4200           if (Max < RHSVal)
4201             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4202           if (Min > RHSVal)
4203             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4204           break;
4205         case Instruction::SetGT:
4206           if (Min > RHSVal)
4207             return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4208           if (Max < RHSVal)
4209             return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4210           break;
4211         }
4212       }
4213     }
4214           
4215     // Since the RHS is a constantInt (CI), if the left hand side is an 
4216     // instruction, see if that instruction also has constants so that the 
4217     // instruction can be folded into the setcc
4218     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4219       switch (LHSI->getOpcode()) {
4220       case Instruction::And:
4221         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4222             LHSI->getOperand(0)->hasOneUse()) {
4223           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4224
4225           // If an operand is an AND of a truncating cast, we can widen the
4226           // and/compare to be the input width without changing the value
4227           // produced, eliminating a cast.
4228           if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4229             // We can do this transformation if either the AND constant does not
4230             // have its sign bit set or if it is an equality comparison. 
4231             // Extending a relational comparison when we're checking the sign
4232             // bit would not work.
4233             if (Cast->hasOneUse() && Cast->isTruncIntCast() && 
4234                 (I.isEquality() ||
4235                  (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4236                  (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4237               ConstantInt *NewCST;
4238               ConstantInt *NewCI;
4239               if (Cast->getOperand(0)->getType()->isSigned()) {
4240                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4241                                            AndCST->getZExtValue());
4242                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4243                                           CI->getZExtValue());
4244               } else {
4245                 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4246                                            AndCST->getZExtValue());
4247                 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4248                                           CI->getZExtValue());
4249               }
4250               Instruction *NewAnd = 
4251                 BinaryOperator::createAnd(Cast->getOperand(0), NewCST, 
4252                                           LHSI->getName());
4253               InsertNewInstBefore(NewAnd, I);
4254               return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4255             }
4256           }
4257           
4258           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4259           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
4260           // happens a LOT in code produced by the C front-end, for bitfield
4261           // access.
4262           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4263
4264           // Check to see if there is a noop-cast between the shift and the and.
4265           if (!Shift) {
4266             if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4267               if (CI->getOperand(0)->getType()->isIntegral() &&
4268                   CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4269                      CI->getType()->getPrimitiveSizeInBits())
4270                 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4271           }
4272
4273           ConstantInt *ShAmt;
4274           ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4275           const Type *Ty = Shift ? Shift->getType() : 0;  // Type of the shift.
4276           const Type *AndTy = AndCST->getType();          // Type of the and.
4277
4278           // We can fold this as long as we can't shift unknown bits
4279           // into the mask.  This can only happen with signed shift
4280           // rights, as they sign-extend.
4281           if (ShAmt) {
4282             bool CanFold = Shift->isLogicalShift();
4283             if (!CanFold) {
4284               // To test for the bad case of the signed shr, see if any
4285               // of the bits shifted in could be tested after the mask.
4286               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4287               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4288
4289               Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
4290               Constant *ShVal =
4291                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy), 
4292                                      OShAmt);
4293               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4294                 CanFold = true;
4295             }
4296
4297             if (CanFold) {
4298               Constant *NewCst;
4299               if (Shift->getOpcode() == Instruction::Shl)
4300                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4301               else
4302                 NewCst = ConstantExpr::getShl(CI, ShAmt);
4303
4304               // Check to see if we are shifting out any of the bits being
4305               // compared.
4306               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4307                 // If we shifted bits out, the fold is not going to work out.
4308                 // As a special case, check to see if this means that the
4309                 // result is always true or false now.
4310                 if (I.getOpcode() == Instruction::SetEQ)
4311                   return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4312                 if (I.getOpcode() == Instruction::SetNE)
4313                   return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4314               } else {
4315                 I.setOperand(1, NewCst);
4316                 Constant *NewAndCST;
4317                 if (Shift->getOpcode() == Instruction::Shl)
4318                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4319                 else
4320                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4321                 LHSI->setOperand(1, NewAndCST);
4322                 if (AndTy == Ty) 
4323                   LHSI->setOperand(0, Shift->getOperand(0));
4324                 else {
4325                   Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4326                                                     *Shift);
4327                   LHSI->setOperand(0, NewCast);
4328                 }
4329                 WorkList.push_back(Shift); // Shift is dead.
4330                 AddUsesToWorkList(I);
4331                 return &I;
4332               }
4333             }
4334           }
4335           
4336           // Turn ((X >> Y) & C) == 0  into  (X & (C << Y)) == 0.  The later is
4337           // preferable because it allows the C<<Y expression to be hoisted out
4338           // of a loop if Y is invariant and X is not.
4339           if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4340               I.isEquality() && !Shift->isArithmeticShift() &&
4341               isa<Instruction>(Shift->getOperand(0))) {
4342             // Compute C << Y.
4343             Value *NS;
4344             if (Shift->getOpcode() == Instruction::Shr) {
4345               NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4346                                  "tmp");
4347             } else {
4348               // Make sure we insert a logical shift.
4349               Constant *NewAndCST = AndCST;
4350               if (AndCST->getType()->isSigned())
4351                 NewAndCST = ConstantExpr::getCast(AndCST,
4352                                       AndCST->getType()->getUnsignedVersion());
4353               NS = new ShiftInst(Instruction::Shr, NewAndCST,
4354                                  Shift->getOperand(1), "tmp");
4355             }
4356             InsertNewInstBefore(cast<Instruction>(NS), I);
4357
4358             // If C's sign doesn't agree with the and, insert a cast now.
4359             if (NS->getType() != LHSI->getType())
4360               NS = InsertCastBefore(NS, LHSI->getType(), I);
4361
4362             Value *ShiftOp = Shift->getOperand(0);
4363             if (ShiftOp->getType() != LHSI->getType())
4364               ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4365               
4366             // Compute X & (C << Y).
4367             Instruction *NewAnd =
4368               BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4369             InsertNewInstBefore(NewAnd, I);
4370             
4371             I.setOperand(0, NewAnd);
4372             return &I;
4373           }
4374         }
4375         break;
4376
4377       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
4378         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4379           if (I.isEquality()) {
4380             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4381
4382             // Check that the shift amount is in range.  If not, don't perform
4383             // undefined shifts.  When the shift is visited it will be
4384             // simplified.
4385             if (ShAmt->getZExtValue() >= TypeBits)
4386               break;
4387
4388             // If we are comparing against bits always shifted out, the
4389             // comparison cannot succeed.
4390             Constant *Comp =
4391               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4392             if (Comp != CI) {// Comparing against a bit that we know is zero.
4393               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4394               Constant *Cst = ConstantBool::get(IsSetNE);
4395               return ReplaceInstUsesWith(I, Cst);
4396             }
4397
4398             if (LHSI->hasOneUse()) {
4399               // Otherwise strength reduce the shift into an and.
4400               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4401               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4402
4403               Constant *Mask;
4404               if (CI->getType()->isUnsigned()) {
4405                 Mask = ConstantInt::get(CI->getType(), Val);
4406               } else if (ShAmtVal != 0) {
4407                 Mask = ConstantInt::get(CI->getType(), Val);
4408               } else {
4409                 Mask = ConstantInt::getAllOnesValue(CI->getType());
4410               }
4411
4412               Instruction *AndI =
4413                 BinaryOperator::createAnd(LHSI->getOperand(0),
4414                                           Mask, LHSI->getName()+".mask");
4415               Value *And = InsertNewInstBefore(AndI, I);
4416               return new SetCondInst(I.getOpcode(), And,
4417                                      ConstantExpr::getUShr(CI, ShAmt));
4418             }
4419           }
4420         }
4421         break;
4422
4423       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
4424         if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4425           if (I.isEquality()) {
4426             // Check that the shift amount is in range.  If not, don't perform
4427             // undefined shifts.  When the shift is visited it will be
4428             // simplified.
4429             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4430             if (ShAmt->getZExtValue() >= TypeBits)
4431               break;
4432
4433             // If we are comparing against bits always shifted out, the
4434             // comparison cannot succeed.
4435             Constant *Comp =
4436               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
4437
4438             if (Comp != CI) {// Comparing against a bit that we know is zero.
4439               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4440               Constant *Cst = ConstantBool::get(IsSetNE);
4441               return ReplaceInstUsesWith(I, Cst);
4442             }
4443
4444             if (LHSI->hasOneUse() || CI->isNullValue()) {
4445               unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4446
4447               // Otherwise strength reduce the shift into an and.
4448               uint64_t Val = ~0ULL;          // All ones.
4449               Val <<= ShAmtVal;              // Shift over to the right spot.
4450
4451               Constant *Mask;
4452               if (CI->getType()->isUnsigned()) {
4453                 Val &= ~0ULL >> (64-TypeBits);
4454                 Mask = ConstantInt::get(CI->getType(), Val);
4455               } else {
4456                 Mask = ConstantInt::get(CI->getType(), Val);
4457               }
4458
4459               Instruction *AndI =
4460                 BinaryOperator::createAnd(LHSI->getOperand(0),
4461                                           Mask, LHSI->getName()+".mask");
4462               Value *And = InsertNewInstBefore(AndI, I);
4463               return new SetCondInst(I.getOpcode(), And,
4464                                      ConstantExpr::getShl(CI, ShAmt));
4465             }
4466           }
4467         }
4468         break;
4469
4470       case Instruction::SDiv:
4471       case Instruction::UDiv:
4472         // Fold: setcc ([us]div X, C1), C2 -> range test
4473         // Fold this div into the comparison, producing a range check. 
4474         // Determine, based on the divide type, what the range is being 
4475         // checked.  If there is an overflow on the low or high side, remember 
4476         // it, otherwise compute the range [low, hi) bounding the new value.
4477         // See: InsertRangeTest above for the kinds of replacements possible.
4478         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4479           // FIXME: If the operand types don't match the type of the divide 
4480           // then don't attempt this transform. The code below doesn't have the
4481           // logic to deal with a signed divide and an unsigned compare (and
4482           // vice versa). This is because (x /s C1) <s C2  produces different 
4483           // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4484           // (x /u C1) <u C2.  Simply casting the operands and result won't 
4485           // work. :(  The if statement below tests that condition and bails 
4486           // if it finds it. 
4487           const Type* DivRHSTy = DivRHS->getType();
4488           unsigned DivOpCode = LHSI->getOpcode();
4489           if (I.isEquality() &&
4490               ((DivOpCode == Instruction::SDiv && DivRHSTy->isUnsigned()) ||
4491                (DivOpCode == Instruction::UDiv && DivRHSTy->isSigned())))
4492             break;
4493
4494           // Initialize the variables that will indicate the nature of the
4495           // range check.
4496           bool LoOverflow = false, HiOverflow = false;
4497           ConstantInt *LoBound = 0, *HiBound = 0;
4498
4499           // Compute Prod = CI * DivRHS. We are essentially solving an equation
4500           // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and 
4501           // C2 (CI). By solving for X we can turn this into a range check 
4502           // instead of computing a divide. 
4503           ConstantInt *Prod = 
4504             cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4505
4506           // Determine if the product overflows by seeing if the product is
4507           // not equal to the divide. Make sure we do the same kind of divide
4508           // as in the LHS instruction that we're folding. 
4509           bool ProdOV = !DivRHS->isNullValue() && 
4510             (DivOpCode == Instruction::SDiv ?  
4511              ConstantExpr::getSDiv(Prod, DivRHS) :
4512               ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4513
4514           // Get the SetCC opcode
4515           Instruction::BinaryOps Opcode = I.getOpcode();
4516
4517           if (DivRHS->isNullValue()) {  
4518             // Don't hack on divide by zeros!
4519           } else if (DivOpCode == Instruction::UDiv) {  // udiv
4520             LoBound = Prod;
4521             LoOverflow = ProdOV;
4522             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4523           } else if (isPositive(DivRHS)) { // Divisor is > 0.
4524             if (CI->isNullValue()) {       // (X / pos) op 0
4525               // Can't overflow.
4526               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4527               HiBound = DivRHS;
4528             } else if (isPositive(CI)) {   // (X / pos) op pos
4529               LoBound = Prod;
4530               LoOverflow = ProdOV;
4531               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4532             } else {                       // (X / pos) op neg
4533               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4534               LoOverflow = AddWithOverflow(LoBound, Prod,
4535                                            cast<ConstantInt>(DivRHSH));
4536               HiBound = Prod;
4537               HiOverflow = ProdOV;
4538             }
4539           } else {                         // Divisor is < 0.
4540             if (CI->isNullValue()) {       // (X / neg) op 0
4541               LoBound = AddOne(DivRHS);
4542               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4543               if (HiBound == DivRHS)
4544                 LoBound = 0;               // - INTMIN = INTMIN
4545             } else if (isPositive(CI)) {   // (X / neg) op pos
4546               HiOverflow = LoOverflow = ProdOV;
4547               if (!LoOverflow)
4548                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4549               HiBound = AddOne(Prod);
4550             } else {                       // (X / neg) op neg
4551               LoBound = Prod;
4552               LoOverflow = HiOverflow = ProdOV;
4553               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4554             }
4555
4556             // Dividing by a negate swaps the condition.
4557             Opcode = SetCondInst::getSwappedCondition(Opcode);
4558           }
4559
4560           if (LoBound) {
4561             Value *X = LHSI->getOperand(0);
4562             switch (Opcode) {
4563             default: assert(0 && "Unhandled setcc opcode!");
4564             case Instruction::SetEQ:
4565               if (LoOverflow && HiOverflow)
4566                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4567               else if (HiOverflow)
4568                 return new SetCondInst(Instruction::SetGE, X, LoBound);
4569               else if (LoOverflow)
4570                 return new SetCondInst(Instruction::SetLT, X, HiBound);
4571               else
4572                 return InsertRangeTest(X, LoBound, HiBound, true, I);
4573             case Instruction::SetNE:
4574               if (LoOverflow && HiOverflow)
4575                 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4576               else if (HiOverflow)
4577                 return new SetCondInst(Instruction::SetLT, X, LoBound);
4578               else if (LoOverflow)
4579                 return new SetCondInst(Instruction::SetGE, X, HiBound);
4580               else
4581                 return InsertRangeTest(X, LoBound, HiBound, false, I);
4582             case Instruction::SetLT:
4583               if (LoOverflow)
4584                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4585               return new SetCondInst(Instruction::SetLT, X, LoBound);
4586             case Instruction::SetGT:
4587               if (HiOverflow)
4588                 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4589               return new SetCondInst(Instruction::SetGE, X, HiBound);
4590             }
4591           }
4592         }
4593         break;
4594       }
4595
4596     // Simplify seteq and setne instructions...
4597     if (I.isEquality()) {
4598       bool isSetNE = I.getOpcode() == Instruction::SetNE;
4599
4600       // If the first operand is (add|sub|and|or|xor|rem) with a constant, and 
4601       // the second operand is a constant, simplify a bit.
4602       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4603         switch (BO->getOpcode()) {
4604         case Instruction::SRem:
4605           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4606           if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4607               BO->hasOneUse()) {
4608             int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4609             if (V > 1 && isPowerOf2_64(V)) {
4610               Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4611                   BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4612               return BinaryOperator::create(I.getOpcode(), NewRem,
4613                 Constant::getNullValue(BO->getType()));
4614             }
4615           }
4616           break;
4617         case Instruction::Add:
4618           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4619           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4620             if (BO->hasOneUse())
4621               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4622                                      ConstantExpr::getSub(CI, BOp1C));
4623           } else if (CI->isNullValue()) {
4624             // Replace ((add A, B) != 0) with (A != -B) if A or B is
4625             // efficiently invertible, or if the add has just this one use.
4626             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4627
4628             if (Value *NegVal = dyn_castNegVal(BOp1))
4629               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4630             else if (Value *NegVal = dyn_castNegVal(BOp0))
4631               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4632             else if (BO->hasOneUse()) {
4633               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4634               BO->setName("");
4635               InsertNewInstBefore(Neg, I);
4636               return new SetCondInst(I.getOpcode(), BOp0, Neg);
4637             }
4638           }
4639           break;
4640         case Instruction::Xor:
4641           // For the xor case, we can xor two constants together, eliminating
4642           // the explicit xor.
4643           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4644             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4645                                   ConstantExpr::getXor(CI, BOC));
4646
4647           // FALLTHROUGH
4648         case Instruction::Sub:
4649           // Replace (([sub|xor] A, B) != 0) with (A != B)
4650           if (CI->isNullValue())
4651             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4652                                    BO->getOperand(1));
4653           break;
4654
4655         case Instruction::Or:
4656           // If bits are being or'd in that are not present in the constant we
4657           // are comparing against, then the comparison could never succeed!
4658           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4659             Constant *NotCI = ConstantExpr::getNot(CI);
4660             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4661               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4662           }
4663           break;
4664
4665         case Instruction::And:
4666           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4667             // If bits are being compared against that are and'd out, then the
4668             // comparison can never succeed!
4669             if (!ConstantExpr::getAnd(CI,
4670                                       ConstantExpr::getNot(BOC))->isNullValue())
4671               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4672
4673             // If we have ((X & C) == C), turn it into ((X & C) != 0).
4674             if (CI == BOC && isOneBitSet(CI))
4675               return new SetCondInst(isSetNE ? Instruction::SetEQ :
4676                                      Instruction::SetNE, Op0,
4677                                      Constant::getNullValue(CI->getType()));
4678
4679             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4680             // to be a signed value as appropriate.
4681             if (isSignBit(BOC)) {
4682               Value *X = BO->getOperand(0);
4683               // If 'X' is not signed, insert a cast now...
4684               if (!BOC->getType()->isSigned()) {
4685                 const Type *DestTy = BOC->getType()->getSignedVersion();
4686                 X = InsertCastBefore(X, DestTy, I);
4687               }
4688               return new SetCondInst(isSetNE ? Instruction::SetLT :
4689                                          Instruction::SetGE, X,
4690                                      Constant::getNullValue(X->getType()));
4691             }
4692
4693             // ((X & ~7) == 0) --> X < 8
4694             if (CI->isNullValue() && isHighOnes(BOC)) {
4695               Value *X = BO->getOperand(0);
4696               Constant *NegX = ConstantExpr::getNeg(BOC);
4697
4698               // If 'X' is signed, insert a cast now.
4699               if (NegX->getType()->isSigned()) {
4700                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4701                 X = InsertCastBefore(X, DestTy, I);
4702                 NegX = ConstantExpr::getCast(NegX, DestTy);
4703               }
4704
4705               return new SetCondInst(isSetNE ? Instruction::SetGE :
4706                                      Instruction::SetLT, X, NegX);
4707             }
4708
4709           }
4710         default: break;
4711         }
4712       }
4713     } else {  // Not a SetEQ/SetNE
4714       // If the LHS is a cast from an integral value of the same size,
4715       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4716         Value *CastOp = Cast->getOperand(0);
4717         const Type *SrcTy = CastOp->getType();
4718         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4719         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4720             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4721           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4722                  "Source and destination signednesses should differ!");
4723           if (Cast->getType()->isSigned()) {
4724             // If this is a signed comparison, check for comparisons in the
4725             // vicinity of zero.
4726             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4727               // X < 0  => x > 127
4728               return BinaryOperator::createSetGT(CastOp,
4729                          ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4730             else if (I.getOpcode() == Instruction::SetGT &&
4731                      cast<ConstantInt>(CI)->getSExtValue() == -1)
4732               // X > -1  => x < 128
4733               return BinaryOperator::createSetLT(CastOp,
4734                          ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4735           } else {
4736             ConstantInt *CUI = cast<ConstantInt>(CI);
4737             if (I.getOpcode() == Instruction::SetLT &&
4738                 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
4739               // X < 128 => X > -1
4740               return BinaryOperator::createSetGT(CastOp,
4741                                                  ConstantInt::get(SrcTy, -1));
4742             else if (I.getOpcode() == Instruction::SetGT &&
4743                      CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
4744               // X > 127 => X < 0
4745               return BinaryOperator::createSetLT(CastOp,
4746                                                  Constant::getNullValue(SrcTy));
4747           }
4748         }
4749       }
4750     }
4751   }
4752
4753   // Handle setcc with constant RHS's that can be integer, FP or pointer.
4754   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4755     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4756       switch (LHSI->getOpcode()) {
4757       case Instruction::GetElementPtr:
4758         if (RHSC->isNullValue()) {
4759           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4760           bool isAllZeros = true;
4761           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4762             if (!isa<Constant>(LHSI->getOperand(i)) ||
4763                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4764               isAllZeros = false;
4765               break;
4766             }
4767           if (isAllZeros)
4768             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4769                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
4770         }
4771         break;
4772
4773       case Instruction::PHI:
4774         if (Instruction *NV = FoldOpIntoPhi(I))
4775           return NV;
4776         break;
4777       case Instruction::Select:
4778         // If either operand of the select is a constant, we can fold the
4779         // comparison into the select arms, which will cause one to be
4780         // constant folded and the select turned into a bitwise or.
4781         Value *Op1 = 0, *Op2 = 0;
4782         if (LHSI->hasOneUse()) {
4783           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4784             // Fold the known value into the constant operand.
4785             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4786             // Insert a new SetCC of the other select operand.
4787             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4788                                                       LHSI->getOperand(2), RHSC,
4789                                                       I.getName()), I);
4790           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4791             // Fold the known value into the constant operand.
4792             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4793             // Insert a new SetCC of the other select operand.
4794             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4795                                                       LHSI->getOperand(1), RHSC,
4796                                                       I.getName()), I);
4797           }
4798         }
4799
4800         if (Op1)
4801           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4802         break;
4803       }
4804   }
4805
4806   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4807   if (User *GEP = dyn_castGetElementPtr(Op0))
4808     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4809       return NI;
4810   if (User *GEP = dyn_castGetElementPtr(Op1))
4811     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4812                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
4813       return NI;
4814
4815   // Test to see if the operands of the setcc are casted versions of other
4816   // values.  If the cast can be stripped off both arguments, we do so now.
4817   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4818     Value *CastOp0 = CI->getOperand(0);
4819     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4820         (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4821       // We keep moving the cast from the left operand over to the right
4822       // operand, where it can often be eliminated completely.
4823       Op0 = CastOp0;
4824
4825       // If operand #1 is a cast instruction, see if we can eliminate it as
4826       // well.
4827       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4828         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4829                                                                Op0->getType()))
4830           Op1 = CI2->getOperand(0);
4831
4832       // If Op1 is a constant, we can fold the cast into the constant.
4833       if (Op1->getType() != Op0->getType())
4834         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4835           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4836         } else {
4837           // Otherwise, cast the RHS right before the setcc
4838           Op1 = InsertCastBefore(Op1, Op0->getType(), I);
4839         }
4840       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4841     }
4842
4843     // Handle the special case of: setcc (cast bool to X), <cst>
4844     // This comes up when you have code like
4845     //   int X = A < B;
4846     //   if (X) ...
4847     // For generality, we handle any zero-extension of any operand comparison
4848     // with a constant or another cast from the same type.
4849     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4850       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4851         return R;
4852   }
4853   
4854   if (I.isEquality()) {
4855     Value *A, *B;
4856     if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4857         (A == Op1 || B == Op1)) {
4858       // (A^B) == A  ->  B == 0
4859       Value *OtherVal = A == Op1 ? B : A;
4860       return BinaryOperator::create(I.getOpcode(), OtherVal,
4861                                     Constant::getNullValue(A->getType()));
4862     } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4863                (A == Op0 || B == Op0)) {
4864       // A == (A^B)  ->  B == 0
4865       Value *OtherVal = A == Op0 ? B : A;
4866       return BinaryOperator::create(I.getOpcode(), OtherVal,
4867                                     Constant::getNullValue(A->getType()));
4868     } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4869       // (A-B) == A  ->  B == 0
4870       return BinaryOperator::create(I.getOpcode(), B,
4871                                     Constant::getNullValue(B->getType()));
4872     } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4873       // A == (A-B)  ->  B == 0
4874       return BinaryOperator::create(I.getOpcode(), B,
4875                                     Constant::getNullValue(B->getType()));
4876     }
4877   }
4878   return Changed ? &I : 0;
4879 }
4880
4881 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4882 // We only handle extending casts so far.
4883 //
4884 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4885   Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4886   const Type *SrcTy = LHSCIOp->getType();
4887   const Type *DestTy = SCI.getOperand(0)->getType();
4888   Value *RHSCIOp;
4889
4890   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4891     return 0;
4892
4893   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
4894   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4895   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
4896
4897   // Is this a sign or zero extension?
4898   bool isSignSrc  = SrcTy->isSigned();
4899   bool isSignDest = DestTy->isSigned();
4900
4901   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4902     // Not an extension from the same type?
4903     RHSCIOp = CI->getOperand(0);
4904     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4905   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4906     // Compute the constant that would happen if we truncated to SrcTy then
4907     // reextended to DestTy.
4908     Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4909
4910     if (ConstantExpr::getCast(Res, DestTy) == CI) {
4911       // Make sure that src sign and dest sign match. For example,
4912       //
4913       // %A = cast short %X to uint
4914       // %B = setgt uint %A, 1330
4915       //
4916       // It is incorrect to transform this into 
4917       //
4918       // %B = setgt short %X, 1330 
4919       // 
4920       // because %A may have negative value. 
4921       // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4922       // OR operation is EQ/NE.
4923       if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
4924         RHSCIOp = Res;
4925       else
4926         return 0;
4927     } else {
4928       // If the value cannot be represented in the shorter type, we cannot emit
4929       // a simple comparison.
4930       if (SCI.getOpcode() == Instruction::SetEQ)
4931         return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
4932       if (SCI.getOpcode() == Instruction::SetNE)
4933         return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
4934
4935       // Evaluate the comparison for LT.
4936       Value *Result;
4937       if (DestTy->isSigned()) {
4938         // We're performing a signed comparison.
4939         if (isSignSrc) {
4940           // Signed extend and signed comparison.
4941           if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
4942             Result = ConstantBool::getFalse();
4943           else
4944             Result = ConstantBool::getTrue();           // X < (large) --> true
4945         } else {
4946           // Unsigned extend and signed comparison.
4947           if (cast<ConstantInt>(CI)->getSExtValue() < 0)
4948             Result = ConstantBool::getFalse();
4949           else
4950             Result = ConstantBool::getTrue();
4951         }
4952       } else {
4953         // We're performing an unsigned comparison.
4954         if (!isSignSrc) {
4955           // Unsigned extend & compare -> always true.
4956           Result = ConstantBool::getTrue();
4957         } else {
4958           // We're performing an unsigned comp with a sign extended value.
4959           // This is true if the input is >= 0. [aka >s -1]
4960           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4961           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4962                                                   NegOne, SCI.getName()), SCI);
4963         }
4964       }
4965
4966       // Finally, return the value computed.
4967       if (SCI.getOpcode() == Instruction::SetLT) {
4968         return ReplaceInstUsesWith(SCI, Result);
4969       } else {
4970         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4971         if (Constant *CI = dyn_cast<Constant>(Result))
4972           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4973         else
4974           return BinaryOperator::createNot(Result);
4975       }
4976     }
4977   } else {
4978     return 0;
4979   }
4980
4981   // Okay, just insert a compare of the reduced operands now!
4982   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4983 }
4984
4985 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4986   assert(I.getOperand(1)->getType() == Type::UByteTy);
4987   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4988   bool isLeftShift = I.getOpcode() == Instruction::Shl;
4989
4990   // shl X, 0 == X and shr X, 0 == X
4991   // shl 0, X == 0 and shr 0, X == 0
4992   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4993       Op0 == Constant::getNullValue(Op0->getType()))
4994     return ReplaceInstUsesWith(I, Op0);
4995   
4996   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
4997     if (!isLeftShift && I.getType()->isSigned())
4998       return ReplaceInstUsesWith(I, Op0);
4999     else                         // undef << X -> 0   AND  undef >>u X -> 0
5000       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5001   }
5002   if (isa<UndefValue>(Op1)) {
5003     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
5004       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5005     else
5006       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
5007   }
5008
5009   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
5010   if (!isLeftShift)
5011     if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5012       if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
5013         return ReplaceInstUsesWith(I, CSI);
5014
5015   // Try to fold constant and into select arguments.
5016   if (isa<Constant>(Op0))
5017     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5018       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5019         return R;
5020
5021   // See if we can turn a signed shr into an unsigned shr.
5022   if (I.isArithmeticShift()) {
5023     if (MaskedValueIsZero(Op0,
5024                           1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5025       Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
5026       V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
5027                                             I.getName()), I);
5028       return new CastInst(V, I.getType());
5029     }
5030   }
5031
5032   if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5033     if (CUI->getType()->isUnsigned())
5034       if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5035         return Res;
5036   return 0;
5037 }
5038
5039 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5040                                                ShiftInst &I) {
5041   bool isLeftShift = I.getOpcode() == Instruction::Shl;
5042   bool isSignedShift = Op0->getType()->isSigned();
5043   bool isUnsignedShift = !isSignedShift;
5044
5045   // See if we can simplify any instructions used by the instruction whose sole 
5046   // purpose is to compute bits we don't care about.
5047   uint64_t KnownZero, KnownOne;
5048   if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
5049                            KnownZero, KnownOne))
5050     return &I;
5051   
5052   // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5053   // of a signed value.
5054   //
5055   unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5056   if (Op1->getZExtValue() >= TypeBits) {
5057     if (isUnsignedShift || isLeftShift)
5058       return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5059     else {
5060       I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
5061       return &I;
5062     }
5063   }
5064   
5065   // ((X*C1) << C2) == (X * (C1 << C2))
5066   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5067     if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5068       if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5069         return BinaryOperator::createMul(BO->getOperand(0),
5070                                          ConstantExpr::getShl(BOOp, Op1));
5071   
5072   // Try to fold constant and into select arguments.
5073   if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5074     if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5075       return R;
5076   if (isa<PHINode>(Op0))
5077     if (Instruction *NV = FoldOpIntoPhi(I))
5078       return NV;
5079   
5080   if (Op0->hasOneUse()) {
5081     if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5082       // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5083       Value *V1, *V2;
5084       ConstantInt *CC;
5085       switch (Op0BO->getOpcode()) {
5086         default: break;
5087         case Instruction::Add:
5088         case Instruction::And:
5089         case Instruction::Or:
5090         case Instruction::Xor:
5091           // These operators commute.
5092           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
5093           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5094               match(Op0BO->getOperand(1),
5095                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5096             Instruction *YS = new ShiftInst(Instruction::Shl, 
5097                                             Op0BO->getOperand(0), Op1,
5098                                             Op0BO->getName());
5099             InsertNewInstBefore(YS, I); // (Y << C)
5100             Instruction *X = 
5101               BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5102                                      Op0BO->getOperand(1)->getName());
5103             InsertNewInstBefore(X, I);  // (X + (Y << C))
5104             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5105             C2 = ConstantExpr::getShl(C2, Op1);
5106             return BinaryOperator::createAnd(X, C2);
5107           }
5108           
5109           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
5110           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5111               match(Op0BO->getOperand(1),
5112                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5113                           m_ConstantInt(CC))) && V2 == Op1 &&
5114       cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5115             Instruction *YS = new ShiftInst(Instruction::Shl, 
5116                                             Op0BO->getOperand(0), Op1,
5117                                             Op0BO->getName());
5118             InsertNewInstBefore(YS, I); // (Y << C)
5119             Instruction *XM =
5120               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5121                                         V1->getName()+".mask");
5122             InsertNewInstBefore(XM, I); // X & (CC << C)
5123             
5124             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5125           }
5126           
5127           // FALL THROUGH.
5128         case Instruction::Sub:
5129           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
5130           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5131               match(Op0BO->getOperand(0),
5132                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5133             Instruction *YS = new ShiftInst(Instruction::Shl, 
5134                                             Op0BO->getOperand(1), Op1,
5135                                             Op0BO->getName());
5136             InsertNewInstBefore(YS, I); // (Y << C)
5137             Instruction *X =
5138               BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5139                                      Op0BO->getOperand(0)->getName());
5140             InsertNewInstBefore(X, I);  // (X + (Y << C))
5141             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5142             C2 = ConstantExpr::getShl(C2, Op1);
5143             return BinaryOperator::createAnd(X, C2);
5144           }
5145           
5146           // Turn (((X >> C)&CC) + Y) << C  ->  (X + (Y << C)) & (CC << C)
5147           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5148               match(Op0BO->getOperand(0),
5149                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
5150                           m_ConstantInt(CC))) && V2 == Op1 &&
5151               cast<BinaryOperator>(Op0BO->getOperand(0))
5152                   ->getOperand(0)->hasOneUse()) {
5153             Instruction *YS = new ShiftInst(Instruction::Shl, 
5154                                             Op0BO->getOperand(1), Op1,
5155                                             Op0BO->getName());
5156             InsertNewInstBefore(YS, I); // (Y << C)
5157             Instruction *XM =
5158               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5159                                         V1->getName()+".mask");
5160             InsertNewInstBefore(XM, I); // X & (CC << C)
5161             
5162             return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5163           }
5164           
5165           break;
5166       }
5167       
5168       
5169       // If the operand is an bitwise operator with a constant RHS, and the
5170       // shift is the only use, we can pull it out of the shift.
5171       if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5172         bool isValid = true;     // Valid only for And, Or, Xor
5173         bool highBitSet = false; // Transform if high bit of constant set?
5174         
5175         switch (Op0BO->getOpcode()) {
5176           default: isValid = false; break;   // Do not perform transform!
5177           case Instruction::Add:
5178             isValid = isLeftShift;
5179             break;
5180           case Instruction::Or:
5181           case Instruction::Xor:
5182             highBitSet = false;
5183             break;
5184           case Instruction::And:
5185             highBitSet = true;
5186             break;
5187         }
5188         
5189         // If this is a signed shift right, and the high bit is modified
5190         // by the logical operation, do not perform the transformation.
5191         // The highBitSet boolean indicates the value of the high bit of
5192         // the constant which would cause it to be modified for this
5193         // operation.
5194         //
5195         if (isValid && !isLeftShift && isSignedShift) {
5196           uint64_t Val = Op0C->getZExtValue();
5197           isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5198         }
5199         
5200         if (isValid) {
5201           Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5202           
5203           Instruction *NewShift =
5204             new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5205                           Op0BO->getName());
5206           Op0BO->setName("");
5207           InsertNewInstBefore(NewShift, I);
5208           
5209           return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5210                                         NewRHS);
5211         }
5212       }
5213     }
5214   }
5215   
5216   // Find out if this is a shift of a shift by a constant.
5217   ShiftInst *ShiftOp = 0;
5218   if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5219     ShiftOp = Op0SI;
5220   else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5221     // If this is a noop-integer case of a shift instruction, use the shift.
5222     if (CI->getOperand(0)->getType()->isInteger() &&
5223         CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5224         CI->getType()->getPrimitiveSizeInBits() &&
5225         isa<ShiftInst>(CI->getOperand(0))) {
5226       ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5227     }
5228   }
5229   
5230   if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5231     // Find the operands and properties of the input shift.  Note that the
5232     // signedness of the input shift may differ from the current shift if there
5233     // is a noop cast between the two.
5234     bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5235     bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
5236     bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5237     
5238     ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5239
5240     unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5241     unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5242     
5243     // Check for (A << c1) << c2   and   (A >> c1) >> c2.
5244     if (isLeftShift == isShiftOfLeftShift) {
5245       // Do not fold these shifts if the first one is signed and the second one
5246       // is unsigned and this is a right shift.  Further, don't do any folding
5247       // on them.
5248       if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5249         return 0;
5250       
5251       unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift.
5252       if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5253         Amt = Op0->getType()->getPrimitiveSizeInBits();
5254       
5255       Value *Op = ShiftOp->getOperand(0);
5256       if (isShiftOfSignedShift != isSignedShift)
5257         Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5258       return new ShiftInst(I.getOpcode(), Op,
5259                            ConstantInt::get(Type::UByteTy, Amt));
5260     }
5261     
5262     // Check for (A << c1) >> c2 or (A >> c1) << c2.  If we are dealing with
5263     // signed types, we can only support the (A >> c1) << c2 configuration,
5264     // because it can not turn an arbitrary bit of A into a sign bit.
5265     if (isUnsignedShift || isLeftShift) {
5266       // Calculate bitmask for what gets shifted off the edge.
5267       Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5268       if (isLeftShift)
5269         C = ConstantExpr::getShl(C, ShiftAmt1C);
5270       else
5271         C = ConstantExpr::getUShr(C, ShiftAmt1C);
5272       
5273       Value *Op = ShiftOp->getOperand(0);
5274       if (isShiftOfSignedShift != isSignedShift)
5275         Op = InsertCastBefore(Op, I.getType(), I);
5276       
5277       Instruction *Mask =
5278         BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5279       InsertNewInstBefore(Mask, I);
5280       
5281       // Figure out what flavor of shift we should use...
5282       if (ShiftAmt1 == ShiftAmt2) {
5283         return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
5284       } else if (ShiftAmt1 < ShiftAmt2) {
5285         return new ShiftInst(I.getOpcode(), Mask,
5286                          ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5287       } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5288         if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5289           // Make sure to emit an unsigned shift right, not a signed one.
5290           Mask = InsertNewInstBefore(new CastInst(Mask, 
5291                                         Mask->getType()->getUnsignedVersion(),
5292                                                   Op->getName()), I);
5293           Mask = new ShiftInst(Instruction::Shr, Mask,
5294                          ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5295           InsertNewInstBefore(Mask, I);
5296           return new CastInst(Mask, I.getType());
5297         } else {
5298           return new ShiftInst(ShiftOp->getOpcode(), Mask,
5299                     ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5300         }
5301       } else {
5302         // (X >>s C1) << C2  where C1 > C2  === (X >>s (C1-C2)) & mask
5303         Op = InsertCastBefore(Mask, I.getType()->getSignedVersion(), I);
5304         Instruction *Shift =
5305           new ShiftInst(ShiftOp->getOpcode(), Op,
5306                         ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5307         InsertNewInstBefore(Shift, I);
5308         
5309         C = ConstantIntegral::getAllOnesValue(Shift->getType());
5310         C = ConstantExpr::getShl(C, Op1);
5311         Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5312         InsertNewInstBefore(Mask, I);
5313         return new CastInst(Mask, I.getType());
5314       }
5315     } else {
5316       // We can handle signed (X << C1) >>s C2 if it's a sign extend.  In
5317       // this case, C1 == C2 and C1 is 8, 16, or 32.
5318       if (ShiftAmt1 == ShiftAmt2) {
5319         const Type *SExtType = 0;
5320         switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5321         case 8 : SExtType = Type::SByteTy; break;
5322         case 16: SExtType = Type::ShortTy; break;
5323         case 32: SExtType = Type::IntTy; break;
5324         }
5325         
5326         if (SExtType) {
5327           Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5328                                                SExtType, "sext");
5329           InsertNewInstBefore(NewTrunc, I);
5330           return new CastInst(NewTrunc, I.getType());
5331         }
5332       }
5333     }
5334   }
5335   return 0;
5336 }
5337
5338
5339 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5340 /// expression.  If so, decompose it, returning some value X, such that Val is
5341 /// X*Scale+Offset.
5342 ///
5343 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5344                                         unsigned &Offset) {
5345   assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5346   if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5347     if (CI->getType()->isUnsigned()) {
5348       Offset = CI->getZExtValue();
5349       Scale  = 1;
5350       return ConstantInt::get(Type::UIntTy, 0);
5351     }
5352   } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5353     if (I->getNumOperands() == 2) {
5354       if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5355         if (CUI->getType()->isUnsigned()) {
5356           if (I->getOpcode() == Instruction::Shl) {
5357             // This is a value scaled by '1 << the shift amt'.
5358             Scale = 1U << CUI->getZExtValue();
5359             Offset = 0;
5360             return I->getOperand(0);
5361           } else if (I->getOpcode() == Instruction::Mul) {
5362             // This value is scaled by 'CUI'.
5363             Scale = CUI->getZExtValue();
5364             Offset = 0;
5365             return I->getOperand(0);
5366           } else if (I->getOpcode() == Instruction::Add) {
5367             // We have X+C.  Check to see if we really have (X*C2)+C1, 
5368             // where C1 is divisible by C2.
5369             unsigned SubScale;
5370             Value *SubVal = 
5371               DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5372             Offset += CUI->getZExtValue();
5373             if (SubScale > 1 && (Offset % SubScale == 0)) {
5374               Scale = SubScale;
5375               return SubVal;
5376             }
5377           }
5378         }
5379       }
5380     }
5381   }
5382
5383   // Otherwise, we can't look past this.
5384   Scale = 1;
5385   Offset = 0;
5386   return Val;
5387 }
5388
5389
5390 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5391 /// try to eliminate the cast by moving the type information into the alloc.
5392 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5393                                                    AllocationInst &AI) {
5394   const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5395   if (!PTy) return 0;   // Not casting the allocation to a pointer type.
5396   
5397   // Remove any uses of AI that are dead.
5398   assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5399   std::vector<Instruction*> DeadUsers;
5400   for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5401     Instruction *User = cast<Instruction>(*UI++);
5402     if (isInstructionTriviallyDead(User)) {
5403       while (UI != E && *UI == User)
5404         ++UI; // If this instruction uses AI more than once, don't break UI.
5405       
5406       // Add operands to the worklist.
5407       AddUsesToWorkList(*User);
5408       ++NumDeadInst;
5409       DEBUG(std::cerr << "IC: DCE: " << *User);
5410       
5411       User->eraseFromParent();
5412       removeFromWorkList(User);
5413     }
5414   }
5415   
5416   // Get the type really allocated and the type casted to.
5417   const Type *AllocElTy = AI.getAllocatedType();
5418   const Type *CastElTy = PTy->getElementType();
5419   if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5420
5421   unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5422   unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5423   if (CastElTyAlign < AllocElTyAlign) return 0;
5424
5425   // If the allocation has multiple uses, only promote it if we are strictly
5426   // increasing the alignment of the resultant allocation.  If we keep it the
5427   // same, we open the door to infinite loops of various kinds.
5428   if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5429
5430   uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5431   uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5432   if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5433
5434   // See if we can satisfy the modulus by pulling a scale out of the array
5435   // size argument.
5436   unsigned ArraySizeScale, ArrayOffset;
5437   Value *NumElements = // See if the array size is a decomposable linear expr.
5438     DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5439  
5440   // If we can now satisfy the modulus, by using a non-1 scale, we really can
5441   // do the xform.
5442   if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5443       (AllocElTySize*ArrayOffset   ) % CastElTySize != 0) return 0;
5444
5445   unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5446   Value *Amt = 0;
5447   if (Scale == 1) {
5448     Amt = NumElements;
5449   } else {
5450     // If the allocation size is constant, form a constant mul expression
5451     Amt = ConstantInt::get(Type::UIntTy, Scale);
5452     if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5453       Amt = ConstantExpr::getMul(
5454               cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5455     // otherwise multiply the amount and the number of elements
5456     else if (Scale != 1) {
5457       Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5458       Amt = InsertNewInstBefore(Tmp, AI);
5459     }
5460   }
5461   
5462   if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5463     Value *Off = ConstantInt::get(Type::UIntTy, Offset);
5464     Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5465     Amt = InsertNewInstBefore(Tmp, AI);
5466   }
5467   
5468   std::string Name = AI.getName(); AI.setName("");
5469   AllocationInst *New;
5470   if (isa<MallocInst>(AI))
5471     New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5472   else
5473     New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5474   InsertNewInstBefore(New, AI);
5475   
5476   // If the allocation has multiple uses, insert a cast and change all things
5477   // that used it to use the new cast.  This will also hack on CI, but it will
5478   // die soon.
5479   if (!AI.hasOneUse()) {
5480     AddUsesToWorkList(AI);
5481     CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5482     InsertNewInstBefore(NewCast, AI);
5483     AI.replaceAllUsesWith(NewCast);
5484   }
5485   return ReplaceInstUsesWith(CI, New);
5486 }
5487
5488 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5489 /// and return it without inserting any new casts.  This is used by code that
5490 /// tries to decide whether promoting or shrinking integer operations to wider
5491 /// or smaller types will allow us to eliminate a truncate or extend.
5492 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5493                                        int &NumCastsRemoved) {
5494   if (isa<Constant>(V)) return true;
5495   
5496   Instruction *I = dyn_cast<Instruction>(V);
5497   if (!I || !I->hasOneUse()) return false;
5498   
5499   switch (I->getOpcode()) {
5500   case Instruction::And:
5501   case Instruction::Or:
5502   case Instruction::Xor:
5503     // These operators can all arbitrarily be extended or truncated.
5504     return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5505            CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5506   case Instruction::Cast:
5507     // If this is a cast from the destination type, we can trivially eliminate
5508     // it, and this will remove a cast overall.
5509     if (I->getOperand(0)->getType() == Ty) {
5510       // If the first operand is itself a cast, and is eliminable, do not count
5511       // this as an eliminable cast.  We would prefer to eliminate those two
5512       // casts first.
5513       if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5514         return true;
5515       
5516       ++NumCastsRemoved;
5517       return true;
5518     }
5519     // TODO: Can handle more cases here.
5520     break;
5521   }
5522   
5523   return false;
5524 }
5525
5526 /// EvaluateInDifferentType - Given an expression that 
5527 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5528 /// evaluate the expression.
5529 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5530   if (Constant *C = dyn_cast<Constant>(V))
5531     return ConstantExpr::getCast(C, Ty);
5532
5533   // Otherwise, it must be an instruction.
5534   Instruction *I = cast<Instruction>(V);
5535   Instruction *Res = 0;
5536   switch (I->getOpcode()) {
5537   case Instruction::And:
5538   case Instruction::Or:
5539   case Instruction::Xor: {
5540     Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5541     Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5542     Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5543                                  LHS, RHS, I->getName());
5544     break;
5545   }
5546   case Instruction::Cast:
5547     // If this is a cast from the destination type, return the input.
5548     if (I->getOperand(0)->getType() == Ty)
5549       return I->getOperand(0);
5550     
5551     // TODO: Can handle more cases here.
5552     assert(0 && "Unreachable!");
5553     break;
5554   }
5555   
5556   return InsertNewInstBefore(Res, *I);
5557 }
5558
5559
5560 // CastInst simplification
5561 //
5562 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5563   Value *Src = CI.getOperand(0);
5564
5565   // If the user is casting a value to the same type, eliminate this cast
5566   // instruction...
5567   if (CI.getType() == Src->getType())
5568     return ReplaceInstUsesWith(CI, Src);
5569
5570   if (isa<UndefValue>(Src))   // cast undef -> undef
5571     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5572
5573   // If casting the result of another cast instruction, try to eliminate this
5574   // one!
5575   //
5576   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
5577     Value *A = CSrc->getOperand(0);
5578     if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5579                                CI.getType(), TD)) {
5580       // This instruction now refers directly to the cast's src operand.  This
5581       // has a good chance of making CSrc dead.
5582       CI.setOperand(0, CSrc->getOperand(0));
5583       return &CI;
5584     }
5585
5586     // If this is an A->B->A cast, and we are dealing with integral types, try
5587     // to convert this into a logical 'and' instruction.
5588     //
5589     if (A->getType()->isInteger() &&
5590         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5591         CSrc->getType()->isUnsigned() &&   // B->A cast must zero extend
5592         CSrc->getType()->getPrimitiveSizeInBits() <
5593                     CI.getType()->getPrimitiveSizeInBits()&&
5594         A->getType()->getPrimitiveSizeInBits() ==
5595               CI.getType()->getPrimitiveSizeInBits()) {
5596       assert(CSrc->getType() != Type::ULongTy &&
5597              "Cannot have type bigger than ulong!");
5598       uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5599       Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
5600                                           AndValue);
5601       AndOp = ConstantExpr::getCast(AndOp, A->getType());
5602       Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5603       if (And->getType() != CI.getType()) {
5604         And->setName(CSrc->getName()+".mask");
5605         InsertNewInstBefore(And, CI);
5606         And = new CastInst(And, CI.getType());
5607       }
5608       return And;
5609     }
5610   }
5611   
5612   // If this is a cast to bool, turn it into the appropriate setne instruction.
5613   if (CI.getType() == Type::BoolTy)
5614     return BinaryOperator::createSetNE(CI.getOperand(0),
5615                        Constant::getNullValue(CI.getOperand(0)->getType()));
5616
5617   // See if we can simplify any instructions used by the LHS whose sole 
5618   // purpose is to compute bits we don't care about.
5619   if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5620     uint64_t KnownZero, KnownOne;
5621     if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5622                              KnownZero, KnownOne))
5623       return &CI;
5624   }
5625   
5626   // If casting the result of a getelementptr instruction with no offset, turn
5627   // this into a cast of the original pointer!
5628   //
5629   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5630     bool AllZeroOperands = true;
5631     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5632       if (!isa<Constant>(GEP->getOperand(i)) ||
5633           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5634         AllZeroOperands = false;
5635         break;
5636       }
5637     if (AllZeroOperands) {
5638       CI.setOperand(0, GEP->getOperand(0));
5639       return &CI;
5640     }
5641   }
5642
5643   // If we are casting a malloc or alloca to a pointer to a type of the same
5644   // size, rewrite the allocation instruction to allocate the "right" type.
5645   //
5646   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5647     if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5648       return V;
5649
5650   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5651     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5652       return NV;
5653   if (isa<PHINode>(Src))
5654     if (Instruction *NV = FoldOpIntoPhi(CI))
5655       return NV;
5656   
5657   // If the source and destination are pointers, and this cast is equivalent to
5658   // a getelementptr X, 0, 0, 0...  turn it into the appropriate getelementptr.
5659   // This can enhance SROA and other transforms that want type-safe pointers.
5660   if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5661     if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5662       const Type *DstTy = DstPTy->getElementType();
5663       const Type *SrcTy = SrcPTy->getElementType();
5664       
5665       Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5666       unsigned NumZeros = 0;
5667       while (SrcTy != DstTy && 
5668              isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5669              SrcTy->getNumContainedTypes() /* not "{}" */) {
5670         SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5671         ++NumZeros;
5672       }
5673
5674       // If we found a path from the src to dest, create the getelementptr now.
5675       if (SrcTy == DstTy) {
5676         std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5677         return new GetElementPtrInst(Src, Idxs);
5678       }
5679     }
5680       
5681   // If the source value is an instruction with only this use, we can attempt to
5682   // propagate the cast into the instruction.  Also, only handle integral types
5683   // for now.
5684   if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5685     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5686         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
5687       
5688       int NumCastsRemoved = 0;
5689       if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5690         // If this cast is a truncate, evaluting in a different type always
5691         // eliminates the cast, so it is always a win.  If this is a noop-cast
5692         // this just removes a noop cast which isn't pointful, but simplifies
5693         // the code.  If this is a zero-extension, we need to do an AND to
5694         // maintain the clear top-part of the computation, so we require that
5695         // the input have eliminated at least one cast.  If this is a sign
5696         // extension, we insert two new casts (to do the extension) so we
5697         // require that two casts have been eliminated.
5698         bool DoXForm;
5699         switch (getCastType(Src->getType(), CI.getType())) {
5700         default: assert(0 && "Unknown cast type!");
5701         case Noop:
5702         case Truncate:
5703           DoXForm = true;
5704           break;
5705         case Zeroext:
5706           DoXForm = NumCastsRemoved >= 1;
5707           break;
5708         case Signext:
5709           DoXForm = NumCastsRemoved >= 2;
5710           break;
5711         }
5712         
5713         if (DoXForm) {
5714           Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5715           assert(Res->getType() == CI.getType());
5716           switch (getCastType(Src->getType(), CI.getType())) {
5717           default: assert(0 && "Unknown cast type!");
5718           case Noop:
5719           case Truncate:
5720             // Just replace this cast with the result.
5721             return ReplaceInstUsesWith(CI, Res);
5722           case Zeroext: {
5723             // We need to emit an AND to clear the high bits.
5724             unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5725             unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5726             assert(SrcBitSize < DestBitSize && "Not a zext?");
5727             Constant *C = 
5728               ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
5729             C = ConstantExpr::getCast(C, CI.getType());
5730             return BinaryOperator::createAnd(Res, C);
5731           }
5732           case Signext:
5733             // We need to emit a cast to truncate, then a cast to sext.
5734             return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5735                                 CI.getType());
5736           }
5737         }
5738       }
5739       
5740       const Type *DestTy = CI.getType();
5741       unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5742       unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5743
5744       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5745       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5746
5747       switch (SrcI->getOpcode()) {
5748       case Instruction::Add:
5749       case Instruction::Mul:
5750       case Instruction::And:
5751       case Instruction::Or:
5752       case Instruction::Xor:
5753         // If we are discarding information, or just changing the sign, rewrite.
5754         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5755           // Don't insert two casts if they cannot be eliminated.  We allow two
5756           // casts to be inserted if the sizes are the same.  This could only be
5757           // converting signedness, which is a noop.
5758           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5759               !ValueRequiresCast(Op0, DestTy, TD)) {
5760             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5761             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5762             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5763                              ->getOpcode(), Op0c, Op1c);
5764           }
5765         }
5766
5767         // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
5768         if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5769             Op1 == ConstantBool::getTrue() &&
5770             (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5771           Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5772           return BinaryOperator::createXor(New,
5773                                            ConstantInt::get(CI.getType(), 1));
5774         }
5775         break;
5776       case Instruction::SDiv:
5777       case Instruction::UDiv:
5778       case Instruction::SRem:
5779       case Instruction::URem:
5780         // If we are just changing the sign, rewrite.
5781         if (DestBitSize == SrcBitSize) {
5782           // Don't insert two casts if they cannot be eliminated.  We allow two
5783           // casts to be inserted if the sizes are the same.  This could only be
5784           // converting signedness, which is a noop.
5785           if (!ValueRequiresCast(Op1, DestTy,TD) || 
5786               !ValueRequiresCast(Op0, DestTy, TD)) {
5787             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5788             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5789             return BinaryOperator::create(
5790               cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
5791           }
5792         }
5793         break;
5794
5795       case Instruction::Shl:
5796         // Allow changing the sign of the source operand.  Do not allow changing
5797         // the size of the shift, UNLESS the shift amount is a constant.  We
5798         // mush not change variable sized shifts to a smaller size, because it
5799         // is undefined to shift more bits out than exist in the value.
5800         if (DestBitSize == SrcBitSize ||
5801             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5802           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5803           return new ShiftInst(Instruction::Shl, Op0c, Op1);
5804         }
5805         break;
5806       case Instruction::Shr:
5807         // If this is a signed shr, and if all bits shifted in are about to be
5808         // truncated off, turn it into an unsigned shr to allow greater
5809         // simplifications.
5810         if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5811             isa<ConstantInt>(Op1)) {
5812           unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
5813           if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5814             // Convert to unsigned.
5815             Value *N1 = InsertOperandCastBefore(Op0,
5816                                      Op0->getType()->getUnsignedVersion(), &CI);
5817             // Insert the new shift, which is now unsigned.
5818             N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5819                                                    Op1, Src->getName()), CI);
5820             return new CastInst(N1, CI.getType());
5821           }
5822         }
5823         break;
5824
5825       case Instruction::SetEQ:
5826       case Instruction::SetNE:
5827         // We if we are just checking for a seteq of a single bit and casting it
5828         // to an integer.  If so, shift the bit to the appropriate place then
5829         // cast to integer to avoid the comparison.
5830         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5831           uint64_t Op1CV = Op1C->getZExtValue();
5832           // cast (X == 0) to int --> X^1        iff X has only the low bit set.
5833           // cast (X == 0) to int --> (X>>1)^1   iff X has only the 2nd bit set.
5834           // cast (X == 1) to int --> X          iff X has only the low bit set.
5835           // cast (X == 2) to int --> X>>1       iff X has only the 2nd bit set.
5836           // cast (X != 0) to int --> X          iff X has only the low bit set.
5837           // cast (X != 0) to int --> X>>1       iff X has only the 2nd bit set.
5838           // cast (X != 1) to int --> X^1        iff X has only the low bit set.
5839           // cast (X != 2) to int --> (X>>1)^1   iff X has only the 2nd bit set.
5840           if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5841             // If Op1C some other power of two, convert:
5842             uint64_t KnownZero, KnownOne;
5843             uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5844             ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5845             
5846             if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5847               bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5848               if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5849                 // (X&4) == 2 --> false
5850                 // (X&4) != 2 --> true
5851                 Constant *Res = ConstantBool::get(isSetNE);
5852                 Res = ConstantExpr::getCast(Res, CI.getType());
5853                 return ReplaceInstUsesWith(CI, Res);
5854               }
5855               
5856               unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5857               Value *In = Op0;
5858               if (ShiftAmt) {
5859                 // Perform an unsigned shr by shiftamt.  Convert input to
5860                 // unsigned if it is signed.
5861                 if (In->getType()->isSigned())
5862                   In = InsertCastBefore(
5863                          In, In->getType()->getUnsignedVersion(), CI);
5864                 // Insert the shift to put the result in the low bit.
5865                 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
5866                                      ConstantInt::get(Type::UByteTy, ShiftAmt),
5867                                      In->getName()+".lobit"), CI);
5868               }
5869               
5870               if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5871                 Constant *One = ConstantInt::get(In->getType(), 1);
5872                 In = BinaryOperator::createXor(In, One, "tmp");
5873                 InsertNewInstBefore(cast<Instruction>(In), CI);
5874               }
5875               
5876               if (CI.getType() == In->getType())
5877                 return ReplaceInstUsesWith(CI, In);
5878               else
5879                 return new CastInst(In, CI.getType());
5880             }
5881           }
5882         }
5883         break;
5884       }
5885     }
5886     
5887     if (SrcI->hasOneUse()) {
5888       if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5889         // Okay, we have (cast (shuffle ..)).  We know this cast is a bitconvert
5890         // because the inputs are known to be a vector.  Check to see if this is
5891         // a cast to a vector with the same # elts.
5892         if (isa<PackedType>(CI.getType()) && 
5893             cast<PackedType>(CI.getType())->getNumElements() == 
5894                   SVI->getType()->getNumElements()) {
5895           CastInst *Tmp;
5896           // If either of the operands is a cast from CI.getType(), then
5897           // evaluating the shuffle in the casted destination's type will allow
5898           // us to eliminate at least one cast.
5899           if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) && 
5900                Tmp->getOperand(0)->getType() == CI.getType()) ||
5901               ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) && 
5902                Tmp->getOperand(0)->getType() == CI.getType())) {
5903             Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5904                                                  CI.getType(), &CI);
5905             Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5906                                                  CI.getType(), &CI);
5907             // Return a new shuffle vector.  Use the same element ID's, as we
5908             // know the vector types match #elts.
5909             return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5910           }
5911         }
5912       }
5913     }
5914   }
5915       
5916   return 0;
5917 }
5918
5919 /// GetSelectFoldableOperands - We want to turn code that looks like this:
5920 ///   %C = or %A, %B
5921 ///   %D = select %cond, %C, %A
5922 /// into:
5923 ///   %C = select %cond, %B, 0
5924 ///   %D = or %A, %C
5925 ///
5926 /// Assuming that the specified instruction is an operand to the select, return
5927 /// a bitmask indicating which operands of this instruction are foldable if they
5928 /// equal the other incoming value of the select.
5929 ///
5930 static unsigned GetSelectFoldableOperands(Instruction *I) {
5931   switch (I->getOpcode()) {
5932   case Instruction::Add:
5933   case Instruction::Mul:
5934   case Instruction::And:
5935   case Instruction::Or:
5936   case Instruction::Xor:
5937     return 3;              // Can fold through either operand.
5938   case Instruction::Sub:   // Can only fold on the amount subtracted.
5939   case Instruction::Shl:   // Can only fold on the shift amount.
5940   case Instruction::Shr:
5941     return 1;
5942   default:
5943     return 0;              // Cannot fold
5944   }
5945 }
5946
5947 /// GetSelectFoldableConstant - For the same transformation as the previous
5948 /// function, return the identity constant that goes into the select.
5949 static Constant *GetSelectFoldableConstant(Instruction *I) {
5950   switch (I->getOpcode()) {
5951   default: assert(0 && "This cannot happen!"); abort();
5952   case Instruction::Add:
5953   case Instruction::Sub:
5954   case Instruction::Or:
5955   case Instruction::Xor:
5956     return Constant::getNullValue(I->getType());
5957   case Instruction::Shl:
5958   case Instruction::Shr:
5959     return Constant::getNullValue(Type::UByteTy);
5960   case Instruction::And:
5961     return ConstantInt::getAllOnesValue(I->getType());
5962   case Instruction::Mul:
5963     return ConstantInt::get(I->getType(), 1);
5964   }
5965 }
5966
5967 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5968 /// have the same opcode and only one use each.  Try to simplify this.
5969 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5970                                           Instruction *FI) {
5971   if (TI->getNumOperands() == 1) {
5972     // If this is a non-volatile load or a cast from the same type,
5973     // merge.
5974     if (TI->getOpcode() == Instruction::Cast) {
5975       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5976         return 0;
5977     } else {
5978       return 0;  // unknown unary op.
5979     }
5980
5981     // Fold this by inserting a select from the input values.
5982     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5983                                        FI->getOperand(0), SI.getName()+".v");
5984     InsertNewInstBefore(NewSI, SI);
5985     return new CastInst(NewSI, TI->getType());
5986   }
5987
5988   // Only handle binary operators here.
5989   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5990     return 0;
5991
5992   // Figure out if the operations have any operands in common.
5993   Value *MatchOp, *OtherOpT, *OtherOpF;
5994   bool MatchIsOpZero;
5995   if (TI->getOperand(0) == FI->getOperand(0)) {
5996     MatchOp  = TI->getOperand(0);
5997     OtherOpT = TI->getOperand(1);
5998     OtherOpF = FI->getOperand(1);
5999     MatchIsOpZero = true;
6000   } else if (TI->getOperand(1) == FI->getOperand(1)) {
6001     MatchOp  = TI->getOperand(1);
6002     OtherOpT = TI->getOperand(0);
6003     OtherOpF = FI->getOperand(0);
6004     MatchIsOpZero = false;
6005   } else if (!TI->isCommutative()) {
6006     return 0;
6007   } else if (TI->getOperand(0) == FI->getOperand(1)) {
6008     MatchOp  = TI->getOperand(0);
6009     OtherOpT = TI->getOperand(1);
6010     OtherOpF = FI->getOperand(0);
6011     MatchIsOpZero = true;
6012   } else if (TI->getOperand(1) == FI->getOperand(0)) {
6013     MatchOp  = TI->getOperand(1);
6014     OtherOpT = TI->getOperand(0);
6015     OtherOpF = FI->getOperand(1);
6016     MatchIsOpZero = true;
6017   } else {
6018     return 0;
6019   }
6020
6021   // If we reach here, they do have operations in common.
6022   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6023                                      OtherOpF, SI.getName()+".v");
6024   InsertNewInstBefore(NewSI, SI);
6025
6026   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6027     if (MatchIsOpZero)
6028       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6029     else
6030       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6031   } else {
6032     if (MatchIsOpZero)
6033       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6034     else
6035       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6036   }
6037 }
6038
6039 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6040   Value *CondVal = SI.getCondition();
6041   Value *TrueVal = SI.getTrueValue();
6042   Value *FalseVal = SI.getFalseValue();
6043
6044   // select true, X, Y  -> X
6045   // select false, X, Y -> Y
6046   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
6047     return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
6048
6049   // select C, X, X -> X
6050   if (TrueVal == FalseVal)
6051     return ReplaceInstUsesWith(SI, TrueVal);
6052
6053   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
6054     return ReplaceInstUsesWith(SI, FalseVal);
6055   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
6056     return ReplaceInstUsesWith(SI, TrueVal);
6057   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
6058     if (isa<Constant>(TrueVal))
6059       return ReplaceInstUsesWith(SI, TrueVal);
6060     else
6061       return ReplaceInstUsesWith(SI, FalseVal);
6062   }
6063
6064   if (SI.getType() == Type::BoolTy)
6065     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
6066       if (C->getValue()) {
6067         // Change: A = select B, true, C --> A = or B, C
6068         return BinaryOperator::createOr(CondVal, FalseVal);
6069       } else {
6070         // Change: A = select B, false, C --> A = and !B, C
6071         Value *NotCond =
6072           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6073                                              "not."+CondVal->getName()), SI);
6074         return BinaryOperator::createAnd(NotCond, FalseVal);
6075       }
6076     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
6077       if (C->getValue() == false) {
6078         // Change: A = select B, C, false --> A = and B, C
6079         return BinaryOperator::createAnd(CondVal, TrueVal);
6080       } else {
6081         // Change: A = select B, C, true --> A = or !B, C
6082         Value *NotCond =
6083           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6084                                              "not."+CondVal->getName()), SI);
6085         return BinaryOperator::createOr(NotCond, TrueVal);
6086       }
6087     }
6088
6089   // Selecting between two integer constants?
6090   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6091     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6092       // select C, 1, 0 -> cast C to int
6093       if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6094         return new CastInst(CondVal, SI.getType());
6095       } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6096         // select C, 0, 1 -> cast !C to int
6097         Value *NotCond =
6098           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6099                                                "not."+CondVal->getName()), SI);
6100         return new CastInst(NotCond, SI.getType());
6101       }
6102
6103       if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
6104
6105         // (x <s 0) ? -1 : 0 -> sra x, 31
6106         // (x >u 2147483647) ? -1 : 0 -> sra x, 31
6107         if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6108           if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6109             bool CanXForm = false;
6110             if (CmpCst->getType()->isSigned())
6111               CanXForm = CmpCst->isNullValue() && 
6112                          IC->getOpcode() == Instruction::SetLT;
6113             else {
6114               unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6115               CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6116                          IC->getOpcode() == Instruction::SetGT;
6117             }
6118             
6119             if (CanXForm) {
6120               // The comparison constant and the result are not neccessarily the
6121               // same width.  In any case, the first step to do is make sure
6122               // that X is signed.
6123               Value *X = IC->getOperand(0);
6124               if (!X->getType()->isSigned())
6125                 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6126               
6127               // Now that X is signed, we have to make the all ones value.  Do
6128               // this by inserting a new SRA.
6129               unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6130               Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
6131               Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6132                                                ShAmt, "ones");
6133               InsertNewInstBefore(SRA, SI);
6134               
6135               // Finally, convert to the type of the select RHS.  If this is
6136               // smaller than the compare value, it will truncate the ones to
6137               // fit. If it is larger, it will sext the ones to fit.
6138               return new CastInst(SRA, SI.getType());
6139             }
6140           }
6141
6142
6143         // If one of the constants is zero (we know they can't both be) and we
6144         // have a setcc instruction with zero, and we have an 'and' with the
6145         // non-constant value, eliminate this whole mess.  This corresponds to
6146         // cases like this: ((X & 27) ? 27 : 0)
6147         if (TrueValC->isNullValue() || FalseValC->isNullValue())
6148           if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6149               cast<Constant>(IC->getOperand(1))->isNullValue())
6150             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6151               if (ICA->getOpcode() == Instruction::And &&
6152                   isa<ConstantInt>(ICA->getOperand(1)) &&
6153                   (ICA->getOperand(1) == TrueValC ||
6154                    ICA->getOperand(1) == FalseValC) &&
6155                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6156                 // Okay, now we know that everything is set up, we just don't
6157                 // know whether we have a setne or seteq and whether the true or
6158                 // false val is the zero.
6159                 bool ShouldNotVal = !TrueValC->isNullValue();
6160                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6161                 Value *V = ICA;
6162                 if (ShouldNotVal)
6163                   V = InsertNewInstBefore(BinaryOperator::create(
6164                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
6165                 return ReplaceInstUsesWith(SI, V);
6166               }
6167       }
6168     }
6169
6170   // See if we are selecting two values based on a comparison of the two values.
6171   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6172     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6173       // Transform (X == Y) ? X : Y  -> Y
6174       if (SCI->getOpcode() == Instruction::SetEQ)
6175         return ReplaceInstUsesWith(SI, FalseVal);
6176       // Transform (X != Y) ? X : Y  -> X
6177       if (SCI->getOpcode() == Instruction::SetNE)
6178         return ReplaceInstUsesWith(SI, TrueVal);
6179       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6180
6181     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6182       // Transform (X == Y) ? Y : X  -> X
6183       if (SCI->getOpcode() == Instruction::SetEQ)
6184         return ReplaceInstUsesWith(SI, FalseVal);
6185       // Transform (X != Y) ? Y : X  -> Y
6186       if (SCI->getOpcode() == Instruction::SetNE)
6187         return ReplaceInstUsesWith(SI, TrueVal);
6188       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6189     }
6190   }
6191
6192   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6193     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6194       if (TI->hasOneUse() && FI->hasOneUse()) {
6195         bool isInverse = false;
6196         Instruction *AddOp = 0, *SubOp = 0;
6197
6198         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6199         if (TI->getOpcode() == FI->getOpcode())
6200           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6201             return IV;
6202
6203         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
6204         // even legal for FP.
6205         if (TI->getOpcode() == Instruction::Sub &&
6206             FI->getOpcode() == Instruction::Add) {
6207           AddOp = FI; SubOp = TI;
6208         } else if (FI->getOpcode() == Instruction::Sub &&
6209                    TI->getOpcode() == Instruction::Add) {
6210           AddOp = TI; SubOp = FI;
6211         }
6212
6213         if (AddOp) {
6214           Value *OtherAddOp = 0;
6215           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6216             OtherAddOp = AddOp->getOperand(1);
6217           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6218             OtherAddOp = AddOp->getOperand(0);
6219           }
6220
6221           if (OtherAddOp) {
6222             // So at this point we know we have (Y -> OtherAddOp):
6223             //        select C, (add X, Y), (sub X, Z)
6224             Value *NegVal;  // Compute -Z
6225             if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6226               NegVal = ConstantExpr::getNeg(C);
6227             } else {
6228               NegVal = InsertNewInstBefore(
6229                     BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6230             }
6231
6232             Value *NewTrueOp = OtherAddOp;
6233             Value *NewFalseOp = NegVal;
6234             if (AddOp != TI)
6235               std::swap(NewTrueOp, NewFalseOp);
6236             Instruction *NewSel =
6237               new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6238
6239             NewSel = InsertNewInstBefore(NewSel, SI);
6240             return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6241           }
6242         }
6243       }
6244
6245   // See if we can fold the select into one of our operands.
6246   if (SI.getType()->isInteger()) {
6247     // See the comment above GetSelectFoldableOperands for a description of the
6248     // transformation we are doing here.
6249     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6250       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6251           !isa<Constant>(FalseVal))
6252         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6253           unsigned OpToFold = 0;
6254           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6255             OpToFold = 1;
6256           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6257             OpToFold = 2;
6258           }
6259
6260           if (OpToFold) {
6261             Constant *C = GetSelectFoldableConstant(TVI);
6262             std::string Name = TVI->getName(); TVI->setName("");
6263             Instruction *NewSel =
6264               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6265                              Name);
6266             InsertNewInstBefore(NewSel, SI);
6267             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6268               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6269             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6270               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6271             else {
6272               assert(0 && "Unknown instruction!!");
6273             }
6274           }
6275         }
6276
6277     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6278       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6279           !isa<Constant>(TrueVal))
6280         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6281           unsigned OpToFold = 0;
6282           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6283             OpToFold = 1;
6284           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6285             OpToFold = 2;
6286           }
6287
6288           if (OpToFold) {
6289             Constant *C = GetSelectFoldableConstant(FVI);
6290             std::string Name = FVI->getName(); FVI->setName("");
6291             Instruction *NewSel =
6292               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6293                              Name);
6294             InsertNewInstBefore(NewSel, SI);
6295             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6296               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6297             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6298               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6299             else {
6300               assert(0 && "Unknown instruction!!");
6301             }
6302           }
6303         }
6304   }
6305
6306   if (BinaryOperator::isNot(CondVal)) {
6307     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6308     SI.setOperand(1, FalseVal);
6309     SI.setOperand(2, TrueVal);
6310     return &SI;
6311   }
6312
6313   return 0;
6314 }
6315
6316 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6317 /// determine, return it, otherwise return 0.
6318 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6319   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6320     unsigned Align = GV->getAlignment();
6321     if (Align == 0 && TD) 
6322       Align = TD->getTypeAlignment(GV->getType()->getElementType());
6323     return Align;
6324   } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6325     unsigned Align = AI->getAlignment();
6326     if (Align == 0 && TD) {
6327       if (isa<AllocaInst>(AI))
6328         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6329       else if (isa<MallocInst>(AI)) {
6330         // Malloc returns maximally aligned memory.
6331         Align = TD->getTypeAlignment(AI->getType()->getElementType());
6332         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6333         Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6334       }
6335     }
6336     return Align;
6337   } else if (isa<CastInst>(V) ||
6338              (isa<ConstantExpr>(V) && 
6339               cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6340     User *CI = cast<User>(V);
6341     if (isa<PointerType>(CI->getOperand(0)->getType()))
6342       return GetKnownAlignment(CI->getOperand(0), TD);
6343     return 0;
6344   } else if (isa<GetElementPtrInst>(V) ||
6345              (isa<ConstantExpr>(V) && 
6346               cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6347     User *GEPI = cast<User>(V);
6348     unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6349     if (BaseAlignment == 0) return 0;
6350     
6351     // If all indexes are zero, it is just the alignment of the base pointer.
6352     bool AllZeroOperands = true;
6353     for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6354       if (!isa<Constant>(GEPI->getOperand(i)) ||
6355           !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6356         AllZeroOperands = false;
6357         break;
6358       }
6359     if (AllZeroOperands)
6360       return BaseAlignment;
6361     
6362     // Otherwise, if the base alignment is >= the alignment we expect for the
6363     // base pointer type, then we know that the resultant pointer is aligned at
6364     // least as much as its type requires.
6365     if (!TD) return 0;
6366
6367     const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6368     if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6369         <= BaseAlignment) {
6370       const Type *GEPTy = GEPI->getType();
6371       return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6372     }
6373     return 0;
6374   }
6375   return 0;
6376 }
6377
6378
6379 /// visitCallInst - CallInst simplification.  This mostly only handles folding 
6380 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
6381 /// the heavy lifting.
6382 ///
6383 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6384   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6385   if (!II) return visitCallSite(&CI);
6386   
6387   // Intrinsics cannot occur in an invoke, so handle them here instead of in
6388   // visitCallSite.
6389   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6390     bool Changed = false;
6391
6392     // memmove/cpy/set of zero bytes is a noop.
6393     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6394       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6395
6396       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6397         if (CI->getZExtValue() == 1) {
6398           // Replace the instruction with just byte operations.  We would
6399           // transform other cases to loads/stores, but we don't know if
6400           // alignment is sufficient.
6401         }
6402     }
6403
6404     // If we have a memmove and the source operation is a constant global,
6405     // then the source and dest pointers can't alias, so we can change this
6406     // into a call to memcpy.
6407     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6408       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6409         if (GVSrc->isConstant()) {
6410           Module *M = CI.getParent()->getParent()->getParent();
6411           const char *Name;
6412           if (CI.getCalledFunction()->getFunctionType()->getParamType(3) == 
6413               Type::UIntTy)
6414             Name = "llvm.memcpy.i32";
6415           else
6416             Name = "llvm.memcpy.i64";
6417           Function *MemCpy = M->getOrInsertFunction(Name,
6418                                      CI.getCalledFunction()->getFunctionType());
6419           CI.setOperand(0, MemCpy);
6420           Changed = true;
6421         }
6422     }
6423
6424     // If we can determine a pointer alignment that is bigger than currently
6425     // set, update the alignment.
6426     if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6427       unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6428       unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6429       unsigned Align = std::min(Alignment1, Alignment2);
6430       if (MI->getAlignment()->getZExtValue() < Align) {
6431         MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
6432         Changed = true;
6433       }
6434     } else if (isa<MemSetInst>(MI)) {
6435       unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6436       if (MI->getAlignment()->getZExtValue() < Alignment) {
6437         MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
6438         Changed = true;
6439       }
6440     }
6441           
6442     if (Changed) return II;
6443   } else {
6444     switch (II->getIntrinsicID()) {
6445     default: break;
6446     case Intrinsic::ppc_altivec_lvx:
6447     case Intrinsic::ppc_altivec_lvxl:
6448     case Intrinsic::x86_sse_loadu_ps:
6449     case Intrinsic::x86_sse2_loadu_pd:
6450     case Intrinsic::x86_sse2_loadu_dq:
6451       // Turn PPC lvx     -> load if the pointer is known aligned.
6452       // Turn X86 loadups -> load if the pointer is known aligned.
6453       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6454         Value *Ptr = InsertCastBefore(II->getOperand(1),
6455                                       PointerType::get(II->getType()), CI);
6456         return new LoadInst(Ptr);
6457       }
6458       break;
6459     case Intrinsic::ppc_altivec_stvx:
6460     case Intrinsic::ppc_altivec_stvxl:
6461       // Turn stvx -> store if the pointer is known aligned.
6462       if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6463         const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6464         Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6465         return new StoreInst(II->getOperand(1), Ptr);
6466       }
6467       break;
6468     case Intrinsic::x86_sse_storeu_ps:
6469     case Intrinsic::x86_sse2_storeu_pd:
6470     case Intrinsic::x86_sse2_storeu_dq:
6471     case Intrinsic::x86_sse2_storel_dq:
6472       // Turn X86 storeu -> store if the pointer is known aligned.
6473       if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6474         const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6475         Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6476         return new StoreInst(II->getOperand(2), Ptr);
6477       }
6478       break;
6479       
6480     case Intrinsic::x86_sse_cvttss2si: {
6481       // These intrinsics only demands the 0th element of its input vector.  If
6482       // we can simplify the input based on that, do so now.
6483       uint64_t UndefElts;
6484       if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1, 
6485                                                 UndefElts)) {
6486         II->setOperand(1, V);
6487         return II;
6488       }
6489       break;
6490     }
6491       
6492     case Intrinsic::ppc_altivec_vperm:
6493       // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6494       if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6495         assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6496         
6497         // Check that all of the elements are integer constants or undefs.
6498         bool AllEltsOk = true;
6499         for (unsigned i = 0; i != 16; ++i) {
6500           if (!isa<ConstantInt>(Mask->getOperand(i)) && 
6501               !isa<UndefValue>(Mask->getOperand(i))) {
6502             AllEltsOk = false;
6503             break;
6504           }
6505         }
6506         
6507         if (AllEltsOk) {
6508           // Cast the input vectors to byte vectors.
6509           Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6510           Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6511           Value *Result = UndefValue::get(Op0->getType());
6512           
6513           // Only extract each element once.
6514           Value *ExtractedElts[32];
6515           memset(ExtractedElts, 0, sizeof(ExtractedElts));
6516           
6517           for (unsigned i = 0; i != 16; ++i) {
6518             if (isa<UndefValue>(Mask->getOperand(i)))
6519               continue;
6520             unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
6521             Idx &= 31;  // Match the hardware behavior.
6522             
6523             if (ExtractedElts[Idx] == 0) {
6524               Instruction *Elt = 
6525                 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6526               InsertNewInstBefore(Elt, CI);
6527               ExtractedElts[Idx] = Elt;
6528             }
6529           
6530             // Insert this value into the result vector.
6531             Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6532             InsertNewInstBefore(cast<Instruction>(Result), CI);
6533           }
6534           return new CastInst(Result, CI.getType());
6535         }
6536       }
6537       break;
6538
6539     case Intrinsic::stackrestore: {
6540       // If the save is right next to the restore, remove the restore.  This can
6541       // happen when variable allocas are DCE'd.
6542       if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6543         if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6544           BasicBlock::iterator BI = SS;
6545           if (&*++BI == II)
6546             return EraseInstFromFunction(CI);
6547         }
6548       }
6549       
6550       // If the stack restore is in a return/unwind block and if there are no
6551       // allocas or calls between the restore and the return, nuke the restore.
6552       TerminatorInst *TI = II->getParent()->getTerminator();
6553       if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6554         BasicBlock::iterator BI = II;
6555         bool CannotRemove = false;
6556         for (++BI; &*BI != TI; ++BI) {
6557           if (isa<AllocaInst>(BI) ||
6558               (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6559             CannotRemove = true;
6560             break;
6561           }
6562         }
6563         if (!CannotRemove)
6564           return EraseInstFromFunction(CI);
6565       }
6566       break;
6567     }
6568     }
6569   }
6570
6571   return visitCallSite(II);
6572 }
6573
6574 // InvokeInst simplification
6575 //
6576 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6577   return visitCallSite(&II);
6578 }
6579
6580 // visitCallSite - Improvements for call and invoke instructions.
6581 //
6582 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6583   bool Changed = false;
6584
6585   // If the callee is a constexpr cast of a function, attempt to move the cast
6586   // to the arguments of the call/invoke.
6587   if (transformConstExprCastCall(CS)) return 0;
6588
6589   Value *Callee = CS.getCalledValue();
6590
6591   if (Function *CalleeF = dyn_cast<Function>(Callee))
6592     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6593       Instruction *OldCall = CS.getInstruction();
6594       // If the call and callee calling conventions don't match, this call must
6595       // be unreachable, as the call is undefined.
6596       new StoreInst(ConstantBool::getTrue(),
6597                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6598       if (!OldCall->use_empty())
6599         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6600       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
6601         return EraseInstFromFunction(*OldCall);
6602       return 0;
6603     }
6604
6605   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6606     // This instruction is not reachable, just remove it.  We insert a store to
6607     // undef so that we know that this code is not reachable, despite the fact
6608     // that we can't modify the CFG here.
6609     new StoreInst(ConstantBool::getTrue(),
6610                   UndefValue::get(PointerType::get(Type::BoolTy)),
6611                   CS.getInstruction());
6612
6613     if (!CS.getInstruction()->use_empty())
6614       CS.getInstruction()->
6615         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6616
6617     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6618       // Don't break the CFG, insert a dummy cond branch.
6619       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6620                      ConstantBool::getTrue(), II);
6621     }
6622     return EraseInstFromFunction(*CS.getInstruction());
6623   }
6624
6625   const PointerType *PTy = cast<PointerType>(Callee->getType());
6626   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6627   if (FTy->isVarArg()) {
6628     // See if we can optimize any arguments passed through the varargs area of
6629     // the call.
6630     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6631            E = CS.arg_end(); I != E; ++I)
6632       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6633         // If this cast does not effect the value passed through the varargs
6634         // area, we can eliminate the use of the cast.
6635         Value *Op = CI->getOperand(0);
6636         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6637           *I = Op;
6638           Changed = true;
6639         }
6640       }
6641   }
6642
6643   return Changed ? CS.getInstruction() : 0;
6644 }
6645
6646 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6647 // attempt to move the cast to the arguments of the call/invoke.
6648 //
6649 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6650   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6651   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6652   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6653     return false;
6654   Function *Callee = cast<Function>(CE->getOperand(0));
6655   Instruction *Caller = CS.getInstruction();
6656
6657   // Okay, this is a cast from a function to a different type.  Unless doing so
6658   // would cause a type conversion of one of our arguments, change this call to
6659   // be a direct call with arguments casted to the appropriate types.
6660   //
6661   const FunctionType *FT = Callee->getFunctionType();
6662   const Type *OldRetTy = Caller->getType();
6663
6664   // Check to see if we are changing the return type...
6665   if (OldRetTy != FT->getReturnType()) {
6666     if (Callee->isExternal() &&
6667         !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6668           (isa<PointerType>(FT->getReturnType()) && 
6669            TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6670         && !Caller->use_empty())
6671       return false;   // Cannot transform this return value...
6672
6673     // If the callsite is an invoke instruction, and the return value is used by
6674     // a PHI node in a successor, we cannot change the return type of the call
6675     // because there is no place to put the cast instruction (without breaking
6676     // the critical edge).  Bail out in this case.
6677     if (!Caller->use_empty())
6678       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6679         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6680              UI != E; ++UI)
6681           if (PHINode *PN = dyn_cast<PHINode>(*UI))
6682             if (PN->getParent() == II->getNormalDest() ||
6683                 PN->getParent() == II->getUnwindDest())
6684               return false;
6685   }
6686
6687   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6688   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6689
6690   CallSite::arg_iterator AI = CS.arg_begin();
6691   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6692     const Type *ParamTy = FT->getParamType(i);
6693     const Type *ActTy = (*AI)->getType();
6694     ConstantInt* c = dyn_cast<ConstantInt>(*AI);
6695     //Either we can cast directly, or we can upconvert the argument
6696     bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6697       (ParamTy->isIntegral() && ActTy->isIntegral() &&
6698        ParamTy->isSigned() == ActTy->isSigned() &&
6699        ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6700       (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6701        c->getSExtValue() > 0);
6702     if (Callee->isExternal() && !isConvertible) return false;
6703   }
6704
6705   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6706       Callee->isExternal())
6707     return false;   // Do not delete arguments unless we have a function body...
6708
6709   // Okay, we decided that this is a safe thing to do: go ahead and start
6710   // inserting cast instructions as necessary...
6711   std::vector<Value*> Args;
6712   Args.reserve(NumActualArgs);
6713
6714   AI = CS.arg_begin();
6715   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6716     const Type *ParamTy = FT->getParamType(i);
6717     if ((*AI)->getType() == ParamTy) {
6718       Args.push_back(*AI);
6719     } else {
6720       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6721                                          *Caller));
6722     }
6723   }
6724
6725   // If the function takes more arguments than the call was taking, add them
6726   // now...
6727   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6728     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6729
6730   // If we are removing arguments to the function, emit an obnoxious warning...
6731   if (FT->getNumParams() < NumActualArgs)
6732     if (!FT->isVarArg()) {
6733       std::cerr << "WARNING: While resolving call to function '"
6734                 << Callee->getName() << "' arguments were dropped!\n";
6735     } else {
6736       // Add all of the arguments in their promoted form to the arg list...
6737       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6738         const Type *PTy = getPromotedType((*AI)->getType());
6739         if (PTy != (*AI)->getType()) {
6740           // Must promote to pass through va_arg area!
6741           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6742           InsertNewInstBefore(Cast, *Caller);
6743           Args.push_back(Cast);
6744         } else {
6745           Args.push_back(*AI);
6746         }
6747       }
6748     }
6749
6750   if (FT->getReturnType() == Type::VoidTy)
6751     Caller->setName("");   // Void type should not have a name...
6752
6753   Instruction *NC;
6754   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6755     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6756                         Args, Caller->getName(), Caller);
6757     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6758   } else {
6759     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6760     if (cast<CallInst>(Caller)->isTailCall())
6761       cast<CallInst>(NC)->setTailCall();
6762    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6763   }
6764
6765   // Insert a cast of the return type as necessary...
6766   Value *NV = NC;
6767   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6768     if (NV->getType() != Type::VoidTy) {
6769       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6770
6771       // If this is an invoke instruction, we should insert it after the first
6772       // non-phi, instruction in the normal successor block.
6773       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6774         BasicBlock::iterator I = II->getNormalDest()->begin();
6775         while (isa<PHINode>(I)) ++I;
6776         InsertNewInstBefore(NC, *I);
6777       } else {
6778         // Otherwise, it's a call, just insert cast right after the call instr
6779         InsertNewInstBefore(NC, *Caller);
6780       }
6781       AddUsersToWorkList(*Caller);
6782     } else {
6783       NV = UndefValue::get(Caller->getType());
6784     }
6785   }
6786
6787   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6788     Caller->replaceAllUsesWith(NV);
6789   Caller->getParent()->getInstList().erase(Caller);
6790   removeFromWorkList(Caller);
6791   return true;
6792 }
6793
6794 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
6795 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
6796 /// and a single binop.
6797 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
6798   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6799   assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
6800          isa<GetElementPtrInst>(FirstInst));
6801   unsigned Opc = FirstInst->getOpcode();
6802   const Type *LHSType = FirstInst->getOperand(0)->getType();
6803   const Type *RHSType = FirstInst->getOperand(1)->getType();
6804   
6805   // Scan to see if all operands are the same opcode, all have one use, and all
6806   // kill their operands (i.e. the operands have one use).
6807   for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
6808     Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
6809     if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
6810         // Verify type of the LHS matches so we don't fold setcc's of different
6811         // types or GEP's with different index types.
6812         I->getOperand(0)->getType() != LHSType ||
6813         I->getOperand(1)->getType() != RHSType)
6814       return 0;
6815   }
6816   
6817   // Otherwise, this is safe and profitable to transform.  Create two phi nodes.
6818   PHINode *NewLHS = new PHINode(FirstInst->getOperand(0)->getType(),
6819                                 FirstInst->getOperand(0)->getName()+".pn");
6820   NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
6821   PHINode *NewRHS = new PHINode(FirstInst->getOperand(1)->getType(),
6822                                 FirstInst->getOperand(1)->getName()+".pn");
6823   NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
6824   
6825   Value *InLHS = FirstInst->getOperand(0);
6826   NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
6827   Value *InRHS = FirstInst->getOperand(1);
6828   NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
6829   
6830   // Add all operands to the new PHsI.
6831   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6832     Value *NewInLHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6833     Value *NewInRHS = cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
6834     if (NewInLHS != InLHS) InLHS = 0;
6835     if (NewInRHS != InRHS) InRHS = 0;
6836     NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
6837     NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
6838   }
6839   
6840   Value *LHSVal;
6841   if (InLHS) {
6842     // The new PHI unions all of the same values together.  This is really
6843     // common, so we handle it intelligently here for compile-time speed.
6844     LHSVal = InLHS;
6845     delete NewLHS;
6846   } else {
6847     InsertNewInstBefore(NewLHS, PN);
6848     LHSVal = NewLHS;
6849   }
6850   Value *RHSVal;
6851   if (InRHS) {
6852     // The new PHI unions all of the same values together.  This is really
6853     // common, so we handle it intelligently here for compile-time speed.
6854     RHSVal = InRHS;
6855     delete NewRHS;
6856   } else {
6857     InsertNewInstBefore(NewRHS, PN);
6858     RHSVal = NewRHS;
6859   }
6860   
6861   if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6862     return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
6863   else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
6864     return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
6865   else {
6866     assert(isa<GetElementPtrInst>(FirstInst));
6867     return new GetElementPtrInst(LHSVal, RHSVal);
6868   }
6869 }
6870
6871 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
6872 /// of the block that defines it.  This means that it must be obvious the value
6873 /// of the load is not changed from the point of the load to the end of the
6874 /// block it is in.
6875 static bool isSafeToSinkLoad(LoadInst *L) {
6876   BasicBlock::iterator BBI = L, E = L->getParent()->end();
6877   
6878   for (++BBI; BBI != E; ++BBI)
6879     if (BBI->mayWriteToMemory())
6880       return false;
6881   return true;
6882 }
6883
6884
6885 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6886 // operator and they all are only used by the PHI, PHI together their
6887 // inputs, and do the operation once, to the result of the PHI.
6888 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6889   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6890
6891   // Scan the instruction, looking for input operations that can be folded away.
6892   // If all input operands to the phi are the same instruction (e.g. a cast from
6893   // the same type or "+42") we can pull the operation through the PHI, reducing
6894   // code size and simplifying code.
6895   Constant *ConstantOp = 0;
6896   const Type *CastSrcTy = 0;
6897   bool isVolatile = false;
6898   if (isa<CastInst>(FirstInst)) {
6899     CastSrcTy = FirstInst->getOperand(0)->getType();
6900   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6901     // Can fold binop or shift here if the RHS is a constant, otherwise call
6902     // FoldPHIArgBinOpIntoPHI.
6903     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6904     if (ConstantOp == 0)
6905       return FoldPHIArgBinOpIntoPHI(PN);
6906   } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
6907     isVolatile = LI->isVolatile();
6908     // We can't sink the load if the loaded value could be modified between the
6909     // load and the PHI.
6910     if (LI->getParent() != PN.getIncomingBlock(0) ||
6911         !isSafeToSinkLoad(LI))
6912       return 0;
6913   } else if (isa<GetElementPtrInst>(FirstInst)) {
6914     if (FirstInst->getNumOperands() == 2)
6915       return FoldPHIArgBinOpIntoPHI(PN);
6916     // Can't handle general GEPs yet.
6917     return 0;
6918   } else {
6919     return 0;  // Cannot fold this operation.
6920   }
6921
6922   // Check to see if all arguments are the same operation.
6923   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6924     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6925     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6926     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6927       return 0;
6928     if (CastSrcTy) {
6929       if (I->getOperand(0)->getType() != CastSrcTy)
6930         return 0;  // Cast operation must match.
6931     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6932       // We can't sink the load if the loaded value could be modified between the
6933       // load and the PHI.
6934       if (LI->isVolatile() != isVolatile ||
6935           LI->getParent() != PN.getIncomingBlock(i) ||
6936           !isSafeToSinkLoad(LI))
6937         return 0;
6938     } else if (I->getOperand(1) != ConstantOp) {
6939       return 0;
6940     }
6941   }
6942
6943   // Okay, they are all the same operation.  Create a new PHI node of the
6944   // correct type, and PHI together all of the LHS's of the instructions.
6945   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6946                                PN.getName()+".in");
6947   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6948
6949   Value *InVal = FirstInst->getOperand(0);
6950   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6951
6952   // Add all operands to the new PHI.
6953   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6954     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6955     if (NewInVal != InVal)
6956       InVal = 0;
6957     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6958   }
6959
6960   Value *PhiVal;
6961   if (InVal) {
6962     // The new PHI unions all of the same values together.  This is really
6963     // common, so we handle it intelligently here for compile-time speed.
6964     PhiVal = InVal;
6965     delete NewPN;
6966   } else {
6967     InsertNewInstBefore(NewPN, PN);
6968     PhiVal = NewPN;
6969   }
6970
6971   // Insert and return the new operation.
6972   if (isa<CastInst>(FirstInst))
6973     return new CastInst(PhiVal, PN.getType());
6974   else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst))
6975     return new LoadInst(PhiVal, "", isVolatile);
6976   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6977     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
6978   else
6979     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6980                          PhiVal, ConstantOp);
6981 }
6982
6983 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6984 /// that is dead.
6985 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6986   if (PN->use_empty()) return true;
6987   if (!PN->hasOneUse()) return false;
6988
6989   // Remember this node, and if we find the cycle, return.
6990   if (!PotentiallyDeadPHIs.insert(PN).second)
6991     return true;
6992
6993   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6994     return DeadPHICycle(PU, PotentiallyDeadPHIs);
6995
6996   return false;
6997 }
6998
6999 // PHINode simplification
7000 //
7001 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7002   // If LCSSA is around, don't mess with Phi nodes
7003   if (mustPreserveAnalysisID(LCSSAID)) return 0;
7004   
7005   if (Value *V = PN.hasConstantValue())
7006     return ReplaceInstUsesWith(PN, V);
7007
7008   // If the only user of this instruction is a cast instruction, and all of the
7009   // incoming values are constants, change this PHI to merge together the casted
7010   // constants.
7011   if (PN.hasOneUse())
7012     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
7013       if (CI->getType() != PN.getType()) {  // noop casts will be folded
7014         bool AllConstant = true;
7015         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
7016           if (!isa<Constant>(PN.getIncomingValue(i))) {
7017             AllConstant = false;
7018             break;
7019           }
7020         if (AllConstant) {
7021           // Make a new PHI with all casted values.
7022           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
7023           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
7024             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
7025             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
7026                              PN.getIncomingBlock(i));
7027           }
7028
7029           // Update the cast instruction.
7030           CI->setOperand(0, New);
7031           WorkList.push_back(CI);    // revisit the cast instruction to fold.
7032           WorkList.push_back(New);   // Make sure to revisit the new Phi
7033           return &PN;                // PN is now dead!
7034         }
7035       }
7036
7037   // If all PHI operands are the same operation, pull them through the PHI,
7038   // reducing code size.
7039   if (isa<Instruction>(PN.getIncomingValue(0)) &&
7040       PN.getIncomingValue(0)->hasOneUse())
7041     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7042       return Result;
7043
7044   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
7045   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7046   // PHI)... break the cycle.
7047   if (PN.hasOneUse())
7048     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
7049       std::set<PHINode*> PotentiallyDeadPHIs;
7050       PotentiallyDeadPHIs.insert(&PN);
7051       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7052         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7053     }
7054
7055   return 0;
7056 }
7057
7058 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
7059                                       Instruction *InsertPoint,
7060                                       InstCombiner *IC) {
7061   unsigned PS = IC->getTargetData().getPointerSize();
7062   const Type *VTy = V->getType();
7063   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
7064     // We must insert a cast to ensure we sign-extend.
7065     V = IC->InsertCastBefore(V, VTy->getSignedVersion(), *InsertPoint);
7066   return IC->InsertCastBefore(V, DTy, *InsertPoint);
7067 }
7068
7069
7070 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7071   Value *PtrOp = GEP.getOperand(0);
7072   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
7073   // If so, eliminate the noop.
7074   if (GEP.getNumOperands() == 1)
7075     return ReplaceInstUsesWith(GEP, PtrOp);
7076
7077   if (isa<UndefValue>(GEP.getOperand(0)))
7078     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7079
7080   bool HasZeroPointerIndex = false;
7081   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7082     HasZeroPointerIndex = C->isNullValue();
7083
7084   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7085     return ReplaceInstUsesWith(GEP, PtrOp);
7086
7087   // Eliminate unneeded casts for indices.
7088   bool MadeChange = false;
7089   gep_type_iterator GTI = gep_type_begin(GEP);
7090   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7091     if (isa<SequentialType>(*GTI)) {
7092       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7093         Value *Src = CI->getOperand(0);
7094         const Type *SrcTy = Src->getType();
7095         const Type *DestTy = CI->getType();
7096         if (Src->getType()->isInteger()) {
7097           if (SrcTy->getPrimitiveSizeInBits() ==
7098                        DestTy->getPrimitiveSizeInBits()) {
7099             // We can always eliminate a cast from ulong or long to the other.
7100             // We can always eliminate a cast from uint to int or the other on
7101             // 32-bit pointer platforms.
7102             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
7103               MadeChange = true;
7104               GEP.setOperand(i, Src);
7105             }
7106           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
7107                      SrcTy->getPrimitiveSize() == 4) {
7108             // We can always eliminate a cast from int to [u]long.  We can
7109             // eliminate a cast from uint to [u]long iff the target is a 32-bit
7110             // pointer target.
7111             if (SrcTy->isSigned() ||
7112                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7113               MadeChange = true;
7114               GEP.setOperand(i, Src);
7115             }
7116           }
7117         }
7118       }
7119       // If we are using a wider index than needed for this platform, shrink it
7120       // to what we need.  If the incoming value needs a cast instruction,
7121       // insert it.  This explicit cast can make subsequent optimizations more
7122       // obvious.
7123       Value *Op = GEP.getOperand(i);
7124       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
7125         if (Constant *C = dyn_cast<Constant>(Op)) {
7126           GEP.setOperand(i, ConstantExpr::getCast(C,
7127                                      TD->getIntPtrType()->getSignedVersion()));
7128           MadeChange = true;
7129         } else {
7130           Op = InsertCastBefore(Op, TD->getIntPtrType(), GEP);
7131           GEP.setOperand(i, Op);
7132           MadeChange = true;
7133         }
7134
7135       // If this is a constant idx, make sure to canonicalize it to be a signed
7136       // operand, otherwise CSE and other optimizations are pessimized.
7137       if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
7138         if (CUI->getType()->isUnsigned()) {
7139           GEP.setOperand(i, 
7140             ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
7141           MadeChange = true;
7142         }
7143     }
7144   if (MadeChange) return &GEP;
7145
7146   // Combine Indices - If the source pointer to this getelementptr instruction
7147   // is a getelementptr instruction, combine the indices of the two
7148   // getelementptr instructions into a single instruction.
7149   //
7150   std::vector<Value*> SrcGEPOperands;
7151   if (User *Src = dyn_castGetElementPtr(PtrOp))
7152     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7153
7154   if (!SrcGEPOperands.empty()) {
7155     // Note that if our source is a gep chain itself that we wait for that
7156     // chain to be resolved before we perform this transformation.  This
7157     // avoids us creating a TON of code in some cases.
7158     //
7159     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7160         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7161       return 0;   // Wait until our source is folded to completion.
7162
7163     std::vector<Value *> Indices;
7164
7165     // Find out whether the last index in the source GEP is a sequential idx.
7166     bool EndsWithSequential = false;
7167     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7168            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7169       EndsWithSequential = !isa<StructType>(*I);
7170
7171     // Can we combine the two pointer arithmetics offsets?
7172     if (EndsWithSequential) {
7173       // Replace: gep (gep %P, long B), long A, ...
7174       // With:    T = long A+B; gep %P, T, ...
7175       //
7176       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7177       if (SO1 == Constant::getNullValue(SO1->getType())) {
7178         Sum = GO1;
7179       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7180         Sum = SO1;
7181       } else {
7182         // If they aren't the same type, convert both to an integer of the
7183         // target's pointer size.
7184         if (SO1->getType() != GO1->getType()) {
7185           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7186             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
7187           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7188             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
7189           } else {
7190             unsigned PS = TD->getPointerSize();
7191             if (SO1->getType()->getPrimitiveSize() == PS) {
7192               // Convert GO1 to SO1's type.
7193               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
7194
7195             } else if (GO1->getType()->getPrimitiveSize() == PS) {
7196               // Convert SO1 to GO1's type.
7197               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
7198             } else {
7199               const Type *PT = TD->getIntPtrType();
7200               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
7201               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
7202             }
7203           }
7204         }
7205         if (isa<Constant>(SO1) && isa<Constant>(GO1))
7206           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7207         else {
7208           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7209           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7210         }
7211       }
7212
7213       // Recycle the GEP we already have if possible.
7214       if (SrcGEPOperands.size() == 2) {
7215         GEP.setOperand(0, SrcGEPOperands[0]);
7216         GEP.setOperand(1, Sum);
7217         return &GEP;
7218       } else {
7219         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7220                        SrcGEPOperands.end()-1);
7221         Indices.push_back(Sum);
7222         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7223       }
7224     } else if (isa<Constant>(*GEP.idx_begin()) &&
7225                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7226                SrcGEPOperands.size() != 1) {
7227       // Otherwise we can do the fold if the first index of the GEP is a zero
7228       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7229                      SrcGEPOperands.end());
7230       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7231     }
7232
7233     if (!Indices.empty())
7234       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7235
7236   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7237     // GEP of global variable.  If all of the indices for this GEP are
7238     // constants, we can promote this to a constexpr instead of an instruction.
7239
7240     // Scan for nonconstants...
7241     std::vector<Constant*> Indices;
7242     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7243     for (; I != E && isa<Constant>(*I); ++I)
7244       Indices.push_back(cast<Constant>(*I));
7245
7246     if (I == E) {  // If they are all constants...
7247       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
7248
7249       // Replace all uses of the GEP with the new constexpr...
7250       return ReplaceInstUsesWith(GEP, CE);
7251     }
7252   } else if (Value *X = isCast(PtrOp)) {  // Is the operand a cast?
7253     if (!isa<PointerType>(X->getType())) {
7254       // Not interesting.  Source pointer must be a cast from pointer.
7255     } else if (HasZeroPointerIndex) {
7256       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7257       // into     : GEP [10 x ubyte]* X, long 0, ...
7258       //
7259       // This occurs when the program declares an array extern like "int X[];"
7260       //
7261       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7262       const PointerType *XTy = cast<PointerType>(X->getType());
7263       if (const ArrayType *XATy =
7264           dyn_cast<ArrayType>(XTy->getElementType()))
7265         if (const ArrayType *CATy =
7266             dyn_cast<ArrayType>(CPTy->getElementType()))
7267           if (CATy->getElementType() == XATy->getElementType()) {
7268             // At this point, we know that the cast source type is a pointer
7269             // to an array of the same type as the destination pointer
7270             // array.  Because the array type is never stepped over (there
7271             // is a leading zero) we can fold the cast into this GEP.
7272             GEP.setOperand(0, X);
7273             return &GEP;
7274           }
7275     } else if (GEP.getNumOperands() == 2) {
7276       // Transform things like:
7277       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7278       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7279       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7280       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7281       if (isa<ArrayType>(SrcElTy) &&
7282           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7283           TD->getTypeSize(ResElTy)) {
7284         Value *V = InsertNewInstBefore(
7285                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7286                                      GEP.getOperand(1), GEP.getName()), GEP);
7287         return new CastInst(V, GEP.getType());
7288       }
7289       
7290       // Transform things like:
7291       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7292       //   (where tmp = 8*tmp2) into:
7293       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7294       
7295       if (isa<ArrayType>(SrcElTy) &&
7296           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7297         uint64_t ArrayEltSize =
7298             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7299         
7300         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
7301         // allow either a mul, shift, or constant here.
7302         Value *NewIdx = 0;
7303         ConstantInt *Scale = 0;
7304         if (ArrayEltSize == 1) {
7305           NewIdx = GEP.getOperand(1);
7306           Scale = ConstantInt::get(NewIdx->getType(), 1);
7307         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7308           NewIdx = ConstantInt::get(CI->getType(), 1);
7309           Scale = CI;
7310         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7311           if (Inst->getOpcode() == Instruction::Shl &&
7312               isa<ConstantInt>(Inst->getOperand(1))) {
7313             unsigned ShAmt =
7314               cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7315             if (Inst->getType()->isSigned())
7316               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7317             else
7318               Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7319             NewIdx = Inst->getOperand(0);
7320           } else if (Inst->getOpcode() == Instruction::Mul &&
7321                      isa<ConstantInt>(Inst->getOperand(1))) {
7322             Scale = cast<ConstantInt>(Inst->getOperand(1));
7323             NewIdx = Inst->getOperand(0);
7324           }
7325         }
7326
7327         // If the index will be to exactly the right offset with the scale taken
7328         // out, perform the transformation.
7329         if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7330           if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7331             Scale = ConstantInt::get(Scale->getType(),
7332                                       Scale->getZExtValue() / ArrayEltSize);
7333           if (Scale->getZExtValue() != 1) {
7334             Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7335             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7336             NewIdx = InsertNewInstBefore(Sc, GEP);
7337           }
7338
7339           // Insert the new GEP instruction.
7340           Instruction *Idx =
7341             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7342                                   NewIdx, GEP.getName());
7343           Idx = InsertNewInstBefore(Idx, GEP);
7344           return new CastInst(Idx, GEP.getType());
7345         }
7346       }
7347     }
7348   }
7349
7350   return 0;
7351 }
7352
7353 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7354   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7355   if (AI.isArrayAllocation())    // Check C != 1
7356     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7357       const Type *NewTy = 
7358         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7359       AllocationInst *New = 0;
7360
7361       // Create and insert the replacement instruction...
7362       if (isa<MallocInst>(AI))
7363         New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7364       else {
7365         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7366         New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7367       }
7368
7369       InsertNewInstBefore(New, AI);
7370
7371       // Scan to the end of the allocation instructions, to skip over a block of
7372       // allocas if possible...
7373       //
7374       BasicBlock::iterator It = New;
7375       while (isa<AllocationInst>(*It)) ++It;
7376
7377       // Now that I is pointing to the first non-allocation-inst in the block,
7378       // insert our getelementptr instruction...
7379       //
7380       Value *NullIdx = Constant::getNullValue(Type::IntTy);
7381       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7382                                        New->getName()+".sub", It);
7383
7384       // Now make everything use the getelementptr instead of the original
7385       // allocation.
7386       return ReplaceInstUsesWith(AI, V);
7387     } else if (isa<UndefValue>(AI.getArraySize())) {
7388       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7389     }
7390
7391   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7392   // Note that we only do this for alloca's, because malloc should allocate and
7393   // return a unique pointer, even for a zero byte allocation.
7394   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7395       TD->getTypeSize(AI.getAllocatedType()) == 0)
7396     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7397
7398   return 0;
7399 }
7400
7401 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7402   Value *Op = FI.getOperand(0);
7403
7404   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7405   if (CastInst *CI = dyn_cast<CastInst>(Op))
7406     if (isa<PointerType>(CI->getOperand(0)->getType())) {
7407       FI.setOperand(0, CI->getOperand(0));
7408       return &FI;
7409     }
7410
7411   // free undef -> unreachable.
7412   if (isa<UndefValue>(Op)) {
7413     // Insert a new store to null because we cannot modify the CFG here.
7414     new StoreInst(ConstantBool::getTrue(),
7415                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7416     return EraseInstFromFunction(FI);
7417   }
7418
7419   // If we have 'free null' delete the instruction.  This can happen in stl code
7420   // when lots of inlining happens.
7421   if (isa<ConstantPointerNull>(Op))
7422     return EraseInstFromFunction(FI);
7423
7424   return 0;
7425 }
7426
7427
7428 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7429 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7430   User *CI = cast<User>(LI.getOperand(0));
7431   Value *CastOp = CI->getOperand(0);
7432
7433   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7434   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7435     const Type *SrcPTy = SrcTy->getElementType();
7436
7437     if (DestPTy->isInteger() || isa<PointerType>(DestPTy) || 
7438         isa<PackedType>(DestPTy)) {
7439       // If the source is an array, the code below will not succeed.  Check to
7440       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7441       // constants.
7442       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7443         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7444           if (ASrcTy->getNumElements() != 0) {
7445             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7446             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7447             SrcTy = cast<PointerType>(CastOp->getType());
7448             SrcPTy = SrcTy->getElementType();
7449           }
7450
7451       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) || 
7452            isa<PackedType>(SrcPTy)) &&
7453           // Do not allow turning this into a load of an integer, which is then
7454           // casted to a pointer, this pessimizes pointer analysis a lot.
7455           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7456           IC.getTargetData().getTypeSize(SrcPTy) ==
7457                IC.getTargetData().getTypeSize(DestPTy)) {
7458
7459         // Okay, we are casting from one integer or pointer type to another of
7460         // the same size.  Instead of casting the pointer before the load, cast
7461         // the result of the loaded value.
7462         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7463                                                              CI->getName(),
7464                                                          LI.isVolatile()),LI);
7465         // Now cast the result of the load.
7466         return new CastInst(NewLoad, LI.getType());
7467       }
7468     }
7469   }
7470   return 0;
7471 }
7472
7473 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7474 /// from this value cannot trap.  If it is not obviously safe to load from the
7475 /// specified pointer, we do a quick local scan of the basic block containing
7476 /// ScanFrom, to determine if the address is already accessed.
7477 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7478   // If it is an alloca or global variable, it is always safe to load from.
7479   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7480
7481   // Otherwise, be a little bit agressive by scanning the local block where we
7482   // want to check to see if the pointer is already being loaded or stored
7483   // from/to.  If so, the previous load or store would have already trapped,
7484   // so there is no harm doing an extra load (also, CSE will later eliminate
7485   // the load entirely).
7486   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7487
7488   while (BBI != E) {
7489     --BBI;
7490
7491     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7492       if (LI->getOperand(0) == V) return true;
7493     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7494       if (SI->getOperand(1) == V) return true;
7495
7496   }
7497   return false;
7498 }
7499
7500 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7501   Value *Op = LI.getOperand(0);
7502
7503   // load (cast X) --> cast (load X) iff safe
7504   if (CastInst *CI = dyn_cast<CastInst>(Op))
7505     if (Instruction *Res = InstCombineLoadCast(*this, LI))
7506       return Res;
7507
7508   // None of the following transforms are legal for volatile loads.
7509   if (LI.isVolatile()) return 0;
7510   
7511   if (&LI.getParent()->front() != &LI) {
7512     BasicBlock::iterator BBI = &LI; --BBI;
7513     // If the instruction immediately before this is a store to the same
7514     // address, do a simple form of store->load forwarding.
7515     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7516       if (SI->getOperand(1) == LI.getOperand(0))
7517         return ReplaceInstUsesWith(LI, SI->getOperand(0));
7518     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7519       if (LIB->getOperand(0) == LI.getOperand(0))
7520         return ReplaceInstUsesWith(LI, LIB);
7521   }
7522
7523   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7524     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7525         isa<UndefValue>(GEPI->getOperand(0))) {
7526       // Insert a new store to null instruction before the load to indicate
7527       // that this code is not reachable.  We do this instead of inserting
7528       // an unreachable instruction directly because we cannot modify the
7529       // CFG.
7530       new StoreInst(UndefValue::get(LI.getType()),
7531                     Constant::getNullValue(Op->getType()), &LI);
7532       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7533     }
7534
7535   if (Constant *C = dyn_cast<Constant>(Op)) {
7536     // load null/undef -> undef
7537     if ((C->isNullValue() || isa<UndefValue>(C))) {
7538       // Insert a new store to null instruction before the load to indicate that
7539       // this code is not reachable.  We do this instead of inserting an
7540       // unreachable instruction directly because we cannot modify the CFG.
7541       new StoreInst(UndefValue::get(LI.getType()),
7542                     Constant::getNullValue(Op->getType()), &LI);
7543       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7544     }
7545
7546     // Instcombine load (constant global) into the value loaded.
7547     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7548       if (GV->isConstant() && !GV->isExternal())
7549         return ReplaceInstUsesWith(LI, GV->getInitializer());
7550
7551     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7552     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7553       if (CE->getOpcode() == Instruction::GetElementPtr) {
7554         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7555           if (GV->isConstant() && !GV->isExternal())
7556             if (Constant *V = 
7557                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7558               return ReplaceInstUsesWith(LI, V);
7559         if (CE->getOperand(0)->isNullValue()) {
7560           // Insert a new store to null instruction before the load to indicate
7561           // that this code is not reachable.  We do this instead of inserting
7562           // an unreachable instruction directly because we cannot modify the
7563           // CFG.
7564           new StoreInst(UndefValue::get(LI.getType()),
7565                         Constant::getNullValue(Op->getType()), &LI);
7566           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7567         }
7568
7569       } else if (CE->getOpcode() == Instruction::Cast) {
7570         if (Instruction *Res = InstCombineLoadCast(*this, LI))
7571           return Res;
7572       }
7573   }
7574
7575   if (Op->hasOneUse()) {
7576     // Change select and PHI nodes to select values instead of addresses: this
7577     // helps alias analysis out a lot, allows many others simplifications, and
7578     // exposes redundancy in the code.
7579     //
7580     // Note that we cannot do the transformation unless we know that the
7581     // introduced loads cannot trap!  Something like this is valid as long as
7582     // the condition is always false: load (select bool %C, int* null, int* %G),
7583     // but it would not be valid if we transformed it to load from null
7584     // unconditionally.
7585     //
7586     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7587       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
7588       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7589           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7590         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7591                                      SI->getOperand(1)->getName()+".val"), LI);
7592         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7593                                      SI->getOperand(2)->getName()+".val"), LI);
7594         return new SelectInst(SI->getCondition(), V1, V2);
7595       }
7596
7597       // load (select (cond, null, P)) -> load P
7598       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7599         if (C->isNullValue()) {
7600           LI.setOperand(0, SI->getOperand(2));
7601           return &LI;
7602         }
7603
7604       // load (select (cond, P, null)) -> load P
7605       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7606         if (C->isNullValue()) {
7607           LI.setOperand(0, SI->getOperand(1));
7608           return &LI;
7609         }
7610     }
7611   }
7612   return 0;
7613 }
7614
7615 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7616 /// when possible.
7617 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7618   User *CI = cast<User>(SI.getOperand(1));
7619   Value *CastOp = CI->getOperand(0);
7620
7621   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7622   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7623     const Type *SrcPTy = SrcTy->getElementType();
7624
7625     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7626       // If the source is an array, the code below will not succeed.  Check to
7627       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
7628       // constants.
7629       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7630         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7631           if (ASrcTy->getNumElements() != 0) {
7632             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7633             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7634             SrcTy = cast<PointerType>(CastOp->getType());
7635             SrcPTy = SrcTy->getElementType();
7636           }
7637
7638       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7639           IC.getTargetData().getTypeSize(SrcPTy) ==
7640                IC.getTargetData().getTypeSize(DestPTy)) {
7641
7642         // Okay, we are casting from one integer or pointer type to another of
7643         // the same size.  Instead of casting the pointer before the store, cast
7644         // the value to be stored.
7645         Value *NewCast;
7646         if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7647           NewCast = ConstantExpr::getCast(C, SrcPTy);
7648         else
7649           NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7650                                                         SrcPTy,
7651                                          SI.getOperand(0)->getName()+".c"), SI);
7652
7653         return new StoreInst(NewCast, CastOp);
7654       }
7655     }
7656   }
7657   return 0;
7658 }
7659
7660 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7661   Value *Val = SI.getOperand(0);
7662   Value *Ptr = SI.getOperand(1);
7663
7664   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
7665     EraseInstFromFunction(SI);
7666     ++NumCombined;
7667     return 0;
7668   }
7669
7670   // Do really simple DSE, to catch cases where there are several consequtive
7671   // stores to the same location, separated by a few arithmetic operations. This
7672   // situation often occurs with bitfield accesses.
7673   BasicBlock::iterator BBI = &SI;
7674   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7675        --ScanInsts) {
7676     --BBI;
7677     
7678     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7679       // Prev store isn't volatile, and stores to the same location?
7680       if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7681         ++NumDeadStore;
7682         ++BBI;
7683         EraseInstFromFunction(*PrevSI);
7684         continue;
7685       }
7686       break;
7687     }
7688     
7689     // If this is a load, we have to stop.  However, if the loaded value is from
7690     // the pointer we're loading and is producing the pointer we're storing,
7691     // then *this* store is dead (X = load P; store X -> P).
7692     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7693       if (LI == Val && LI->getOperand(0) == Ptr) {
7694         EraseInstFromFunction(SI);
7695         ++NumCombined;
7696         return 0;
7697       }
7698       // Otherwise, this is a load from some other location.  Stores before it
7699       // may not be dead.
7700       break;
7701     }
7702     
7703     // Don't skip over loads or things that can modify memory.
7704     if (BBI->mayWriteToMemory())
7705       break;
7706   }
7707   
7708   
7709   if (SI.isVolatile()) return 0;  // Don't hack volatile stores.
7710
7711   // store X, null    -> turns into 'unreachable' in SimplifyCFG
7712   if (isa<ConstantPointerNull>(Ptr)) {
7713     if (!isa<UndefValue>(Val)) {
7714       SI.setOperand(0, UndefValue::get(Val->getType()));
7715       if (Instruction *U = dyn_cast<Instruction>(Val))
7716         WorkList.push_back(U);  // Dropped a use.
7717       ++NumCombined;
7718     }
7719     return 0;  // Do not modify these!
7720   }
7721
7722   // store undef, Ptr -> noop
7723   if (isa<UndefValue>(Val)) {
7724     EraseInstFromFunction(SI);
7725     ++NumCombined;
7726     return 0;
7727   }
7728
7729   // If the pointer destination is a cast, see if we can fold the cast into the
7730   // source instead.
7731   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7732     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7733       return Res;
7734   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7735     if (CE->getOpcode() == Instruction::Cast)
7736       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7737         return Res;
7738
7739   
7740   // If this store is the last instruction in the basic block, and if the block
7741   // ends with an unconditional branch, try to move it to the successor block.
7742   BBI = &SI; ++BBI;
7743   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7744     if (BI->isUnconditional()) {
7745       // Check to see if the successor block has exactly two incoming edges.  If
7746       // so, see if the other predecessor contains a store to the same location.
7747       // if so, insert a PHI node (if needed) and move the stores down.
7748       BasicBlock *Dest = BI->getSuccessor(0);
7749
7750       pred_iterator PI = pred_begin(Dest);
7751       BasicBlock *Other = 0;
7752       if (*PI != BI->getParent())
7753         Other = *PI;
7754       ++PI;
7755       if (PI != pred_end(Dest)) {
7756         if (*PI != BI->getParent())
7757           if (Other)
7758             Other = 0;
7759           else
7760             Other = *PI;
7761         if (++PI != pred_end(Dest))
7762           Other = 0;
7763       }
7764       if (Other) {  // If only one other pred...
7765         BBI = Other->getTerminator();
7766         // Make sure this other block ends in an unconditional branch and that
7767         // there is an instruction before the branch.
7768         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7769             BBI != Other->begin()) {
7770           --BBI;
7771           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7772           
7773           // If this instruction is a store to the same location.
7774           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7775             // Okay, we know we can perform this transformation.  Insert a PHI
7776             // node now if we need it.
7777             Value *MergedVal = OtherStore->getOperand(0);
7778             if (MergedVal != SI.getOperand(0)) {
7779               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7780               PN->reserveOperandSpace(2);
7781               PN->addIncoming(SI.getOperand(0), SI.getParent());
7782               PN->addIncoming(OtherStore->getOperand(0), Other);
7783               MergedVal = InsertNewInstBefore(PN, Dest->front());
7784             }
7785             
7786             // Advance to a place where it is safe to insert the new store and
7787             // insert it.
7788             BBI = Dest->begin();
7789             while (isa<PHINode>(BBI)) ++BBI;
7790             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7791                                               OtherStore->isVolatile()), *BBI);
7792
7793             // Nuke the old stores.
7794             EraseInstFromFunction(SI);
7795             EraseInstFromFunction(*OtherStore);
7796             ++NumCombined;
7797             return 0;
7798           }
7799         }
7800       }
7801     }
7802   
7803   return 0;
7804 }
7805
7806
7807 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7808   // Change br (not X), label True, label False to: br X, label False, True
7809   Value *X = 0;
7810   BasicBlock *TrueDest;
7811   BasicBlock *FalseDest;
7812   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7813       !isa<Constant>(X)) {
7814     // Swap Destinations and condition...
7815     BI.setCondition(X);
7816     BI.setSuccessor(0, FalseDest);
7817     BI.setSuccessor(1, TrueDest);
7818     return &BI;
7819   }
7820
7821   // Cannonicalize setne -> seteq
7822   Instruction::BinaryOps Op; Value *Y;
7823   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7824                       TrueDest, FalseDest)))
7825     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7826          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7827       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7828       std::string Name = I->getName(); I->setName("");
7829       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7830       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
7831       // Swap Destinations and condition...
7832       BI.setCondition(NewSCC);
7833       BI.setSuccessor(0, FalseDest);
7834       BI.setSuccessor(1, TrueDest);
7835       removeFromWorkList(I);
7836       I->getParent()->getInstList().erase(I);
7837       WorkList.push_back(cast<Instruction>(NewSCC));
7838       return &BI;
7839     }
7840
7841   return 0;
7842 }
7843
7844 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7845   Value *Cond = SI.getCondition();
7846   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7847     if (I->getOpcode() == Instruction::Add)
7848       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7849         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7850         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7851           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7852                                                 AddRHS));
7853         SI.setOperand(0, I->getOperand(0));
7854         WorkList.push_back(I);
7855         return &SI;
7856       }
7857   }
7858   return 0;
7859 }
7860
7861 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7862 /// is to leave as a vector operation.
7863 static bool CheapToScalarize(Value *V, bool isConstant) {
7864   if (isa<ConstantAggregateZero>(V)) 
7865     return true;
7866   if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7867     if (isConstant) return true;
7868     // If all elts are the same, we can extract.
7869     Constant *Op0 = C->getOperand(0);
7870     for (unsigned i = 1; i < C->getNumOperands(); ++i)
7871       if (C->getOperand(i) != Op0)
7872         return false;
7873     return true;
7874   }
7875   Instruction *I = dyn_cast<Instruction>(V);
7876   if (!I) return false;
7877   
7878   // Insert element gets simplified to the inserted element or is deleted if
7879   // this is constant idx extract element and its a constant idx insertelt.
7880   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7881       isa<ConstantInt>(I->getOperand(2)))
7882     return true;
7883   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7884     return true;
7885   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7886     if (BO->hasOneUse() &&
7887         (CheapToScalarize(BO->getOperand(0), isConstant) ||
7888          CheapToScalarize(BO->getOperand(1), isConstant)))
7889       return true;
7890   
7891   return false;
7892 }
7893
7894 /// getShuffleMask - Read and decode a shufflevector mask.  It turns undef
7895 /// elements into values that are larger than the #elts in the input.
7896 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7897   unsigned NElts = SVI->getType()->getNumElements();
7898   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7899     return std::vector<unsigned>(NElts, 0);
7900   if (isa<UndefValue>(SVI->getOperand(2)))
7901     return std::vector<unsigned>(NElts, 2*NElts);
7902
7903   std::vector<unsigned> Result;
7904   const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7905   for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7906     if (isa<UndefValue>(CP->getOperand(i)))
7907       Result.push_back(NElts*2);  // undef -> 8
7908     else
7909       Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
7910   return Result;
7911 }
7912
7913 /// FindScalarElement - Given a vector and an element number, see if the scalar
7914 /// value is already around as a register, for example if it were inserted then
7915 /// extracted from the vector.
7916 static Value *FindScalarElement(Value *V, unsigned EltNo) {
7917   assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7918   const PackedType *PTy = cast<PackedType>(V->getType());
7919   unsigned Width = PTy->getNumElements();
7920   if (EltNo >= Width)  // Out of range access.
7921     return UndefValue::get(PTy->getElementType());
7922   
7923   if (isa<UndefValue>(V))
7924     return UndefValue::get(PTy->getElementType());
7925   else if (isa<ConstantAggregateZero>(V))
7926     return Constant::getNullValue(PTy->getElementType());
7927   else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7928     return CP->getOperand(EltNo);
7929   else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7930     // If this is an insert to a variable element, we don't know what it is.
7931     if (!isa<ConstantInt>(III->getOperand(2))) 
7932       return 0;
7933     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
7934     
7935     // If this is an insert to the element we are looking for, return the
7936     // inserted value.
7937     if (EltNo == IIElt) 
7938       return III->getOperand(1);
7939     
7940     // Otherwise, the insertelement doesn't modify the value, recurse on its
7941     // vector input.
7942     return FindScalarElement(III->getOperand(0), EltNo);
7943   } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7944     unsigned InEl = getShuffleMask(SVI)[EltNo];
7945     if (InEl < Width)
7946       return FindScalarElement(SVI->getOperand(0), InEl);
7947     else if (InEl < Width*2)
7948       return FindScalarElement(SVI->getOperand(1), InEl - Width);
7949     else
7950       return UndefValue::get(PTy->getElementType());
7951   }
7952   
7953   // Otherwise, we don't know.
7954   return 0;
7955 }
7956
7957 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
7958
7959   // If packed val is undef, replace extract with scalar undef.
7960   if (isa<UndefValue>(EI.getOperand(0)))
7961     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7962
7963   // If packed val is constant 0, replace extract with scalar 0.
7964   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7965     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7966   
7967   if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7968     // If packed val is constant with uniform operands, replace EI
7969     // with that operand
7970     Constant *op0 = C->getOperand(0);
7971     for (unsigned i = 1; i < C->getNumOperands(); ++i)
7972       if (C->getOperand(i) != op0) {
7973         op0 = 0; 
7974         break;
7975       }
7976     if (op0)
7977       return ReplaceInstUsesWith(EI, op0);
7978   }
7979   
7980   // If extracting a specified index from the vector, see if we can recursively
7981   // find a previously computed scalar that was inserted into the vector.
7982   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7983     // This instruction only demands the single element from the input vector.
7984     // If the input vector has a single use, simplify it based on this use
7985     // property.
7986     uint64_t IndexVal = IdxC->getZExtValue();
7987     if (EI.getOperand(0)->hasOneUse()) {
7988       uint64_t UndefElts;
7989       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
7990                                                 1 << IndexVal,
7991                                                 UndefElts)) {
7992         EI.setOperand(0, V);
7993         return &EI;
7994       }
7995     }
7996     
7997     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
7998       return ReplaceInstUsesWith(EI, Elt);
7999   }
8000   
8001   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8002     if (I->hasOneUse()) {
8003       // Push extractelement into predecessor operation if legal and
8004       // profitable to do so
8005       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8006         bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8007         if (CheapToScalarize(BO, isConstantElt)) {
8008           ExtractElementInst *newEI0 = 
8009             new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8010                                    EI.getName()+".lhs");
8011           ExtractElementInst *newEI1 =
8012             new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8013                                    EI.getName()+".rhs");
8014           InsertNewInstBefore(newEI0, EI);
8015           InsertNewInstBefore(newEI1, EI);
8016           return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8017         }
8018       } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8019         Value *Ptr = InsertCastBefore(I->getOperand(0),
8020                                       PointerType::get(EI.getType()), EI);
8021         GetElementPtrInst *GEP = 
8022           new GetElementPtrInst(Ptr, EI.getOperand(1),
8023                                 I->getName() + ".gep");
8024         InsertNewInstBefore(GEP, EI);
8025         return new LoadInst(GEP);
8026       }
8027     }
8028     if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8029       // Extracting the inserted element?
8030       if (IE->getOperand(2) == EI.getOperand(1))
8031         return ReplaceInstUsesWith(EI, IE->getOperand(1));
8032       // If the inserted and extracted elements are constants, they must not
8033       // be the same value, extract from the pre-inserted value instead.
8034       if (isa<Constant>(IE->getOperand(2)) &&
8035           isa<Constant>(EI.getOperand(1))) {
8036         AddUsesToWorkList(EI);
8037         EI.setOperand(0, IE->getOperand(0));
8038         return &EI;
8039       }
8040     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8041       // If this is extracting an element from a shufflevector, figure out where
8042       // it came from and extract from the appropriate input element instead.
8043       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8044         unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8045         Value *Src;
8046         if (SrcIdx < SVI->getType()->getNumElements())
8047           Src = SVI->getOperand(0);
8048         else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8049           SrcIdx -= SVI->getType()->getNumElements();
8050           Src = SVI->getOperand(1);
8051         } else {
8052           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8053         }
8054         return new ExtractElementInst(Src, SrcIdx);
8055       }
8056     }
8057   }
8058   return 0;
8059 }
8060
8061 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8062 /// elements from either LHS or RHS, return the shuffle mask and true. 
8063 /// Otherwise, return false.
8064 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8065                                          std::vector<Constant*> &Mask) {
8066   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8067          "Invalid CollectSingleShuffleElements");
8068   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8069
8070   if (isa<UndefValue>(V)) {
8071     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8072     return true;
8073   } else if (V == LHS) {
8074     for (unsigned i = 0; i != NumElts; ++i)
8075       Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8076     return true;
8077   } else if (V == RHS) {
8078     for (unsigned i = 0; i != NumElts; ++i)
8079       Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
8080     return true;
8081   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8082     // If this is an insert of an extract from some other vector, include it.
8083     Value *VecOp    = IEI->getOperand(0);
8084     Value *ScalarOp = IEI->getOperand(1);
8085     Value *IdxOp    = IEI->getOperand(2);
8086     
8087     if (!isa<ConstantInt>(IdxOp))
8088       return false;
8089     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8090     
8091     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
8092       // Okay, we can handle this if the vector we are insertinting into is
8093       // transitively ok.
8094       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8095         // If so, update the mask to reflect the inserted undef.
8096         Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
8097         return true;
8098       }      
8099     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8100       if (isa<ConstantInt>(EI->getOperand(1)) &&
8101           EI->getOperand(0)->getType() == V->getType()) {
8102         unsigned ExtractedIdx =
8103           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8104         
8105         // This must be extracting from either LHS or RHS.
8106         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8107           // Okay, we can handle this if the vector we are insertinting into is
8108           // transitively ok.
8109           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8110             // If so, update the mask to reflect the inserted value.
8111             if (EI->getOperand(0) == LHS) {
8112               Mask[InsertedIdx & (NumElts-1)] = 
8113                  ConstantInt::get(Type::UIntTy, ExtractedIdx);
8114             } else {
8115               assert(EI->getOperand(0) == RHS);
8116               Mask[InsertedIdx & (NumElts-1)] = 
8117                 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
8118               
8119             }
8120             return true;
8121           }
8122         }
8123       }
8124     }
8125   }
8126   // TODO: Handle shufflevector here!
8127   
8128   return false;
8129 }
8130
8131 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8132 /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
8133 /// that computes V and the LHS value of the shuffle.
8134 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8135                                      Value *&RHS) {
8136   assert(isa<PackedType>(V->getType()) && 
8137          (RHS == 0 || V->getType() == RHS->getType()) &&
8138          "Invalid shuffle!");
8139   unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8140
8141   if (isa<UndefValue>(V)) {
8142     Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
8143     return V;
8144   } else if (isa<ConstantAggregateZero>(V)) {
8145     Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
8146     return V;
8147   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8148     // If this is an insert of an extract from some other vector, include it.
8149     Value *VecOp    = IEI->getOperand(0);
8150     Value *ScalarOp = IEI->getOperand(1);
8151     Value *IdxOp    = IEI->getOperand(2);
8152     
8153     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8154       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8155           EI->getOperand(0)->getType() == V->getType()) {
8156         unsigned ExtractedIdx =
8157           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8158         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8159         
8160         // Either the extracted from or inserted into vector must be RHSVec,
8161         // otherwise we'd end up with a shuffle of three inputs.
8162         if (EI->getOperand(0) == RHS || RHS == 0) {
8163           RHS = EI->getOperand(0);
8164           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8165           Mask[InsertedIdx & (NumElts-1)] = 
8166             ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
8167           return V;
8168         }
8169         
8170         if (VecOp == RHS) {
8171           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8172           // Everything but the extracted element is replaced with the RHS.
8173           for (unsigned i = 0; i != NumElts; ++i) {
8174             if (i != InsertedIdx)
8175               Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
8176           }
8177           return V;
8178         }
8179         
8180         // If this insertelement is a chain that comes from exactly these two
8181         // vectors, return the vector and the effective shuffle.
8182         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8183           return EI->getOperand(0);
8184         
8185       }
8186     }
8187   }
8188   // TODO: Handle shufflevector here!
8189   
8190   // Otherwise, can't do anything fancy.  Return an identity vector.
8191   for (unsigned i = 0; i != NumElts; ++i)
8192     Mask.push_back(ConstantInt::get(Type::UIntTy, i));
8193   return V;
8194 }
8195
8196 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8197   Value *VecOp    = IE.getOperand(0);
8198   Value *ScalarOp = IE.getOperand(1);
8199   Value *IdxOp    = IE.getOperand(2);
8200   
8201   // If the inserted element was extracted from some other vector, and if the 
8202   // indexes are constant, try to turn this into a shufflevector operation.
8203   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8204     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8205         EI->getOperand(0)->getType() == IE.getType()) {
8206       unsigned NumVectorElts = IE.getType()->getNumElements();
8207       unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8208       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8209       
8210       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8211         return ReplaceInstUsesWith(IE, VecOp);
8212       
8213       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
8214         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8215       
8216       // If we are extracting a value from a vector, then inserting it right
8217       // back into the same place, just use the input vector.
8218       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8219         return ReplaceInstUsesWith(IE, VecOp);      
8220       
8221       // We could theoretically do this for ANY input.  However, doing so could
8222       // turn chains of insertelement instructions into a chain of shufflevector
8223       // instructions, and right now we do not merge shufflevectors.  As such,
8224       // only do this in a situation where it is clear that there is benefit.
8225       if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8226         // Turn this into shuffle(EIOp0, VecOp, Mask).  The result has all of
8227         // the values of VecOp, except then one read from EIOp0.
8228         // Build a new shuffle mask.
8229         std::vector<Constant*> Mask;
8230         if (isa<UndefValue>(VecOp))
8231           Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8232         else {
8233           assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8234           Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
8235                                                        NumVectorElts));
8236         } 
8237         Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
8238         return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8239                                      ConstantPacked::get(Mask));
8240       }
8241       
8242       // If this insertelement isn't used by some other insertelement, turn it
8243       // (and any insertelements it points to), into one big shuffle.
8244       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8245         std::vector<Constant*> Mask;
8246         Value *RHS = 0;
8247         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8248         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8249         // We now have a shuffle of LHS, RHS, Mask.
8250         return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8251       }
8252     }
8253   }
8254
8255   return 0;
8256 }
8257
8258
8259 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8260   Value *LHS = SVI.getOperand(0);
8261   Value *RHS = SVI.getOperand(1);
8262   std::vector<unsigned> Mask = getShuffleMask(&SVI);
8263
8264   bool MadeChange = false;
8265   
8266   // Undefined shuffle mask -> undefined value.
8267   if (isa<UndefValue>(SVI.getOperand(2)))
8268     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8269   
8270   // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8271   // the undef, change them to undefs.
8272   
8273   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
8274   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8275   if (LHS == RHS || isa<UndefValue>(LHS)) {
8276     if (isa<UndefValue>(LHS) && LHS == RHS) {
8277       // shuffle(undef,undef,mask) -> undef.
8278       return ReplaceInstUsesWith(SVI, LHS);
8279     }
8280     
8281     // Remap any references to RHS to use LHS.
8282     std::vector<Constant*> Elts;
8283     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8284       if (Mask[i] >= 2*e)
8285         Elts.push_back(UndefValue::get(Type::UIntTy));
8286       else {
8287         if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8288             (Mask[i] <  e && isa<UndefValue>(LHS)))
8289           Mask[i] = 2*e;     // Turn into undef.
8290         else
8291           Mask[i] &= (e-1);  // Force to LHS.
8292         Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
8293       }
8294     }
8295     SVI.setOperand(0, SVI.getOperand(1));
8296     SVI.setOperand(1, UndefValue::get(RHS->getType()));
8297     SVI.setOperand(2, ConstantPacked::get(Elts));
8298     LHS = SVI.getOperand(0);
8299     RHS = SVI.getOperand(1);
8300     MadeChange = true;
8301   }
8302   
8303   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8304   bool isLHSID = true, isRHSID = true;
8305     
8306   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8307     if (Mask[i] >= e*2) continue;  // Ignore undef values.
8308     // Is this an identity shuffle of the LHS value?
8309     isLHSID &= (Mask[i] == i);
8310       
8311     // Is this an identity shuffle of the RHS value?
8312     isRHSID &= (Mask[i]-e == i);
8313   }
8314
8315   // Eliminate identity shuffles.
8316   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8317   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8318   
8319   // If the LHS is a shufflevector itself, see if we can combine it with this
8320   // one without producing an unusual shuffle.  Here we are really conservative:
8321   // we are absolutely afraid of producing a shuffle mask not in the input
8322   // program, because the code gen may not be smart enough to turn a merged
8323   // shuffle into two specific shuffles: it may produce worse code.  As such,
8324   // we only merge two shuffles if the result is one of the two input shuffle
8325   // masks.  In this case, merging the shuffles just removes one instruction,
8326   // which we know is safe.  This is good for things like turning:
8327   // (splat(splat)) -> splat.
8328   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8329     if (isa<UndefValue>(RHS)) {
8330       std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8331
8332       std::vector<unsigned> NewMask;
8333       for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8334         if (Mask[i] >= 2*e)
8335           NewMask.push_back(2*e);
8336         else
8337           NewMask.push_back(LHSMask[Mask[i]]);
8338       
8339       // If the result mask is equal to the src shuffle or this shuffle mask, do
8340       // the replacement.
8341       if (NewMask == LHSMask || NewMask == Mask) {
8342         std::vector<Constant*> Elts;
8343         for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8344           if (NewMask[i] >= e*2) {
8345             Elts.push_back(UndefValue::get(Type::UIntTy));
8346           } else {
8347             Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
8348           }
8349         }
8350         return new ShuffleVectorInst(LHSSVI->getOperand(0),
8351                                      LHSSVI->getOperand(1),
8352                                      ConstantPacked::get(Elts));
8353       }
8354     }
8355   }
8356   
8357   return MadeChange ? &SVI : 0;
8358 }
8359
8360
8361
8362 void InstCombiner::removeFromWorkList(Instruction *I) {
8363   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8364                  WorkList.end());
8365 }
8366
8367
8368 /// TryToSinkInstruction - Try to move the specified instruction from its
8369 /// current block into the beginning of DestBlock, which can only happen if it's
8370 /// safe to move the instruction past all of the instructions between it and the
8371 /// end of its block.
8372 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8373   assert(I->hasOneUse() && "Invariants didn't hold!");
8374
8375   // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8376   if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8377
8378   // Do not sink alloca instructions out of the entry block.
8379   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8380     return false;
8381
8382   // We can only sink load instructions if there is nothing between the load and
8383   // the end of block that could change the value.
8384   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8385     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8386          Scan != E; ++Scan)
8387       if (Scan->mayWriteToMemory())
8388         return false;
8389   }
8390
8391   BasicBlock::iterator InsertPos = DestBlock->begin();
8392   while (isa<PHINode>(InsertPos)) ++InsertPos;
8393
8394   I->moveBefore(InsertPos);
8395   ++NumSunkInst;
8396   return true;
8397 }
8398
8399 /// OptimizeConstantExpr - Given a constant expression and target data layout
8400 /// information, symbolically evaluation the constant expr to something simpler
8401 /// if possible.
8402 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8403   if (!TD) return CE;
8404   
8405   Constant *Ptr = CE->getOperand(0);
8406   if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8407       cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8408     // If this is a constant expr gep that is effectively computing an
8409     // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8410     bool isFoldableGEP = true;
8411     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8412       if (!isa<ConstantInt>(CE->getOperand(i)))
8413         isFoldableGEP = false;
8414     if (isFoldableGEP) {
8415       std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8416       uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8417       Constant *C = ConstantInt::get(Type::ULongTy, Offset);
8418       C = ConstantExpr::getCast(C, TD->getIntPtrType());
8419       return ConstantExpr::getCast(C, CE->getType());
8420     }
8421   }
8422   
8423   return CE;
8424 }
8425
8426
8427 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8428 /// all reachable code to the worklist.
8429 ///
8430 /// This has a couple of tricks to make the code faster and more powerful.  In
8431 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8432 /// them to the worklist (this significantly speeds up instcombine on code where
8433 /// many instructions are dead or constant).  Additionally, if we find a branch
8434 /// whose condition is a known constant, we only visit the reachable successors.
8435 ///
8436 static void AddReachableCodeToWorklist(BasicBlock *BB, 
8437                                        std::set<BasicBlock*> &Visited,
8438                                        std::vector<Instruction*> &WorkList,
8439                                        const TargetData *TD) {
8440   // We have now visited this block!  If we've already been here, bail out.
8441   if (!Visited.insert(BB).second) return;
8442     
8443   for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8444     Instruction *Inst = BBI++;
8445     
8446     // DCE instruction if trivially dead.
8447     if (isInstructionTriviallyDead(Inst)) {
8448       ++NumDeadInst;
8449       DEBUG(std::cerr << "IC: DCE: " << *Inst);
8450       Inst->eraseFromParent();
8451       continue;
8452     }
8453     
8454     // ConstantProp instruction if trivially constant.
8455     if (Constant *C = ConstantFoldInstruction(Inst)) {
8456       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8457         C = OptimizeConstantExpr(CE, TD);
8458       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8459       Inst->replaceAllUsesWith(C);
8460       ++NumConstProp;
8461       Inst->eraseFromParent();
8462       continue;
8463     }
8464     
8465     WorkList.push_back(Inst);
8466   }
8467
8468   // Recursively visit successors.  If this is a branch or switch on a constant,
8469   // only visit the reachable successor.
8470   TerminatorInst *TI = BB->getTerminator();
8471   if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8472     if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8473       bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8474       AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8475                                  TD);
8476       return;
8477     }
8478   } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8479     if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8480       // See if this is an explicit destination.
8481       for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8482         if (SI->getCaseValue(i) == Cond) {
8483           AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8484           return;
8485         }
8486       
8487       // Otherwise it is the default destination.
8488       AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8489       return;
8490     }
8491   }
8492   
8493   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8494     AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8495 }
8496
8497 bool InstCombiner::runOnFunction(Function &F) {
8498   bool Changed = false;
8499   TD = &getAnalysis<TargetData>();
8500
8501   {
8502     // Do a depth-first traversal of the function, populate the worklist with
8503     // the reachable instructions.  Ignore blocks that are not reachable.  Keep
8504     // track of which blocks we visit.
8505     std::set<BasicBlock*> Visited;
8506     AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8507
8508     // Do a quick scan over the function.  If we find any blocks that are
8509     // unreachable, remove any instructions inside of them.  This prevents
8510     // the instcombine code from having to deal with some bad special cases.
8511     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8512       if (!Visited.count(BB)) {
8513         Instruction *Term = BB->getTerminator();
8514         while (Term != BB->begin()) {   // Remove instrs bottom-up
8515           BasicBlock::iterator I = Term; --I;
8516
8517           DEBUG(std::cerr << "IC: DCE: " << *I);
8518           ++NumDeadInst;
8519
8520           if (!I->use_empty())
8521             I->replaceAllUsesWith(UndefValue::get(I->getType()));
8522           I->eraseFromParent();
8523         }
8524       }
8525   }
8526
8527   while (!WorkList.empty()) {
8528     Instruction *I = WorkList.back();  // Get an instruction from the worklist
8529     WorkList.pop_back();
8530
8531     // Check to see if we can DCE the instruction.
8532     if (isInstructionTriviallyDead(I)) {
8533       // Add operands to the worklist.
8534       if (I->getNumOperands() < 4)
8535         AddUsesToWorkList(*I);
8536       ++NumDeadInst;
8537
8538       DEBUG(std::cerr << "IC: DCE: " << *I);
8539
8540       I->eraseFromParent();
8541       removeFromWorkList(I);
8542       continue;
8543     }
8544
8545     // Instruction isn't dead, see if we can constant propagate it.
8546     if (Constant *C = ConstantFoldInstruction(I)) {
8547       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8548         C = OptimizeConstantExpr(CE, TD);
8549       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8550
8551       // Add operands to the worklist.
8552       AddUsesToWorkList(*I);
8553       ReplaceInstUsesWith(*I, C);
8554
8555       ++NumConstProp;
8556       I->eraseFromParent();
8557       removeFromWorkList(I);
8558       continue;
8559     }
8560
8561     // See if we can trivially sink this instruction to a successor basic block.
8562     if (I->hasOneUse()) {
8563       BasicBlock *BB = I->getParent();
8564       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8565       if (UserParent != BB) {
8566         bool UserIsSuccessor = false;
8567         // See if the user is one of our successors.
8568         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8569           if (*SI == UserParent) {
8570             UserIsSuccessor = true;
8571             break;
8572           }
8573
8574         // If the user is one of our immediate successors, and if that successor
8575         // only has us as a predecessors (we'd have to split the critical edge
8576         // otherwise), we can keep going.
8577         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8578             next(pred_begin(UserParent)) == pred_end(UserParent))
8579           // Okay, the CFG is simple enough, try to sink this instruction.
8580           Changed |= TryToSinkInstruction(I, UserParent);
8581       }
8582     }
8583
8584     // Now that we have an instruction, try combining it to simplify it...
8585     if (Instruction *Result = visit(*I)) {
8586       ++NumCombined;
8587       // Should we replace the old instruction with a new one?
8588       if (Result != I) {
8589         DEBUG(std::cerr << "IC: Old = " << *I
8590                         << "    New = " << *Result);
8591
8592         // Everything uses the new instruction now.
8593         I->replaceAllUsesWith(Result);
8594
8595         // Push the new instruction and any users onto the worklist.
8596         WorkList.push_back(Result);
8597         AddUsersToWorkList(*Result);
8598
8599         // Move the name to the new instruction first...
8600         std::string OldName = I->getName(); I->setName("");
8601         Result->setName(OldName);
8602
8603         // Insert the new instruction into the basic block...
8604         BasicBlock *InstParent = I->getParent();
8605         BasicBlock::iterator InsertPos = I;
8606
8607         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
8608           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8609             ++InsertPos;
8610
8611         InstParent->getInstList().insert(InsertPos, Result);
8612
8613         // Make sure that we reprocess all operands now that we reduced their
8614         // use counts.
8615         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8616           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8617             WorkList.push_back(OpI);
8618
8619         // Instructions can end up on the worklist more than once.  Make sure
8620         // we do not process an instruction that has been deleted.
8621         removeFromWorkList(I);
8622
8623         // Erase the old instruction.
8624         InstParent->getInstList().erase(I);
8625       } else {
8626         DEBUG(std::cerr << "IC: MOD = " << *I);
8627
8628         // If the instruction was modified, it's possible that it is now dead.
8629         // if so, remove it.
8630         if (isInstructionTriviallyDead(I)) {
8631           // Make sure we process all operands now that we are reducing their
8632           // use counts.
8633           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8634             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8635               WorkList.push_back(OpI);
8636
8637           // Instructions may end up in the worklist more than once.  Erase all
8638           // occurrences of this instruction.
8639           removeFromWorkList(I);
8640           I->eraseFromParent();
8641         } else {
8642           WorkList.push_back(Result);
8643           AddUsersToWorkList(*Result);
8644         }
8645       }
8646       Changed = true;
8647     }
8648   }
8649
8650   return Changed;
8651 }
8652
8653 FunctionPass *llvm::createInstructionCombiningPass() {
8654   return new InstCombiner();
8655 }
8656