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