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