d98f1f14d659989e8e95636c4915bcc35da93d80
[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/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include <algorithm>
55 using namespace llvm;
56 using namespace llvm::PatternMatch;
57
58 namespace {
59   Statistic<> NumCombined ("instcombine", "Number of insts combined");
60   Statistic<> NumConstProp("instcombine", "Number of constant folds");
61   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62   Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
63
64   class InstCombiner : public FunctionPass,
65                        public InstVisitor<InstCombiner, Instruction*> {
66     // Worklist of all of the instructions that need to be simplified.
67     std::vector<Instruction*> WorkList;
68     TargetData *TD;
69
70     /// AddUsersToWorkList - When an instruction is simplified, add all users of
71     /// the instruction to the work lists because they might get more simplified
72     /// now.
73     ///
74     void AddUsersToWorkList(Instruction &I) {
75       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
76            UI != UE; ++UI)
77         WorkList.push_back(cast<Instruction>(*UI));
78     }
79
80     /// AddUsesToWorkList - When an instruction is simplified, add operands to
81     /// the work lists because they might get more simplified now.
82     ///
83     void AddUsesToWorkList(Instruction &I) {
84       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86           WorkList.push_back(Op);
87     }
88
89     // removeFromWorkList - remove all instances of I from the worklist.
90     void removeFromWorkList(Instruction *I);
91   public:
92     virtual bool runOnFunction(Function &F);
93
94     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95       AU.addRequired<TargetData>();
96       AU.setPreservesCFG();
97     }
98
99     TargetData &getTargetData() const { return *TD; }
100
101     // Visitation implementation - Implement instruction combining for different
102     // instruction types.  The semantics are as follows:
103     // Return Value:
104     //    null        - No change was made
105     //     I          - Change was made, I is still valid, I may be dead though
106     //   otherwise    - Change was made, replace I with returned instruction
107     //
108     Instruction *visitAdd(BinaryOperator &I);
109     Instruction *visitSub(BinaryOperator &I);
110     Instruction *visitMul(BinaryOperator &I);
111     Instruction *visitDiv(BinaryOperator &I);
112     Instruction *visitRem(BinaryOperator &I);
113     Instruction *visitAnd(BinaryOperator &I);
114     Instruction *visitOr (BinaryOperator &I);
115     Instruction *visitXor(BinaryOperator &I);
116     Instruction *visitSetCondInst(SetCondInst &I);
117     Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
118
119     Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120                               Instruction::BinaryOps Cond, Instruction &I);
121     Instruction *visitShiftInst(ShiftInst &I);
122     Instruction *visitCastInst(CastInst &CI);
123     Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124                                 Instruction *FI);
125     Instruction *visitSelectInst(SelectInst &CI);
126     Instruction *visitCallInst(CallInst &CI);
127     Instruction *visitInvokeInst(InvokeInst &II);
128     Instruction *visitPHINode(PHINode &PN);
129     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
130     Instruction *visitAllocationInst(AllocationInst &AI);
131     Instruction *visitFreeInst(FreeInst &FI);
132     Instruction *visitLoadInst(LoadInst &LI);
133     Instruction *visitStoreInst(StoreInst &SI);
134     Instruction *visitBranchInst(BranchInst &BI);
135     Instruction *visitSwitchInst(SwitchInst &SI);
136
137     // visitInstruction - Specify what to return for unhandled instructions...
138     Instruction *visitInstruction(Instruction &I) { return 0; }
139
140   private:
141     Instruction *visitCallSite(CallSite CS);
142     bool transformConstExprCastCall(CallSite CS);
143
144   public:
145     // InsertNewInstBefore - insert an instruction New before instruction Old
146     // in the program.  Add the new instruction to the worklist.
147     //
148     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
149       assert(New && New->getParent() == 0 &&
150              "New instruction already inserted into a basic block!");
151       BasicBlock *BB = Old.getParent();
152       BB->getInstList().insert(&Old, New);  // Insert inst
153       WorkList.push_back(New);              // Add to worklist
154       return New;
155     }
156
157     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158     /// This also adds the cast to the worklist.  Finally, this returns the
159     /// cast.
160     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161       if (V->getType() == Ty) return V;
162
163       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164       WorkList.push_back(C);
165       return C;
166     }
167
168     // ReplaceInstUsesWith - This method is to be used when an instruction is
169     // found to be dead, replacable with another preexisting expression.  Here
170     // we add all uses of I to the worklist, replace all uses of I with the new
171     // value, then return I, so that the inst combiner will know that I was
172     // modified.
173     //
174     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
175       AddUsersToWorkList(I);         // Add all modified instrs to worklist
176       if (&I != V) {
177         I.replaceAllUsesWith(V);
178         return &I;
179       } else {
180         // If we are replacing the instruction with itself, this must be in a
181         // segment of unreachable code, so just clobber the instruction.
182         I.replaceAllUsesWith(UndefValue::get(I.getType()));
183         return &I;
184       }
185     }
186
187     // EraseInstFromFunction - When dealing with an instruction that has side
188     // effects or produces a void value, we can't rely on DCE to delete the
189     // instruction.  Instead, visit methods should return the value returned by
190     // this function.
191     Instruction *EraseInstFromFunction(Instruction &I) {
192       assert(I.use_empty() && "Cannot erase instruction that is used!");
193       AddUsesToWorkList(I);
194       removeFromWorkList(&I);
195       I.eraseFromParent();
196       return 0;  // Don't do anything with FI
197     }
198
199
200   private:
201     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
203     /// casts that are known to not do anything...
204     ///
205     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206                                    Instruction *InsertBefore);
207
208     // SimplifyCommutative - This performs a few simplifications for commutative
209     // operators.
210     bool SimplifyCommutative(BinaryOperator &I);
211
212
213     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214     // PHI node as operand #0, see if we can fold the instruction into the PHI
215     // (which is only possible if all operands to the PHI are constants).
216     Instruction *FoldOpIntoPhi(Instruction &I);
217
218     // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219     // operator and they all are only used by the PHI, PHI together their
220     // inputs, and do the operation once, to the result of the PHI.
221     Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
223     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
225     
226     Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
227                               bool isSub, Instruction &I);
228     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
229                                  bool Inside, Instruction &IB);
230   };
231
232   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
233 }
234
235 // getComplexity:  Assign a complexity or rank value to LLVM Values...
236 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
237 static unsigned getComplexity(Value *V) {
238   if (isa<Instruction>(V)) {
239     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
240       return 3;
241     return 4;
242   }
243   if (isa<Argument>(V)) return 3;
244   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
245 }
246
247 // isOnlyUse - Return true if this instruction will be deleted if we stop using
248 // it.
249 static bool isOnlyUse(Value *V) {
250   return V->hasOneUse() || isa<Constant>(V);
251 }
252
253 // getPromotedType - Return the specified type promoted as it would be to pass
254 // though a va_arg area...
255 static const Type *getPromotedType(const Type *Ty) {
256   switch (Ty->getTypeID()) {
257   case Type::SByteTyID:
258   case Type::ShortTyID:  return Type::IntTy;
259   case Type::UByteTyID:
260   case Type::UShortTyID: return Type::UIntTy;
261   case Type::FloatTyID:  return Type::DoubleTy;
262   default:               return Ty;
263   }
264 }
265
266 /// isCast - If the specified operand is a CastInst or a constant expr cast,
267 /// return the operand value, otherwise return null.
268 static Value *isCast(Value *V) {
269   if (CastInst *I = dyn_cast<CastInst>(V))
270     return I->getOperand(0);
271   else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
272     if (CE->getOpcode() == Instruction::Cast)
273       return CE->getOperand(0);
274   return 0;
275 }
276
277 // SimplifyCommutative - This performs a few simplifications for commutative
278 // operators:
279 //
280 //  1. Order operands such that they are listed from right (least complex) to
281 //     left (most complex).  This puts constants before unary operators before
282 //     binary operators.
283 //
284 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
285 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
286 //
287 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
288   bool Changed = false;
289   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
290     Changed = !I.swapOperands();
291
292   if (!I.isAssociative()) return Changed;
293   Instruction::BinaryOps Opcode = I.getOpcode();
294   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
295     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
296       if (isa<Constant>(I.getOperand(1))) {
297         Constant *Folded = ConstantExpr::get(I.getOpcode(),
298                                              cast<Constant>(I.getOperand(1)),
299                                              cast<Constant>(Op->getOperand(1)));
300         I.setOperand(0, Op->getOperand(0));
301         I.setOperand(1, Folded);
302         return true;
303       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
304         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
305             isOnlyUse(Op) && isOnlyUse(Op1)) {
306           Constant *C1 = cast<Constant>(Op->getOperand(1));
307           Constant *C2 = cast<Constant>(Op1->getOperand(1));
308
309           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
310           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
311           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
312                                                     Op1->getOperand(0),
313                                                     Op1->getName(), &I);
314           WorkList.push_back(New);
315           I.setOperand(0, New);
316           I.setOperand(1, Folded);
317           return true;
318         }
319     }
320   return Changed;
321 }
322
323 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
324 // if the LHS is a constant zero (which is the 'negate' form).
325 //
326 static inline Value *dyn_castNegVal(Value *V) {
327   if (BinaryOperator::isNeg(V))
328     return BinaryOperator::getNegArgument(V);
329
330   // Constants can be considered to be negated values if they can be folded.
331   if (ConstantInt *C = dyn_cast<ConstantInt>(V))
332     return ConstantExpr::getNeg(C);
333   return 0;
334 }
335
336 static inline Value *dyn_castNotVal(Value *V) {
337   if (BinaryOperator::isNot(V))
338     return BinaryOperator::getNotArgument(V);
339
340   // Constants can be considered to be not'ed values...
341   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
342     return ConstantExpr::getNot(C);
343   return 0;
344 }
345
346 // dyn_castFoldableMul - If this value is a multiply that can be folded into
347 // other computations (because it has a constant operand), return the
348 // non-constant operand of the multiply, and set CST to point to the multiplier.
349 // Otherwise, return null.
350 //
351 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
352   if (V->hasOneUse() && V->getType()->isInteger())
353     if (Instruction *I = dyn_cast<Instruction>(V)) {
354       if (I->getOpcode() == Instruction::Mul)
355         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
356           return I->getOperand(0);
357       if (I->getOpcode() == Instruction::Shl)
358         if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
359           // The multiplier is really 1 << CST.
360           Constant *One = ConstantInt::get(V->getType(), 1);
361           CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
362           return I->getOperand(0);
363         }
364     }
365   return 0;
366 }
367
368 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
369 /// expression, return it.
370 static User *dyn_castGetElementPtr(Value *V) {
371   if (isa<GetElementPtrInst>(V)) return cast<User>(V);
372   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
373     if (CE->getOpcode() == Instruction::GetElementPtr)
374       return cast<User>(V);
375   return false;
376 }
377
378 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
379 static ConstantInt *AddOne(ConstantInt *C) {
380   return cast<ConstantInt>(ConstantExpr::getAdd(C,
381                                          ConstantInt::get(C->getType(), 1)));
382 }
383 static ConstantInt *SubOne(ConstantInt *C) {
384   return cast<ConstantInt>(ConstantExpr::getSub(C,
385                                          ConstantInt::get(C->getType(), 1)));
386 }
387
388 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
389 /// this predicate to simplify operations downstream.  V and Mask are known to
390 /// be the same type.
391 static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
392   // Note, we cannot consider 'undef' to be "IsZero" here.  The problem is that
393   // we cannot optimize based on the assumption that it is zero without changing
394   // to to an explicit zero.  If we don't change it to zero, other code could
395   // optimized based on the contradictory assumption that it is non-zero.
396   // Because instcombine aggressively folds operations with undef args anyway,
397   // this won't lose us code quality.
398   if (Mask->isNullValue())
399     return true;
400   if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
401     return ConstantExpr::getAnd(CI, Mask)->isNullValue();
402   
403   if (Instruction *I = dyn_cast<Instruction>(V)) {
404     switch (I->getOpcode()) {
405       case Instruction::And:
406         // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
407         if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
408           if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
409             return true;
410         break;
411       case Instruction::Or:
412         // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
413         return MaskedValueIsZero(I->getOperand(1), Mask) &&
414         MaskedValueIsZero(I->getOperand(0), Mask);
415       case Instruction::Select:
416         // If the T and F values are MaskedValueIsZero, the result is also zero.
417         return MaskedValueIsZero(I->getOperand(2), Mask) &&
418         MaskedValueIsZero(I->getOperand(1), Mask);
419       case Instruction::Cast: {
420         const Type *SrcTy = I->getOperand(0)->getType();
421         if (SrcTy == Type::BoolTy)
422           return (Mask->getRawValue() & 1) == 0;
423         
424         if (SrcTy->isInteger()) {
425           // (cast <ty> X to int) & C2 == 0  iff <ty> could not have contained C2.
426           if (SrcTy->isUnsigned() &&                      // Only handle zero ext.
427               ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
428             return true;
429           
430           // If this is a noop cast, recurse.
431           if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
432               SrcTy->getSignedVersion() == I->getType()) {
433             Constant *NewMask =
434             ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
435             return MaskedValueIsZero(I->getOperand(0),
436                                      cast<ConstantIntegral>(NewMask));
437           }
438         }
439         break;
440       }
441       case Instruction::Shl:
442         // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
443         if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
444           return MaskedValueIsZero(I->getOperand(0),
445                                    cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
446         break;
447       case Instruction::Shr:
448         // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
449         if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
450           if (I->getType()->isUnsigned()) {
451             Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
452             C1 = ConstantExpr::getShr(C1, SA);
453             C1 = ConstantExpr::getAnd(C1, Mask);
454             if (C1->isNullValue())
455               return true;
456           }
457             break;
458     }
459   }
460   
461   return false;
462 }
463
464 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
465 // true when both operands are equal...
466 //
467 static bool isTrueWhenEqual(Instruction &I) {
468   return I.getOpcode() == Instruction::SetEQ ||
469          I.getOpcode() == Instruction::SetGE ||
470          I.getOpcode() == Instruction::SetLE;
471 }
472
473 /// AssociativeOpt - Perform an optimization on an associative operator.  This
474 /// function is designed to check a chain of associative operators for a
475 /// potential to apply a certain optimization.  Since the optimization may be
476 /// applicable if the expression was reassociated, this checks the chain, then
477 /// reassociates the expression as necessary to expose the optimization
478 /// opportunity.  This makes use of a special Functor, which must define
479 /// 'shouldApply' and 'apply' methods.
480 ///
481 template<typename Functor>
482 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
483   unsigned Opcode = Root.getOpcode();
484   Value *LHS = Root.getOperand(0);
485
486   // Quick check, see if the immediate LHS matches...
487   if (F.shouldApply(LHS))
488     return F.apply(Root);
489
490   // Otherwise, if the LHS is not of the same opcode as the root, return.
491   Instruction *LHSI = dyn_cast<Instruction>(LHS);
492   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
493     // Should we apply this transform to the RHS?
494     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
495
496     // If not to the RHS, check to see if we should apply to the LHS...
497     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
498       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
499       ShouldApply = true;
500     }
501
502     // If the functor wants to apply the optimization to the RHS of LHSI,
503     // reassociate the expression from ((? op A) op B) to (? op (A op B))
504     if (ShouldApply) {
505       BasicBlock *BB = Root.getParent();
506
507       // Now all of the instructions are in the current basic block, go ahead
508       // and perform the reassociation.
509       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
510
511       // First move the selected RHS to the LHS of the root...
512       Root.setOperand(0, LHSI->getOperand(1));
513
514       // Make what used to be the LHS of the root be the user of the root...
515       Value *ExtraOperand = TmpLHSI->getOperand(1);
516       if (&Root == TmpLHSI) {
517         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
518         return 0;
519       }
520       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
521       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
522       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
523       BasicBlock::iterator ARI = &Root; ++ARI;
524       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
525       ARI = Root;
526
527       // Now propagate the ExtraOperand down the chain of instructions until we
528       // get to LHSI.
529       while (TmpLHSI != LHSI) {
530         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
531         // Move the instruction to immediately before the chain we are
532         // constructing to avoid breaking dominance properties.
533         NextLHSI->getParent()->getInstList().remove(NextLHSI);
534         BB->getInstList().insert(ARI, NextLHSI);
535         ARI = NextLHSI;
536
537         Value *NextOp = NextLHSI->getOperand(1);
538         NextLHSI->setOperand(1, ExtraOperand);
539         TmpLHSI = NextLHSI;
540         ExtraOperand = NextOp;
541       }
542
543       // Now that the instructions are reassociated, have the functor perform
544       // the transformation...
545       return F.apply(Root);
546     }
547
548     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
549   }
550   return 0;
551 }
552
553
554 // AddRHS - Implements: X + X --> X << 1
555 struct AddRHS {
556   Value *RHS;
557   AddRHS(Value *rhs) : RHS(rhs) {}
558   bool shouldApply(Value *LHS) const { return LHS == RHS; }
559   Instruction *apply(BinaryOperator &Add) const {
560     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
561                          ConstantInt::get(Type::UByteTy, 1));
562   }
563 };
564
565 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
566 //                 iff C1&C2 == 0
567 struct AddMaskingAnd {
568   Constant *C2;
569   AddMaskingAnd(Constant *c) : C2(c) {}
570   bool shouldApply(Value *LHS) const {
571     ConstantInt *C1;
572     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
573            ConstantExpr::getAnd(C1, C2)->isNullValue();
574   }
575   Instruction *apply(BinaryOperator &Add) const {
576     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
577   }
578 };
579
580 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
581                                              InstCombiner *IC) {
582   if (isa<CastInst>(I)) {
583     if (Constant *SOC = dyn_cast<Constant>(SO))
584       return ConstantExpr::getCast(SOC, I.getType());
585
586     return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
587                                                 SO->getName() + ".cast"), I);
588   }
589
590   // Figure out if the constant is the left or the right argument.
591   bool ConstIsRHS = isa<Constant>(I.getOperand(1));
592   Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
593
594   if (Constant *SOC = dyn_cast<Constant>(SO)) {
595     if (ConstIsRHS)
596       return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
597     return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
598   }
599
600   Value *Op0 = SO, *Op1 = ConstOperand;
601   if (!ConstIsRHS)
602     std::swap(Op0, Op1);
603   Instruction *New;
604   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
605     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
606   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
607     New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
608   else {
609     assert(0 && "Unknown binary instruction type!");
610     abort();
611   }
612   return IC->InsertNewInstBefore(New, I);
613 }
614
615 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
616 // constant as the other operand, try to fold the binary operator into the
617 // select arguments.  This also works for Cast instructions, which obviously do
618 // not have a second operand.
619 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
620                                      InstCombiner *IC) {
621   // Don't modify shared select instructions
622   if (!SI->hasOneUse()) return 0;
623   Value *TV = SI->getOperand(1);
624   Value *FV = SI->getOperand(2);
625
626   if (isa<Constant>(TV) || isa<Constant>(FV)) {
627     // Bool selects with constant operands can be folded to logical ops.
628     if (SI->getType() == Type::BoolTy) return 0;
629
630     Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
631     Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
632
633     return new SelectInst(SI->getCondition(), SelectTrueVal,
634                           SelectFalseVal);
635   }
636   return 0;
637 }
638
639
640 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
641 /// node as operand #0, see if we can fold the instruction into the PHI (which
642 /// is only possible if all operands to the PHI are constants).
643 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
644   PHINode *PN = cast<PHINode>(I.getOperand(0));
645   unsigned NumPHIValues = PN->getNumIncomingValues();
646   if (!PN->hasOneUse() || NumPHIValues == 0 ||
647       !isa<Constant>(PN->getIncomingValue(0))) return 0;
648
649   // Check to see if all of the operands of the PHI are constants.  If not, we
650   // cannot do the transformation.
651   for (unsigned i = 1; i != NumPHIValues; ++i)
652     if (!isa<Constant>(PN->getIncomingValue(i)))
653       return 0;
654
655   // Okay, we can do the transformation: create the new PHI node.
656   PHINode *NewPN = new PHINode(I.getType(), I.getName());
657   I.setName("");
658   NewPN->reserveOperandSpace(PN->getNumOperands()/2);
659   InsertNewInstBefore(NewPN, *PN);
660
661   // Next, add all of the operands to the PHI.
662   if (I.getNumOperands() == 2) {
663     Constant *C = cast<Constant>(I.getOperand(1));
664     for (unsigned i = 0; i != NumPHIValues; ++i) {
665       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
666       NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
667                          PN->getIncomingBlock(i));
668     }
669   } else {
670     assert(isa<CastInst>(I) && "Unary op should be a cast!");
671     const Type *RetTy = I.getType();
672     for (unsigned i = 0; i != NumPHIValues; ++i) {
673       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
674       NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
675                          PN->getIncomingBlock(i));
676     }
677   }
678   return ReplaceInstUsesWith(I, NewPN);
679 }
680
681 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
682   bool Changed = SimplifyCommutative(I);
683   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
684
685   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
686     // X + undef -> undef
687     if (isa<UndefValue>(RHS))
688       return ReplaceInstUsesWith(I, RHS);
689
690     // X + 0 --> X
691     if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
692         RHSC->isNullValue())
693       return ReplaceInstUsesWith(I, LHS);
694
695     // X + (signbit) --> X ^ signbit
696     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
697       unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
698       uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
699       if (Val == (1ULL << (NumBits-1)))
700         return BinaryOperator::createXor(LHS, RHS);
701     }
702
703     if (isa<PHINode>(LHS))
704       if (Instruction *NV = FoldOpIntoPhi(I))
705         return NV;
706     
707     ConstantInt *XorRHS;
708     Value *XorLHS;
709     if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
710       unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
711       int64_t  RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
712       uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
713       
714       uint64_t C0080Val = 1ULL << 31;
715       int64_t CFF80Val = -C0080Val;
716       unsigned Size = 32;
717       do {
718         if (TySizeBits > Size) {
719           bool Found = false;
720           // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
721           // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
722           if (RHSSExt == CFF80Val) {
723             if (XorRHS->getZExtValue() == C0080Val)
724               Found = true;
725           } else if (RHSZExt == C0080Val) {
726             if (XorRHS->getSExtValue() == CFF80Val)
727               Found = true;
728           }
729           if (Found) {
730             // This is a sign extend if the top bits are known zero.
731             Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
732             Mask = ConstantExpr::getShl(Mask, 
733                            ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
734             if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
735               Size = 0;  // Not a sign ext, but can't be any others either.
736             goto FoundSExt;
737           }
738         }
739         Size >>= 1;
740         C0080Val >>= Size;
741         CFF80Val >>= Size;
742       } while (Size >= 8);
743       
744 FoundSExt:
745       const Type *MiddleType = 0;
746       switch (Size) {
747       default: break;
748       case 32: MiddleType = Type::IntTy; break;
749       case 16: MiddleType = Type::ShortTy; break;
750       case 8:  MiddleType = Type::SByteTy; break;
751       }
752       if (MiddleType) {
753         Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
754         InsertNewInstBefore(NewTrunc, I);
755         return new CastInst(NewTrunc, I.getType());
756       }
757     }
758   }
759
760   // X + X --> X << 1
761   if (I.getType()->isInteger()) {
762     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
763
764     if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
765       if (RHSI->getOpcode() == Instruction::Sub)
766         if (LHS == RHSI->getOperand(1))                   // A + (B - A) --> B
767           return ReplaceInstUsesWith(I, RHSI->getOperand(0));
768     }
769     if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
770       if (LHSI->getOpcode() == Instruction::Sub)
771         if (RHS == LHSI->getOperand(1))                   // (B - A) + A --> B
772           return ReplaceInstUsesWith(I, LHSI->getOperand(0));
773     }
774   }
775
776   // -A + B  -->  B - A
777   if (Value *V = dyn_castNegVal(LHS))
778     return BinaryOperator::createSub(RHS, V);
779
780   // A + -B  -->  A - B
781   if (!isa<Constant>(RHS))
782     if (Value *V = dyn_castNegVal(RHS))
783       return BinaryOperator::createSub(LHS, V);
784
785
786   ConstantInt *C2;
787   if (Value *X = dyn_castFoldableMul(LHS, C2)) {
788     if (X == RHS)   // X*C + X --> X * (C+1)
789       return BinaryOperator::createMul(RHS, AddOne(C2));
790
791     // X*C1 + X*C2 --> X * (C1+C2)
792     ConstantInt *C1;
793     if (X == dyn_castFoldableMul(RHS, C1))
794       return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
795   }
796
797   // X + X*C --> X * (C+1)
798   if (dyn_castFoldableMul(RHS, C2) == LHS)
799     return BinaryOperator::createMul(LHS, AddOne(C2));
800
801
802   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
803   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
804     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
805
806   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
807     Value *X;
808     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
809       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
810       return BinaryOperator::createSub(C, X);
811     }
812
813     // (X & FF00) + xx00  -> (X+xx00) & FF00
814     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
815       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
816       if (Anded == CRHS) {
817         // See if all bits from the first bit set in the Add RHS up are included
818         // in the mask.  First, get the rightmost bit.
819         uint64_t AddRHSV = CRHS->getRawValue();
820
821         // Form a mask of all bits from the lowest bit added through the top.
822         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
823         AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
824
825         // See if the and mask includes all of these bits.
826         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
827
828         if (AddRHSHighBits == AddRHSHighBitsAnd) {
829           // Okay, the xform is safe.  Insert the new add pronto.
830           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
831                                                             LHS->getName()), I);
832           return BinaryOperator::createAnd(NewAdd, C2);
833         }
834       }
835     }
836
837     // Try to fold constant add into select arguments.
838     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
839       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
840         return R;
841   }
842
843   return Changed ? &I : 0;
844 }
845
846 // isSignBit - Return true if the value represented by the constant only has the
847 // highest order bit set.
848 static bool isSignBit(ConstantInt *CI) {
849   unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
850   return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
851 }
852
853 /// RemoveNoopCast - Strip off nonconverting casts from the value.
854 ///
855 static Value *RemoveNoopCast(Value *V) {
856   if (CastInst *CI = dyn_cast<CastInst>(V)) {
857     const Type *CTy = CI->getType();
858     const Type *OpTy = CI->getOperand(0)->getType();
859     if (CTy->isInteger() && OpTy->isInteger()) {
860       if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
861         return RemoveNoopCast(CI->getOperand(0));
862     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
863       return RemoveNoopCast(CI->getOperand(0));
864   }
865   return V;
866 }
867
868 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
869   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
870
871   if (Op0 == Op1)         // sub X, X  -> 0
872     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
873
874   // If this is a 'B = x-(-A)', change to B = x+A...
875   if (Value *V = dyn_castNegVal(Op1))
876     return BinaryOperator::createAdd(Op0, V);
877
878   if (isa<UndefValue>(Op0))
879     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
880   if (isa<UndefValue>(Op1))
881     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
882
883   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
884     // Replace (-1 - A) with (~A)...
885     if (C->isAllOnesValue())
886       return BinaryOperator::createNot(Op1);
887
888     // C - ~X == X + (1+C)
889     Value *X = 0;
890     if (match(Op1, m_Not(m_Value(X))))
891       return BinaryOperator::createAdd(X,
892                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
893     // -((uint)X >> 31) -> ((int)X >> 31)
894     // -((int)X >> 31) -> ((uint)X >> 31)
895     if (C->isNullValue()) {
896       Value *NoopCastedRHS = RemoveNoopCast(Op1);
897       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
898         if (SI->getOpcode() == Instruction::Shr)
899           if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
900             const Type *NewTy;
901             if (SI->getType()->isSigned())
902               NewTy = SI->getType()->getUnsignedVersion();
903             else
904               NewTy = SI->getType()->getSignedVersion();
905             // Check to see if we are shifting out everything but the sign bit.
906             if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
907               // Ok, the transformation is safe.  Insert a cast of the incoming
908               // value, then the new shift, then the new cast.
909               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
910                                                  SI->getOperand(0)->getName());
911               Value *InV = InsertNewInstBefore(FirstCast, I);
912               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
913                                                     CU, SI->getName());
914               if (NewShift->getType() == I.getType())
915                 return NewShift;
916               else {
917                 InV = InsertNewInstBefore(NewShift, I);
918                 return new CastInst(NewShift, I.getType());
919               }
920             }
921           }
922     }
923
924     // Try to fold constant sub into select arguments.
925     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
926       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
927         return R;
928
929     if (isa<PHINode>(Op0))
930       if (Instruction *NV = FoldOpIntoPhi(I))
931         return NV;
932   }
933
934   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
935     if (Op1I->getOpcode() == Instruction::Add &&
936         !Op0->getType()->isFloatingPoint()) {
937       if (Op1I->getOperand(0) == Op0)              // X-(X+Y) == -Y
938         return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
939       else if (Op1I->getOperand(1) == Op0)         // X-(Y+X) == -Y
940         return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
941       else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
942         if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
943           // C1-(X+C2) --> (C1-C2)-X
944           return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
945                                            Op1I->getOperand(0));
946       }
947     }
948
949     if (Op1I->hasOneUse()) {
950       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
951       // is not used by anyone else...
952       //
953       if (Op1I->getOpcode() == Instruction::Sub &&
954           !Op1I->getType()->isFloatingPoint()) {
955         // Swap the two operands of the subexpr...
956         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
957         Op1I->setOperand(0, IIOp1);
958         Op1I->setOperand(1, IIOp0);
959
960         // Create the new top level add instruction...
961         return BinaryOperator::createAdd(Op0, Op1);
962       }
963
964       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
965       //
966       if (Op1I->getOpcode() == Instruction::And &&
967           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
968         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
969
970         Value *NewNot =
971           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
972         return BinaryOperator::createAnd(Op0, NewNot);
973       }
974
975       // -(X sdiv C)  -> (X sdiv -C)
976       if (Op1I->getOpcode() == Instruction::Div)
977         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
978           if (CSI->isNullValue())
979             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
980               return BinaryOperator::createDiv(Op1I->getOperand(0),
981                                                ConstantExpr::getNeg(DivRHS));
982
983       // X - X*C --> X * (1-C)
984       ConstantInt *C2 = 0;
985       if (dyn_castFoldableMul(Op1I, C2) == Op0) {
986         Constant *CP1 =
987           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
988         return BinaryOperator::createMul(Op0, CP1);
989       }
990     }
991   }
992
993   if (!Op0->getType()->isFloatingPoint())
994     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
995       if (Op0I->getOpcode() == Instruction::Add) {
996         if (Op0I->getOperand(0) == Op1)             // (Y+X)-Y == X
997           return ReplaceInstUsesWith(I, Op0I->getOperand(1));
998         else if (Op0I->getOperand(1) == Op1)        // (X+Y)-Y == X
999           return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1000       } else if (Op0I->getOpcode() == Instruction::Sub) {
1001         if (Op0I->getOperand(0) == Op1)             // (X-Y)-X == -Y
1002           return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1003       }
1004
1005   ConstantInt *C1;
1006   if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1007     if (X == Op1) { // X*C - X --> X * (C-1)
1008       Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1009       return BinaryOperator::createMul(Op1, CP1);
1010     }
1011
1012     ConstantInt *C2;   // X*C1 - X*C2 -> X * (C1-C2)
1013     if (X == dyn_castFoldableMul(Op1, C2))
1014       return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1015   }
1016   return 0;
1017 }
1018
1019 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1020 /// really just returns true if the most significant (sign) bit is set.
1021 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1022   if (RHS->getType()->isSigned()) {
1023     // True if source is LHS < 0 or LHS <= -1
1024     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1025            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1026   } else {
1027     ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1028     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1029     // the size of the integer type.
1030     if (Opcode == Instruction::SetGE)
1031       return RHSC->getValue() ==
1032         1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1033     if (Opcode == Instruction::SetGT)
1034       return RHSC->getValue() ==
1035         (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1036   }
1037   return false;
1038 }
1039
1040 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1041   bool Changed = SimplifyCommutative(I);
1042   Value *Op0 = I.getOperand(0);
1043
1044   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
1045     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1046
1047   // Simplify mul instructions with a constant RHS...
1048   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1049     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1050
1051       // ((X << C1)*C2) == (X * (C2 << C1))
1052       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1053         if (SI->getOpcode() == Instruction::Shl)
1054           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1055             return BinaryOperator::createMul(SI->getOperand(0),
1056                                              ConstantExpr::getShl(CI, ShOp));
1057
1058       if (CI->isNullValue())
1059         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
1060       if (CI->equalsInt(1))                  // X * 1  == X
1061         return ReplaceInstUsesWith(I, Op0);
1062       if (CI->isAllOnesValue())              // X * -1 == 0 - X
1063         return BinaryOperator::createNeg(Op0, I.getName());
1064
1065       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1066       if (isPowerOf2_64(Val)) {          // Replace X*(2^C) with X << C
1067         uint64_t C = Log2_64(Val);
1068         return new ShiftInst(Instruction::Shl, Op0,
1069                              ConstantUInt::get(Type::UByteTy, C));
1070       }
1071     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1072       if (Op1F->isNullValue())
1073         return ReplaceInstUsesWith(I, Op1);
1074
1075       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
1076       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1077       if (Op1F->getValue() == 1.0)
1078         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
1079     }
1080
1081     // Try to fold constant mul into select arguments.
1082     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1083       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1084         return R;
1085
1086     if (isa<PHINode>(Op0))
1087       if (Instruction *NV = FoldOpIntoPhi(I))
1088         return NV;
1089   }
1090
1091   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
1092     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1093       return BinaryOperator::createMul(Op0v, Op1v);
1094
1095   // If one of the operands of the multiply is a cast from a boolean value, then
1096   // we know the bool is either zero or one, so this is a 'masking' multiply.
1097   // See if we can simplify things based on how the boolean was originally
1098   // formed.
1099   CastInst *BoolCast = 0;
1100   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1101     if (CI->getOperand(0)->getType() == Type::BoolTy)
1102       BoolCast = CI;
1103   if (!BoolCast)
1104     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1105       if (CI->getOperand(0)->getType() == Type::BoolTy)
1106         BoolCast = CI;
1107   if (BoolCast) {
1108     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1109       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1110       const Type *SCOpTy = SCIOp0->getType();
1111
1112       // If the setcc is true iff the sign bit of X is set, then convert this
1113       // multiply into a shift/and combination.
1114       if (isa<ConstantInt>(SCIOp1) &&
1115           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1116         // Shift the X value right to turn it into "all signbits".
1117         Constant *Amt = ConstantUInt::get(Type::UByteTy,
1118                                           SCOpTy->getPrimitiveSizeInBits()-1);
1119         if (SCIOp0->getType()->isUnsigned()) {
1120           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1121           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1122                                                     SCIOp0->getName()), I);
1123         }
1124
1125         Value *V =
1126           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1127                                             BoolCast->getOperand(0)->getName()+
1128                                             ".mask"), I);
1129
1130         // If the multiply type is not the same as the source type, sign extend
1131         // or truncate to the multiply type.
1132         if (I.getType() != V->getType())
1133           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1134
1135         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1136         return BinaryOperator::createAnd(V, OtherOp);
1137       }
1138     }
1139   }
1140
1141   return Changed ? &I : 0;
1142 }
1143
1144 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1145   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1146
1147   if (isa<UndefValue>(Op0))              // undef / X -> 0
1148     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1149   if (isa<UndefValue>(Op1))
1150     return ReplaceInstUsesWith(I, Op1);  // X / undef -> undef
1151
1152   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1153     // div X, 1 == X
1154     if (RHS->equalsInt(1))
1155       return ReplaceInstUsesWith(I, Op0);
1156
1157     // div X, -1 == -X
1158     if (RHS->isAllOnesValue())
1159       return BinaryOperator::createNeg(Op0);
1160
1161     if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1162       if (LHS->getOpcode() == Instruction::Div)
1163         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1164           // (X / C1) / C2  -> X / (C1*C2)
1165           return BinaryOperator::createDiv(LHS->getOperand(0),
1166                                            ConstantExpr::getMul(RHS, LHSRHS));
1167         }
1168
1169     // Check to see if this is an unsigned division with an exact power of 2,
1170     // if so, convert to a right shift.
1171     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1172       if (uint64_t Val = C->getValue())    // Don't break X / 0
1173         if (isPowerOf2_64(Val)) {
1174           uint64_t C = Log2_64(Val);
1175           return new ShiftInst(Instruction::Shr, Op0,
1176                                ConstantUInt::get(Type::UByteTy, C));
1177         }
1178
1179     // -X/C -> X/-C
1180     if (RHS->getType()->isSigned())
1181       if (Value *LHSNeg = dyn_castNegVal(Op0))
1182         return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1183
1184     if (!RHS->isNullValue()) {
1185       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1186         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1187           return R;
1188       if (isa<PHINode>(Op0))
1189         if (Instruction *NV = FoldOpIntoPhi(I))
1190           return NV;
1191     }
1192   }
1193
1194   // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1195   // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1196   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1197     if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1198       if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1199         if (STO->getValue() == 0) { // Couldn't be this argument.
1200           I.setOperand(1, SFO);
1201           return &I;
1202         } else if (SFO->getValue() == 0) {
1203           I.setOperand(1, STO);
1204           return &I;
1205         }
1206
1207         uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1208         if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1209           unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1210           Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1211           Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1212                                            TC, SI->getName()+".t");
1213           TSI = InsertNewInstBefore(TSI, I);
1214
1215           Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1216           Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1217                                            FC, SI->getName()+".f");
1218           FSI = InsertNewInstBefore(FSI, I);
1219           return new SelectInst(SI->getOperand(0), TSI, FSI);
1220         }
1221       }
1222
1223   // 0 / X == 0, we don't need to preserve faults!
1224   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1225     if (LHS->equalsInt(0))
1226       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1227
1228   return 0;
1229 }
1230
1231
1232 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1233   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1234   if (I.getType()->isSigned())
1235     if (Value *RHSNeg = dyn_castNegVal(Op1))
1236       if (!isa<ConstantSInt>(RHSNeg) ||
1237           cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1238         // X % -Y -> X % Y
1239         AddUsesToWorkList(I);
1240         I.setOperand(1, RHSNeg);
1241         return &I;
1242       }
1243
1244   if (isa<UndefValue>(Op0))              // undef % X -> 0
1245     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1246   if (isa<UndefValue>(Op1))
1247     return ReplaceInstUsesWith(I, Op1);  // X % undef -> undef
1248
1249   if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1250     if (RHS->equalsInt(1))  // X % 1 == 0
1251       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1252
1253     // Check to see if this is an unsigned remainder with an exact power of 2,
1254     // if so, convert to a bitwise and.
1255     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1256       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
1257         if (!(Val & (Val-1)))              // Power of 2
1258           return BinaryOperator::createAnd(Op0,
1259                                          ConstantUInt::get(I.getType(), Val-1));
1260
1261     if (!RHS->isNullValue()) {
1262       if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1263         if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1264           return R;
1265       if (isa<PHINode>(Op0))
1266         if (Instruction *NV = FoldOpIntoPhi(I))
1267           return NV;
1268     }
1269   }
1270
1271   // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1272   // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1273   if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1274     if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1275       if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1276         if (STO->getValue() == 0) { // Couldn't be this argument.
1277           I.setOperand(1, SFO);
1278           return &I;
1279         } else if (SFO->getValue() == 0) {
1280           I.setOperand(1, STO);
1281           return &I;
1282         }
1283
1284         if (!(STO->getValue() & (STO->getValue()-1)) &&
1285             !(SFO->getValue() & (SFO->getValue()-1))) {
1286           Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1287                                          SubOne(STO), SI->getName()+".t"), I);
1288           Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1289                                          SubOne(SFO), SI->getName()+".f"), I);
1290           return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1291         }
1292       }
1293
1294   // 0 % X == 0, we don't need to preserve faults!
1295   if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1296     if (LHS->equalsInt(0))
1297       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1298
1299   return 0;
1300 }
1301
1302 // isMaxValueMinusOne - return true if this is Max-1
1303 static bool isMaxValueMinusOne(const ConstantInt *C) {
1304   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1305     // Calculate -1 casted to the right type...
1306     unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1307     uint64_t Val = ~0ULL;                // All ones
1308     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1309     return CU->getValue() == Val-1;
1310   }
1311
1312   const ConstantSInt *CS = cast<ConstantSInt>(C);
1313
1314   // Calculate 0111111111..11111
1315   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1316   int64_t Val = INT64_MAX;             // All ones
1317   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1318   return CS->getValue() == Val-1;
1319 }
1320
1321 // isMinValuePlusOne - return true if this is Min+1
1322 static bool isMinValuePlusOne(const ConstantInt *C) {
1323   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1324     return CU->getValue() == 1;
1325
1326   const ConstantSInt *CS = cast<ConstantSInt>(C);
1327
1328   // Calculate 1111111111000000000000
1329   unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1330   int64_t Val = -1;                    // All ones
1331   Val <<= TypeBits-1;                  // Shift over to the right spot
1332   return CS->getValue() == Val+1;
1333 }
1334
1335 // isOneBitSet - Return true if there is exactly one bit set in the specified
1336 // constant.
1337 static bool isOneBitSet(const ConstantInt *CI) {
1338   uint64_t V = CI->getRawValue();
1339   return V && (V & (V-1)) == 0;
1340 }
1341
1342 #if 0   // Currently unused
1343 // isLowOnes - Return true if the constant is of the form 0+1+.
1344 static bool isLowOnes(const ConstantInt *CI) {
1345   uint64_t V = CI->getRawValue();
1346
1347   // There won't be bits set in parts that the type doesn't contain.
1348   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1349
1350   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1351   return U && V && (U & V) == 0;
1352 }
1353 #endif
1354
1355 // isHighOnes - Return true if the constant is of the form 1+0+.
1356 // This is the same as lowones(~X).
1357 static bool isHighOnes(const ConstantInt *CI) {
1358   uint64_t V = ~CI->getRawValue();
1359   if (~V == 0) return false;  // 0's does not match "1+"
1360
1361   // There won't be bits set in parts that the type doesn't contain.
1362   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1363
1364   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1365   return U && V && (U & V) == 0;
1366 }
1367
1368
1369 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
1370 /// are carefully arranged to allow folding of expressions such as:
1371 ///
1372 ///      (A < B) | (A > B) --> (A != B)
1373 ///
1374 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1375 /// represents that the comparison is true if A == B, and bit value '1' is true
1376 /// if A < B.
1377 ///
1378 static unsigned getSetCondCode(const SetCondInst *SCI) {
1379   switch (SCI->getOpcode()) {
1380     // False -> 0
1381   case Instruction::SetGT: return 1;
1382   case Instruction::SetEQ: return 2;
1383   case Instruction::SetGE: return 3;
1384   case Instruction::SetLT: return 4;
1385   case Instruction::SetNE: return 5;
1386   case Instruction::SetLE: return 6;
1387     // True -> 7
1388   default:
1389     assert(0 && "Invalid SetCC opcode!");
1390     return 0;
1391   }
1392 }
1393
1394 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1395 /// opcode and two operands into either a constant true or false, or a brand new
1396 /// SetCC instruction.
1397 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1398   switch (Opcode) {
1399   case 0: return ConstantBool::False;
1400   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1401   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1402   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1403   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1404   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1405   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1406   case 7: return ConstantBool::True;
1407   default: assert(0 && "Illegal SetCCCode!"); return 0;
1408   }
1409 }
1410
1411 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1412 struct FoldSetCCLogical {
1413   InstCombiner &IC;
1414   Value *LHS, *RHS;
1415   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1416     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1417   bool shouldApply(Value *V) const {
1418     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1419       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1420               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1421     return false;
1422   }
1423   Instruction *apply(BinaryOperator &Log) const {
1424     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1425     if (SCI->getOperand(0) != LHS) {
1426       assert(SCI->getOperand(1) == LHS);
1427       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
1428     }
1429
1430     unsigned LHSCode = getSetCondCode(SCI);
1431     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1432     unsigned Code;
1433     switch (Log.getOpcode()) {
1434     case Instruction::And: Code = LHSCode & RHSCode; break;
1435     case Instruction::Or:  Code = LHSCode | RHSCode; break;
1436     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1437     default: assert(0 && "Illegal logical opcode!"); return 0;
1438     }
1439
1440     Value *RV = getSetCCValue(Code, LHS, RHS);
1441     if (Instruction *I = dyn_cast<Instruction>(RV))
1442       return I;
1443     // Otherwise, it's a constant boolean value...
1444     return IC.ReplaceInstUsesWith(Log, RV);
1445   }
1446 };
1447
1448 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
1449 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
1450 // guaranteed to be either a shift instruction or a binary operator.
1451 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1452                                     ConstantIntegral *OpRHS,
1453                                     ConstantIntegral *AndRHS,
1454                                     BinaryOperator &TheAnd) {
1455   Value *X = Op->getOperand(0);
1456   Constant *Together = 0;
1457   if (!isa<ShiftInst>(Op))
1458     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1459
1460   switch (Op->getOpcode()) {
1461   case Instruction::Xor:
1462     if (Op->hasOneUse()) {
1463       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1464       std::string OpName = Op->getName(); Op->setName("");
1465       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1466       InsertNewInstBefore(And, TheAnd);
1467       return BinaryOperator::createXor(And, Together);
1468     }
1469     break;
1470   case Instruction::Or:
1471     if (Together == AndRHS) // (X | C) & C --> C
1472       return ReplaceInstUsesWith(TheAnd, AndRHS);
1473
1474     if (Op->hasOneUse() && Together != OpRHS) {
1475       // (X | C1) & C2 --> (X | (C1&C2)) & C2
1476       std::string Op0Name = Op->getName(); Op->setName("");
1477       Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1478       InsertNewInstBefore(Or, TheAnd);
1479       return BinaryOperator::createAnd(Or, AndRHS);
1480     }
1481     break;
1482   case Instruction::Add:
1483     if (Op->hasOneUse()) {
1484       // Adding a one to a single bit bit-field should be turned into an XOR
1485       // of the bit.  First thing to check is to see if this AND is with a
1486       // single bit constant.
1487       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1488
1489       // Clear bits that are not part of the constant.
1490       AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
1491
1492       // If there is only one bit set...
1493       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1494         // Ok, at this point, we know that we are masking the result of the
1495         // ADD down to exactly one bit.  If the constant we are adding has
1496         // no bits set below this bit, then we can eliminate the ADD.
1497         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1498
1499         // Check to see if any bits below the one bit set in AndRHSV are set.
1500         if ((AddRHS & (AndRHSV-1)) == 0) {
1501           // If not, the only thing that can effect the output of the AND is
1502           // the bit specified by AndRHSV.  If that bit is set, the effect of
1503           // the XOR is to toggle the bit.  If it is clear, then the ADD has
1504           // no effect.
1505           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1506             TheAnd.setOperand(0, X);
1507             return &TheAnd;
1508           } else {
1509             std::string Name = Op->getName(); Op->setName("");
1510             // Pull the XOR out of the AND.
1511             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1512             InsertNewInstBefore(NewAnd, TheAnd);
1513             return BinaryOperator::createXor(NewAnd, AndRHS);
1514           }
1515         }
1516       }
1517     }
1518     break;
1519
1520   case Instruction::Shl: {
1521     // We know that the AND will not produce any of the bits shifted in, so if
1522     // the anded constant includes them, clear them now!
1523     //
1524     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1525     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1526     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1527
1528     if (CI == ShlMask) {   // Masking out bits that the shift already masks
1529       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
1530     } else if (CI != AndRHS) {                  // Reducing bits set in and.
1531       TheAnd.setOperand(1, CI);
1532       return &TheAnd;
1533     }
1534     break;
1535   }
1536   case Instruction::Shr:
1537     // We know that the AND will not produce any of the bits shifted in, so if
1538     // the anded constant includes them, clear them now!  This only applies to
1539     // unsigned shifts, because a signed shr may bring in set bits!
1540     //
1541     if (AndRHS->getType()->isUnsigned()) {
1542       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1543       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1544       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1545
1546       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
1547         return ReplaceInstUsesWith(TheAnd, Op);
1548       } else if (CI != AndRHS) {
1549         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
1550         return &TheAnd;
1551       }
1552     } else {   // Signed shr.
1553       // See if this is shifting in some sign extension, then masking it out
1554       // with an and.
1555       if (Op->hasOneUse()) {
1556         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1557         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1558         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1559         if (CI == AndRHS) {          // Masking out bits shifted in.
1560           // Make the argument unsigned.
1561           Value *ShVal = Op->getOperand(0);
1562           ShVal = InsertCastBefore(ShVal,
1563                                    ShVal->getType()->getUnsignedVersion(),
1564                                    TheAnd);
1565           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1566                                                     OpRHS, Op->getName()),
1567                                       TheAnd);
1568           Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1569           ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1570                                                              TheAnd.getName()),
1571                                       TheAnd);
1572           return new CastInst(ShVal, Op->getType());
1573         }
1574       }
1575     }
1576     break;
1577   }
1578   return 0;
1579 }
1580
1581
1582 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1583 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
1584 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
1585 /// insert new instructions.
1586 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1587                                            bool Inside, Instruction &IB) {
1588   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1589          "Lo is not <= Hi in range emission code!");
1590   if (Inside) {
1591     if (Lo == Hi)  // Trivially false.
1592       return new SetCondInst(Instruction::SetNE, V, V);
1593     if (cast<ConstantIntegral>(Lo)->isMinValue())
1594       return new SetCondInst(Instruction::SetLT, V, Hi);
1595
1596     Constant *AddCST = ConstantExpr::getNeg(Lo);
1597     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1598     InsertNewInstBefore(Add, IB);
1599     // Convert to unsigned for the comparison.
1600     const Type *UnsType = Add->getType()->getUnsignedVersion();
1601     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1602     AddCST = ConstantExpr::getAdd(AddCST, Hi);
1603     AddCST = ConstantExpr::getCast(AddCST, UnsType);
1604     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1605   }
1606
1607   if (Lo == Hi)  // Trivially true.
1608     return new SetCondInst(Instruction::SetEQ, V, V);
1609
1610   Hi = SubOne(cast<ConstantInt>(Hi));
1611   if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1612     return new SetCondInst(Instruction::SetGT, V, Hi);
1613
1614   // Emit X-Lo > Hi-Lo-1
1615   Constant *AddCST = ConstantExpr::getNeg(Lo);
1616   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1617   InsertNewInstBefore(Add, IB);
1618   // Convert to unsigned for the comparison.
1619   const Type *UnsType = Add->getType()->getUnsignedVersion();
1620   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1621   AddCST = ConstantExpr::getAdd(AddCST, Hi);
1622   AddCST = ConstantExpr::getCast(AddCST, UnsType);
1623   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1624 }
1625
1626 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1627 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
1628 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
1629 // not, since all 1s are not contiguous.
1630 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1631   uint64_t V = Val->getRawValue();
1632   if (!isShiftedMask_64(V)) return false;
1633
1634   // look for the first zero bit after the run of ones
1635   MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1636   // look for the first non-zero bit
1637   ME = 64-CountLeadingZeros_64(V);
1638   return true;
1639 }
1640
1641
1642
1643 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1644 /// where isSub determines whether the operator is a sub.  If we can fold one of
1645 /// the following xforms:
1646 /// 
1647 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1648 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1649 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1650 ///
1651 /// return (A +/- B).
1652 ///
1653 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1654                                         ConstantIntegral *Mask, bool isSub,
1655                                         Instruction &I) {
1656   Instruction *LHSI = dyn_cast<Instruction>(LHS);
1657   if (!LHSI || LHSI->getNumOperands() != 2 ||
1658       !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1659
1660   ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1661
1662   switch (LHSI->getOpcode()) {
1663   default: return 0;
1664   case Instruction::And:
1665     if (ConstantExpr::getAnd(N, Mask) == Mask) {
1666       // If the AndRHS is a power of two minus one (0+1+), this is simple.
1667       if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1668         break;
1669
1670       // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1671       // part, we don't need any explicit masks to take them out of A.  If that
1672       // is all N is, ignore it.
1673       unsigned MB, ME;
1674       if (isRunOfOnes(Mask, MB, ME)) {  // begin/end bit of run, inclusive
1675         Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1676         Mask = ConstantExpr::getUShr(Mask,
1677                                      ConstantInt::get(Type::UByteTy,
1678                                                       (64-MB+1)));
1679         if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1680           break;
1681       }
1682     }
1683     return 0;
1684   case Instruction::Or:
1685   case Instruction::Xor:
1686     // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1687     if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1688         ConstantExpr::getAnd(N, Mask)->isNullValue())
1689       break;
1690     return 0;
1691   }
1692   
1693   Instruction *New;
1694   if (isSub)
1695     New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1696   else
1697     New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1698   return InsertNewInstBefore(New, I);
1699 }
1700
1701
1702 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1703   bool Changed = SimplifyCommutative(I);
1704   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1705
1706   if (isa<UndefValue>(Op1))                         // X & undef -> 0
1707     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1708
1709   // and X, X = X
1710   if (Op0 == Op1)
1711     return ReplaceInstUsesWith(I, Op1);
1712
1713   if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1714     // and X, -1 == X
1715     if (AndRHS->isAllOnesValue())
1716       return ReplaceInstUsesWith(I, Op0);
1717
1718     if (MaskedValueIsZero(Op0, AndRHS))        // LHS & RHS == 0
1719       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1720
1721     // If the mask is not masking out any bits, there is no reason to do the
1722     // and in the first place.
1723     ConstantIntegral *NotAndRHS =
1724       cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1725     if (MaskedValueIsZero(Op0, NotAndRHS))
1726       return ReplaceInstUsesWith(I, Op0);
1727
1728     // Optimize a variety of ((val OP C1) & C2) combinations...
1729     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1730       Instruction *Op0I = cast<Instruction>(Op0);
1731       Value *Op0LHS = Op0I->getOperand(0);
1732       Value *Op0RHS = Op0I->getOperand(1);
1733       switch (Op0I->getOpcode()) {
1734       case Instruction::Xor:
1735       case Instruction::Or:
1736         // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1737         // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1738         if (MaskedValueIsZero(Op0LHS, AndRHS))
1739           return BinaryOperator::createAnd(Op0RHS, AndRHS);
1740         if (MaskedValueIsZero(Op0RHS, AndRHS))
1741           return BinaryOperator::createAnd(Op0LHS, AndRHS);
1742
1743         // If the mask is only needed on one incoming arm, push it up.
1744         if (Op0I->hasOneUse()) {
1745           if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1746             // Not masking anything out for the LHS, move to RHS.
1747             Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1748                                                    Op0RHS->getName()+".masked");
1749             InsertNewInstBefore(NewRHS, I);
1750             return BinaryOperator::create(
1751                        cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1752           }
1753           if (!isa<Constant>(NotAndRHS) &&
1754               MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1755             // Not masking anything out for the RHS, move to LHS.
1756             Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1757                                                    Op0LHS->getName()+".masked");
1758             InsertNewInstBefore(NewLHS, I);
1759             return BinaryOperator::create(
1760                        cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1761           }
1762         }
1763
1764         break;
1765       case Instruction::And:
1766         // (X & V) & C2 --> 0 iff (V & C2) == 0
1767         if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1768             MaskedValueIsZero(Op0RHS, AndRHS))
1769           return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1770         break;
1771       case Instruction::Add:
1772         // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1773         // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1774         // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1775         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1776           return BinaryOperator::createAnd(V, AndRHS);
1777         if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1778           return BinaryOperator::createAnd(V, AndRHS);  // Add commutes
1779         break;
1780
1781       case Instruction::Sub:
1782         // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1783         // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1784         // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1785         if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1786           return BinaryOperator::createAnd(V, AndRHS);
1787         break;
1788       }
1789
1790       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1791         if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1792           return Res;
1793     } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1794       const Type *SrcTy = CI->getOperand(0)->getType();
1795
1796       // If this is an integer truncation or change from signed-to-unsigned, and
1797       // if the source is an and/or with immediate, transform it.  This
1798       // frequently occurs for bitfield accesses.
1799       if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1800         if (SrcTy->getPrimitiveSizeInBits() >= 
1801               I.getType()->getPrimitiveSizeInBits() &&
1802             CastOp->getNumOperands() == 2)
1803           if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1804             if (CastOp->getOpcode() == Instruction::And) {
1805               // Change: and (cast (and X, C1) to T), C2
1806               // into  : and (cast X to T), trunc(C1)&C2
1807               // This will folds the two ands together, which may allow other
1808               // simplifications.
1809               Instruction *NewCast =
1810                 new CastInst(CastOp->getOperand(0), I.getType(),
1811                              CastOp->getName()+".shrunk");
1812               NewCast = InsertNewInstBefore(NewCast, I);
1813               
1814               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1815               C3 = ConstantExpr::getAnd(C3, AndRHS);            // trunc(C1)&C2
1816               return BinaryOperator::createAnd(NewCast, C3);
1817             } else if (CastOp->getOpcode() == Instruction::Or) {
1818               // Change: and (cast (or X, C1) to T), C2
1819               // into  : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1820               Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1821               if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)   // trunc(C1)&C2
1822                 return ReplaceInstUsesWith(I, AndRHS);
1823             }
1824       }
1825
1826
1827       // If this is an integer sign or zero extension instruction.
1828       if (SrcTy->isIntegral() &&
1829           SrcTy->getPrimitiveSizeInBits() <
1830           CI->getType()->getPrimitiveSizeInBits()) {
1831
1832         if (SrcTy->isUnsigned()) {
1833           // See if this and is clearing out bits that are known to be zero
1834           // anyway (due to the zero extension).
1835           Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1836           Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1837           Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1838           if (Result == Mask)  // The "and" isn't doing anything, remove it.
1839             return ReplaceInstUsesWith(I, CI);
1840           if (Result != AndRHS) { // Reduce the and RHS constant.
1841             I.setOperand(1, Result);
1842             return &I;
1843           }
1844
1845         } else {
1846           if (CI->hasOneUse() && SrcTy->isInteger()) {
1847             // We can only do this if all of the sign bits brought in are masked
1848             // out.  Compute this by first getting 0000011111, then inverting
1849             // it.
1850             Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1851             Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1852             Mask = ConstantExpr::getNot(Mask);    // 1's in the new bits.
1853             if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1854               // If the and is clearing all of the sign bits, change this to a
1855               // zero extension cast.  To do this, cast the cast input to
1856               // unsigned, then to the requested size.
1857               Value *CastOp = CI->getOperand(0);
1858               Instruction *NC =
1859                 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1860                              CI->getName()+".uns");
1861               NC = InsertNewInstBefore(NC, I);
1862               // Finally, insert a replacement for CI.
1863               NC = new CastInst(NC, CI->getType(), CI->getName());
1864               CI->setName("");
1865               NC = InsertNewInstBefore(NC, I);
1866               WorkList.push_back(CI);  // Delete CI later.
1867               I.setOperand(0, NC);
1868               return &I;               // The AND operand was modified.
1869             }
1870           }
1871         }
1872       }
1873     }
1874
1875     // Try to fold constant and into select arguments.
1876     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1877       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1878         return R;
1879     if (isa<PHINode>(Op0))
1880       if (Instruction *NV = FoldOpIntoPhi(I))
1881         return NV;
1882   }
1883
1884   Value *Op0NotVal = dyn_castNotVal(Op0);
1885   Value *Op1NotVal = dyn_castNotVal(Op1);
1886
1887   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
1888     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1889
1890   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1891   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1892     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1893                                                I.getName()+".demorgan");
1894     InsertNewInstBefore(Or, I);
1895     return BinaryOperator::createNot(Or);
1896   }
1897
1898   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1899     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1900     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1901       return R;
1902
1903     Value *LHSVal, *RHSVal;
1904     ConstantInt *LHSCst, *RHSCst;
1905     Instruction::BinaryOps LHSCC, RHSCC;
1906     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1907       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1908         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
1909             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1910             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1911             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1912           // Ensure that the larger constant is on the RHS.
1913           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1914           SetCondInst *LHS = cast<SetCondInst>(Op0);
1915           if (cast<ConstantBool>(Cmp)->getValue()) {
1916             std::swap(LHS, RHS);
1917             std::swap(LHSCst, RHSCst);
1918             std::swap(LHSCC, RHSCC);
1919           }
1920
1921           // At this point, we know we have have two setcc instructions
1922           // comparing a value against two constants and and'ing the result
1923           // together.  Because of the above check, we know that we only have
1924           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
1925           // FoldSetCCLogical check above), that the two constants are not
1926           // equal.
1927           assert(LHSCst != RHSCst && "Compares not folded above?");
1928
1929           switch (LHSCC) {
1930           default: assert(0 && "Unknown integer condition code!");
1931           case Instruction::SetEQ:
1932             switch (RHSCC) {
1933             default: assert(0 && "Unknown integer condition code!");
1934             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
1935             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
1936               return ReplaceInstUsesWith(I, ConstantBool::False);
1937             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
1938             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
1939               return ReplaceInstUsesWith(I, LHS);
1940             }
1941           case Instruction::SetNE:
1942             switch (RHSCC) {
1943             default: assert(0 && "Unknown integer condition code!");
1944             case Instruction::SetLT:
1945               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1946                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1947               break;                        // (X != 13 & X < 15) -> no change
1948             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
1949             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
1950               return ReplaceInstUsesWith(I, RHS);
1951             case Instruction::SetNE:
1952               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1953                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1954                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1955                                                       LHSVal->getName()+".off");
1956                 InsertNewInstBefore(Add, I);
1957                 const Type *UnsType = Add->getType()->getUnsignedVersion();
1958                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1959                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1960                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1961                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1962               }
1963               break;                        // (X != 13 & X != 15) -> no change
1964             }
1965             break;
1966           case Instruction::SetLT:
1967             switch (RHSCC) {
1968             default: assert(0 && "Unknown integer condition code!");
1969             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
1970             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
1971               return ReplaceInstUsesWith(I, ConstantBool::False);
1972             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
1973             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
1974               return ReplaceInstUsesWith(I, LHS);
1975             }
1976           case Instruction::SetGT:
1977             switch (RHSCC) {
1978             default: assert(0 && "Unknown integer condition code!");
1979             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
1980               return ReplaceInstUsesWith(I, LHS);
1981             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
1982               return ReplaceInstUsesWith(I, RHS);
1983             case Instruction::SetNE:
1984               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1985                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1986               break;                        // (X > 13 & X != 15) -> no change
1987             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
1988               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
1989             }
1990           }
1991         }
1992   }
1993
1994   return Changed ? &I : 0;
1995 }
1996
1997 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1998   bool Changed = SimplifyCommutative(I);
1999   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2000
2001   if (isa<UndefValue>(Op1))
2002     return ReplaceInstUsesWith(I,                         // X | undef -> -1
2003                                ConstantIntegral::getAllOnesValue(I.getType()));
2004
2005   // or X, X = X   or X, 0 == X
2006   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2007     return ReplaceInstUsesWith(I, Op0);
2008
2009   // or X, -1 == -1
2010   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2011     // If X is known to only contain bits that already exist in RHS, just
2012     // replace this instruction with RHS directly.
2013     if (MaskedValueIsZero(Op0,
2014                           cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2015       return ReplaceInstUsesWith(I, RHS);
2016
2017     ConstantInt *C1; Value *X;
2018     // (X & C1) | C2 --> (X | C2) & (C1|C2)
2019     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2020       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2021       Op0->setName("");
2022       InsertNewInstBefore(Or, I);
2023       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2024     }
2025
2026     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2027     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2028       std::string Op0Name = Op0->getName(); Op0->setName("");
2029       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2030       InsertNewInstBefore(Or, I);
2031       return BinaryOperator::createXor(Or,
2032                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2033     }
2034
2035     // Try to fold constant and into select arguments.
2036     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2037       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2038         return R;
2039     if (isa<PHINode>(Op0))
2040       if (Instruction *NV = FoldOpIntoPhi(I))
2041         return NV;
2042   }
2043
2044   Value *A, *B; ConstantInt *C1, *C2;
2045
2046   if (match(Op0, m_And(m_Value(A), m_Value(B))))
2047     if (A == Op1 || B == Op1)    // (A & ?) | A  --> A
2048       return ReplaceInstUsesWith(I, Op1);
2049   if (match(Op1, m_And(m_Value(A), m_Value(B))))
2050     if (A == Op0 || B == Op0)    // A | (A & ?)  --> A
2051       return ReplaceInstUsesWith(I, Op0);
2052
2053   // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2054   if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2055       MaskedValueIsZero(Op1, C1)) {
2056     Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2057     Op0->setName("");
2058     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2059   }
2060
2061   // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2062   if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2063       MaskedValueIsZero(Op0, C1)) {
2064     Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2065     Op0->setName("");
2066     return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2067   }
2068
2069   // (A & C1)|(B & C2)
2070   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2071       match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2072
2073     if (A == B)  // (A & C1)|(A & C2) == A & (C1|C2)
2074       return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2075
2076
2077     // If we have: ((V + N) & C1) | (V & C2)
2078     // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2079     // replace with V+N.
2080     if (C1 == ConstantExpr::getNot(C2)) {
2081       Value *V1, *V2;
2082       if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2083           match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2084         // Add commutes, try both ways.
2085         if (V1 == B && MaskedValueIsZero(V2, C2))
2086           return ReplaceInstUsesWith(I, A);
2087         if (V2 == B && MaskedValueIsZero(V1, C2))
2088           return ReplaceInstUsesWith(I, A);
2089       }
2090       // Or commutes, try both ways.
2091       if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2092           match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2093         // Add commutes, try both ways.
2094         if (V1 == A && MaskedValueIsZero(V2, C1))
2095           return ReplaceInstUsesWith(I, B);
2096         if (V2 == A && MaskedValueIsZero(V1, C1))
2097           return ReplaceInstUsesWith(I, B);
2098       }
2099     }
2100   }
2101
2102   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
2103     if (A == Op1)   // ~A | A == -1
2104       return ReplaceInstUsesWith(I,
2105                                 ConstantIntegral::getAllOnesValue(I.getType()));
2106   } else {
2107     A = 0;
2108   }
2109   // Note, A is still live here!
2110   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
2111     if (Op0 == B)
2112       return ReplaceInstUsesWith(I,
2113                                 ConstantIntegral::getAllOnesValue(I.getType()));
2114
2115     // (~A | ~B) == (~(A & B)) - De Morgan's Law
2116     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2117       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2118                                               I.getName()+".demorgan"), I);
2119       return BinaryOperator::createNot(And);
2120     }
2121   }
2122
2123   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2124   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2125     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2126       return R;
2127
2128     Value *LHSVal, *RHSVal;
2129     ConstantInt *LHSCst, *RHSCst;
2130     Instruction::BinaryOps LHSCC, RHSCC;
2131     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2132       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2133         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
2134             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2135             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2136             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2137           // Ensure that the larger constant is on the RHS.
2138           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2139           SetCondInst *LHS = cast<SetCondInst>(Op0);
2140           if (cast<ConstantBool>(Cmp)->getValue()) {
2141             std::swap(LHS, RHS);
2142             std::swap(LHSCst, RHSCst);
2143             std::swap(LHSCC, RHSCC);
2144           }
2145
2146           // At this point, we know we have have two setcc instructions
2147           // comparing a value against two constants and or'ing the result
2148           // together.  Because of the above check, we know that we only have
2149           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
2150           // FoldSetCCLogical check above), that the two constants are not
2151           // equal.
2152           assert(LHSCst != RHSCst && "Compares not folded above?");
2153
2154           switch (LHSCC) {
2155           default: assert(0 && "Unknown integer condition code!");
2156           case Instruction::SetEQ:
2157             switch (RHSCC) {
2158             default: assert(0 && "Unknown integer condition code!");
2159             case Instruction::SetEQ:
2160               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2161                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2162                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2163                                                       LHSVal->getName()+".off");
2164                 InsertNewInstBefore(Add, I);
2165                 const Type *UnsType = Add->getType()->getUnsignedVersion();
2166                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2167                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2168                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2169                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2170               }
2171               break;                  // (X == 13 | X == 15) -> no change
2172
2173             case Instruction::SetGT:  // (X == 13 | X > 14) -> no change
2174               break;
2175             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
2176             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
2177               return ReplaceInstUsesWith(I, RHS);
2178             }
2179             break;
2180           case Instruction::SetNE:
2181             switch (RHSCC) {
2182             default: assert(0 && "Unknown integer condition code!");
2183             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
2184             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
2185               return ReplaceInstUsesWith(I, LHS);
2186             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
2187             case Instruction::SetLT:        // (X != 13 | X < 15)  -> true
2188               return ReplaceInstUsesWith(I, ConstantBool::True);
2189             }
2190             break;
2191           case Instruction::SetLT:
2192             switch (RHSCC) {
2193             default: assert(0 && "Unknown integer condition code!");
2194             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
2195               break;
2196             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
2197               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2198             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
2199             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
2200               return ReplaceInstUsesWith(I, RHS);
2201             }
2202             break;
2203           case Instruction::SetGT:
2204             switch (RHSCC) {
2205             default: assert(0 && "Unknown integer condition code!");
2206             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
2207             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
2208               return ReplaceInstUsesWith(I, LHS);
2209             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
2210             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
2211               return ReplaceInstUsesWith(I, ConstantBool::True);
2212             }
2213           }
2214         }
2215   }
2216
2217   return Changed ? &I : 0;
2218 }
2219
2220 // XorSelf - Implements: X ^ X --> 0
2221 struct XorSelf {
2222   Value *RHS;
2223   XorSelf(Value *rhs) : RHS(rhs) {}
2224   bool shouldApply(Value *LHS) const { return LHS == RHS; }
2225   Instruction *apply(BinaryOperator &Xor) const {
2226     return &Xor;
2227   }
2228 };
2229
2230
2231 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2232   bool Changed = SimplifyCommutative(I);
2233   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2234
2235   if (isa<UndefValue>(Op1))
2236     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
2237
2238   // xor X, X = 0, even if X is nested in a sequence of Xor's.
2239   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2240     assert(Result == &I && "AssociativeOpt didn't work?");
2241     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2242   }
2243
2244   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2245     // xor X, 0 == X
2246     if (RHS->isNullValue())
2247       return ReplaceInstUsesWith(I, Op0);
2248
2249     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2250       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2251       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2252         if (RHS == ConstantBool::True && SCI->hasOneUse())
2253           return new SetCondInst(SCI->getInverseCondition(),
2254                                  SCI->getOperand(0), SCI->getOperand(1));
2255
2256       // ~(c-X) == X-c-1 == X+(-c-1)
2257       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2258         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2259           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2260           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2261                                               ConstantInt::get(I.getType(), 1));
2262           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2263         }
2264
2265       // ~(~X & Y) --> (X | ~Y)
2266       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2267         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2268         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2269           Instruction *NotY =
2270             BinaryOperator::createNot(Op0I->getOperand(1),
2271                                       Op0I->getOperand(1)->getName()+".not");
2272           InsertNewInstBefore(NotY, I);
2273           return BinaryOperator::createOr(Op0NotVal, NotY);
2274         }
2275       }
2276
2277       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2278         switch (Op0I->getOpcode()) {
2279         case Instruction::Add:
2280           // ~(X-c) --> (-c-1)-X
2281           if (RHS->isAllOnesValue()) {
2282             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2283             return BinaryOperator::createSub(
2284                            ConstantExpr::getSub(NegOp0CI,
2285                                              ConstantInt::get(I.getType(), 1)),
2286                                           Op0I->getOperand(0));
2287           }
2288           break;
2289         case Instruction::And:
2290           // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
2291           if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2292             return BinaryOperator::createOr(Op0, RHS);
2293           break;
2294         case Instruction::Or:
2295           // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
2296           if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
2297             return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
2298           break;
2299         default: break;
2300         }
2301     }
2302
2303     // Try to fold constant and into select arguments.
2304     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2305       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2306         return R;
2307     if (isa<PHINode>(Op0))
2308       if (Instruction *NV = FoldOpIntoPhi(I))
2309         return NV;
2310   }
2311
2312   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
2313     if (X == Op1)
2314       return ReplaceInstUsesWith(I,
2315                                 ConstantIntegral::getAllOnesValue(I.getType()));
2316
2317   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
2318     if (X == Op0)
2319       return ReplaceInstUsesWith(I,
2320                                 ConstantIntegral::getAllOnesValue(I.getType()));
2321
2322   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2323     if (Op1I->getOpcode() == Instruction::Or) {
2324       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
2325         cast<BinaryOperator>(Op1I)->swapOperands();
2326         I.swapOperands();
2327         std::swap(Op0, Op1);
2328       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
2329         I.swapOperands();
2330         std::swap(Op0, Op1);
2331       }
2332     } else if (Op1I->getOpcode() == Instruction::Xor) {
2333       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
2334         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2335       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
2336         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2337     }
2338
2339   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2340     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2341       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
2342         cast<BinaryOperator>(Op0I)->swapOperands();
2343       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
2344         Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2345                                                      Op1->getName()+".not"), I);
2346         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2347       }
2348     } else if (Op0I->getOpcode() == Instruction::Xor) {
2349       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
2350         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2351       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
2352         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2353     }
2354
2355   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
2356   Value *A, *B; ConstantInt *C1, *C2;
2357   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2358       match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
2359       ConstantExpr::getAnd(C1, C2)->isNullValue())
2360     return BinaryOperator::createOr(Op0, Op1);
2361
2362   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2363   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2364     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2365       return R;
2366
2367   return Changed ? &I : 0;
2368 }
2369
2370 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2371 /// overflowed for this type.
2372 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2373                             ConstantInt *In2) {
2374   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2375   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2376 }
2377
2378 static bool isPositive(ConstantInt *C) {
2379   return cast<ConstantSInt>(C)->getValue() >= 0;
2380 }
2381
2382 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2383 /// overflowed for this type.
2384 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2385                             ConstantInt *In2) {
2386   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2387
2388   if (In1->getType()->isUnsigned())
2389     return cast<ConstantUInt>(Result)->getValue() <
2390            cast<ConstantUInt>(In1)->getValue();
2391   if (isPositive(In1) != isPositive(In2))
2392     return false;
2393   if (isPositive(In1))
2394     return cast<ConstantSInt>(Result)->getValue() <
2395            cast<ConstantSInt>(In1)->getValue();
2396   return cast<ConstantSInt>(Result)->getValue() >
2397          cast<ConstantSInt>(In1)->getValue();
2398 }
2399
2400 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2401 /// code necessary to compute the offset from the base pointer (without adding
2402 /// in the base pointer).  Return the result as a signed integer of intptr size.
2403 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2404   TargetData &TD = IC.getTargetData();
2405   gep_type_iterator GTI = gep_type_begin(GEP);
2406   const Type *UIntPtrTy = TD.getIntPtrType();
2407   const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2408   Value *Result = Constant::getNullValue(SIntPtrTy);
2409
2410   // Build a mask for high order bits.
2411   uint64_t PtrSizeMask = ~0ULL;
2412   PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2413
2414   for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2415     Value *Op = GEP->getOperand(i);
2416     uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
2417     Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2418                                             SIntPtrTy);
2419     if (Constant *OpC = dyn_cast<Constant>(Op)) {
2420       if (!OpC->isNullValue()) {
2421         OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
2422         Scale = ConstantExpr::getMul(OpC, Scale);
2423         if (Constant *RC = dyn_cast<Constant>(Result))
2424           Result = ConstantExpr::getAdd(RC, Scale);
2425         else {
2426           // Emit an add instruction.
2427           Result = IC.InsertNewInstBefore(
2428              BinaryOperator::createAdd(Result, Scale,
2429                                        GEP->getName()+".offs"), I);
2430         }
2431       }
2432     } else {
2433       // Convert to correct type.
2434       Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2435                                                Op->getName()+".c"), I);
2436       if (Size != 1)
2437         // We'll let instcombine(mul) convert this to a shl if possible.
2438         Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2439                                                     GEP->getName()+".idx"), I);
2440
2441       // Emit an add instruction.
2442       Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
2443                                                     GEP->getName()+".offs"), I);
2444     }
2445   }
2446   return Result;
2447 }
2448
2449 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2450 /// else.  At this point we know that the GEP is on the LHS of the comparison.
2451 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2452                                         Instruction::BinaryOps Cond,
2453                                         Instruction &I) {
2454   assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
2455
2456   if (CastInst *CI = dyn_cast<CastInst>(RHS))
2457     if (isa<PointerType>(CI->getOperand(0)->getType()))
2458       RHS = CI->getOperand(0);
2459
2460   Value *PtrBase = GEPLHS->getOperand(0);
2461   if (PtrBase == RHS) {
2462     // As an optimization, we don't actually have to compute the actual value of
2463     // OFFSET if this is a seteq or setne comparison, just return whether each
2464     // index is zero or not.
2465     if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2466       Instruction *InVal = 0;
2467       gep_type_iterator GTI = gep_type_begin(GEPLHS);
2468       for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
2469         bool EmitIt = true;
2470         if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2471           if (isa<UndefValue>(C))  // undef index -> undef.
2472             return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2473           if (C->isNullValue())
2474             EmitIt = false;
2475           else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2476             EmitIt = false;  // This is indexing into a zero sized array?
2477           } else if (isa<ConstantInt>(C))
2478             return ReplaceInstUsesWith(I, // No comparison is needed here.
2479                                  ConstantBool::get(Cond == Instruction::SetNE));
2480         }
2481
2482         if (EmitIt) {
2483           Instruction *Comp =
2484             new SetCondInst(Cond, GEPLHS->getOperand(i),
2485                     Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2486           if (InVal == 0)
2487             InVal = Comp;
2488           else {
2489             InVal = InsertNewInstBefore(InVal, I);
2490             InsertNewInstBefore(Comp, I);
2491             if (Cond == Instruction::SetNE)   // True if any are unequal
2492               InVal = BinaryOperator::createOr(InVal, Comp);
2493             else                              // True if all are equal
2494               InVal = BinaryOperator::createAnd(InVal, Comp);
2495           }
2496         }
2497       }
2498
2499       if (InVal)
2500         return InVal;
2501       else
2502         ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2503                             ConstantBool::get(Cond == Instruction::SetEQ));
2504     }
2505
2506     // Only lower this if the setcc is the only user of the GEP or if we expect
2507     // the result to fold to a constant!
2508     if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2509       // ((gep Ptr, OFFSET) cmp Ptr)   ---> (OFFSET cmp 0).
2510       Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2511       return new SetCondInst(Cond, Offset,
2512                              Constant::getNullValue(Offset->getType()));
2513     }
2514   } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2515     // If the base pointers are different, but the indices are the same, just
2516     // compare the base pointer.
2517     if (PtrBase != GEPRHS->getOperand(0)) {
2518       bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
2519       IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2520                         GEPRHS->getOperand(0)->getType();
2521       if (IndicesTheSame)
2522         for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2523           if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2524             IndicesTheSame = false;
2525             break;
2526           }
2527
2528       // If all indices are the same, just compare the base pointers.
2529       if (IndicesTheSame)
2530         return new SetCondInst(Cond, GEPLHS->getOperand(0),
2531                                GEPRHS->getOperand(0));
2532
2533       // Otherwise, the base pointers are different and the indices are
2534       // different, bail out.
2535       return 0;
2536     }
2537
2538     // If one of the GEPs has all zero indices, recurse.
2539     bool AllZeros = true;
2540     for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2541       if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2542           !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2543         AllZeros = false;
2544         break;
2545       }
2546     if (AllZeros)
2547       return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2548                           SetCondInst::getSwappedCondition(Cond), I);
2549
2550     // If the other GEP has all zero indices, recurse.
2551     AllZeros = true;
2552     for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2553       if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2554           !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2555         AllZeros = false;
2556         break;
2557       }
2558     if (AllZeros)
2559       return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2560
2561     if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2562       // If the GEPs only differ by one index, compare it.
2563       unsigned NumDifferences = 0;  // Keep track of # differences.
2564       unsigned DiffOperand = 0;     // The operand that differs.
2565       for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2566         if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2567           if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2568                    GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
2569             // Irreconcilable differences.
2570             NumDifferences = 2;
2571             break;
2572           } else {
2573             if (NumDifferences++) break;
2574             DiffOperand = i;
2575           }
2576         }
2577
2578       if (NumDifferences == 0)   // SAME GEP?
2579         return ReplaceInstUsesWith(I, // No comparison is needed here.
2580                                  ConstantBool::get(Cond == Instruction::SetEQ));
2581       else if (NumDifferences == 1) {
2582         Value *LHSV = GEPLHS->getOperand(DiffOperand);
2583         Value *RHSV = GEPRHS->getOperand(DiffOperand);
2584
2585         // Convert the operands to signed values to make sure to perform a
2586         // signed comparison.
2587         const Type *NewTy = LHSV->getType()->getSignedVersion();
2588         if (LHSV->getType() != NewTy)
2589           LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2590                                                   LHSV->getName()), I);
2591         if (RHSV->getType() != NewTy)
2592           RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2593                                                   RHSV->getName()), I);
2594         return new SetCondInst(Cond, LHSV, RHSV);
2595       }
2596     }
2597
2598     // Only lower this if the setcc is the only user of the GEP or if we expect
2599     // the result to fold to a constant!
2600     if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2601         (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2602       // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)  --->  (OFFSET1 cmp OFFSET2)
2603       Value *L = EmitGEPOffset(GEPLHS, I, *this);
2604       Value *R = EmitGEPOffset(GEPRHS, I, *this);
2605       return new SetCondInst(Cond, L, R);
2606     }
2607   }
2608   return 0;
2609 }
2610
2611
2612 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
2613   bool Changed = SimplifyCommutative(I);
2614   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2615   const Type *Ty = Op0->getType();
2616
2617   // setcc X, X
2618   if (Op0 == Op1)
2619     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
2620
2621   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
2622     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2623
2624   // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2625   // addresses never equal each other!  We already know that Op0 != Op1.
2626   if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2627        isa<ConstantPointerNull>(Op0)) &&
2628       (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2629        isa<ConstantPointerNull>(Op1)))
2630     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2631
2632   // setcc's with boolean values can always be turned into bitwise operations
2633   if (Ty == Type::BoolTy) {
2634     switch (I.getOpcode()) {
2635     default: assert(0 && "Invalid setcc instruction!");
2636     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
2637       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
2638       InsertNewInstBefore(Xor, I);
2639       return BinaryOperator::createNot(Xor);
2640     }
2641     case Instruction::SetNE:
2642       return BinaryOperator::createXor(Op0, Op1);
2643
2644     case Instruction::SetGT:
2645       std::swap(Op0, Op1);                   // Change setgt -> setlt
2646       // FALL THROUGH
2647     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
2648       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2649       InsertNewInstBefore(Not, I);
2650       return BinaryOperator::createAnd(Not, Op1);
2651     }
2652     case Instruction::SetGE:
2653       std::swap(Op0, Op1);                   // Change setge -> setle
2654       // FALL THROUGH
2655     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
2656       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2657       InsertNewInstBefore(Not, I);
2658       return BinaryOperator::createOr(Not, Op1);
2659     }
2660     }
2661   }
2662
2663   // See if we are doing a comparison between a constant and an instruction that
2664   // can be folded into the comparison.
2665   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2666     // Check to see if we are comparing against the minimum or maximum value...
2667     if (CI->isMinValue()) {
2668       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
2669         return ReplaceInstUsesWith(I, ConstantBool::False);
2670       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
2671         return ReplaceInstUsesWith(I, ConstantBool::True);
2672       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
2673         return BinaryOperator::createSetEQ(Op0, Op1);
2674       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
2675         return BinaryOperator::createSetNE(Op0, Op1);
2676
2677     } else if (CI->isMaxValue()) {
2678       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
2679         return ReplaceInstUsesWith(I, ConstantBool::False);
2680       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
2681         return ReplaceInstUsesWith(I, ConstantBool::True);
2682       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
2683         return BinaryOperator::createSetEQ(Op0, Op1);
2684       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
2685         return BinaryOperator::createSetNE(Op0, Op1);
2686
2687       // Comparing against a value really close to min or max?
2688     } else if (isMinValuePlusOne(CI)) {
2689       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
2690         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2691       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
2692         return BinaryOperator::createSetNE(Op0, SubOne(CI));
2693
2694     } else if (isMaxValueMinusOne(CI)) {
2695       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
2696         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2697       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
2698         return BinaryOperator::createSetNE(Op0, AddOne(CI));
2699     }
2700
2701     // If we still have a setle or setge instruction, turn it into the
2702     // appropriate setlt or setgt instruction.  Since the border cases have
2703     // already been handled above, this requires little checking.
2704     //
2705     if (I.getOpcode() == Instruction::SetLE)
2706       return BinaryOperator::createSetLT(Op0, AddOne(CI));
2707     if (I.getOpcode() == Instruction::SetGE)
2708       return BinaryOperator::createSetGT(Op0, SubOne(CI));
2709
2710     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2711       switch (LHSI->getOpcode()) {
2712       case Instruction::And:
2713         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2714             LHSI->getOperand(0)->hasOneUse()) {
2715           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2716           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
2717           // happens a LOT in code produced by the C front-end, for bitfield
2718           // access.
2719           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2720           ConstantUInt *ShAmt;
2721           ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2722           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2723           const Type *Ty = LHSI->getType();
2724
2725           // We can fold this as long as we can't shift unknown bits
2726           // into the mask.  This can only happen with signed shift
2727           // rights, as they sign-extend.
2728           if (ShAmt) {
2729             bool CanFold = Shift->getOpcode() != Instruction::Shr ||
2730                            Shift->getType()->isUnsigned();
2731             if (!CanFold) {
2732               // To test for the bad case of the signed shr, see if any
2733               // of the bits shifted in could be tested after the mask.
2734               int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2735               if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2736
2737               Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
2738               Constant *ShVal =
2739                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2740               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2741                 CanFold = true;
2742             }
2743
2744             if (CanFold) {
2745               Constant *NewCst;
2746               if (Shift->getOpcode() == Instruction::Shl)
2747                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2748               else
2749                 NewCst = ConstantExpr::getShl(CI, ShAmt);
2750
2751               // Check to see if we are shifting out any of the bits being
2752               // compared.
2753               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2754                 // If we shifted bits out, the fold is not going to work out.
2755                 // As a special case, check to see if this means that the
2756                 // result is always true or false now.
2757                 if (I.getOpcode() == Instruction::SetEQ)
2758                   return ReplaceInstUsesWith(I, ConstantBool::False);
2759                 if (I.getOpcode() == Instruction::SetNE)
2760                   return ReplaceInstUsesWith(I, ConstantBool::True);
2761               } else {
2762                 I.setOperand(1, NewCst);
2763                 Constant *NewAndCST;
2764                 if (Shift->getOpcode() == Instruction::Shl)
2765                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2766                 else
2767                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2768                 LHSI->setOperand(1, NewAndCST);
2769                 LHSI->setOperand(0, Shift->getOperand(0));
2770                 WorkList.push_back(Shift); // Shift is dead.
2771                 AddUsesToWorkList(I);
2772                 return &I;
2773               }
2774             }
2775           }
2776         }
2777         break;
2778
2779       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
2780         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2781           switch (I.getOpcode()) {
2782           default: break;
2783           case Instruction::SetEQ:
2784           case Instruction::SetNE: {
2785             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2786
2787             // Check that the shift amount is in range.  If not, don't perform
2788             // undefined shifts.  When the shift is visited it will be
2789             // simplified.
2790             if (ShAmt->getValue() >= TypeBits)
2791               break;
2792
2793             // If we are comparing against bits always shifted out, the
2794             // comparison cannot succeed.
2795             Constant *Comp =
2796               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2797             if (Comp != CI) {// Comparing against a bit that we know is zero.
2798               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2799               Constant *Cst = ConstantBool::get(IsSetNE);
2800               return ReplaceInstUsesWith(I, Cst);
2801             }
2802
2803             if (LHSI->hasOneUse()) {
2804               // Otherwise strength reduce the shift into an and.
2805               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2806               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2807
2808               Constant *Mask;
2809               if (CI->getType()->isUnsigned()) {
2810                 Mask = ConstantUInt::get(CI->getType(), Val);
2811               } else if (ShAmtVal != 0) {
2812                 Mask = ConstantSInt::get(CI->getType(), Val);
2813               } else {
2814                 Mask = ConstantInt::getAllOnesValue(CI->getType());
2815               }
2816
2817               Instruction *AndI =
2818                 BinaryOperator::createAnd(LHSI->getOperand(0),
2819                                           Mask, LHSI->getName()+".mask");
2820               Value *And = InsertNewInstBefore(AndI, I);
2821               return new SetCondInst(I.getOpcode(), And,
2822                                      ConstantExpr::getUShr(CI, ShAmt));
2823             }
2824           }
2825           }
2826         }
2827         break;
2828
2829       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
2830         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2831           switch (I.getOpcode()) {
2832           default: break;
2833           case Instruction::SetEQ:
2834           case Instruction::SetNE: {
2835
2836             // Check that the shift amount is in range.  If not, don't perform
2837             // undefined shifts.  When the shift is visited it will be
2838             // simplified.
2839             unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2840             if (ShAmt->getValue() >= TypeBits)
2841               break;
2842
2843             // If we are comparing against bits always shifted out, the
2844             // comparison cannot succeed.
2845             Constant *Comp =
2846               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2847
2848             if (Comp != CI) {// Comparing against a bit that we know is zero.
2849               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2850               Constant *Cst = ConstantBool::get(IsSetNE);
2851               return ReplaceInstUsesWith(I, Cst);
2852             }
2853
2854             if (LHSI->hasOneUse() || CI->isNullValue()) {
2855               unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2856
2857               // Otherwise strength reduce the shift into an and.
2858               uint64_t Val = ~0ULL;          // All ones.
2859               Val <<= ShAmtVal;              // Shift over to the right spot.
2860
2861               Constant *Mask;
2862               if (CI->getType()->isUnsigned()) {
2863                 Val &= ~0ULL >> (64-TypeBits);
2864                 Mask = ConstantUInt::get(CI->getType(), Val);
2865               } else {
2866                 Mask = ConstantSInt::get(CI->getType(), Val);
2867               }
2868
2869               Instruction *AndI =
2870                 BinaryOperator::createAnd(LHSI->getOperand(0),
2871                                           Mask, LHSI->getName()+".mask");
2872               Value *And = InsertNewInstBefore(AndI, I);
2873               return new SetCondInst(I.getOpcode(), And,
2874                                      ConstantExpr::getShl(CI, ShAmt));
2875             }
2876             break;
2877           }
2878           }
2879         }
2880         break;
2881
2882       case Instruction::Div:
2883         // Fold: (div X, C1) op C2 -> range check
2884         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2885           // Fold this div into the comparison, producing a range check.
2886           // Determine, based on the divide type, what the range is being
2887           // checked.  If there is an overflow on the low or high side, remember
2888           // it, otherwise compute the range [low, hi) bounding the new value.
2889           bool LoOverflow = false, HiOverflow = 0;
2890           ConstantInt *LoBound = 0, *HiBound = 0;
2891
2892           ConstantInt *Prod;
2893           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2894
2895           Instruction::BinaryOps Opcode = I.getOpcode();
2896
2897           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
2898           } else if (LHSI->getType()->isUnsigned()) {  // udiv
2899             LoBound = Prod;
2900             LoOverflow = ProdOV;
2901             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2902           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
2903             if (CI->isNullValue()) {       // (X / pos) op 0
2904               // Can't overflow.
2905               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2906               HiBound = DivRHS;
2907             } else if (isPositive(CI)) {   // (X / pos) op pos
2908               LoBound = Prod;
2909               LoOverflow = ProdOV;
2910               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2911             } else {                       // (X / pos) op neg
2912               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2913               LoOverflow = AddWithOverflow(LoBound, Prod,
2914                                            cast<ConstantInt>(DivRHSH));
2915               HiBound = Prod;
2916               HiOverflow = ProdOV;
2917             }
2918           } else {                                     // Divisor is < 0.
2919             if (CI->isNullValue()) {       // (X / neg) op 0
2920               LoBound = AddOne(DivRHS);
2921               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2922               if (HiBound == DivRHS)
2923                 LoBound = 0;  // - INTMIN = INTMIN
2924             } else if (isPositive(CI)) {   // (X / neg) op pos
2925               HiOverflow = LoOverflow = ProdOV;
2926               if (!LoOverflow)
2927                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2928               HiBound = AddOne(Prod);
2929             } else {                       // (X / neg) op neg
2930               LoBound = Prod;
2931               LoOverflow = HiOverflow = ProdOV;
2932               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2933             }
2934
2935             // Dividing by a negate swaps the condition.
2936             Opcode = SetCondInst::getSwappedCondition(Opcode);
2937           }
2938
2939           if (LoBound) {
2940             Value *X = LHSI->getOperand(0);
2941             switch (Opcode) {
2942             default: assert(0 && "Unhandled setcc opcode!");
2943             case Instruction::SetEQ:
2944               if (LoOverflow && HiOverflow)
2945                 return ReplaceInstUsesWith(I, ConstantBool::False);
2946               else if (HiOverflow)
2947                 return new SetCondInst(Instruction::SetGE, X, LoBound);
2948               else if (LoOverflow)
2949                 return new SetCondInst(Instruction::SetLT, X, HiBound);
2950               else
2951                 return InsertRangeTest(X, LoBound, HiBound, true, I);
2952             case Instruction::SetNE:
2953               if (LoOverflow && HiOverflow)
2954                 return ReplaceInstUsesWith(I, ConstantBool::True);
2955               else if (HiOverflow)
2956                 return new SetCondInst(Instruction::SetLT, X, LoBound);
2957               else if (LoOverflow)
2958                 return new SetCondInst(Instruction::SetGE, X, HiBound);
2959               else
2960                 return InsertRangeTest(X, LoBound, HiBound, false, I);
2961             case Instruction::SetLT:
2962               if (LoOverflow)
2963                 return ReplaceInstUsesWith(I, ConstantBool::False);
2964               return new SetCondInst(Instruction::SetLT, X, LoBound);
2965             case Instruction::SetGT:
2966               if (HiOverflow)
2967                 return ReplaceInstUsesWith(I, ConstantBool::False);
2968               return new SetCondInst(Instruction::SetGE, X, HiBound);
2969             }
2970           }
2971         }
2972         break;
2973       }
2974
2975     // Simplify seteq and setne instructions...
2976     if (I.getOpcode() == Instruction::SetEQ ||
2977         I.getOpcode() == Instruction::SetNE) {
2978       bool isSetNE = I.getOpcode() == Instruction::SetNE;
2979
2980       // If the first operand is (and|or|xor) with a constant, and the second
2981       // operand is a constant, simplify a bit.
2982       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2983         switch (BO->getOpcode()) {
2984         case Instruction::Rem:
2985           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2986           if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2987               BO->hasOneUse() &&
2988               cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
2989             int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
2990             if (isPowerOf2_64(V)) {
2991               unsigned L2 = Log2_64(V);
2992               const Type *UTy = BO->getType()->getUnsignedVersion();
2993               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2994                                                              UTy, "tmp"), I);
2995               Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2996               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2997                                                     RHSCst, BO->getName()), I);
2998               return BinaryOperator::create(I.getOpcode(), NewRem,
2999                                             Constant::getNullValue(UTy));
3000             }
3001           }
3002           break;
3003
3004         case Instruction::Add:
3005           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3006           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3007             if (BO->hasOneUse())
3008               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3009                                      ConstantExpr::getSub(CI, BOp1C));
3010           } else if (CI->isNullValue()) {
3011             // Replace ((add A, B) != 0) with (A != -B) if A or B is
3012             // efficiently invertible, or if the add has just this one use.
3013             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3014
3015             if (Value *NegVal = dyn_castNegVal(BOp1))
3016               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3017             else if (Value *NegVal = dyn_castNegVal(BOp0))
3018               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3019             else if (BO->hasOneUse()) {
3020               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3021               BO->setName("");
3022               InsertNewInstBefore(Neg, I);
3023               return new SetCondInst(I.getOpcode(), BOp0, Neg);
3024             }
3025           }
3026           break;
3027         case Instruction::Xor:
3028           // For the xor case, we can xor two constants together, eliminating
3029           // the explicit xor.
3030           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3031             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3032                                   ConstantExpr::getXor(CI, BOC));
3033
3034           // FALLTHROUGH
3035         case Instruction::Sub:
3036           // Replace (([sub|xor] A, B) != 0) with (A != B)
3037           if (CI->isNullValue())
3038             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3039                                    BO->getOperand(1));
3040           break;
3041
3042         case Instruction::Or:
3043           // If bits are being or'd in that are not present in the constant we
3044           // are comparing against, then the comparison could never succeed!
3045           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3046             Constant *NotCI = ConstantExpr::getNot(CI);
3047             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3048               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3049           }
3050           break;
3051
3052         case Instruction::And:
3053           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3054             // If bits are being compared against that are and'd out, then the
3055             // comparison can never succeed!
3056             if (!ConstantExpr::getAnd(CI,
3057                                       ConstantExpr::getNot(BOC))->isNullValue())
3058               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3059
3060             // If we have ((X & C) == C), turn it into ((X & C) != 0).
3061             if (CI == BOC && isOneBitSet(CI))
3062               return new SetCondInst(isSetNE ? Instruction::SetEQ :
3063                                      Instruction::SetNE, Op0,
3064                                      Constant::getNullValue(CI->getType()));
3065
3066             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3067             // to be a signed value as appropriate.
3068             if (isSignBit(BOC)) {
3069               Value *X = BO->getOperand(0);
3070               // If 'X' is not signed, insert a cast now...
3071               if (!BOC->getType()->isSigned()) {
3072                 const Type *DestTy = BOC->getType()->getSignedVersion();
3073                 X = InsertCastBefore(X, DestTy, I);
3074               }
3075               return new SetCondInst(isSetNE ? Instruction::SetLT :
3076                                          Instruction::SetGE, X,
3077                                      Constant::getNullValue(X->getType()));
3078             }
3079
3080             // ((X & ~7) == 0) --> X < 8
3081             if (CI->isNullValue() && isHighOnes(BOC)) {
3082               Value *X = BO->getOperand(0);
3083               Constant *NegX = ConstantExpr::getNeg(BOC);
3084
3085               // If 'X' is signed, insert a cast now.
3086               if (NegX->getType()->isSigned()) {
3087                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3088                 X = InsertCastBefore(X, DestTy, I);
3089                 NegX = ConstantExpr::getCast(NegX, DestTy);
3090               }
3091
3092               return new SetCondInst(isSetNE ? Instruction::SetGE :
3093                                      Instruction::SetLT, X, NegX);
3094             }
3095
3096           }
3097         default: break;
3098         }
3099       }
3100     } else {  // Not a SetEQ/SetNE
3101       // If the LHS is a cast from an integral value of the same size,
3102       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3103         Value *CastOp = Cast->getOperand(0);
3104         const Type *SrcTy = CastOp->getType();
3105         unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3106         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3107             SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3108           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3109                  "Source and destination signednesses should differ!");
3110           if (Cast->getType()->isSigned()) {
3111             // If this is a signed comparison, check for comparisons in the
3112             // vicinity of zero.
3113             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3114               // X < 0  => x > 127
3115               return BinaryOperator::createSetGT(CastOp,
3116                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3117             else if (I.getOpcode() == Instruction::SetGT &&
3118                      cast<ConstantSInt>(CI)->getValue() == -1)
3119               // X > -1  => x < 128
3120               return BinaryOperator::createSetLT(CastOp,
3121                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3122           } else {
3123             ConstantUInt *CUI = cast<ConstantUInt>(CI);
3124             if (I.getOpcode() == Instruction::SetLT &&
3125                 CUI->getValue() == 1ULL << (SrcTySize-1))
3126               // X < 128 => X > -1
3127               return BinaryOperator::createSetGT(CastOp,
3128                                                  ConstantSInt::get(SrcTy, -1));
3129             else if (I.getOpcode() == Instruction::SetGT &&
3130                      CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3131               // X > 127 => X < 0
3132               return BinaryOperator::createSetLT(CastOp,
3133                                                  Constant::getNullValue(SrcTy));
3134           }
3135         }
3136       }
3137     }
3138   }
3139
3140   // Handle setcc with constant RHS's that can be integer, FP or pointer.
3141   if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3142     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3143       switch (LHSI->getOpcode()) {
3144       case Instruction::GetElementPtr:
3145         if (RHSC->isNullValue()) {
3146           // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3147           bool isAllZeros = true;
3148           for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3149             if (!isa<Constant>(LHSI->getOperand(i)) ||
3150                 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3151               isAllZeros = false;
3152               break;
3153             }
3154           if (isAllZeros)
3155             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3156                     Constant::getNullValue(LHSI->getOperand(0)->getType()));
3157         }
3158         break;
3159
3160       case Instruction::PHI:
3161         if (Instruction *NV = FoldOpIntoPhi(I))
3162           return NV;
3163         break;
3164       case Instruction::Select:
3165         // If either operand of the select is a constant, we can fold the
3166         // comparison into the select arms, which will cause one to be
3167         // constant folded and the select turned into a bitwise or.
3168         Value *Op1 = 0, *Op2 = 0;
3169         if (LHSI->hasOneUse()) {
3170           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3171             // Fold the known value into the constant operand.
3172             Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3173             // Insert a new SetCC of the other select operand.
3174             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3175                                                       LHSI->getOperand(2), RHSC,
3176                                                       I.getName()), I);
3177           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3178             // Fold the known value into the constant operand.
3179             Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3180             // Insert a new SetCC of the other select operand.
3181             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3182                                                       LHSI->getOperand(1), RHSC,
3183                                                       I.getName()), I);
3184           }
3185         }
3186
3187         if (Op1)
3188           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3189         break;
3190       }
3191   }
3192
3193   // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3194   if (User *GEP = dyn_castGetElementPtr(Op0))
3195     if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3196       return NI;
3197   if (User *GEP = dyn_castGetElementPtr(Op1))
3198     if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3199                            SetCondInst::getSwappedCondition(I.getOpcode()), I))
3200       return NI;
3201
3202   // Test to see if the operands of the setcc are casted versions of other
3203   // values.  If the cast can be stripped off both arguments, we do so now.
3204   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3205     Value *CastOp0 = CI->getOperand(0);
3206     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3207         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3208         (I.getOpcode() == Instruction::SetEQ ||
3209          I.getOpcode() == Instruction::SetNE)) {
3210       // We keep moving the cast from the left operand over to the right
3211       // operand, where it can often be eliminated completely.
3212       Op0 = CastOp0;
3213
3214       // If operand #1 is a cast instruction, see if we can eliminate it as
3215       // well.
3216       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3217         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3218                                                                Op0->getType()))
3219           Op1 = CI2->getOperand(0);
3220
3221       // If Op1 is a constant, we can fold the cast into the constant.
3222       if (Op1->getType() != Op0->getType())
3223         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3224           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3225         } else {
3226           // Otherwise, cast the RHS right before the setcc
3227           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3228           InsertNewInstBefore(cast<Instruction>(Op1), I);
3229         }
3230       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3231     }
3232
3233     // Handle the special case of: setcc (cast bool to X), <cst>
3234     // This comes up when you have code like
3235     //   int X = A < B;
3236     //   if (X) ...
3237     // For generality, we handle any zero-extension of any operand comparison
3238     // with a constant or another cast from the same type.
3239     if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3240       if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3241         return R;
3242   }
3243   return Changed ? &I : 0;
3244 }
3245
3246 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3247 // We only handle extending casts so far.
3248 //
3249 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3250   Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3251   const Type *SrcTy = LHSCIOp->getType();
3252   const Type *DestTy = SCI.getOperand(0)->getType();
3253   Value *RHSCIOp;
3254
3255   if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3256     return 0;
3257
3258   unsigned SrcBits  = SrcTy->getPrimitiveSizeInBits();
3259   unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3260   if (SrcBits >= DestBits) return 0;  // Only handle extending cast.
3261
3262   // Is this a sign or zero extension?
3263   bool isSignSrc  = SrcTy->isSigned();
3264   bool isSignDest = DestTy->isSigned();
3265
3266   if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3267     // Not an extension from the same type?
3268     RHSCIOp = CI->getOperand(0);
3269     if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3270   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3271     // Compute the constant that would happen if we truncated to SrcTy then
3272     // reextended to DestTy.
3273     Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3274
3275     if (ConstantExpr::getCast(Res, DestTy) == CI) {
3276       RHSCIOp = Res;
3277     } else {
3278       // If the value cannot be represented in the shorter type, we cannot emit
3279       // a simple comparison.
3280       if (SCI.getOpcode() == Instruction::SetEQ)
3281         return ReplaceInstUsesWith(SCI, ConstantBool::False);
3282       if (SCI.getOpcode() == Instruction::SetNE)
3283         return ReplaceInstUsesWith(SCI, ConstantBool::True);
3284
3285       // Evaluate the comparison for LT.
3286       Value *Result;
3287       if (DestTy->isSigned()) {
3288         // We're performing a signed comparison.
3289         if (isSignSrc) {
3290           // Signed extend and signed comparison.
3291           if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3292             Result = ConstantBool::False;
3293           else
3294             Result = ConstantBool::True;              // X < (large) --> true
3295         } else {
3296           // Unsigned extend and signed comparison.
3297           if (cast<ConstantSInt>(CI)->getValue() < 0)
3298             Result = ConstantBool::False;
3299           else
3300             Result = ConstantBool::True;
3301         }
3302       } else {
3303         // We're performing an unsigned comparison.
3304         if (!isSignSrc) {
3305           // Unsigned extend & compare -> always true.
3306           Result = ConstantBool::True;
3307         } else {
3308           // We're performing an unsigned comp with a sign extended value.
3309           // This is true if the input is >= 0. [aka >s -1]
3310           Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3311           Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3312                                                   NegOne, SCI.getName()), SCI);
3313         }
3314       }
3315
3316       // Finally, return the value computed.
3317       if (SCI.getOpcode() == Instruction::SetLT) {
3318         return ReplaceInstUsesWith(SCI, Result);
3319       } else {
3320         assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3321         if (Constant *CI = dyn_cast<Constant>(Result))
3322           return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3323         else
3324           return BinaryOperator::createNot(Result);
3325       }
3326     }
3327   } else {
3328     return 0;
3329   }
3330
3331   // Okay, just insert a compare of the reduced operands now!
3332   return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3333 }
3334
3335 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
3336   assert(I.getOperand(1)->getType() == Type::UByteTy);
3337   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3338   bool isLeftShift = I.getOpcode() == Instruction::Shl;
3339
3340   // shl X, 0 == X and shr X, 0 == X
3341   // shl 0, X == 0 and shr 0, X == 0
3342   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
3343       Op0 == Constant::getNullValue(Op0->getType()))
3344     return ReplaceInstUsesWith(I, Op0);
3345
3346   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
3347     if (!isLeftShift && I.getType()->isSigned())
3348       return ReplaceInstUsesWith(I, Op0);
3349     else                         // undef << X -> 0   AND  undef >>u X -> 0
3350       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3351   }
3352   if (isa<UndefValue>(Op1)) {
3353     if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
3354       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3355     else
3356       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
3357   }
3358
3359   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
3360   if (!isLeftShift)
3361     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3362       if (CSI->isAllOnesValue())
3363         return ReplaceInstUsesWith(I, CSI);
3364
3365   // Try to fold constant and into select arguments.
3366   if (isa<Constant>(Op0))
3367     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3368       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3369         return R;
3370
3371   // See if we can turn a signed shr into an unsigned shr.
3372   if (!isLeftShift && I.getType()->isSigned()) {
3373     if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3374       Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3375       V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3376                                             I.getName()), I);
3377       return new CastInst(V, I.getType());
3378     }
3379   }
3380
3381   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
3382     // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3383     // of a signed value.
3384     //
3385     unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3386     if (CUI->getValue() >= TypeBits) {
3387       if (!Op0->getType()->isSigned() || isLeftShift)
3388         return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3389       else {
3390         I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3391         return &I;
3392       }
3393     }
3394
3395     // ((X*C1) << C2) == (X * (C1 << C2))
3396     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3397       if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3398         if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3399           return BinaryOperator::createMul(BO->getOperand(0),
3400                                            ConstantExpr::getShl(BOOp, CUI));
3401
3402     // Try to fold constant and into select arguments.
3403     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3404       if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3405         return R;
3406     if (isa<PHINode>(Op0))
3407       if (Instruction *NV = FoldOpIntoPhi(I))
3408         return NV;
3409
3410     if (Op0->hasOneUse()) {
3411       // If this is a SHL of a sign-extending cast, see if we can turn the input
3412       // into a zero extending cast (a simple strength reduction).
3413       if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3414         const Type *SrcTy = CI->getOperand(0)->getType();
3415         if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3416             SrcTy->getPrimitiveSizeInBits() <
3417                    CI->getType()->getPrimitiveSizeInBits()) {
3418           // We can change it to a zero extension if we are shifting out all of
3419           // the sign extended bits.  To check this, form a mask of all of the
3420           // sign extend bits, then shift them left and see if we have anything
3421           // left.
3422           Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); //     1111
3423           Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());   // 00001111
3424           Mask = ConstantExpr::getNot(Mask);   // 1's in the sign bits: 11110000
3425           if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3426             // If the shift is nuking all of the sign bits, change this to a
3427             // zero extension cast.  To do this, cast the cast input to
3428             // unsigned, then to the requested size.
3429             Value *CastOp = CI->getOperand(0);
3430             Instruction *NC =
3431               new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3432                            CI->getName()+".uns");
3433             NC = InsertNewInstBefore(NC, I);
3434             // Finally, insert a replacement for CI.
3435             NC = new CastInst(NC, CI->getType(), CI->getName());
3436             CI->setName("");
3437             NC = InsertNewInstBefore(NC, I);
3438             WorkList.push_back(CI);  // Delete CI later.
3439             I.setOperand(0, NC);
3440             return &I;               // The SHL operand was modified.
3441           }
3442         }
3443       }
3444
3445       if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3446         // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
3447         Value *V1, *V2;
3448         ConstantInt *CC;
3449         switch (Op0BO->getOpcode()) {
3450         default: break;
3451         case Instruction::Add:
3452         case Instruction::And:
3453         case Instruction::Or:
3454         case Instruction::Xor:
3455           // These operators commute.
3456           // Turn (Y + (X >> C)) << C  ->  (X + (Y << C)) & (~0 << C)
3457           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3458               match(Op0BO->getOperand(1),
3459                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3460             Instruction *YS = new ShiftInst(Instruction::Shl, 
3461                                             Op0BO->getOperand(0), CUI,
3462                                             Op0BO->getName());
3463             InsertNewInstBefore(YS, I); // (Y << C)
3464             Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3465                                                     V1,
3466                                                Op0BO->getOperand(1)->getName());
3467             InsertNewInstBefore(X, I);  // (X + (Y << C))
3468             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3469             C2 = ConstantExpr::getShl(C2, CUI);
3470             return BinaryOperator::createAnd(X, C2);
3471           }
3472
3473           // Turn (Y + ((X >> C) & CC)) << C  ->  ((X & (CC << C)) + (Y << C))
3474           if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3475               match(Op0BO->getOperand(1),
3476                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
3477                           m_ConstantInt(CC))) && V2 == CUI &&
3478        cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3479             Instruction *YS = new ShiftInst(Instruction::Shl, 
3480                                             Op0BO->getOperand(0), CUI,
3481                                             Op0BO->getName());
3482             InsertNewInstBefore(YS, I); // (Y << C)
3483             Instruction *XM =
3484               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3485                                         V1->getName()+".mask");
3486             InsertNewInstBefore(XM, I); // X & (CC << C)
3487             
3488             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3489           }
3490               
3491           // FALL THROUGH.
3492         case Instruction::Sub:
3493           // Turn ((X >> C) + Y) << C  ->  (X + (Y << C)) & (~0 << C)
3494           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3495               match(Op0BO->getOperand(0),
3496                     m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3497             Instruction *YS = new ShiftInst(Instruction::Shl, 
3498                                             Op0BO->getOperand(1), CUI,
3499                                             Op0BO->getName());
3500             InsertNewInstBefore(YS, I); // (Y << C)
3501             Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3502                                                     V1,
3503                                               Op0BO->getOperand(0)->getName());
3504             InsertNewInstBefore(X, I);  // (X + (Y << C))
3505             Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3506             C2 = ConstantExpr::getShl(C2, CUI);
3507             return BinaryOperator::createAnd(X, C2);
3508           }
3509
3510           if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3511               match(Op0BO->getOperand(0),
3512                     m_And(m_Shr(m_Value(V1), m_Value(V2)),
3513                           m_ConstantInt(CC))) && V2 == CUI &&
3514        cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3515             Instruction *YS = new ShiftInst(Instruction::Shl, 
3516                                             Op0BO->getOperand(1), CUI,
3517                                             Op0BO->getName());
3518             InsertNewInstBefore(YS, I); // (Y << C)
3519             Instruction *XM =
3520               BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3521                                         V1->getName()+".mask");
3522             InsertNewInstBefore(XM, I); // X & (CC << C)
3523             
3524             return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3525           }
3526
3527           break;
3528         }
3529
3530
3531         // If the operand is an bitwise operator with a constant RHS, and the
3532         // shift is the only use, we can pull it out of the shift.
3533         if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3534           bool isValid = true;     // Valid only for And, Or, Xor
3535           bool highBitSet = false; // Transform if high bit of constant set?
3536
3537           switch (Op0BO->getOpcode()) {
3538           default: isValid = false; break;   // Do not perform transform!
3539           case Instruction::Add:
3540             isValid = isLeftShift;
3541             break;
3542           case Instruction::Or:
3543           case Instruction::Xor:
3544             highBitSet = false;
3545             break;
3546           case Instruction::And:
3547             highBitSet = true;
3548             break;
3549           }
3550
3551           // If this is a signed shift right, and the high bit is modified
3552           // by the logical operation, do not perform the transformation.
3553           // The highBitSet boolean indicates the value of the high bit of
3554           // the constant which would cause it to be modified for this
3555           // operation.
3556           //
3557           if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3558             uint64_t Val = Op0C->getRawValue();
3559             isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3560           }
3561
3562           if (isValid) {
3563             Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
3564
3565             Instruction *NewShift =
3566               new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3567                             Op0BO->getName());
3568             Op0BO->setName("");
3569             InsertNewInstBefore(NewShift, I);
3570
3571             return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3572                                           NewRHS);
3573           }
3574         }
3575       }
3576     }
3577
3578     // If this is a shift of a shift, see if we can fold the two together...
3579     if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
3580       if (ConstantUInt *ShiftAmt1C =
3581                                  dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
3582         unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3583         unsigned ShiftAmt2 = (unsigned)CUI->getValue();
3584
3585         // Check for (A << c1) << c2   and   (A >> c1) >> c2
3586         if (I.getOpcode() == Op0SI->getOpcode()) {
3587           unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
3588           if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3589             Amt = Op0->getType()->getPrimitiveSizeInBits();
3590           return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3591                                ConstantUInt::get(Type::UByteTy, Amt));
3592         }
3593
3594         // Check for (A << c1) >> c2 or visaversa.  If we are dealing with
3595         // signed types, we can only support the (A >> c1) << c2 configuration,
3596         // because it can not turn an arbitrary bit of A into a sign bit.
3597         if (I.getType()->isUnsigned() || isLeftShift) {
3598           // Calculate bitmask for what gets shifted off the edge...
3599           Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3600           if (isLeftShift)
3601             C = ConstantExpr::getShl(C, ShiftAmt1C);
3602           else
3603             C = ConstantExpr::getShr(C, ShiftAmt1C);
3604
3605           Instruction *Mask =
3606             BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3607                                       Op0SI->getOperand(0)->getName()+".mask");
3608           InsertNewInstBefore(Mask, I);
3609
3610           // Figure out what flavor of shift we should use...
3611           if (ShiftAmt1 == ShiftAmt2)
3612             return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
3613           else if (ShiftAmt1 < ShiftAmt2) {
3614             return new ShiftInst(I.getOpcode(), Mask,
3615                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3616           } else {
3617             return new ShiftInst(Op0SI->getOpcode(), Mask,
3618                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3619           }
3620         } else {
3621           // We can handle signed (X << C1) >> C2 if it's a sign extend.  In
3622           // this case, C1 == C2 and C1 is 8, 16, or 32.
3623           if (ShiftAmt1 == ShiftAmt2) {
3624             const Type *SExtType = 0;
3625             switch (ShiftAmt1) {
3626             case 8 : SExtType = Type::SByteTy; break;
3627             case 16: SExtType = Type::ShortTy; break;
3628             case 32: SExtType = Type::IntTy; break;
3629             }
3630             
3631             if (SExtType) {
3632               Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3633                                                    SExtType, "sext");
3634               InsertNewInstBefore(NewTrunc, I);
3635               return new CastInst(NewTrunc, I.getType());
3636             }
3637           }
3638         }
3639       }
3640   }
3641
3642   return 0;
3643 }
3644
3645 enum CastType {
3646   Noop     = 0,
3647   Truncate = 1,
3648   Signext  = 2,
3649   Zeroext  = 3
3650 };
3651
3652 /// getCastType - In the future, we will split the cast instruction into these
3653 /// various types.  Until then, we have to do the analysis here.
3654 static CastType getCastType(const Type *Src, const Type *Dest) {
3655   assert(Src->isIntegral() && Dest->isIntegral() &&
3656          "Only works on integral types!");
3657   unsigned SrcSize = Src->getPrimitiveSizeInBits();
3658   unsigned DestSize = Dest->getPrimitiveSizeInBits();
3659
3660   if (SrcSize == DestSize) return Noop;
3661   if (SrcSize > DestSize)  return Truncate;
3662   if (Src->isSigned()) return Signext;
3663   return Zeroext;
3664 }
3665
3666
3667 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3668 // instruction.
3669 //
3670 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3671                                           const Type *DstTy, TargetData *TD) {
3672
3673   // It is legal to eliminate the instruction if casting A->B->A if the sizes
3674   // are identical and the bits don't get reinterpreted (for example
3675   // int->float->int would not be allowed).
3676   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
3677     return true;
3678
3679   // If we are casting between pointer and integer types, treat pointers as
3680   // integers of the appropriate size for the code below.
3681   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3682   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3683   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
3684
3685   // Allow free casting and conversion of sizes as long as the sign doesn't
3686   // change...
3687   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
3688     CastType FirstCast = getCastType(SrcTy, MidTy);
3689     CastType SecondCast = getCastType(MidTy, DstTy);
3690
3691     // Capture the effect of these two casts.  If the result is a legal cast,
3692     // the CastType is stored here, otherwise a special code is used.
3693     static const unsigned CastResult[] = {
3694       // First cast is noop
3695       0, 1, 2, 3,
3696       // First cast is a truncate
3697       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
3698       // First cast is a sign ext
3699       2, 5, 2, 4,         // signext->zeroext never ok
3700       // First cast is a zero ext
3701       3, 5, 3, 3,
3702     };
3703
3704     unsigned Result = CastResult[FirstCast*4+SecondCast];
3705     switch (Result) {
3706     default: assert(0 && "Illegal table value!");
3707     case 0:
3708     case 1:
3709     case 2:
3710     case 3:
3711       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3712       // truncates, we could eliminate more casts.
3713       return (unsigned)getCastType(SrcTy, DstTy) == Result;
3714     case 4:
3715       return false;  // Not possible to eliminate this here.
3716     case 5:
3717       // Sign or zero extend followed by truncate is always ok if the result
3718       // is a truncate or noop.
3719       CastType ResultCast = getCastType(SrcTy, DstTy);
3720       if (ResultCast == Noop || ResultCast == Truncate)
3721         return true;
3722       // Otherwise we are still growing the value, we are only safe if the
3723       // result will match the sign/zeroextendness of the result.
3724       return ResultCast == FirstCast;
3725     }
3726   }
3727   return false;
3728 }
3729
3730 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
3731   if (V->getType() == Ty || isa<Constant>(V)) return false;
3732   if (const CastInst *CI = dyn_cast<CastInst>(V))
3733     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3734                                TD))
3735       return false;
3736   return true;
3737 }
3738
3739 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3740 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
3741 /// casts that are known to not do anything...
3742 ///
3743 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3744                                              Instruction *InsertBefore) {
3745   if (V->getType() == DestTy) return V;
3746   if (Constant *C = dyn_cast<Constant>(V))
3747     return ConstantExpr::getCast(C, DestTy);
3748
3749   CastInst *CI = new CastInst(V, DestTy, V->getName());
3750   InsertNewInstBefore(CI, *InsertBefore);
3751   return CI;
3752 }
3753
3754 // CastInst simplification
3755 //
3756 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
3757   Value *Src = CI.getOperand(0);
3758
3759   // If the user is casting a value to the same type, eliminate this cast
3760   // instruction...
3761   if (CI.getType() == Src->getType())
3762     return ReplaceInstUsesWith(CI, Src);
3763
3764   if (isa<UndefValue>(Src))   // cast undef -> undef
3765     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3766
3767   // If casting the result of another cast instruction, try to eliminate this
3768   // one!
3769   //
3770   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {   // A->B->C cast
3771     Value *A = CSrc->getOperand(0);
3772     if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3773                                CI.getType(), TD)) {
3774       // This instruction now refers directly to the cast's src operand.  This
3775       // has a good chance of making CSrc dead.
3776       CI.setOperand(0, CSrc->getOperand(0));
3777       return &CI;
3778     }
3779
3780     // If this is an A->B->A cast, and we are dealing with integral types, try
3781     // to convert this into a logical 'and' instruction.
3782     //
3783     if (A->getType()->isInteger() &&
3784         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
3785         CSrc->getType()->isUnsigned() &&   // B->A cast must zero extend
3786         CSrc->getType()->getPrimitiveSizeInBits() <
3787                     CI.getType()->getPrimitiveSizeInBits()&&
3788         A->getType()->getPrimitiveSizeInBits() ==
3789               CI.getType()->getPrimitiveSizeInBits()) {
3790       assert(CSrc->getType() != Type::ULongTy &&
3791              "Cannot have type bigger than ulong!");
3792       uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
3793       Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3794                                           AndValue);
3795       AndOp = ConstantExpr::getCast(AndOp, A->getType());
3796       Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3797       if (And->getType() != CI.getType()) {
3798         And->setName(CSrc->getName()+".mask");
3799         InsertNewInstBefore(And, CI);
3800         And = new CastInst(And, CI.getType());
3801       }
3802       return And;
3803     }
3804   }
3805
3806   // If this is a cast to bool, turn it into the appropriate setne instruction.
3807   if (CI.getType() == Type::BoolTy)
3808     return BinaryOperator::createSetNE(CI.getOperand(0),
3809                        Constant::getNullValue(CI.getOperand(0)->getType()));
3810
3811   // If casting the result of a getelementptr instruction with no offset, turn
3812   // this into a cast of the original pointer!
3813   //
3814   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
3815     bool AllZeroOperands = true;
3816     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3817       if (!isa<Constant>(GEP->getOperand(i)) ||
3818           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3819         AllZeroOperands = false;
3820         break;
3821       }
3822     if (AllZeroOperands) {
3823       CI.setOperand(0, GEP->getOperand(0));
3824       return &CI;
3825     }
3826   }
3827
3828   // If we are casting a malloc or alloca to a pointer to a type of the same
3829   // size, rewrite the allocation instruction to allocate the "right" type.
3830   //
3831   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
3832     if (AI->hasOneUse() && !AI->isArrayAllocation())
3833       if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3834         // Get the type really allocated and the type casted to...
3835         const Type *AllocElTy = AI->getAllocatedType();
3836         const Type *CastElTy = PTy->getElementType();
3837         if (AllocElTy->isSized() && CastElTy->isSized()) {
3838           uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3839           uint64_t CastElTySize = TD->getTypeSize(CastElTy);
3840
3841           // If the allocation is for an even multiple of the cast type size
3842           if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3843             Value *Amt = ConstantUInt::get(Type::UIntTy,
3844                                          AllocElTySize/CastElTySize);
3845             std::string Name = AI->getName(); AI->setName("");
3846             AllocationInst *New;
3847             if (isa<MallocInst>(AI))
3848               New = new MallocInst(CastElTy, Amt, Name);
3849             else
3850               New = new AllocaInst(CastElTy, Amt, Name);
3851             InsertNewInstBefore(New, *AI);
3852             return ReplaceInstUsesWith(CI, New);
3853           }
3854         }
3855       }
3856
3857   if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3858     if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3859       return NV;
3860   if (isa<PHINode>(Src))
3861     if (Instruction *NV = FoldOpIntoPhi(CI))
3862       return NV;
3863
3864   // If the source value is an instruction with only this use, we can attempt to
3865   // propagate the cast into the instruction.  Also, only handle integral types
3866   // for now.
3867   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
3868     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
3869         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
3870       const Type *DestTy = CI.getType();
3871       unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3872       unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
3873
3874       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3875       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3876
3877       switch (SrcI->getOpcode()) {
3878       case Instruction::Add:
3879       case Instruction::Mul:
3880       case Instruction::And:
3881       case Instruction::Or:
3882       case Instruction::Xor:
3883         // If we are discarding information, or just changing the sign, rewrite.
3884         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3885           // Don't insert two casts if they cannot be eliminated.  We allow two
3886           // casts to be inserted if the sizes are the same.  This could only be
3887           // converting signedness, which is a noop.
3888           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3889               !ValueRequiresCast(Op0, DestTy, TD)) {
3890             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3891             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3892             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3893                              ->getOpcode(), Op0c, Op1c);
3894           }
3895         }
3896
3897         // cast (xor bool X, true) to int  --> xor (cast bool X to int), 1
3898         if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3899             Op1 == ConstantBool::True &&
3900             (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3901           Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3902           return BinaryOperator::createXor(New,
3903                                            ConstantInt::get(CI.getType(), 1));
3904         }
3905         break;
3906       case Instruction::Shl:
3907         // Allow changing the sign of the source operand.  Do not allow changing
3908         // the size of the shift, UNLESS the shift amount is a constant.  We
3909         // mush not change variable sized shifts to a smaller size, because it
3910         // is undefined to shift more bits out than exist in the value.
3911         if (DestBitSize == SrcBitSize ||
3912             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3913           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3914           return new ShiftInst(Instruction::Shl, Op0c, Op1);
3915         }
3916         break;
3917       case Instruction::Shr:
3918         // If this is a signed shr, and if all bits shifted in are about to be
3919         // truncated off, turn it into an unsigned shr to allow greater
3920         // simplifications.
3921         if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3922             isa<ConstantInt>(Op1)) {
3923           unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3924           if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3925             // Convert to unsigned.
3926             Value *N1 = InsertOperandCastBefore(Op0,
3927                                      Op0->getType()->getUnsignedVersion(), &CI);
3928             // Insert the new shift, which is now unsigned.
3929             N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3930                                                    Op1, Src->getName()), CI);
3931             return new CastInst(N1, CI.getType());
3932           }
3933         }
3934         break;
3935
3936       case Instruction::SetNE:
3937         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3938           if (Op1C->getRawValue() == 0) {
3939             // If the input only has the low bit set, simplify directly.
3940             Constant *Not1 =
3941               ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3942             // cast (X != 0) to int  --> X if X&~1 == 0
3943             if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3944               if (CI.getType() == Op0->getType())
3945                 return ReplaceInstUsesWith(CI, Op0);
3946               else
3947                 return new CastInst(Op0, CI.getType());
3948             }
3949
3950             // If the input is an and with a single bit, shift then simplify.
3951             ConstantInt *AndRHS;
3952             if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3953               if (AndRHS->getRawValue() &&
3954                   (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
3955                 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
3956                 // Perform an unsigned shr by shiftamt.  Convert input to
3957                 // unsigned if it is signed.
3958                 Value *In = Op0;
3959                 if (In->getType()->isSigned())
3960                   In = InsertNewInstBefore(new CastInst(In,
3961                         In->getType()->getUnsignedVersion(), In->getName()),CI);
3962                 // Insert the shift to put the result in the low bit.
3963                 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3964                                       ConstantInt::get(Type::UByteTy, ShiftAmt),
3965                                                    In->getName()+".lobit"), CI);
3966                 if (CI.getType() == In->getType())
3967                   return ReplaceInstUsesWith(CI, In);
3968                 else
3969                   return new CastInst(In, CI.getType());
3970               }
3971           }
3972         }
3973         break;
3974       case Instruction::SetEQ:
3975         // We if we are just checking for a seteq of a single bit and casting it
3976         // to an integer.  If so, shift the bit to the appropriate place then
3977         // cast to integer to avoid the comparison.
3978         if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3979           // Is Op1C a power of two or zero?
3980           if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3981             // cast (X == 1) to int -> X iff X has only the low bit set.
3982             if (Op1C->getRawValue() == 1) {
3983               Constant *Not1 =
3984                 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3985               if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3986                 if (CI.getType() == Op0->getType())
3987                   return ReplaceInstUsesWith(CI, Op0);
3988                 else
3989                   return new CastInst(Op0, CI.getType());
3990               }
3991             }
3992           }
3993         }
3994         break;
3995       }
3996     }
3997   return 0;
3998 }
3999
4000 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4001 ///   %C = or %A, %B
4002 ///   %D = select %cond, %C, %A
4003 /// into:
4004 ///   %C = select %cond, %B, 0
4005 ///   %D = or %A, %C
4006 ///
4007 /// Assuming that the specified instruction is an operand to the select, return
4008 /// a bitmask indicating which operands of this instruction are foldable if they
4009 /// equal the other incoming value of the select.
4010 ///
4011 static unsigned GetSelectFoldableOperands(Instruction *I) {
4012   switch (I->getOpcode()) {
4013   case Instruction::Add:
4014   case Instruction::Mul:
4015   case Instruction::And:
4016   case Instruction::Or:
4017   case Instruction::Xor:
4018     return 3;              // Can fold through either operand.
4019   case Instruction::Sub:   // Can only fold on the amount subtracted.
4020   case Instruction::Shl:   // Can only fold on the shift amount.
4021   case Instruction::Shr:
4022     return 1;
4023   default:
4024     return 0;              // Cannot fold
4025   }
4026 }
4027
4028 /// GetSelectFoldableConstant - For the same transformation as the previous
4029 /// function, return the identity constant that goes into the select.
4030 static Constant *GetSelectFoldableConstant(Instruction *I) {
4031   switch (I->getOpcode()) {
4032   default: assert(0 && "This cannot happen!"); abort();
4033   case Instruction::Add:
4034   case Instruction::Sub:
4035   case Instruction::Or:
4036   case Instruction::Xor:
4037     return Constant::getNullValue(I->getType());
4038   case Instruction::Shl:
4039   case Instruction::Shr:
4040     return Constant::getNullValue(Type::UByteTy);
4041   case Instruction::And:
4042     return ConstantInt::getAllOnesValue(I->getType());
4043   case Instruction::Mul:
4044     return ConstantInt::get(I->getType(), 1);
4045   }
4046 }
4047
4048 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4049 /// have the same opcode and only one use each.  Try to simplify this.
4050 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4051                                           Instruction *FI) {
4052   if (TI->getNumOperands() == 1) {
4053     // If this is a non-volatile load or a cast from the same type,
4054     // merge.
4055     if (TI->getOpcode() == Instruction::Cast) {
4056       if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4057         return 0;
4058     } else {
4059       return 0;  // unknown unary op.
4060     }
4061
4062     // Fold this by inserting a select from the input values.
4063     SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4064                                        FI->getOperand(0), SI.getName()+".v");
4065     InsertNewInstBefore(NewSI, SI);
4066     return new CastInst(NewSI, TI->getType());
4067   }
4068
4069   // Only handle binary operators here.
4070   if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4071     return 0;
4072
4073   // Figure out if the operations have any operands in common.
4074   Value *MatchOp, *OtherOpT, *OtherOpF;
4075   bool MatchIsOpZero;
4076   if (TI->getOperand(0) == FI->getOperand(0)) {
4077     MatchOp  = TI->getOperand(0);
4078     OtherOpT = TI->getOperand(1);
4079     OtherOpF = FI->getOperand(1);
4080     MatchIsOpZero = true;
4081   } else if (TI->getOperand(1) == FI->getOperand(1)) {
4082     MatchOp  = TI->getOperand(1);
4083     OtherOpT = TI->getOperand(0);
4084     OtherOpF = FI->getOperand(0);
4085     MatchIsOpZero = false;
4086   } else if (!TI->isCommutative()) {
4087     return 0;
4088   } else if (TI->getOperand(0) == FI->getOperand(1)) {
4089     MatchOp  = TI->getOperand(0);
4090     OtherOpT = TI->getOperand(1);
4091     OtherOpF = FI->getOperand(0);
4092     MatchIsOpZero = true;
4093   } else if (TI->getOperand(1) == FI->getOperand(0)) {
4094     MatchOp  = TI->getOperand(1);
4095     OtherOpT = TI->getOperand(0);
4096     OtherOpF = FI->getOperand(1);
4097     MatchIsOpZero = true;
4098   } else {
4099     return 0;
4100   }
4101
4102   // If we reach here, they do have operations in common.
4103   SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4104                                      OtherOpF, SI.getName()+".v");
4105   InsertNewInstBefore(NewSI, SI);
4106
4107   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4108     if (MatchIsOpZero)
4109       return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4110     else
4111       return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4112   } else {
4113     if (MatchIsOpZero)
4114       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4115     else
4116       return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4117   }
4118 }
4119
4120 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
4121   Value *CondVal = SI.getCondition();
4122   Value *TrueVal = SI.getTrueValue();
4123   Value *FalseVal = SI.getFalseValue();
4124
4125   // select true, X, Y  -> X
4126   // select false, X, Y -> Y
4127   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
4128     if (C == ConstantBool::True)
4129       return ReplaceInstUsesWith(SI, TrueVal);
4130     else {
4131       assert(C == ConstantBool::False);
4132       return ReplaceInstUsesWith(SI, FalseVal);
4133     }
4134
4135   // select C, X, X -> X
4136   if (TrueVal == FalseVal)
4137     return ReplaceInstUsesWith(SI, TrueVal);
4138
4139   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
4140     return ReplaceInstUsesWith(SI, FalseVal);
4141   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
4142     return ReplaceInstUsesWith(SI, TrueVal);
4143   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
4144     if (isa<Constant>(TrueVal))
4145       return ReplaceInstUsesWith(SI, TrueVal);
4146     else
4147       return ReplaceInstUsesWith(SI, FalseVal);
4148   }
4149
4150   if (SI.getType() == Type::BoolTy)
4151     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4152       if (C == ConstantBool::True) {
4153         // Change: A = select B, true, C --> A = or B, C
4154         return BinaryOperator::createOr(CondVal, FalseVal);
4155       } else {
4156         // Change: A = select B, false, C --> A = and !B, C
4157         Value *NotCond =
4158           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4159                                              "not."+CondVal->getName()), SI);
4160         return BinaryOperator::createAnd(NotCond, FalseVal);
4161       }
4162     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4163       if (C == ConstantBool::False) {
4164         // Change: A = select B, C, false --> A = and B, C
4165         return BinaryOperator::createAnd(CondVal, TrueVal);
4166       } else {
4167         // Change: A = select B, C, true --> A = or !B, C
4168         Value *NotCond =
4169           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4170                                              "not."+CondVal->getName()), SI);
4171         return BinaryOperator::createOr(NotCond, TrueVal);
4172       }
4173     }
4174
4175   // Selecting between two integer constants?
4176   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4177     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4178       // select C, 1, 0 -> cast C to int
4179       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4180         return new CastInst(CondVal, SI.getType());
4181       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4182         // select C, 0, 1 -> cast !C to int
4183         Value *NotCond =
4184           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4185                                                "not."+CondVal->getName()), SI);
4186         return new CastInst(NotCond, SI.getType());
4187       }
4188
4189       // If one of the constants is zero (we know they can't both be) and we
4190       // have a setcc instruction with zero, and we have an 'and' with the
4191       // non-constant value, eliminate this whole mess.  This corresponds to
4192       // cases like this: ((X & 27) ? 27 : 0)
4193       if (TrueValC->isNullValue() || FalseValC->isNullValue())
4194         if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4195           if ((IC->getOpcode() == Instruction::SetEQ ||
4196                IC->getOpcode() == Instruction::SetNE) &&
4197               isa<ConstantInt>(IC->getOperand(1)) &&
4198               cast<Constant>(IC->getOperand(1))->isNullValue())
4199             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4200               if (ICA->getOpcode() == Instruction::And &&
4201                   isa<ConstantInt>(ICA->getOperand(1)) &&
4202                   (ICA->getOperand(1) == TrueValC ||
4203                    ICA->getOperand(1) == FalseValC) &&
4204                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4205                 // Okay, now we know that everything is set up, we just don't
4206                 // know whether we have a setne or seteq and whether the true or
4207                 // false val is the zero.
4208                 bool ShouldNotVal = !TrueValC->isNullValue();
4209                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4210                 Value *V = ICA;
4211                 if (ShouldNotVal)
4212                   V = InsertNewInstBefore(BinaryOperator::create(
4213                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
4214                 return ReplaceInstUsesWith(SI, V);
4215               }
4216     }
4217
4218   // See if we are selecting two values based on a comparison of the two values.
4219   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4220     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4221       // Transform (X == Y) ? X : Y  -> Y
4222       if (SCI->getOpcode() == Instruction::SetEQ)
4223         return ReplaceInstUsesWith(SI, FalseVal);
4224       // Transform (X != Y) ? X : Y  -> X
4225       if (SCI->getOpcode() == Instruction::SetNE)
4226         return ReplaceInstUsesWith(SI, TrueVal);
4227       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4228
4229     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4230       // Transform (X == Y) ? Y : X  -> X
4231       if (SCI->getOpcode() == Instruction::SetEQ)
4232         return ReplaceInstUsesWith(SI, FalseVal);
4233       // Transform (X != Y) ? Y : X  -> Y
4234       if (SCI->getOpcode() == Instruction::SetNE)
4235         return ReplaceInstUsesWith(SI, TrueVal);
4236       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4237     }
4238   }
4239
4240   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4241     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4242       if (TI->hasOneUse() && FI->hasOneUse()) {
4243         bool isInverse = false;
4244         Instruction *AddOp = 0, *SubOp = 0;
4245
4246         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4247         if (TI->getOpcode() == FI->getOpcode())
4248           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4249             return IV;
4250
4251         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
4252         // even legal for FP.
4253         if (TI->getOpcode() == Instruction::Sub &&
4254             FI->getOpcode() == Instruction::Add) {
4255           AddOp = FI; SubOp = TI;
4256         } else if (FI->getOpcode() == Instruction::Sub &&
4257                    TI->getOpcode() == Instruction::Add) {
4258           AddOp = TI; SubOp = FI;
4259         }
4260
4261         if (AddOp) {
4262           Value *OtherAddOp = 0;
4263           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4264             OtherAddOp = AddOp->getOperand(1);
4265           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4266             OtherAddOp = AddOp->getOperand(0);
4267           }
4268
4269           if (OtherAddOp) {
4270             // So at this point we know we have:
4271             //        select C, (add X, Y), (sub X, ?)
4272             // We can do the transform profitably if either 'Y' = '?' or '?' is
4273             // a constant.
4274             if (SubOp->getOperand(1) == AddOp ||
4275                 isa<Constant>(SubOp->getOperand(1))) {
4276               Value *NegVal;
4277               if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4278                 NegVal = ConstantExpr::getNeg(C);
4279               } else {
4280                 NegVal = InsertNewInstBefore(
4281                            BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4282               }
4283
4284               Value *NewTrueOp = OtherAddOp;
4285               Value *NewFalseOp = NegVal;
4286               if (AddOp != TI)
4287                 std::swap(NewTrueOp, NewFalseOp);
4288               Instruction *NewSel =
4289                 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
4290
4291               NewSel = InsertNewInstBefore(NewSel, SI);
4292               return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
4293             }
4294           }
4295         }
4296       }
4297
4298   // See if we can fold the select into one of our operands.
4299   if (SI.getType()->isInteger()) {
4300     // See the comment above GetSelectFoldableOperands for a description of the
4301     // transformation we are doing here.
4302     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4303       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4304           !isa<Constant>(FalseVal))
4305         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4306           unsigned OpToFold = 0;
4307           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4308             OpToFold = 1;
4309           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4310             OpToFold = 2;
4311           }
4312
4313           if (OpToFold) {
4314             Constant *C = GetSelectFoldableConstant(TVI);
4315             std::string Name = TVI->getName(); TVI->setName("");
4316             Instruction *NewSel =
4317               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4318                              Name);
4319             InsertNewInstBefore(NewSel, SI);
4320             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4321               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4322             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4323               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4324             else {
4325               assert(0 && "Unknown instruction!!");
4326             }
4327           }
4328         }
4329
4330     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4331       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4332           !isa<Constant>(TrueVal))
4333         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4334           unsigned OpToFold = 0;
4335           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4336             OpToFold = 1;
4337           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4338             OpToFold = 2;
4339           }
4340
4341           if (OpToFold) {
4342             Constant *C = GetSelectFoldableConstant(FVI);
4343             std::string Name = FVI->getName(); FVI->setName("");
4344             Instruction *NewSel =
4345               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4346                              Name);
4347             InsertNewInstBefore(NewSel, SI);
4348             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4349               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4350             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4351               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4352             else {
4353               assert(0 && "Unknown instruction!!");
4354             }
4355           }
4356         }
4357   }
4358
4359   if (BinaryOperator::isNot(CondVal)) {
4360     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4361     SI.setOperand(1, FalseVal);
4362     SI.setOperand(2, TrueVal);
4363     return &SI;
4364   }
4365
4366   return 0;
4367 }
4368
4369
4370 // CallInst simplification
4371 //
4372 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
4373   // Intrinsics cannot occur in an invoke, so handle them here instead of in
4374   // visitCallSite.
4375   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4376     bool Changed = false;
4377
4378     // memmove/cpy/set of zero bytes is a noop.
4379     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4380       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4381
4382       // FIXME: Increase alignment here.
4383
4384       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4385         if (CI->getRawValue() == 1) {
4386           // Replace the instruction with just byte operations.  We would
4387           // transform other cases to loads/stores, but we don't know if
4388           // alignment is sufficient.
4389         }
4390     }
4391
4392     // If we have a memmove and the source operation is a constant global,
4393     // then the source and dest pointers can't alias, so we can change this
4394     // into a call to memcpy.
4395     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4396       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4397         if (GVSrc->isConstant()) {
4398           Module *M = CI.getParent()->getParent()->getParent();
4399           Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4400                                      CI.getCalledFunction()->getFunctionType());
4401           CI.setOperand(0, MemCpy);
4402           Changed = true;
4403         }
4404
4405     if (Changed) return &CI;
4406   } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4407     // If this stoppoint is at the same source location as the previous
4408     // stoppoint in the chain, it is not needed.
4409     if (DbgStopPointInst *PrevSPI =
4410         dyn_cast<DbgStopPointInst>(SPI->getChain()))
4411       if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4412           SPI->getColNo() == PrevSPI->getColNo()) {
4413         SPI->replaceAllUsesWith(PrevSPI);
4414         return EraseInstFromFunction(CI);
4415       }
4416   }
4417
4418   return visitCallSite(&CI);
4419 }
4420
4421 // InvokeInst simplification
4422 //
4423 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4424   return visitCallSite(&II);
4425 }
4426
4427 // visitCallSite - Improvements for call and invoke instructions.
4428 //
4429 Instruction *InstCombiner::visitCallSite(CallSite CS) {
4430   bool Changed = false;
4431
4432   // If the callee is a constexpr cast of a function, attempt to move the cast
4433   // to the arguments of the call/invoke.
4434   if (transformConstExprCastCall(CS)) return 0;
4435
4436   Value *Callee = CS.getCalledValue();
4437
4438   if (Function *CalleeF = dyn_cast<Function>(Callee))
4439     if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4440       Instruction *OldCall = CS.getInstruction();
4441       // If the call and callee calling conventions don't match, this call must
4442       // be unreachable, as the call is undefined.
4443       new StoreInst(ConstantBool::True,
4444                     UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4445       if (!OldCall->use_empty())
4446         OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4447       if (isa<CallInst>(OldCall))   // Not worth removing an invoke here.
4448         return EraseInstFromFunction(*OldCall);
4449       return 0;
4450     }
4451
4452   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4453     // This instruction is not reachable, just remove it.  We insert a store to
4454     // undef so that we know that this code is not reachable, despite the fact
4455     // that we can't modify the CFG here.
4456     new StoreInst(ConstantBool::True,
4457                   UndefValue::get(PointerType::get(Type::BoolTy)),
4458                   CS.getInstruction());
4459
4460     if (!CS.getInstruction()->use_empty())
4461       CS.getInstruction()->
4462         replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4463
4464     if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4465       // Don't break the CFG, insert a dummy cond branch.
4466       new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4467                      ConstantBool::True, II);
4468     }
4469     return EraseInstFromFunction(*CS.getInstruction());
4470   }
4471
4472   const PointerType *PTy = cast<PointerType>(Callee->getType());
4473   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4474   if (FTy->isVarArg()) {
4475     // See if we can optimize any arguments passed through the varargs area of
4476     // the call.
4477     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4478            E = CS.arg_end(); I != E; ++I)
4479       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4480         // If this cast does not effect the value passed through the varargs
4481         // area, we can eliminate the use of the cast.
4482         Value *Op = CI->getOperand(0);
4483         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4484           *I = Op;
4485           Changed = true;
4486         }
4487       }
4488   }
4489
4490   return Changed ? CS.getInstruction() : 0;
4491 }
4492
4493 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
4494 // attempt to move the cast to the arguments of the call/invoke.
4495 //
4496 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4497   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4498   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
4499   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
4500     return false;
4501   Function *Callee = cast<Function>(CE->getOperand(0));
4502   Instruction *Caller = CS.getInstruction();
4503
4504   // Okay, this is a cast from a function to a different type.  Unless doing so
4505   // would cause a type conversion of one of our arguments, change this call to
4506   // be a direct call with arguments casted to the appropriate types.
4507   //
4508   const FunctionType *FT = Callee->getFunctionType();
4509   const Type *OldRetTy = Caller->getType();
4510
4511   // Check to see if we are changing the return type...
4512   if (OldRetTy != FT->getReturnType()) {
4513     if (Callee->isExternal() &&
4514         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4515         !Caller->use_empty())
4516       return false;   // Cannot transform this return value...
4517
4518     // If the callsite is an invoke instruction, and the return value is used by
4519     // a PHI node in a successor, we cannot change the return type of the call
4520     // because there is no place to put the cast instruction (without breaking
4521     // the critical edge).  Bail out in this case.
4522     if (!Caller->use_empty())
4523       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4524         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4525              UI != E; ++UI)
4526           if (PHINode *PN = dyn_cast<PHINode>(*UI))
4527             if (PN->getParent() == II->getNormalDest() ||
4528                 PN->getParent() == II->getUnwindDest())
4529               return false;
4530   }
4531
4532   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4533   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4534
4535   CallSite::arg_iterator AI = CS.arg_begin();
4536   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4537     const Type *ParamTy = FT->getParamType(i);
4538     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4539     if (Callee->isExternal() && !isConvertible) return false;
4540   }
4541
4542   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4543       Callee->isExternal())
4544     return false;   // Do not delete arguments unless we have a function body...
4545
4546   // Okay, we decided that this is a safe thing to do: go ahead and start
4547   // inserting cast instructions as necessary...
4548   std::vector<Value*> Args;
4549   Args.reserve(NumActualArgs);
4550
4551   AI = CS.arg_begin();
4552   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4553     const Type *ParamTy = FT->getParamType(i);
4554     if ((*AI)->getType() == ParamTy) {
4555       Args.push_back(*AI);
4556     } else {
4557       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4558                                          *Caller));
4559     }
4560   }
4561
4562   // If the function takes more arguments than the call was taking, add them
4563   // now...
4564   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4565     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4566
4567   // If we are removing arguments to the function, emit an obnoxious warning...
4568   if (FT->getNumParams() < NumActualArgs)
4569     if (!FT->isVarArg()) {
4570       std::cerr << "WARNING: While resolving call to function '"
4571                 << Callee->getName() << "' arguments were dropped!\n";
4572     } else {
4573       // Add all of the arguments in their promoted form to the arg list...
4574       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4575         const Type *PTy = getPromotedType((*AI)->getType());
4576         if (PTy != (*AI)->getType()) {
4577           // Must promote to pass through va_arg area!
4578           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4579           InsertNewInstBefore(Cast, *Caller);
4580           Args.push_back(Cast);
4581         } else {
4582           Args.push_back(*AI);
4583         }
4584       }
4585     }
4586
4587   if (FT->getReturnType() == Type::VoidTy)
4588     Caller->setName("");   // Void type should not have a name...
4589
4590   Instruction *NC;
4591   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4592     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
4593                         Args, Caller->getName(), Caller);
4594     cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
4595   } else {
4596     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4597     if (cast<CallInst>(Caller)->isTailCall())
4598       cast<CallInst>(NC)->setTailCall();
4599    cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
4600   }
4601
4602   // Insert a cast of the return type as necessary...
4603   Value *NV = NC;
4604   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4605     if (NV->getType() != Type::VoidTy) {
4606       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
4607
4608       // If this is an invoke instruction, we should insert it after the first
4609       // non-phi, instruction in the normal successor block.
4610       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4611         BasicBlock::iterator I = II->getNormalDest()->begin();
4612         while (isa<PHINode>(I)) ++I;
4613         InsertNewInstBefore(NC, *I);
4614       } else {
4615         // Otherwise, it's a call, just insert cast right after the call instr
4616         InsertNewInstBefore(NC, *Caller);
4617       }
4618       AddUsersToWorkList(*Caller);
4619     } else {
4620       NV = UndefValue::get(Caller->getType());
4621     }
4622   }
4623
4624   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4625     Caller->replaceAllUsesWith(NV);
4626   Caller->getParent()->getInstList().erase(Caller);
4627   removeFromWorkList(Caller);
4628   return true;
4629 }
4630
4631
4632 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4633 // operator and they all are only used by the PHI, PHI together their
4634 // inputs, and do the operation once, to the result of the PHI.
4635 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4636   Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4637
4638   // Scan the instruction, looking for input operations that can be folded away.
4639   // If all input operands to the phi are the same instruction (e.g. a cast from
4640   // the same type or "+42") we can pull the operation through the PHI, reducing
4641   // code size and simplifying code.
4642   Constant *ConstantOp = 0;
4643   const Type *CastSrcTy = 0;
4644   if (isa<CastInst>(FirstInst)) {
4645     CastSrcTy = FirstInst->getOperand(0)->getType();
4646   } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4647     // Can fold binop or shift if the RHS is a constant.
4648     ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4649     if (ConstantOp == 0) return 0;
4650   } else {
4651     return 0;  // Cannot fold this operation.
4652   }
4653
4654   // Check to see if all arguments are the same operation.
4655   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4656     if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4657     Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4658     if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4659       return 0;
4660     if (CastSrcTy) {
4661       if (I->getOperand(0)->getType() != CastSrcTy)
4662         return 0;  // Cast operation must match.
4663     } else if (I->getOperand(1) != ConstantOp) {
4664       return 0;
4665     }
4666   }
4667
4668   // Okay, they are all the same operation.  Create a new PHI node of the
4669   // correct type, and PHI together all of the LHS's of the instructions.
4670   PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4671                                PN.getName()+".in");
4672   NewPN->reserveOperandSpace(PN.getNumOperands()/2);
4673
4674   Value *InVal = FirstInst->getOperand(0);
4675   NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
4676
4677   // Add all operands to the new PHI.
4678   for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4679     Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4680     if (NewInVal != InVal)
4681       InVal = 0;
4682     NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4683   }
4684
4685   Value *PhiVal;
4686   if (InVal) {
4687     // The new PHI unions all of the same values together.  This is really
4688     // common, so we handle it intelligently here for compile-time speed.
4689     PhiVal = InVal;
4690     delete NewPN;
4691   } else {
4692     InsertNewInstBefore(NewPN, PN);
4693     PhiVal = NewPN;
4694   }
4695
4696   // Insert and return the new operation.
4697   if (isa<CastInst>(FirstInst))
4698     return new CastInst(PhiVal, PN.getType());
4699   else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
4700     return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
4701   else
4702     return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
4703                          PhiVal, ConstantOp);
4704 }
4705
4706 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4707 /// that is dead.
4708 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4709   if (PN->use_empty()) return true;
4710   if (!PN->hasOneUse()) return false;
4711
4712   // Remember this node, and if we find the cycle, return.
4713   if (!PotentiallyDeadPHIs.insert(PN).second)
4714     return true;
4715
4716   if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4717     return DeadPHICycle(PU, PotentiallyDeadPHIs);
4718
4719   return false;
4720 }
4721
4722 // PHINode simplification
4723 //
4724 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
4725   if (Value *V = PN.hasConstantValue())
4726     return ReplaceInstUsesWith(PN, V);
4727
4728   // If the only user of this instruction is a cast instruction, and all of the
4729   // incoming values are constants, change this PHI to merge together the casted
4730   // constants.
4731   if (PN.hasOneUse())
4732     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4733       if (CI->getType() != PN.getType()) {  // noop casts will be folded
4734         bool AllConstant = true;
4735         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4736           if (!isa<Constant>(PN.getIncomingValue(i))) {
4737             AllConstant = false;
4738             break;
4739           }
4740         if (AllConstant) {
4741           // Make a new PHI with all casted values.
4742           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4743           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4744             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4745             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4746                              PN.getIncomingBlock(i));
4747           }
4748
4749           // Update the cast instruction.
4750           CI->setOperand(0, New);
4751           WorkList.push_back(CI);    // revisit the cast instruction to fold.
4752           WorkList.push_back(New);   // Make sure to revisit the new Phi
4753           return &PN;                // PN is now dead!
4754         }
4755       }
4756
4757   // If all PHI operands are the same operation, pull them through the PHI,
4758   // reducing code size.
4759   if (isa<Instruction>(PN.getIncomingValue(0)) &&
4760       PN.getIncomingValue(0)->hasOneUse())
4761     if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4762       return Result;
4763
4764   // If this is a trivial cycle in the PHI node graph, remove it.  Basically, if
4765   // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4766   // PHI)... break the cycle.
4767   if (PN.hasOneUse())
4768     if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4769       std::set<PHINode*> PotentiallyDeadPHIs;
4770       PotentiallyDeadPHIs.insert(&PN);
4771       if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4772         return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4773     }
4774
4775   return 0;
4776 }
4777
4778 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4779                                       Instruction *InsertPoint,
4780                                       InstCombiner *IC) {
4781   unsigned PS = IC->getTargetData().getPointerSize();
4782   const Type *VTy = V->getType();
4783   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4784     // We must insert a cast to ensure we sign-extend.
4785     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4786                                              V->getName()), *InsertPoint);
4787   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4788                                  *InsertPoint);
4789 }
4790
4791
4792 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
4793   Value *PtrOp = GEP.getOperand(0);
4794   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
4795   // If so, eliminate the noop.
4796   if (GEP.getNumOperands() == 1)
4797     return ReplaceInstUsesWith(GEP, PtrOp);
4798
4799   if (isa<UndefValue>(GEP.getOperand(0)))
4800     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4801
4802   bool HasZeroPointerIndex = false;
4803   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4804     HasZeroPointerIndex = C->isNullValue();
4805
4806   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
4807     return ReplaceInstUsesWith(GEP, PtrOp);
4808
4809   // Eliminate unneeded casts for indices.
4810   bool MadeChange = false;
4811   gep_type_iterator GTI = gep_type_begin(GEP);
4812   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4813     if (isa<SequentialType>(*GTI)) {
4814       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4815         Value *Src = CI->getOperand(0);
4816         const Type *SrcTy = Src->getType();
4817         const Type *DestTy = CI->getType();
4818         if (Src->getType()->isInteger()) {
4819           if (SrcTy->getPrimitiveSizeInBits() ==
4820                        DestTy->getPrimitiveSizeInBits()) {
4821             // We can always eliminate a cast from ulong or long to the other.
4822             // We can always eliminate a cast from uint to int or the other on
4823             // 32-bit pointer platforms.
4824             if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
4825               MadeChange = true;
4826               GEP.setOperand(i, Src);
4827             }
4828           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4829                      SrcTy->getPrimitiveSize() == 4) {
4830             // We can always eliminate a cast from int to [u]long.  We can
4831             // eliminate a cast from uint to [u]long iff the target is a 32-bit
4832             // pointer target.
4833             if (SrcTy->isSigned() ||
4834                 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
4835               MadeChange = true;
4836               GEP.setOperand(i, Src);
4837             }
4838           }
4839         }
4840       }
4841       // If we are using a wider index than needed for this platform, shrink it
4842       // to what we need.  If the incoming value needs a cast instruction,
4843       // insert it.  This explicit cast can make subsequent optimizations more
4844       // obvious.
4845       Value *Op = GEP.getOperand(i);
4846       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
4847         if (Constant *C = dyn_cast<Constant>(Op)) {
4848           GEP.setOperand(i, ConstantExpr::getCast(C,
4849                                      TD->getIntPtrType()->getSignedVersion()));
4850           MadeChange = true;
4851         } else {
4852           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4853                                                 Op->getName()), GEP);
4854           GEP.setOperand(i, Op);
4855           MadeChange = true;
4856         }
4857
4858       // If this is a constant idx, make sure to canonicalize it to be a signed
4859       // operand, otherwise CSE and other optimizations are pessimized.
4860       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4861         GEP.setOperand(i, ConstantExpr::getCast(CUI,
4862                                           CUI->getType()->getSignedVersion()));
4863         MadeChange = true;
4864       }
4865     }
4866   if (MadeChange) return &GEP;
4867
4868   // Combine Indices - If the source pointer to this getelementptr instruction
4869   // is a getelementptr instruction, combine the indices of the two
4870   // getelementptr instructions into a single instruction.
4871   //
4872   std::vector<Value*> SrcGEPOperands;
4873   if (User *Src = dyn_castGetElementPtr(PtrOp))
4874     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
4875
4876   if (!SrcGEPOperands.empty()) {
4877     // Note that if our source is a gep chain itself that we wait for that
4878     // chain to be resolved before we perform this transformation.  This
4879     // avoids us creating a TON of code in some cases.
4880     //
4881     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4882         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4883       return 0;   // Wait until our source is folded to completion.
4884
4885     std::vector<Value *> Indices;
4886
4887     // Find out whether the last index in the source GEP is a sequential idx.
4888     bool EndsWithSequential = false;
4889     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4890            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
4891       EndsWithSequential = !isa<StructType>(*I);
4892
4893     // Can we combine the two pointer arithmetics offsets?
4894     if (EndsWithSequential) {
4895       // Replace: gep (gep %P, long B), long A, ...
4896       // With:    T = long A+B; gep %P, T, ...
4897       //
4898       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
4899       if (SO1 == Constant::getNullValue(SO1->getType())) {
4900         Sum = GO1;
4901       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4902         Sum = SO1;
4903       } else {
4904         // If they aren't the same type, convert both to an integer of the
4905         // target's pointer size.
4906         if (SO1->getType() != GO1->getType()) {
4907           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4908             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4909           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4910             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4911           } else {
4912             unsigned PS = TD->getPointerSize();
4913             if (SO1->getType()->getPrimitiveSize() == PS) {
4914               // Convert GO1 to SO1's type.
4915               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4916
4917             } else if (GO1->getType()->getPrimitiveSize() == PS) {
4918               // Convert SO1 to GO1's type.
4919               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4920             } else {
4921               const Type *PT = TD->getIntPtrType();
4922               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4923               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4924             }
4925           }
4926         }
4927         if (isa<Constant>(SO1) && isa<Constant>(GO1))
4928           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4929         else {
4930           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4931           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
4932         }
4933       }
4934
4935       // Recycle the GEP we already have if possible.
4936       if (SrcGEPOperands.size() == 2) {
4937         GEP.setOperand(0, SrcGEPOperands[0]);
4938         GEP.setOperand(1, Sum);
4939         return &GEP;
4940       } else {
4941         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4942                        SrcGEPOperands.end()-1);
4943         Indices.push_back(Sum);
4944         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4945       }
4946     } else if (isa<Constant>(*GEP.idx_begin()) &&
4947                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
4948                SrcGEPOperands.size() != 1) {
4949       // Otherwise we can do the fold if the first index of the GEP is a zero
4950       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4951                      SrcGEPOperands.end());
4952       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4953     }
4954
4955     if (!Indices.empty())
4956       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
4957
4958   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
4959     // GEP of global variable.  If all of the indices for this GEP are
4960     // constants, we can promote this to a constexpr instead of an instruction.
4961
4962     // Scan for nonconstants...
4963     std::vector<Constant*> Indices;
4964     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4965     for (; I != E && isa<Constant>(*I); ++I)
4966       Indices.push_back(cast<Constant>(*I));
4967
4968     if (I == E) {  // If they are all constants...
4969       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
4970
4971       // Replace all uses of the GEP with the new constexpr...
4972       return ReplaceInstUsesWith(GEP, CE);
4973     }
4974   } else if (Value *X = isCast(PtrOp)) {  // Is the operand a cast?
4975     if (!isa<PointerType>(X->getType())) {
4976       // Not interesting.  Source pointer must be a cast from pointer.
4977     } else if (HasZeroPointerIndex) {
4978       // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4979       // into     : GEP [10 x ubyte]* X, long 0, ...
4980       //
4981       // This occurs when the program declares an array extern like "int X[];"
4982       //
4983       const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4984       const PointerType *XTy = cast<PointerType>(X->getType());
4985       if (const ArrayType *XATy =
4986           dyn_cast<ArrayType>(XTy->getElementType()))
4987         if (const ArrayType *CATy =
4988             dyn_cast<ArrayType>(CPTy->getElementType()))
4989           if (CATy->getElementType() == XATy->getElementType()) {
4990             // At this point, we know that the cast source type is a pointer
4991             // to an array of the same type as the destination pointer
4992             // array.  Because the array type is never stepped over (there
4993             // is a leading zero) we can fold the cast into this GEP.
4994             GEP.setOperand(0, X);
4995             return &GEP;
4996           }
4997     } else if (GEP.getNumOperands() == 2) {
4998       // Transform things like:
4999       // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5000       // into:  %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5001       const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5002       const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5003       if (isa<ArrayType>(SrcElTy) &&
5004           TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5005           TD->getTypeSize(ResElTy)) {
5006         Value *V = InsertNewInstBefore(
5007                new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5008                                      GEP.getOperand(1), GEP.getName()), GEP);
5009         return new CastInst(V, GEP.getType());
5010       }
5011       
5012       // Transform things like:
5013       // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5014       //   (where tmp = 8*tmp2) into:
5015       // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5016       
5017       if (isa<ArrayType>(SrcElTy) &&
5018           (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5019         uint64_t ArrayEltSize =
5020             TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5021         
5022         // Check to see if "tmp" is a scale by a multiple of ArrayEltSize.  We
5023         // allow either a mul, shift, or constant here.
5024         Value *NewIdx = 0;
5025         ConstantInt *Scale = 0;
5026         if (ArrayEltSize == 1) {
5027           NewIdx = GEP.getOperand(1);
5028           Scale = ConstantInt::get(NewIdx->getType(), 1);
5029         } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5030           NewIdx = ConstantInt::get(CI->getType(), 1);
5031           Scale = CI;
5032         } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5033           if (Inst->getOpcode() == Instruction::Shl &&
5034               isa<ConstantInt>(Inst->getOperand(1))) {
5035             unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5036             if (Inst->getType()->isSigned())
5037               Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5038             else
5039               Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5040             NewIdx = Inst->getOperand(0);
5041           } else if (Inst->getOpcode() == Instruction::Mul &&
5042                      isa<ConstantInt>(Inst->getOperand(1))) {
5043             Scale = cast<ConstantInt>(Inst->getOperand(1));
5044             NewIdx = Inst->getOperand(0);
5045           }
5046         }
5047
5048         // If the index will be to exactly the right offset with the scale taken
5049         // out, perform the transformation.
5050         if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5051           if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5052             Scale = ConstantSInt::get(C->getType(),
5053                                       (int64_t)C->getRawValue() / 
5054                                       (int64_t)ArrayEltSize);
5055           else
5056             Scale = ConstantUInt::get(Scale->getType(),
5057                                       Scale->getRawValue() / ArrayEltSize);
5058           if (Scale->getRawValue() != 1) {
5059             Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5060             Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5061             NewIdx = InsertNewInstBefore(Sc, GEP);
5062           }
5063
5064           // Insert the new GEP instruction.
5065           Instruction *Idx =
5066             new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5067                                   NewIdx, GEP.getName());
5068           Idx = InsertNewInstBefore(Idx, GEP);
5069           return new CastInst(Idx, GEP.getType());
5070         }
5071       }
5072     }
5073   }
5074
5075   return 0;
5076 }
5077
5078 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5079   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5080   if (AI.isArrayAllocation())    // Check C != 1
5081     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5082       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
5083       AllocationInst *New = 0;
5084
5085       // Create and insert the replacement instruction...
5086       if (isa<MallocInst>(AI))
5087         New = new MallocInst(NewTy, 0, AI.getName());
5088       else {
5089         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
5090         New = new AllocaInst(NewTy, 0, AI.getName());
5091       }
5092
5093       InsertNewInstBefore(New, AI);
5094
5095       // Scan to the end of the allocation instructions, to skip over a block of
5096       // allocas if possible...
5097       //
5098       BasicBlock::iterator It = New;
5099       while (isa<AllocationInst>(*It)) ++It;
5100
5101       // Now that I is pointing to the first non-allocation-inst in the block,
5102       // insert our getelementptr instruction...
5103       //
5104       Value *NullIdx = Constant::getNullValue(Type::IntTy);
5105       Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5106                                        New->getName()+".sub", It);
5107
5108       // Now make everything use the getelementptr instead of the original
5109       // allocation.
5110       return ReplaceInstUsesWith(AI, V);
5111     } else if (isa<UndefValue>(AI.getArraySize())) {
5112       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5113     }
5114
5115   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5116   // Note that we only do this for alloca's, because malloc should allocate and
5117   // return a unique pointer, even for a zero byte allocation.
5118   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
5119       TD->getTypeSize(AI.getAllocatedType()) == 0)
5120     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5121
5122   return 0;
5123 }
5124
5125 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5126   Value *Op = FI.getOperand(0);
5127
5128   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5129   if (CastInst *CI = dyn_cast<CastInst>(Op))
5130     if (isa<PointerType>(CI->getOperand(0)->getType())) {
5131       FI.setOperand(0, CI->getOperand(0));
5132       return &FI;
5133     }
5134
5135   // free undef -> unreachable.
5136   if (isa<UndefValue>(Op)) {
5137     // Insert a new store to null because we cannot modify the CFG here.
5138     new StoreInst(ConstantBool::True,
5139                   UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5140     return EraseInstFromFunction(FI);
5141   }
5142
5143   // If we have 'free null' delete the instruction.  This can happen in stl code
5144   // when lots of inlining happens.
5145   if (isa<ConstantPointerNull>(Op))
5146     return EraseInstFromFunction(FI);
5147
5148   return 0;
5149 }
5150
5151
5152 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
5153 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5154   User *CI = cast<User>(LI.getOperand(0));
5155   Value *CastOp = CI->getOperand(0);
5156
5157   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5158   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5159     const Type *SrcPTy = SrcTy->getElementType();
5160
5161     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5162       // If the source is an array, the code below will not succeed.  Check to
5163       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
5164       // constants.
5165       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5166         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5167           if (ASrcTy->getNumElements() != 0) {
5168             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5169             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5170             SrcTy = cast<PointerType>(CastOp->getType());
5171             SrcPTy = SrcTy->getElementType();
5172           }
5173
5174       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5175           // Do not allow turning this into a load of an integer, which is then
5176           // casted to a pointer, this pessimizes pointer analysis a lot.
5177           (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
5178           IC.getTargetData().getTypeSize(SrcPTy) ==
5179                IC.getTargetData().getTypeSize(DestPTy)) {
5180
5181         // Okay, we are casting from one integer or pointer type to another of
5182         // the same size.  Instead of casting the pointer before the load, cast
5183         // the result of the loaded value.
5184         Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5185                                                              CI->getName(),
5186                                                          LI.isVolatile()),LI);
5187         // Now cast the result of the load.
5188         return new CastInst(NewLoad, LI.getType());
5189       }
5190     }
5191   }
5192   return 0;
5193 }
5194
5195 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
5196 /// from this value cannot trap.  If it is not obviously safe to load from the
5197 /// specified pointer, we do a quick local scan of the basic block containing
5198 /// ScanFrom, to determine if the address is already accessed.
5199 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5200   // If it is an alloca or global variable, it is always safe to load from.
5201   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5202
5203   // Otherwise, be a little bit agressive by scanning the local block where we
5204   // want to check to see if the pointer is already being loaded or stored
5205   // from/to.  If so, the previous load or store would have already trapped,
5206   // so there is no harm doing an extra load (also, CSE will later eliminate
5207   // the load entirely).
5208   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5209
5210   while (BBI != E) {
5211     --BBI;
5212
5213     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5214       if (LI->getOperand(0) == V) return true;
5215     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5216       if (SI->getOperand(1) == V) return true;
5217
5218   }
5219   return false;
5220 }
5221
5222 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5223   Value *Op = LI.getOperand(0);
5224
5225   // load (cast X) --> cast (load X) iff safe
5226   if (CastInst *CI = dyn_cast<CastInst>(Op))
5227     if (Instruction *Res = InstCombineLoadCast(*this, LI))
5228       return Res;
5229
5230   // None of the following transforms are legal for volatile loads.
5231   if (LI.isVolatile()) return 0;
5232   
5233   if (&LI.getParent()->front() != &LI) {
5234     BasicBlock::iterator BBI = &LI; --BBI;
5235     // If the instruction immediately before this is a store to the same
5236     // address, do a simple form of store->load forwarding.
5237     if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5238       if (SI->getOperand(1) == LI.getOperand(0))
5239         return ReplaceInstUsesWith(LI, SI->getOperand(0));
5240     if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5241       if (LIB->getOperand(0) == LI.getOperand(0))
5242         return ReplaceInstUsesWith(LI, LIB);
5243   }
5244
5245   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5246     if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5247         isa<UndefValue>(GEPI->getOperand(0))) {
5248       // Insert a new store to null instruction before the load to indicate
5249       // that this code is not reachable.  We do this instead of inserting
5250       // an unreachable instruction directly because we cannot modify the
5251       // CFG.
5252       new StoreInst(UndefValue::get(LI.getType()),
5253                     Constant::getNullValue(Op->getType()), &LI);
5254       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5255     }
5256
5257   if (Constant *C = dyn_cast<Constant>(Op)) {
5258     // load null/undef -> undef
5259     if ((C->isNullValue() || isa<UndefValue>(C))) {
5260       // Insert a new store to null instruction before the load to indicate that
5261       // this code is not reachable.  We do this instead of inserting an
5262       // unreachable instruction directly because we cannot modify the CFG.
5263       new StoreInst(UndefValue::get(LI.getType()),
5264                     Constant::getNullValue(Op->getType()), &LI);
5265       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5266     }
5267
5268     // Instcombine load (constant global) into the value loaded.
5269     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5270       if (GV->isConstant() && !GV->isExternal())
5271         return ReplaceInstUsesWith(LI, GV->getInitializer());
5272
5273     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5274     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5275       if (CE->getOpcode() == Instruction::GetElementPtr) {
5276         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5277           if (GV->isConstant() && !GV->isExternal())
5278             if (Constant *V = 
5279                ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
5280               return ReplaceInstUsesWith(LI, V);
5281         if (CE->getOperand(0)->isNullValue()) {
5282           // Insert a new store to null instruction before the load to indicate
5283           // that this code is not reachable.  We do this instead of inserting
5284           // an unreachable instruction directly because we cannot modify the
5285           // CFG.
5286           new StoreInst(UndefValue::get(LI.getType()),
5287                         Constant::getNullValue(Op->getType()), &LI);
5288           return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5289         }
5290
5291       } else if (CE->getOpcode() == Instruction::Cast) {
5292         if (Instruction *Res = InstCombineLoadCast(*this, LI))
5293           return Res;
5294       }
5295   }
5296
5297   if (Op->hasOneUse()) {
5298     // Change select and PHI nodes to select values instead of addresses: this
5299     // helps alias analysis out a lot, allows many others simplifications, and
5300     // exposes redundancy in the code.
5301     //
5302     // Note that we cannot do the transformation unless we know that the
5303     // introduced loads cannot trap!  Something like this is valid as long as
5304     // the condition is always false: load (select bool %C, int* null, int* %G),
5305     // but it would not be valid if we transformed it to load from null
5306     // unconditionally.
5307     //
5308     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5309       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
5310       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5311           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
5312         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
5313                                      SI->getOperand(1)->getName()+".val"), LI);
5314         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
5315                                      SI->getOperand(2)->getName()+".val"), LI);
5316         return new SelectInst(SI->getCondition(), V1, V2);
5317       }
5318
5319       // load (select (cond, null, P)) -> load P
5320       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5321         if (C->isNullValue()) {
5322           LI.setOperand(0, SI->getOperand(2));
5323           return &LI;
5324         }
5325
5326       // load (select (cond, P, null)) -> load P
5327       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5328         if (C->isNullValue()) {
5329           LI.setOperand(0, SI->getOperand(1));
5330           return &LI;
5331         }
5332
5333     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5334       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
5335       bool Safe = PN->getParent() == LI.getParent();
5336
5337       // Scan all of the instructions between the PHI and the load to make
5338       // sure there are no instructions that might possibly alter the value
5339       // loaded from the PHI.
5340       if (Safe) {
5341         BasicBlock::iterator I = &LI;
5342         for (--I; !isa<PHINode>(I); --I)
5343           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5344             Safe = false;
5345             break;
5346           }
5347       }
5348
5349       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
5350         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
5351                                     PN->getIncomingBlock(i)->getTerminator()))
5352           Safe = false;
5353
5354       if (Safe) {
5355         // Create the PHI.
5356         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5357         InsertNewInstBefore(NewPN, *PN);
5358         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
5359
5360         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5361           BasicBlock *BB = PN->getIncomingBlock(i);
5362           Value *&TheLoad = LoadMap[BB];
5363           if (TheLoad == 0) {
5364             Value *InVal = PN->getIncomingValue(i);
5365             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5366                                                        InVal->getName()+".val"),
5367                                           *BB->getTerminator());
5368           }
5369           NewPN->addIncoming(TheLoad, BB);
5370         }
5371         return ReplaceInstUsesWith(LI, NewPN);
5372       }
5373     }
5374   }
5375   return 0;
5376 }
5377
5378 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5379 /// when possible.
5380 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5381   User *CI = cast<User>(SI.getOperand(1));
5382   Value *CastOp = CI->getOperand(0);
5383
5384   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5385   if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5386     const Type *SrcPTy = SrcTy->getElementType();
5387
5388     if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5389       // If the source is an array, the code below will not succeed.  Check to
5390       // see if a trivial 'gep P, 0, 0' will help matters.  Only do this for
5391       // constants.
5392       if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5393         if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5394           if (ASrcTy->getNumElements() != 0) {
5395             std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5396             CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5397             SrcTy = cast<PointerType>(CastOp->getType());
5398             SrcPTy = SrcTy->getElementType();
5399           }
5400
5401       if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5402           IC.getTargetData().getTypeSize(SrcPTy) ==
5403                IC.getTargetData().getTypeSize(DestPTy)) {
5404
5405         // Okay, we are casting from one integer or pointer type to another of
5406         // the same size.  Instead of casting the pointer before the store, cast
5407         // the value to be stored.
5408         Value *NewCast;
5409         if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5410           NewCast = ConstantExpr::getCast(C, SrcPTy);
5411         else
5412           NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5413                                                         SrcPTy,
5414                                          SI.getOperand(0)->getName()+".c"), SI);
5415
5416         return new StoreInst(NewCast, CastOp);
5417       }
5418     }
5419   }
5420   return 0;
5421 }
5422
5423 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5424   Value *Val = SI.getOperand(0);
5425   Value *Ptr = SI.getOperand(1);
5426
5427   if (isa<UndefValue>(Ptr)) {     // store X, undef -> noop (even if volatile)
5428     removeFromWorkList(&SI);
5429     SI.eraseFromParent();
5430     ++NumCombined;
5431     return 0;
5432   }
5433
5434   if (SI.isVolatile()) return 0;  // Don't hack volatile loads.
5435
5436   // store X, null    -> turns into 'unreachable' in SimplifyCFG
5437   if (isa<ConstantPointerNull>(Ptr)) {
5438     if (!isa<UndefValue>(Val)) {
5439       SI.setOperand(0, UndefValue::get(Val->getType()));
5440       if (Instruction *U = dyn_cast<Instruction>(Val))
5441         WorkList.push_back(U);  // Dropped a use.
5442       ++NumCombined;
5443     }
5444     return 0;  // Do not modify these!
5445   }
5446
5447   // store undef, Ptr -> noop
5448   if (isa<UndefValue>(Val)) {
5449     removeFromWorkList(&SI);
5450     SI.eraseFromParent();
5451     ++NumCombined;
5452     return 0;
5453   }
5454
5455   // If the pointer destination is a cast, see if we can fold the cast into the
5456   // source instead.
5457   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5458     if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5459       return Res;
5460   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5461     if (CE->getOpcode() == Instruction::Cast)
5462       if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5463         return Res;
5464
5465   
5466   // If this store is the last instruction in the basic block, and if the block
5467   // ends with an unconditional branch, try to move it to the successor block.
5468   BasicBlock::iterator BBI = &SI; ++BBI;
5469   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5470     if (BI->isUnconditional()) {
5471       // Check to see if the successor block has exactly two incoming edges.  If
5472       // so, see if the other predecessor contains a store to the same location.
5473       // if so, insert a PHI node (if needed) and move the stores down.
5474       BasicBlock *Dest = BI->getSuccessor(0);
5475
5476       pred_iterator PI = pred_begin(Dest);
5477       BasicBlock *Other = 0;
5478       if (*PI != BI->getParent())
5479         Other = *PI;
5480       ++PI;
5481       if (PI != pred_end(Dest)) {
5482         if (*PI != BI->getParent())
5483           if (Other)
5484             Other = 0;
5485           else
5486             Other = *PI;
5487         if (++PI != pred_end(Dest))
5488           Other = 0;
5489       }
5490       if (Other) {  // If only one other pred...
5491         BBI = Other->getTerminator();
5492         // Make sure this other block ends in an unconditional branch and that
5493         // there is an instruction before the branch.
5494         if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5495             BBI != Other->begin()) {
5496           --BBI;
5497           StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5498           
5499           // If this instruction is a store to the same location.
5500           if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5501             // Okay, we know we can perform this transformation.  Insert a PHI
5502             // node now if we need it.
5503             Value *MergedVal = OtherStore->getOperand(0);
5504             if (MergedVal != SI.getOperand(0)) {
5505               PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5506               PN->reserveOperandSpace(2);
5507               PN->addIncoming(SI.getOperand(0), SI.getParent());
5508               PN->addIncoming(OtherStore->getOperand(0), Other);
5509               MergedVal = InsertNewInstBefore(PN, Dest->front());
5510             }
5511             
5512             // Advance to a place where it is safe to insert the new store and
5513             // insert it.
5514             BBI = Dest->begin();
5515             while (isa<PHINode>(BBI)) ++BBI;
5516             InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5517                                               OtherStore->isVolatile()), *BBI);
5518
5519             // Nuke the old stores.
5520             removeFromWorkList(&SI);
5521             removeFromWorkList(OtherStore);
5522             SI.eraseFromParent();
5523             OtherStore->eraseFromParent();
5524             ++NumCombined;
5525             return 0;
5526           }
5527         }
5528       }
5529     }
5530   
5531   return 0;
5532 }
5533
5534
5535 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5536   // Change br (not X), label True, label False to: br X, label False, True
5537   Value *X = 0;
5538   BasicBlock *TrueDest;
5539   BasicBlock *FalseDest;
5540   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5541       !isa<Constant>(X)) {
5542     // Swap Destinations and condition...
5543     BI.setCondition(X);
5544     BI.setSuccessor(0, FalseDest);
5545     BI.setSuccessor(1, TrueDest);
5546     return &BI;
5547   }
5548
5549   // Cannonicalize setne -> seteq
5550   Instruction::BinaryOps Op; Value *Y;
5551   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5552                       TrueDest, FalseDest)))
5553     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5554          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5555       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5556       std::string Name = I->getName(); I->setName("");
5557       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5558       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
5559       // Swap Destinations and condition...
5560       BI.setCondition(NewSCC);
5561       BI.setSuccessor(0, FalseDest);
5562       BI.setSuccessor(1, TrueDest);
5563       removeFromWorkList(I);
5564       I->getParent()->getInstList().erase(I);
5565       WorkList.push_back(cast<Instruction>(NewSCC));
5566       return &BI;
5567     }
5568
5569   return 0;
5570 }
5571
5572 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5573   Value *Cond = SI.getCondition();
5574   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5575     if (I->getOpcode() == Instruction::Add)
5576       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5577         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5578         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
5579           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
5580                                                 AddRHS));
5581         SI.setOperand(0, I->getOperand(0));
5582         WorkList.push_back(I);
5583         return &SI;
5584       }
5585   }
5586   return 0;
5587 }
5588
5589
5590 void InstCombiner::removeFromWorkList(Instruction *I) {
5591   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5592                  WorkList.end());
5593 }
5594
5595
5596 /// TryToSinkInstruction - Try to move the specified instruction from its
5597 /// current block into the beginning of DestBlock, which can only happen if it's
5598 /// safe to move the instruction past all of the instructions between it and the
5599 /// end of its block.
5600 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5601   assert(I->hasOneUse() && "Invariants didn't hold!");
5602
5603   // Cannot move control-flow-involving instructions.
5604   if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
5605
5606   // Do not sink alloca instructions out of the entry block.
5607   if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5608     return false;
5609
5610   // We can only sink load instructions if there is nothing between the load and
5611   // the end of block that could change the value.
5612   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5613     if (LI->isVolatile()) return false;  // Don't sink volatile loads.
5614
5615     for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5616          Scan != E; ++Scan)
5617       if (Scan->mayWriteToMemory())
5618         return false;
5619   }
5620
5621   BasicBlock::iterator InsertPos = DestBlock->begin();
5622   while (isa<PHINode>(InsertPos)) ++InsertPos;
5623
5624   I->moveBefore(InsertPos);
5625   ++NumSunkInst;
5626   return true;
5627 }
5628
5629 bool InstCombiner::runOnFunction(Function &F) {
5630   bool Changed = false;
5631   TD = &getAnalysis<TargetData>();
5632
5633   {
5634     // Populate the worklist with the reachable instructions.
5635     std::set<BasicBlock*> Visited;
5636     for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5637            E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5638       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5639         WorkList.push_back(I);
5640
5641     // Do a quick scan over the function.  If we find any blocks that are
5642     // unreachable, remove any instructions inside of them.  This prevents
5643     // the instcombine code from having to deal with some bad special cases.
5644     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5645       if (!Visited.count(BB)) {
5646         Instruction *Term = BB->getTerminator();
5647         while (Term != BB->begin()) {   // Remove instrs bottom-up
5648           BasicBlock::iterator I = Term; --I;
5649
5650           DEBUG(std::cerr << "IC: DCE: " << *I);
5651           ++NumDeadInst;
5652
5653           if (!I->use_empty())
5654             I->replaceAllUsesWith(UndefValue::get(I->getType()));
5655           I->eraseFromParent();
5656         }
5657       }
5658   }
5659
5660   while (!WorkList.empty()) {
5661     Instruction *I = WorkList.back();  // Get an instruction from the worklist
5662     WorkList.pop_back();
5663
5664     // Check to see if we can DCE or ConstantPropagate the instruction...
5665     // Check to see if we can DIE the instruction...
5666     if (isInstructionTriviallyDead(I)) {
5667       // Add operands to the worklist...
5668       if (I->getNumOperands() < 4)
5669         AddUsesToWorkList(*I);
5670       ++NumDeadInst;
5671
5672       DEBUG(std::cerr << "IC: DCE: " << *I);
5673
5674       I->eraseFromParent();
5675       removeFromWorkList(I);
5676       continue;
5677     }
5678
5679     // Instruction isn't dead, see if we can constant propagate it...
5680     if (Constant *C = ConstantFoldInstruction(I)) {
5681       Value* Ptr = I->getOperand(0);
5682       if (isa<GetElementPtrInst>(I) &&
5683           cast<Constant>(Ptr)->isNullValue() &&
5684           !isa<ConstantPointerNull>(C) &&
5685           cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
5686         // If this is a constant expr gep that is effectively computing an
5687         // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5688         bool isFoldableGEP = true;
5689         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5690           if (!isa<ConstantInt>(I->getOperand(i)))
5691             isFoldableGEP = false;
5692         if (isFoldableGEP) {
5693           uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
5694                              std::vector<Value*>(I->op_begin()+1, I->op_end()));
5695           C = ConstantUInt::get(Type::ULongTy, Offset);
5696           C = ConstantExpr::getCast(C, TD->getIntPtrType());
5697           C = ConstantExpr::getCast(C, I->getType());
5698         }
5699       }
5700
5701       DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5702
5703       // Add operands to the worklist...
5704       AddUsesToWorkList(*I);
5705       ReplaceInstUsesWith(*I, C);
5706
5707       ++NumConstProp;
5708       I->getParent()->getInstList().erase(I);
5709       removeFromWorkList(I);
5710       continue;
5711     }
5712
5713     // See if we can trivially sink this instruction to a successor basic block.
5714     if (I->hasOneUse()) {
5715       BasicBlock *BB = I->getParent();
5716       BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5717       if (UserParent != BB) {
5718         bool UserIsSuccessor = false;
5719         // See if the user is one of our successors.
5720         for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5721           if (*SI == UserParent) {
5722             UserIsSuccessor = true;
5723             break;
5724           }
5725
5726         // If the user is one of our immediate successors, and if that successor
5727         // only has us as a predecessors (we'd have to split the critical edge
5728         // otherwise), we can keep going.
5729         if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5730             next(pred_begin(UserParent)) == pred_end(UserParent))
5731           // Okay, the CFG is simple enough, try to sink this instruction.
5732           Changed |= TryToSinkInstruction(I, UserParent);
5733       }
5734     }
5735
5736     // Now that we have an instruction, try combining it to simplify it...
5737     if (Instruction *Result = visit(*I)) {
5738       ++NumCombined;
5739       // Should we replace the old instruction with a new one?
5740       if (Result != I) {
5741         DEBUG(std::cerr << "IC: Old = " << *I
5742                         << "    New = " << *Result);
5743
5744         // Everything uses the new instruction now.
5745         I->replaceAllUsesWith(Result);
5746
5747         // Push the new instruction and any users onto the worklist.
5748         WorkList.push_back(Result);
5749         AddUsersToWorkList(*Result);
5750
5751         // Move the name to the new instruction first...
5752         std::string OldName = I->getName(); I->setName("");
5753         Result->setName(OldName);
5754
5755         // Insert the new instruction into the basic block...
5756         BasicBlock *InstParent = I->getParent();
5757         BasicBlock::iterator InsertPos = I;
5758
5759         if (!isa<PHINode>(Result))        // If combining a PHI, don't insert
5760           while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5761             ++InsertPos;
5762
5763         InstParent->getInstList().insert(InsertPos, Result);
5764
5765         // Make sure that we reprocess all operands now that we reduced their
5766         // use counts.
5767         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5768           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5769             WorkList.push_back(OpI);
5770
5771         // Instructions can end up on the worklist more than once.  Make sure
5772         // we do not process an instruction that has been deleted.
5773         removeFromWorkList(I);
5774
5775         // Erase the old instruction.
5776         InstParent->getInstList().erase(I);
5777       } else {
5778         DEBUG(std::cerr << "IC: MOD = " << *I);
5779
5780         // If the instruction was modified, it's possible that it is now dead.
5781         // if so, remove it.
5782         if (isInstructionTriviallyDead(I)) {
5783           // Make sure we process all operands now that we are reducing their
5784           // use counts.
5785           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5786             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5787               WorkList.push_back(OpI);
5788
5789           // Instructions may end up in the worklist more than once.  Erase all
5790           // occurrances of this instruction.
5791           removeFromWorkList(I);
5792           I->eraseFromParent();
5793         } else {
5794           WorkList.push_back(Result);
5795           AddUsersToWorkList(*Result);
5796         }
5797       }
5798       Changed = true;
5799     }
5800   }
5801
5802   return Changed;
5803 }
5804
5805 FunctionPass *llvm::createInstructionCombiningPass() {
5806   return new InstCombiner();
5807 }
5808