Optimize instructions involving undef values. For example X+undef == undef.
[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 //    N. This list is incomplete
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/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/InstIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/PatternMatch.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/ADT/Statistic.h"
52 #include <algorithm>
53 using namespace llvm;
54 using namespace llvm::PatternMatch;
55
56 namespace {
57   Statistic<> NumCombined ("instcombine", "Number of insts combined");
58   Statistic<> NumConstProp("instcombine", "Number of constant folds");
59   Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
61   class InstCombiner : public FunctionPass,
62                        public InstVisitor<InstCombiner, Instruction*> {
63     // Worklist of all of the instructions that need to be simplified.
64     std::vector<Instruction*> WorkList;
65     TargetData *TD;
66
67     /// AddUsersToWorkList - When an instruction is simplified, add all users of
68     /// the instruction to the work lists because they might get more simplified
69     /// now.
70     ///
71     void AddUsersToWorkList(Instruction &I) {
72       for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
73            UI != UE; ++UI)
74         WorkList.push_back(cast<Instruction>(*UI));
75     }
76
77     /// AddUsesToWorkList - When an instruction is simplified, add operands to
78     /// the work lists because they might get more simplified now.
79     ///
80     void AddUsesToWorkList(Instruction &I) {
81       for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82         if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83           WorkList.push_back(Op);
84     }
85
86     // removeFromWorkList - remove all instances of I from the worklist.
87     void removeFromWorkList(Instruction *I);
88   public:
89     virtual bool runOnFunction(Function &F);
90
91     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92       AU.addRequired<TargetData>();
93       AU.setPreservesCFG();
94     }
95
96     TargetData &getTargetData() const { return *TD; }
97
98     // Visitation implementation - Implement instruction combining for different
99     // instruction types.  The semantics are as follows:
100     // Return Value:
101     //    null        - No change was made
102     //     I          - Change was made, I is still valid, I may be dead though
103     //   otherwise    - Change was made, replace I with returned instruction
104     //   
105     Instruction *visitAdd(BinaryOperator &I);
106     Instruction *visitSub(BinaryOperator &I);
107     Instruction *visitMul(BinaryOperator &I);
108     Instruction *visitDiv(BinaryOperator &I);
109     Instruction *visitRem(BinaryOperator &I);
110     Instruction *visitAnd(BinaryOperator &I);
111     Instruction *visitOr (BinaryOperator &I);
112     Instruction *visitXor(BinaryOperator &I);
113     Instruction *visitSetCondInst(BinaryOperator &I);
114     Instruction *visitShiftInst(ShiftInst &I);
115     Instruction *visitCastInst(CastInst &CI);
116     Instruction *visitSelectInst(SelectInst &CI);
117     Instruction *visitCallInst(CallInst &CI);
118     Instruction *visitInvokeInst(InvokeInst &II);
119     Instruction *visitPHINode(PHINode &PN);
120     Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
121     Instruction *visitAllocationInst(AllocationInst &AI);
122     Instruction *visitFreeInst(FreeInst &FI);
123     Instruction *visitLoadInst(LoadInst &LI);
124     Instruction *visitStoreInst(StoreInst &SI);
125     Instruction *visitBranchInst(BranchInst &BI);
126     Instruction *visitSwitchInst(SwitchInst &SI);
127
128     // visitInstruction - Specify what to return for unhandled instructions...
129     Instruction *visitInstruction(Instruction &I) { return 0; }
130
131   private:
132     Instruction *visitCallSite(CallSite CS);
133     bool transformConstExprCastCall(CallSite CS);
134
135   public:
136     // InsertNewInstBefore - insert an instruction New before instruction Old
137     // in the program.  Add the new instruction to the worklist.
138     //
139     Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
140       assert(New && New->getParent() == 0 &&
141              "New instruction already inserted into a basic block!");
142       BasicBlock *BB = Old.getParent();
143       BB->getInstList().insert(&Old, New);  // Insert inst
144       WorkList.push_back(New);              // Add to worklist
145       return New;
146     }
147
148     /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
149     /// This also adds the cast to the worklist.  Finally, this returns the
150     /// cast.
151     Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
152       if (V->getType() == Ty) return V;
153       
154       Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
155       WorkList.push_back(C);
156       return C;
157     }
158
159     // ReplaceInstUsesWith - This method is to be used when an instruction is
160     // found to be dead, replacable with another preexisting expression.  Here
161     // we add all uses of I to the worklist, replace all uses of I with the new
162     // value, then return I, so that the inst combiner will know that I was
163     // modified.
164     //
165     Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
166       AddUsersToWorkList(I);         // Add all modified instrs to worklist
167       if (&I != V) {
168         I.replaceAllUsesWith(V);
169         return &I;
170       } else {
171         // If we are replacing the instruction with itself, this must be in a
172         // segment of unreachable code, so just clobber the instruction.
173         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
174         return &I;
175       }
176     }
177
178     // EraseInstFromFunction - When dealing with an instruction that has side
179     // effects or produces a void value, we can't rely on DCE to delete the
180     // instruction.  Instead, visit methods should return the value returned by
181     // this function.
182     Instruction *EraseInstFromFunction(Instruction &I) {
183       assert(I.use_empty() && "Cannot erase instruction that is used!");
184       AddUsesToWorkList(I);
185       removeFromWorkList(&I);
186       I.getParent()->getInstList().erase(&I);
187       return 0;  // Don't do anything with FI
188     }
189
190
191   private:
192     /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
193     /// InsertBefore instruction.  This is specialized a bit to avoid inserting
194     /// casts that are known to not do anything...
195     ///
196     Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
197                                    Instruction *InsertBefore);
198
199     // SimplifyCommutative - This performs a few simplifications for commutative
200     // operators.
201     bool SimplifyCommutative(BinaryOperator &I);
202
203
204     // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
205     // PHI node as operand #0, see if we can fold the instruction into the PHI
206     // (which is only possible if all operands to the PHI are constants).
207     Instruction *FoldOpIntoPhi(Instruction &I);
208
209     Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
210                           ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
211
212     Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
213                                  bool Inside, Instruction &IB);
214   };
215
216   RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
217 }
218
219 // getComplexity:  Assign a complexity or rank value to LLVM Values...
220 //   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
221 static unsigned getComplexity(Value *V) {
222   if (isa<Instruction>(V)) {
223     if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
224       return 3;
225     return 4;
226   }
227   if (isa<Argument>(V)) return 3;
228   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
229 }
230
231 // isOnlyUse - Return true if this instruction will be deleted if we stop using
232 // it.
233 static bool isOnlyUse(Value *V) {
234   return V->hasOneUse() || isa<Constant>(V);
235 }
236
237 // getPromotedType - Return the specified type promoted as it would be to pass
238 // though a va_arg area...
239 static const Type *getPromotedType(const Type *Ty) {
240   switch (Ty->getTypeID()) {
241   case Type::SByteTyID:
242   case Type::ShortTyID:  return Type::IntTy;
243   case Type::UByteTyID:
244   case Type::UShortTyID: return Type::UIntTy;
245   case Type::FloatTyID:  return Type::DoubleTy;
246   default:               return Ty;
247   }
248 }
249
250 // SimplifyCommutative - This performs a few simplifications for commutative
251 // operators:
252 //
253 //  1. Order operands such that they are listed from right (least complex) to
254 //     left (most complex).  This puts constants before unary operators before
255 //     binary operators.
256 //
257 //  2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
258 //  3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
259 //
260 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
261   bool Changed = false;
262   if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
263     Changed = !I.swapOperands();
264   
265   if (!I.isAssociative()) return Changed;
266   Instruction::BinaryOps Opcode = I.getOpcode();
267   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
268     if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
269       if (isa<Constant>(I.getOperand(1))) {
270         Constant *Folded = ConstantExpr::get(I.getOpcode(),
271                                              cast<Constant>(I.getOperand(1)),
272                                              cast<Constant>(Op->getOperand(1)));
273         I.setOperand(0, Op->getOperand(0));
274         I.setOperand(1, Folded);
275         return true;
276       } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
277         if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
278             isOnlyUse(Op) && isOnlyUse(Op1)) {
279           Constant *C1 = cast<Constant>(Op->getOperand(1));
280           Constant *C2 = cast<Constant>(Op1->getOperand(1));
281
282           // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
283           Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
284           Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
285                                                     Op1->getOperand(0),
286                                                     Op1->getName(), &I);
287           WorkList.push_back(New);
288           I.setOperand(0, New);
289           I.setOperand(1, Folded);
290           return true;
291         }      
292     }
293   return Changed;
294 }
295
296 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
297 // if the LHS is a constant zero (which is the 'negate' form).
298 //
299 static inline Value *dyn_castNegVal(Value *V) {
300   if (BinaryOperator::isNeg(V))
301     return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
302
303   // Constants can be considered to be negated values if they can be folded...
304   if (Constant *C = dyn_cast<Constant>(V))
305     return ConstantExpr::getNeg(C);
306   return 0;
307 }
308
309 static inline Value *dyn_castNotVal(Value *V) {
310   if (BinaryOperator::isNot(V))
311     return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
312
313   // Constants can be considered to be not'ed values...
314   if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
315     return ConstantExpr::getNot(C);
316   return 0;
317 }
318
319 // dyn_castFoldableMul - If this value is a multiply that can be folded into
320 // other computations (because it has a constant operand), return the
321 // non-constant operand of the multiply.
322 //
323 static inline Value *dyn_castFoldableMul(Value *V) {
324   if (V->hasOneUse() && V->getType()->isInteger())
325     if (Instruction *I = dyn_cast<Instruction>(V))
326       if (I->getOpcode() == Instruction::Mul)
327         if (isa<Constant>(I->getOperand(1)))
328           return I->getOperand(0);
329   return 0;
330 }
331
332 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
333 // power of 2.
334 static unsigned Log2(uint64_t Val) {
335   assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
336   unsigned Count = 0;
337   while (Val != 1) {
338     if (Val & 1) return 0;    // Multiple bits set?
339     Val >>= 1;
340     ++Count;
341   }
342   return Count;
343 }
344
345 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
346 static ConstantInt *AddOne(ConstantInt *C) {
347   return cast<ConstantInt>(ConstantExpr::getAdd(C,
348                                          ConstantInt::get(C->getType(), 1)));
349 }
350 static ConstantInt *SubOne(ConstantInt *C) {
351   return cast<ConstantInt>(ConstantExpr::getSub(C,
352                                          ConstantInt::get(C->getType(), 1)));
353 }
354
355 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
356 // true when both operands are equal...
357 //
358 static bool isTrueWhenEqual(Instruction &I) {
359   return I.getOpcode() == Instruction::SetEQ ||
360          I.getOpcode() == Instruction::SetGE ||
361          I.getOpcode() == Instruction::SetLE;
362 }
363
364 /// AssociativeOpt - Perform an optimization on an associative operator.  This
365 /// function is designed to check a chain of associative operators for a
366 /// potential to apply a certain optimization.  Since the optimization may be
367 /// applicable if the expression was reassociated, this checks the chain, then
368 /// reassociates the expression as necessary to expose the optimization
369 /// opportunity.  This makes use of a special Functor, which must define
370 /// 'shouldApply' and 'apply' methods.
371 ///
372 template<typename Functor>
373 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
374   unsigned Opcode = Root.getOpcode();
375   Value *LHS = Root.getOperand(0);
376
377   // Quick check, see if the immediate LHS matches...
378   if (F.shouldApply(LHS))
379     return F.apply(Root);
380
381   // Otherwise, if the LHS is not of the same opcode as the root, return.
382   Instruction *LHSI = dyn_cast<Instruction>(LHS);
383   while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
384     // Should we apply this transform to the RHS?
385     bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
386
387     // If not to the RHS, check to see if we should apply to the LHS...
388     if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
389       cast<BinaryOperator>(LHSI)->swapOperands();   // Make the LHS the RHS
390       ShouldApply = true;
391     }
392
393     // If the functor wants to apply the optimization to the RHS of LHSI,
394     // reassociate the expression from ((? op A) op B) to (? op (A op B))
395     if (ShouldApply) {
396       BasicBlock *BB = Root.getParent();
397       
398       // Now all of the instructions are in the current basic block, go ahead
399       // and perform the reassociation.
400       Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
401
402       // First move the selected RHS to the LHS of the root...
403       Root.setOperand(0, LHSI->getOperand(1));
404
405       // Make what used to be the LHS of the root be the user of the root...
406       Value *ExtraOperand = TmpLHSI->getOperand(1);
407       if (&Root == TmpLHSI) {
408         Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
409         return 0;
410       }
411       Root.replaceAllUsesWith(TmpLHSI);          // Users now use TmpLHSI
412       TmpLHSI->setOperand(1, &Root);             // TmpLHSI now uses the root
413       TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
414       BasicBlock::iterator ARI = &Root; ++ARI;
415       BB->getInstList().insert(ARI, TmpLHSI);    // Move TmpLHSI to after Root
416       ARI = Root;
417
418       // Now propagate the ExtraOperand down the chain of instructions until we
419       // get to LHSI.
420       while (TmpLHSI != LHSI) {
421         Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
422         // Move the instruction to immediately before the chain we are
423         // constructing to avoid breaking dominance properties.
424         NextLHSI->getParent()->getInstList().remove(NextLHSI);
425         BB->getInstList().insert(ARI, NextLHSI);
426         ARI = NextLHSI;
427
428         Value *NextOp = NextLHSI->getOperand(1);
429         NextLHSI->setOperand(1, ExtraOperand);
430         TmpLHSI = NextLHSI;
431         ExtraOperand = NextOp;
432       }
433       
434       // Now that the instructions are reassociated, have the functor perform
435       // the transformation...
436       return F.apply(Root);
437     }
438     
439     LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
440   }
441   return 0;
442 }
443
444
445 // AddRHS - Implements: X + X --> X << 1
446 struct AddRHS {
447   Value *RHS;
448   AddRHS(Value *rhs) : RHS(rhs) {}
449   bool shouldApply(Value *LHS) const { return LHS == RHS; }
450   Instruction *apply(BinaryOperator &Add) const {
451     return new ShiftInst(Instruction::Shl, Add.getOperand(0),
452                          ConstantInt::get(Type::UByteTy, 1));
453   }
454 };
455
456 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
457 //                 iff C1&C2 == 0
458 struct AddMaskingAnd {
459   Constant *C2;
460   AddMaskingAnd(Constant *c) : C2(c) {}
461   bool shouldApply(Value *LHS) const {
462     ConstantInt *C1;
463     return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) && 
464            ConstantExpr::getAnd(C1, C2)->isNullValue();
465   }
466   Instruction *apply(BinaryOperator &Add) const {
467     return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
468   }
469 };
470
471 static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
472                                              InstCombiner *IC) {
473   // Figure out if the constant is the left or the right argument.
474   bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
475   Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
476
477   if (Constant *SOC = dyn_cast<Constant>(SO)) {
478     if (ConstIsRHS)
479       return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
480     return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
481   }
482
483   Value *Op0 = SO, *Op1 = ConstOperand;
484   if (!ConstIsRHS)
485     std::swap(Op0, Op1);
486   Instruction *New;
487   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
488     New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
489   else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
490     New = new ShiftInst(SI->getOpcode(), Op0, Op1);
491   else {
492     assert(0 && "Unknown binary instruction type!");
493     abort();
494   }
495   return IC->InsertNewInstBefore(New, BI);
496 }
497
498
499 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
500 /// node as operand #0, see if we can fold the instruction into the PHI (which
501 /// is only possible if all operands to the PHI are constants).
502 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
503   PHINode *PN = cast<PHINode>(I.getOperand(0));
504   if (!PN->hasOneUse()) return 0;
505
506   // Check to see if all of the operands of the PHI are constants.  If not, we
507   // cannot do the transformation.
508   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
509     if (!isa<Constant>(PN->getIncomingValue(i)))
510       return 0;
511
512   // Okay, we can do the transformation: create the new PHI node.
513   PHINode *NewPN = new PHINode(I.getType(), I.getName());
514   I.setName("");
515   NewPN->op_reserve(PN->getNumOperands());
516   InsertNewInstBefore(NewPN, *PN);
517
518   // Next, add all of the operands to the PHI.
519   if (I.getNumOperands() == 2) {
520     Constant *C = cast<Constant>(I.getOperand(1));
521     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
522       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
523       NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
524                          PN->getIncomingBlock(i));
525     }
526   } else {
527     assert(isa<CastInst>(I) && "Unary op should be a cast!");
528     const Type *RetTy = I.getType();
529     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
530       Constant *InV = cast<Constant>(PN->getIncomingValue(i));
531       NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
532                          PN->getIncomingBlock(i));
533     }
534   }
535   return ReplaceInstUsesWith(I, NewPN);
536 }
537
538 // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
539 // constant as the other operand, try to fold the binary operator into the
540 // select arguments.
541 static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
542                                         InstCombiner *IC) {
543   // Don't modify shared select instructions
544   if (!SI->hasOneUse()) return 0;
545   Value *TV = SI->getOperand(1);
546   Value *FV = SI->getOperand(2);
547
548   if (isa<Constant>(TV) || isa<Constant>(FV)) {
549     Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
550     Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
551
552     return new SelectInst(SI->getCondition(), SelectTrueVal,
553                           SelectFalseVal);
554   }
555   return 0;
556 }
557
558 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
559   bool Changed = SimplifyCommutative(I);
560   Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
561
562   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
563     // X + undef -> undef
564     if (isa<UndefValue>(RHS))
565       return ReplaceInstUsesWith(I, RHS);
566
567     // X + 0 --> X
568     if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
569         RHSC->isNullValue())
570       return ReplaceInstUsesWith(I, LHS);
571     
572     // X + (signbit) --> X ^ signbit
573     if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
574       unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
575       uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
576       if (Val == (1ULL << NumBits-1))
577         return BinaryOperator::createXor(LHS, RHS);
578     }
579
580     if (isa<PHINode>(LHS))
581       if (Instruction *NV = FoldOpIntoPhi(I))
582         return NV;
583   }
584
585   // X + X --> X << 1
586   if (I.getType()->isInteger()) {
587     if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
588   }
589
590   // -A + B  -->  B - A
591   if (Value *V = dyn_castNegVal(LHS))
592     return BinaryOperator::createSub(RHS, V);
593
594   // A + -B  -->  A - B
595   if (!isa<Constant>(RHS))
596     if (Value *V = dyn_castNegVal(RHS))
597       return BinaryOperator::createSub(LHS, V);
598
599   // X*C + X --> X * (C+1)
600   if (dyn_castFoldableMul(LHS) == RHS) {
601     Constant *CP1 =
602       ConstantExpr::getAdd(
603                         cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
604                         ConstantInt::get(I.getType(), 1));
605     return BinaryOperator::createMul(RHS, CP1);
606   }
607
608   // X + X*C --> X * (C+1)
609   if (dyn_castFoldableMul(RHS) == LHS) {
610     Constant *CP1 =
611       ConstantExpr::getAdd(
612                         cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
613                         ConstantInt::get(I.getType(), 1));
614     return BinaryOperator::createMul(LHS, CP1);
615   }
616
617   // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
618   ConstantInt *C2;
619   if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
620     if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
621
622   if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
623     Value *X;
624     if (match(LHS, m_Not(m_Value(X)))) {   // ~X + C --> (C-1) - X
625       Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
626       return BinaryOperator::createSub(C, X);
627     }
628
629     // (X & FF00) + xx00  -> (X+xx00) & FF00
630     if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
631       Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
632       if (Anded == CRHS) {
633         // See if all bits from the first bit set in the Add RHS up are included
634         // in the mask.  First, get the rightmost bit.
635         uint64_t AddRHSV = CRHS->getRawValue();
636
637         // Form a mask of all bits from the lowest bit added through the top.
638         uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
639         AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
640
641         // See if the and mask includes all of these bits.
642         uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
643         
644         if (AddRHSHighBits == AddRHSHighBitsAnd) {
645           // Okay, the xform is safe.  Insert the new add pronto.
646           Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
647                                                             LHS->getName()), I);
648           return BinaryOperator::createAnd(NewAdd, C2);
649         }
650       }
651     }
652
653
654     // Try to fold constant add into select arguments.
655     if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
656       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
657         return R;
658   }
659
660   return Changed ? &I : 0;
661 }
662
663 // isSignBit - Return true if the value represented by the constant only has the
664 // highest order bit set.
665 static bool isSignBit(ConstantInt *CI) {
666   unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
667   return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
668 }
669
670 static unsigned getTypeSizeInBits(const Type *Ty) {
671   return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
672 }
673
674 /// RemoveNoopCast - Strip off nonconverting casts from the value.
675 ///
676 static Value *RemoveNoopCast(Value *V) {
677   if (CastInst *CI = dyn_cast<CastInst>(V)) {
678     const Type *CTy = CI->getType();
679     const Type *OpTy = CI->getOperand(0)->getType();
680     if (CTy->isInteger() && OpTy->isInteger()) {
681       if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
682         return RemoveNoopCast(CI->getOperand(0));
683     } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
684       return RemoveNoopCast(CI->getOperand(0));
685   }
686   return V;
687 }
688
689 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
690   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
691
692   if (Op0 == Op1)         // sub X, X  -> 0
693     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
694
695   // If this is a 'B = x-(-A)', change to B = x+A...
696   if (Value *V = dyn_castNegVal(Op1))
697     return BinaryOperator::createAdd(Op0, V);
698
699   if (isa<UndefValue>(Op0))
700     return ReplaceInstUsesWith(I, Op0);    // undef - X -> undef
701   if (isa<UndefValue>(Op1))
702     return ReplaceInstUsesWith(I, Op1);    // X - undef -> undef
703
704   if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
705     // Replace (-1 - A) with (~A)...
706     if (C->isAllOnesValue())
707       return BinaryOperator::createNot(Op1);
708
709     // C - ~X == X + (1+C)
710     Value *X;
711     if (match(Op1, m_Not(m_Value(X))))
712       return BinaryOperator::createAdd(X,
713                     ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
714     // -((uint)X >> 31) -> ((int)X >> 31)
715     // -((int)X >> 31) -> ((uint)X >> 31)
716     if (C->isNullValue()) {
717       Value *NoopCastedRHS = RemoveNoopCast(Op1);
718       if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
719         if (SI->getOpcode() == Instruction::Shr)
720           if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
721             const Type *NewTy;
722             if (SI->getType()->isSigned())
723               NewTy = SI->getType()->getUnsignedVersion();
724             else
725               NewTy = SI->getType()->getSignedVersion();
726             // Check to see if we are shifting out everything but the sign bit.
727             if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
728               // Ok, the transformation is safe.  Insert a cast of the incoming
729               // value, then the new shift, then the new cast.
730               Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
731                                                  SI->getOperand(0)->getName());
732               Value *InV = InsertNewInstBefore(FirstCast, I);
733               Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
734                                                     CU, SI->getName());
735               if (NewShift->getType() == I.getType())
736                 return NewShift;
737               else {
738                 InV = InsertNewInstBefore(NewShift, I);
739                 return new CastInst(NewShift, I.getType());
740               }
741             }
742           }
743     }
744
745     // Try to fold constant sub into select arguments.
746     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
747       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
748         return R;
749
750     if (isa<PHINode>(Op0))
751       if (Instruction *NV = FoldOpIntoPhi(I))
752         return NV;
753   }
754
755   if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
756     if (Op1I->hasOneUse()) {
757       // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
758       // is not used by anyone else...
759       //
760       if (Op1I->getOpcode() == Instruction::Sub &&
761           !Op1I->getType()->isFloatingPoint()) {
762         // Swap the two operands of the subexpr...
763         Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
764         Op1I->setOperand(0, IIOp1);
765         Op1I->setOperand(1, IIOp0);
766         
767         // Create the new top level add instruction...
768         return BinaryOperator::createAdd(Op0, Op1);
769       }
770
771       // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
772       //
773       if (Op1I->getOpcode() == Instruction::And &&
774           (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
775         Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
776
777         Value *NewNot =
778           InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
779         return BinaryOperator::createAnd(Op0, NewNot);
780       }
781
782       // -(X sdiv C)  -> (X sdiv -C)
783       if (Op1I->getOpcode() == Instruction::Div)
784         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
785           if (CSI->getValue() == 0)
786             if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
787               return BinaryOperator::createDiv(Op1I->getOperand(0), 
788                                                ConstantExpr::getNeg(DivRHS));
789
790       // X - X*C --> X * (1-C)
791       if (dyn_castFoldableMul(Op1I) == Op0) {
792         Constant *CP1 =
793           ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
794                          cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
795         assert(CP1 && "Couldn't constant fold 1-C?");
796         return BinaryOperator::createMul(Op0, CP1);
797       }
798     }
799
800   // X*C - X --> X * (C-1)
801   if (dyn_castFoldableMul(Op0) == Op1) {
802     Constant *CP1 =
803      ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
804                         ConstantInt::get(I.getType(), 1));
805     assert(CP1 && "Couldn't constant fold C - 1?");
806     return BinaryOperator::createMul(Op1, CP1);
807   }
808
809   return 0;
810 }
811
812 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
813 /// really just returns true if the most significant (sign) bit is set.
814 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
815   if (RHS->getType()->isSigned()) {
816     // True if source is LHS < 0 or LHS <= -1
817     return Opcode == Instruction::SetLT && RHS->isNullValue() ||
818            Opcode == Instruction::SetLE && RHS->isAllOnesValue();
819   } else {
820     ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
821     // True if source is LHS > 127 or LHS >= 128, where the constants depend on
822     // the size of the integer type.
823     if (Opcode == Instruction::SetGE)
824       return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
825     if (Opcode == Instruction::SetGT)
826       return RHSC->getValue() ==
827         (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
828   }
829   return false;
830 }
831
832 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
833   bool Changed = SimplifyCommutative(I);
834   Value *Op0 = I.getOperand(0);
835
836   if (isa<UndefValue>(I.getOperand(1)))              // undef * X -> 0
837     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
838
839   // Simplify mul instructions with a constant RHS...
840   if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
841     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
842
843       // ((X << C1)*C2) == (X * (C2 << C1))
844       if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
845         if (SI->getOpcode() == Instruction::Shl)
846           if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
847             return BinaryOperator::createMul(SI->getOperand(0),
848                                              ConstantExpr::getShl(CI, ShOp));
849       
850       if (CI->isNullValue())
851         return ReplaceInstUsesWith(I, Op1);  // X * 0  == 0
852       if (CI->equalsInt(1))                  // X * 1  == X
853         return ReplaceInstUsesWith(I, Op0);
854       if (CI->isAllOnesValue())              // X * -1 == 0 - X
855         return BinaryOperator::createNeg(Op0, I.getName());
856
857       int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
858       if (uint64_t C = Log2(Val))            // Replace X*(2^C) with X << C
859         return new ShiftInst(Instruction::Shl, Op0,
860                              ConstantUInt::get(Type::UByteTy, C));
861     } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
862       if (Op1F->isNullValue())
863         return ReplaceInstUsesWith(I, Op1);
864
865       // "In IEEE floating point, x*1 is not equivalent to x for nans.  However,
866       // ANSI says we can drop signals, so we can do this anyway." (from GCC)
867       if (Op1F->getValue() == 1.0)
868         return ReplaceInstUsesWith(I, Op0);  // Eliminate 'mul double %X, 1.0'
869     }
870
871     // Try to fold constant mul into select arguments.
872     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
873       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
874         return R;
875
876     if (isa<PHINode>(Op0))
877       if (Instruction *NV = FoldOpIntoPhi(I))
878         return NV;
879   }
880
881   if (Value *Op0v = dyn_castNegVal(Op0))     // -X * -Y = X*Y
882     if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
883       return BinaryOperator::createMul(Op0v, Op1v);
884
885   // If one of the operands of the multiply is a cast from a boolean value, then
886   // we know the bool is either zero or one, so this is a 'masking' multiply.
887   // See if we can simplify things based on how the boolean was originally
888   // formed.
889   CastInst *BoolCast = 0;
890   if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
891     if (CI->getOperand(0)->getType() == Type::BoolTy)
892       BoolCast = CI;
893   if (!BoolCast)
894     if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
895       if (CI->getOperand(0)->getType() == Type::BoolTy)
896         BoolCast = CI;
897   if (BoolCast) {
898     if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
899       Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
900       const Type *SCOpTy = SCIOp0->getType();
901
902       // If the setcc is true iff the sign bit of X is set, then convert this
903       // multiply into a shift/and combination.
904       if (isa<ConstantInt>(SCIOp1) &&
905           isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
906         // Shift the X value right to turn it into "all signbits".
907         Constant *Amt = ConstantUInt::get(Type::UByteTy,
908                                           SCOpTy->getPrimitiveSize()*8-1);
909         if (SCIOp0->getType()->isUnsigned()) {
910           const Type *NewTy = SCIOp0->getType()->getSignedVersion();
911           SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
912                                                     SCIOp0->getName()), I);
913         }
914
915         Value *V =
916           InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
917                                             BoolCast->getOperand(0)->getName()+
918                                             ".mask"), I);
919
920         // If the multiply type is not the same as the source type, sign extend
921         // or truncate to the multiply type.
922         if (I.getType() != V->getType())
923           V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
924         
925         Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
926         return BinaryOperator::createAnd(V, OtherOp);
927       }
928     }
929   }
930
931   return Changed ? &I : 0;
932 }
933
934 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
935   if (isa<UndefValue>(I.getOperand(0)))              // undef / X -> 0
936     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
937   if (isa<UndefValue>(I.getOperand(1)))
938     return ReplaceInstUsesWith(I, I.getOperand(1));  // X / undef -> undef
939
940   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
941     // div X, 1 == X
942     if (RHS->equalsInt(1))
943       return ReplaceInstUsesWith(I, I.getOperand(0));
944
945     // div X, -1 == -X
946     if (RHS->isAllOnesValue())
947       return BinaryOperator::createNeg(I.getOperand(0));
948
949     if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
950       if (LHS->getOpcode() == Instruction::Div)
951         if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
952           // (X / C1) / C2  -> X / (C1*C2)
953           return BinaryOperator::createDiv(LHS->getOperand(0),
954                                            ConstantExpr::getMul(RHS, LHSRHS));
955         }
956
957     // Check to see if this is an unsigned division with an exact power of 2,
958     // if so, convert to a right shift.
959     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
960       if (uint64_t Val = C->getValue())    // Don't break X / 0
961         if (uint64_t C = Log2(Val))
962           return new ShiftInst(Instruction::Shr, I.getOperand(0),
963                                ConstantUInt::get(Type::UByteTy, C));
964
965     // -X/C -> X/-C
966     if (RHS->getType()->isSigned())
967       if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
968         return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
969
970     if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
971       if (Instruction *NV = FoldOpIntoPhi(I))
972         return NV;
973   }
974
975   // 0 / X == 0, we don't need to preserve faults!
976   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
977     if (LHS->equalsInt(0))
978       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
979
980   return 0;
981 }
982
983
984 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
985   if (I.getType()->isSigned())
986     if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
987       if (!isa<ConstantSInt>(RHSNeg) ||
988           cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
989         // X % -Y -> X % Y
990         AddUsesToWorkList(I);
991         I.setOperand(1, RHSNeg);
992         return &I;
993       }
994
995   if (isa<UndefValue>(I.getOperand(0)))              // undef % X -> 0
996     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
997   if (isa<UndefValue>(I.getOperand(1)))
998     return ReplaceInstUsesWith(I, I.getOperand(1));  // X % undef -> undef
999
1000   if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1001     if (RHS->equalsInt(1))  // X % 1 == 0
1002       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1003
1004     // Check to see if this is an unsigned remainder with an exact power of 2,
1005     // if so, convert to a bitwise and.
1006     if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1007       if (uint64_t Val = C->getValue())    // Don't break X % 0 (divide by zero)
1008         if (!(Val & (Val-1)))              // Power of 2
1009           return BinaryOperator::createAnd(I.getOperand(0),
1010                                         ConstantUInt::get(I.getType(), Val-1));
1011     if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1012       if (Instruction *NV = FoldOpIntoPhi(I))
1013         return NV;
1014   }
1015
1016   // 0 % X == 0, we don't need to preserve faults!
1017   if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1018     if (LHS->equalsInt(0))
1019       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1020
1021   return 0;
1022 }
1023
1024 // isMaxValueMinusOne - return true if this is Max-1
1025 static bool isMaxValueMinusOne(const ConstantInt *C) {
1026   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1027     // Calculate -1 casted to the right type...
1028     unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1029     uint64_t Val = ~0ULL;                // All ones
1030     Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1031     return CU->getValue() == Val-1;
1032   }
1033
1034   const ConstantSInt *CS = cast<ConstantSInt>(C);
1035   
1036   // Calculate 0111111111..11111
1037   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1038   int64_t Val = INT64_MAX;             // All ones
1039   Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
1040   return CS->getValue() == Val-1;
1041 }
1042
1043 // isMinValuePlusOne - return true if this is Min+1
1044 static bool isMinValuePlusOne(const ConstantInt *C) {
1045   if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1046     return CU->getValue() == 1;
1047
1048   const ConstantSInt *CS = cast<ConstantSInt>(C);
1049   
1050   // Calculate 1111111111000000000000 
1051   unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1052   int64_t Val = -1;                    // All ones
1053   Val <<= TypeBits-1;                  // Shift over to the right spot
1054   return CS->getValue() == Val+1;
1055 }
1056
1057 // isOneBitSet - Return true if there is exactly one bit set in the specified
1058 // constant.
1059 static bool isOneBitSet(const ConstantInt *CI) {
1060   uint64_t V = CI->getRawValue();
1061   return V && (V & (V-1)) == 0;
1062 }
1063
1064 #if 0   // Currently unused
1065 // isLowOnes - Return true if the constant is of the form 0+1+.
1066 static bool isLowOnes(const ConstantInt *CI) {
1067   uint64_t V = CI->getRawValue();
1068
1069   // There won't be bits set in parts that the type doesn't contain.
1070   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1071
1072   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1073   return U && V && (U & V) == 0;
1074 }
1075 #endif
1076
1077 // isHighOnes - Return true if the constant is of the form 1+0+.
1078 // This is the same as lowones(~X).
1079 static bool isHighOnes(const ConstantInt *CI) {
1080   uint64_t V = ~CI->getRawValue();
1081
1082   // There won't be bits set in parts that the type doesn't contain.
1083   V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1084
1085   uint64_t U = V+1;  // If it is low ones, this should be a power of two.
1086   return U && V && (U & V) == 0;
1087 }
1088
1089
1090 /// getSetCondCode - Encode a setcc opcode into a three bit mask.  These bits
1091 /// are carefully arranged to allow folding of expressions such as:
1092 ///
1093 ///      (A < B) | (A > B) --> (A != B)
1094 ///
1095 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1096 /// represents that the comparison is true if A == B, and bit value '1' is true
1097 /// if A < B.
1098 ///
1099 static unsigned getSetCondCode(const SetCondInst *SCI) {
1100   switch (SCI->getOpcode()) {
1101     // False -> 0
1102   case Instruction::SetGT: return 1;
1103   case Instruction::SetEQ: return 2;
1104   case Instruction::SetGE: return 3;
1105   case Instruction::SetLT: return 4;
1106   case Instruction::SetNE: return 5;
1107   case Instruction::SetLE: return 6;
1108     // True -> 7
1109   default:
1110     assert(0 && "Invalid SetCC opcode!");
1111     return 0;
1112   }
1113 }
1114
1115 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1116 /// opcode and two operands into either a constant true or false, or a brand new
1117 /// SetCC instruction.
1118 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1119   switch (Opcode) {
1120   case 0: return ConstantBool::False;
1121   case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1122   case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1123   case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1124   case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1125   case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1126   case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1127   case 7: return ConstantBool::True;
1128   default: assert(0 && "Illegal SetCCCode!"); return 0;
1129   }
1130 }
1131
1132 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1133 struct FoldSetCCLogical {
1134   InstCombiner &IC;
1135   Value *LHS, *RHS;
1136   FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1137     : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1138   bool shouldApply(Value *V) const {
1139     if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1140       return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1141               SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1142     return false;
1143   }
1144   Instruction *apply(BinaryOperator &Log) const {
1145     SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1146     if (SCI->getOperand(0) != LHS) {
1147       assert(SCI->getOperand(1) == LHS);
1148       SCI->swapOperands();  // Swap the LHS and RHS of the SetCC
1149     }
1150
1151     unsigned LHSCode = getSetCondCode(SCI);
1152     unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1153     unsigned Code;
1154     switch (Log.getOpcode()) {
1155     case Instruction::And: Code = LHSCode & RHSCode; break;
1156     case Instruction::Or:  Code = LHSCode | RHSCode; break;
1157     case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1158     default: assert(0 && "Illegal logical opcode!"); return 0;
1159     }
1160
1161     Value *RV = getSetCCValue(Code, LHS, RHS);
1162     if (Instruction *I = dyn_cast<Instruction>(RV))
1163       return I;
1164     // Otherwise, it's a constant boolean value...
1165     return IC.ReplaceInstUsesWith(Log, RV);
1166   }
1167 };
1168
1169
1170 // OptAndOp - This handles expressions of the form ((val OP C1) & C2).  Where
1171 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'.  Op is
1172 // guaranteed to be either a shift instruction or a binary operator.
1173 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1174                                     ConstantIntegral *OpRHS,
1175                                     ConstantIntegral *AndRHS,
1176                                     BinaryOperator &TheAnd) {
1177   Value *X = Op->getOperand(0);
1178   Constant *Together = 0;
1179   if (!isa<ShiftInst>(Op))
1180     Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1181
1182   switch (Op->getOpcode()) {
1183   case Instruction::Xor:
1184     if (Together->isNullValue()) {
1185       // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
1186       return BinaryOperator::createAnd(X, AndRHS);
1187     } else if (Op->hasOneUse()) {
1188       // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1189       std::string OpName = Op->getName(); Op->setName("");
1190       Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1191       InsertNewInstBefore(And, TheAnd);
1192       return BinaryOperator::createXor(And, Together);
1193     }
1194     break;
1195   case Instruction::Or:
1196     // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
1197     if (Together->isNullValue())
1198       return BinaryOperator::createAnd(X, AndRHS);
1199     else {
1200       if (Together == AndRHS) // (X | C) & C --> C
1201         return ReplaceInstUsesWith(TheAnd, AndRHS);
1202       
1203       if (Op->hasOneUse() && Together != OpRHS) {
1204         // (X | C1) & C2 --> (X | (C1&C2)) & C2
1205         std::string Op0Name = Op->getName(); Op->setName("");
1206         Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1207         InsertNewInstBefore(Or, TheAnd);
1208         return BinaryOperator::createAnd(Or, AndRHS);
1209       }
1210     }
1211     break;
1212   case Instruction::Add:
1213     if (Op->hasOneUse()) {
1214       // Adding a one to a single bit bit-field should be turned into an XOR
1215       // of the bit.  First thing to check is to see if this AND is with a
1216       // single bit constant.
1217       uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1218
1219       // Clear bits that are not part of the constant.
1220       AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1221
1222       // If there is only one bit set...
1223       if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1224         // Ok, at this point, we know that we are masking the result of the
1225         // ADD down to exactly one bit.  If the constant we are adding has
1226         // no bits set below this bit, then we can eliminate the ADD.
1227         uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1228             
1229         // Check to see if any bits below the one bit set in AndRHSV are set.
1230         if ((AddRHS & (AndRHSV-1)) == 0) {
1231           // If not, the only thing that can effect the output of the AND is
1232           // the bit specified by AndRHSV.  If that bit is set, the effect of
1233           // the XOR is to toggle the bit.  If it is clear, then the ADD has
1234           // no effect.
1235           if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1236             TheAnd.setOperand(0, X);
1237             return &TheAnd;
1238           } else {
1239             std::string Name = Op->getName(); Op->setName("");
1240             // Pull the XOR out of the AND.
1241             Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1242             InsertNewInstBefore(NewAnd, TheAnd);
1243             return BinaryOperator::createXor(NewAnd, AndRHS);
1244           }
1245         }
1246       }
1247     }
1248     break;
1249
1250   case Instruction::Shl: {
1251     // We know that the AND will not produce any of the bits shifted in, so if
1252     // the anded constant includes them, clear them now!
1253     //
1254     Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1255     Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1256     Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1257                                         
1258     if (CI == ShlMask) {   // Masking out bits that the shift already masks
1259       return ReplaceInstUsesWith(TheAnd, Op);   // No need for the and.
1260     } else if (CI != AndRHS) {                  // Reducing bits set in and.
1261       TheAnd.setOperand(1, CI);
1262       return &TheAnd;
1263     }
1264     break;
1265   } 
1266   case Instruction::Shr:
1267     // We know that the AND will not produce any of the bits shifted in, so if
1268     // the anded constant includes them, clear them now!  This only applies to
1269     // unsigned shifts, because a signed shr may bring in set bits!
1270     //
1271     if (AndRHS->getType()->isUnsigned()) {
1272       Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1273       Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1274       Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1275
1276       if (CI == ShrMask) {   // Masking out bits that the shift already masks.
1277         return ReplaceInstUsesWith(TheAnd, Op);
1278       } else if (CI != AndRHS) {
1279         TheAnd.setOperand(1, CI);  // Reduce bits set in and cst.
1280         return &TheAnd;
1281       }
1282     } else {   // Signed shr.
1283       // See if this is shifting in some sign extension, then masking it out
1284       // with an and.
1285       if (Op->hasOneUse()) {
1286         Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1287         Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1288         Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1289         if (CI == ShrMask) {          // Masking out bits shifted in.
1290           // Make the argument unsigned.
1291           Value *ShVal = Op->getOperand(0);
1292           ShVal = InsertCastBefore(ShVal,
1293                                    ShVal->getType()->getUnsignedVersion(),
1294                                    TheAnd);
1295           ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1296                                                     OpRHS, Op->getName()),
1297                                       TheAnd);
1298           return new CastInst(ShVal, Op->getType());
1299         }
1300       }
1301     }
1302     break;
1303   }
1304   return 0;
1305 }
1306
1307
1308 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1309 /// true, otherwise (V < Lo || V >= Hi).  In pratice, we emit the more efficient
1310 /// (V-Lo) <u Hi-Lo.  This method expects that Lo <= Hi.  IB is the location to
1311 /// insert new instructions.
1312 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1313                                            bool Inside, Instruction &IB) {
1314   assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1315          "Lo is not <= Hi in range emission code!");
1316   if (Inside) {
1317     if (Lo == Hi)  // Trivially false.
1318       return new SetCondInst(Instruction::SetNE, V, V);
1319     if (cast<ConstantIntegral>(Lo)->isMinValue())
1320       return new SetCondInst(Instruction::SetLT, V, Hi);
1321     
1322     Constant *AddCST = ConstantExpr::getNeg(Lo);
1323     Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1324     InsertNewInstBefore(Add, IB);
1325     // Convert to unsigned for the comparison.
1326     const Type *UnsType = Add->getType()->getUnsignedVersion();
1327     Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1328     AddCST = ConstantExpr::getAdd(AddCST, Hi);
1329     AddCST = ConstantExpr::getCast(AddCST, UnsType);
1330     return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1331   }
1332
1333   if (Lo == Hi)  // Trivially true.
1334     return new SetCondInst(Instruction::SetEQ, V, V);
1335
1336   Hi = SubOne(cast<ConstantInt>(Hi));
1337   if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1338     return new SetCondInst(Instruction::SetGT, V, Hi);
1339
1340   // Emit X-Lo > Hi-Lo-1
1341   Constant *AddCST = ConstantExpr::getNeg(Lo);
1342   Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1343   InsertNewInstBefore(Add, IB);
1344   // Convert to unsigned for the comparison.
1345   const Type *UnsType = Add->getType()->getUnsignedVersion();
1346   Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1347   AddCST = ConstantExpr::getAdd(AddCST, Hi);
1348   AddCST = ConstantExpr::getCast(AddCST, UnsType);
1349   return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1350 }
1351
1352
1353 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1354   bool Changed = SimplifyCommutative(I);
1355   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1356
1357   if (isa<UndefValue>(Op1))                         // X & undef -> 0
1358     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1359
1360   // and X, X = X   and X, 0 == 0
1361   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1362     return ReplaceInstUsesWith(I, Op1);
1363
1364   // and X, -1 == X
1365   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1366     if (RHS->isAllOnesValue())
1367       return ReplaceInstUsesWith(I, Op0);
1368
1369     // Optimize a variety of ((val OP C1) & C2) combinations...
1370     if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1371       Instruction *Op0I = cast<Instruction>(Op0);
1372       Value *X = Op0I->getOperand(0);
1373       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1374         if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1375           return Res;
1376     }
1377
1378     // Try to fold constant and into select arguments.
1379     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1380       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1381         return R;
1382     if (isa<PHINode>(Op0))
1383       if (Instruction *NV = FoldOpIntoPhi(I))
1384         return NV;
1385   }
1386
1387   Value *Op0NotVal = dyn_castNotVal(Op0);
1388   Value *Op1NotVal = dyn_castNotVal(Op1);
1389
1390   if (Op0NotVal == Op1 || Op1NotVal == Op0)  // A & ~A  == ~A & A == 0
1391     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1392
1393   // (~A & ~B) == (~(A | B)) - De Morgan's Law
1394   if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1395     Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1396                                                I.getName()+".demorgan");
1397     InsertNewInstBefore(Or, I);
1398     return BinaryOperator::createNot(Or);
1399   }
1400
1401   if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1402     // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1403     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1404       return R;
1405
1406     Value *LHSVal, *RHSVal;
1407     ConstantInt *LHSCst, *RHSCst;
1408     Instruction::BinaryOps LHSCC, RHSCC;
1409     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1410       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1411         if (LHSVal == RHSVal &&    // Found (X setcc C1) & (X setcc C2)
1412             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1413             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && 
1414             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1415           // Ensure that the larger constant is on the RHS.
1416           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1417           SetCondInst *LHS = cast<SetCondInst>(Op0);
1418           if (cast<ConstantBool>(Cmp)->getValue()) {
1419             std::swap(LHS, RHS);
1420             std::swap(LHSCst, RHSCst);
1421             std::swap(LHSCC, RHSCC);
1422           }
1423
1424           // At this point, we know we have have two setcc instructions
1425           // comparing a value against two constants and and'ing the result
1426           // together.  Because of the above check, we know that we only have
1427           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
1428           // FoldSetCCLogical check above), that the two constants are not
1429           // equal.
1430           assert(LHSCst != RHSCst && "Compares not folded above?");
1431
1432           switch (LHSCC) {
1433           default: assert(0 && "Unknown integer condition code!");
1434           case Instruction::SetEQ:
1435             switch (RHSCC) {
1436             default: assert(0 && "Unknown integer condition code!");
1437             case Instruction::SetEQ:  // (X == 13 & X == 15) -> false
1438             case Instruction::SetGT:  // (X == 13 & X > 15)  -> false
1439               return ReplaceInstUsesWith(I, ConstantBool::False);
1440             case Instruction::SetNE:  // (X == 13 & X != 15) -> X == 13
1441             case Instruction::SetLT:  // (X == 13 & X < 15)  -> X == 13
1442               return ReplaceInstUsesWith(I, LHS);
1443             }
1444           case Instruction::SetNE:
1445             switch (RHSCC) {
1446             default: assert(0 && "Unknown integer condition code!");
1447             case Instruction::SetLT:
1448               if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1449                 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1450               break;                        // (X != 13 & X < 15) -> no change
1451             case Instruction::SetEQ:        // (X != 13 & X == 15) -> X == 15
1452             case Instruction::SetGT:        // (X != 13 & X > 15)  -> X > 15
1453               return ReplaceInstUsesWith(I, RHS);
1454             case Instruction::SetNE:
1455               if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1456                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1457                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1458                                                       LHSVal->getName()+".off");
1459                 InsertNewInstBefore(Add, I);
1460                 const Type *UnsType = Add->getType()->getUnsignedVersion();
1461                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1462                 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1463                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1464                 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1465               }
1466               break;                        // (X != 13 & X != 15) -> no change
1467             }
1468             break;
1469           case Instruction::SetLT:
1470             switch (RHSCC) {
1471             default: assert(0 && "Unknown integer condition code!");
1472             case Instruction::SetEQ:  // (X < 13 & X == 15) -> false
1473             case Instruction::SetGT:  // (X < 13 & X > 15)  -> false
1474               return ReplaceInstUsesWith(I, ConstantBool::False);
1475             case Instruction::SetNE:  // (X < 13 & X != 15) -> X < 13
1476             case Instruction::SetLT:  // (X < 13 & X < 15) -> X < 13
1477               return ReplaceInstUsesWith(I, LHS);
1478             }
1479           case Instruction::SetGT:
1480             switch (RHSCC) {
1481             default: assert(0 && "Unknown integer condition code!");
1482             case Instruction::SetEQ:  // (X > 13 & X == 15) -> X > 13
1483               return ReplaceInstUsesWith(I, LHS);
1484             case Instruction::SetGT:  // (X > 13 & X > 15)  -> X > 15
1485               return ReplaceInstUsesWith(I, RHS);
1486             case Instruction::SetNE:
1487               if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1488                 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1489               break;                        // (X > 13 & X != 15) -> no change
1490             case Instruction::SetLT:   // (X > 13 & X < 15) -> (X-14) <u 1
1491               return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
1492             }
1493           }
1494         }
1495   }
1496
1497   return Changed ? &I : 0;
1498 }
1499
1500 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1501   bool Changed = SimplifyCommutative(I);
1502   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1503
1504   if (isa<UndefValue>(Op1))
1505     return ReplaceInstUsesWith(I,                         // X | undef -> -1
1506                                ConstantIntegral::getAllOnesValue(I.getType()));
1507
1508   // or X, X = X   or X, 0 == X
1509   if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1510     return ReplaceInstUsesWith(I, Op0);
1511
1512   // or X, -1 == -1
1513   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1514     if (RHS->isAllOnesValue())
1515       return ReplaceInstUsesWith(I, Op1);
1516
1517     ConstantInt *C1; Value *X;
1518     // (X & C1) | C2 --> (X | C2) & (C1|C2)
1519     if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1520       std::string Op0Name = Op0->getName(); Op0->setName("");
1521       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1522       InsertNewInstBefore(Or, I);
1523       return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1524     }
1525
1526     // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1527     if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1528       std::string Op0Name = Op0->getName(); Op0->setName("");
1529       Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1530       InsertNewInstBefore(Or, I);
1531       return BinaryOperator::createXor(Or,
1532                  ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
1533     }
1534
1535     // Try to fold constant and into select arguments.
1536     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1537       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1538         return R;
1539     if (isa<PHINode>(Op0))
1540       if (Instruction *NV = FoldOpIntoPhi(I))
1541         return NV;
1542   }
1543
1544   // (A & C1)|(A & C2) == A & (C1|C2)
1545   Value *A, *B; ConstantInt *C1, *C2;
1546   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1547       match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1548     return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1549
1550   if (match(Op0, m_Not(m_Value(A)))) {   // ~A | Op1
1551     if (A == Op1)   // ~A | A == -1
1552       return ReplaceInstUsesWith(I, 
1553                                 ConstantIntegral::getAllOnesValue(I.getType()));
1554   } else {
1555     A = 0;
1556   }
1557
1558   if (match(Op1, m_Not(m_Value(B)))) {   // Op0 | ~B
1559     if (Op0 == B)
1560       return ReplaceInstUsesWith(I, 
1561                                 ConstantIntegral::getAllOnesValue(I.getType()));
1562
1563     // (~A | ~B) == (~(A & B)) - De Morgan's Law
1564     if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1565       Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1566                                               I.getName()+".demorgan"), I);
1567       return BinaryOperator::createNot(And);
1568     }
1569   }
1570
1571   // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1572   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
1573     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1574       return R;
1575
1576     Value *LHSVal, *RHSVal;
1577     ConstantInt *LHSCst, *RHSCst;
1578     Instruction::BinaryOps LHSCC, RHSCC;
1579     if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1580       if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1581         if (LHSVal == RHSVal &&    // Found (X setcc C1) | (X setcc C2)
1582             // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1583             LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE && 
1584             RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1585           // Ensure that the larger constant is on the RHS.
1586           Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1587           SetCondInst *LHS = cast<SetCondInst>(Op0);
1588           if (cast<ConstantBool>(Cmp)->getValue()) {
1589             std::swap(LHS, RHS);
1590             std::swap(LHSCst, RHSCst);
1591             std::swap(LHSCC, RHSCC);
1592           }
1593
1594           // At this point, we know we have have two setcc instructions
1595           // comparing a value against two constants and or'ing the result
1596           // together.  Because of the above check, we know that we only have
1597           // SetEQ, SetNE, SetLT, and SetGT here.  We also know (from the
1598           // FoldSetCCLogical check above), that the two constants are not
1599           // equal.
1600           assert(LHSCst != RHSCst && "Compares not folded above?");
1601
1602           switch (LHSCC) {
1603           default: assert(0 && "Unknown integer condition code!");
1604           case Instruction::SetEQ:
1605             switch (RHSCC) {
1606             default: assert(0 && "Unknown integer condition code!");
1607             case Instruction::SetEQ:
1608               if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1609                 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1610                 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1611                                                       LHSVal->getName()+".off");
1612                 InsertNewInstBefore(Add, I);
1613                 const Type *UnsType = Add->getType()->getUnsignedVersion();
1614                 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1615                 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1616                 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1617                 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1618               }
1619               break;                  // (X == 13 | X == 15) -> no change
1620
1621             case Instruction::SetGT:
1622               if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1623                 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1624               break;                        // (X == 13 | X > 15) -> no change
1625             case Instruction::SetNE:  // (X == 13 | X != 15) -> X != 15
1626             case Instruction::SetLT:  // (X == 13 | X < 15)  -> X < 15
1627               return ReplaceInstUsesWith(I, RHS);
1628             }
1629             break;
1630           case Instruction::SetNE:
1631             switch (RHSCC) {
1632             default: assert(0 && "Unknown integer condition code!");
1633             case Instruction::SetLT:        // (X != 13 | X < 15) -> X < 15
1634               return ReplaceInstUsesWith(I, RHS);
1635             case Instruction::SetEQ:        // (X != 13 | X == 15) -> X != 13
1636             case Instruction::SetGT:        // (X != 13 | X > 15)  -> X != 13
1637               return ReplaceInstUsesWith(I, LHS);
1638             case Instruction::SetNE:        // (X != 13 | X != 15) -> true
1639               return ReplaceInstUsesWith(I, ConstantBool::True);
1640             }
1641             break;
1642           case Instruction::SetLT:
1643             switch (RHSCC) {
1644             default: assert(0 && "Unknown integer condition code!");
1645             case Instruction::SetEQ:  // (X < 13 | X == 14) -> no change
1646               break;
1647             case Instruction::SetGT:  // (X < 13 | X > 15)  -> (X-13) > 2
1648               return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
1649             case Instruction::SetNE:  // (X < 13 | X != 15) -> X != 15
1650             case Instruction::SetLT:  // (X < 13 | X < 15) -> X < 15
1651               return ReplaceInstUsesWith(I, RHS);
1652             }
1653             break;
1654           case Instruction::SetGT:
1655             switch (RHSCC) {
1656             default: assert(0 && "Unknown integer condition code!");
1657             case Instruction::SetEQ:  // (X > 13 | X == 15) -> X > 13
1658             case Instruction::SetGT:  // (X > 13 | X > 15)  -> X > 13
1659               return ReplaceInstUsesWith(I, LHS);
1660             case Instruction::SetNE:  // (X > 13 | X != 15)  -> true
1661             case Instruction::SetLT:  // (X > 13 | X < 15) -> true
1662               return ReplaceInstUsesWith(I, ConstantBool::True);
1663             }
1664           }
1665         }
1666   }
1667   return Changed ? &I : 0;
1668 }
1669
1670 // XorSelf - Implements: X ^ X --> 0
1671 struct XorSelf {
1672   Value *RHS;
1673   XorSelf(Value *rhs) : RHS(rhs) {}
1674   bool shouldApply(Value *LHS) const { return LHS == RHS; }
1675   Instruction *apply(BinaryOperator &Xor) const {
1676     return &Xor;
1677   }
1678 };
1679
1680
1681 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1682   bool Changed = SimplifyCommutative(I);
1683   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1684
1685   if (isa<UndefValue>(Op1))
1686     return ReplaceInstUsesWith(I, Op1);  // X ^ undef -> undef
1687
1688   // xor X, X = 0, even if X is nested in a sequence of Xor's.
1689   if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1690     assert(Result == &I && "AssociativeOpt didn't work?");
1691     return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1692   }
1693
1694   if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1695     // xor X, 0 == X
1696     if (RHS->isNullValue())
1697       return ReplaceInstUsesWith(I, Op0);
1698
1699     if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1700       // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
1701       if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
1702         if (RHS == ConstantBool::True && SCI->hasOneUse())
1703           return new SetCondInst(SCI->getInverseCondition(),
1704                                  SCI->getOperand(0), SCI->getOperand(1));
1705
1706       // ~(c-X) == X-c-1 == X+(-c-1)
1707       if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1708         if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1709           Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1710           Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1711                                               ConstantInt::get(I.getType(), 1));
1712           return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
1713         }
1714
1715       // ~(~X & Y) --> (X | ~Y)
1716       if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1717         if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1718         if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1719           Instruction *NotY =
1720             BinaryOperator::createNot(Op0I->getOperand(1), 
1721                                       Op0I->getOperand(1)->getName()+".not");
1722           InsertNewInstBefore(NotY, I);
1723           return BinaryOperator::createOr(Op0NotVal, NotY);
1724         }
1725       }
1726           
1727       if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1728         switch (Op0I->getOpcode()) {
1729         case Instruction::Add:
1730           // ~(X-c) --> (-c-1)-X
1731           if (RHS->isAllOnesValue()) {
1732             Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1733             return BinaryOperator::createSub(
1734                            ConstantExpr::getSub(NegOp0CI,
1735                                              ConstantInt::get(I.getType(), 1)),
1736                                           Op0I->getOperand(0));
1737           }
1738           break;
1739         case Instruction::And:
1740           // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1741           if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1742             return BinaryOperator::createOr(Op0, RHS);
1743           break;
1744         case Instruction::Or:
1745           // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1746           if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
1747             return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
1748           break;
1749         default: break;
1750         }
1751     }
1752
1753     // Try to fold constant and into select arguments.
1754     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1755       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1756         return R;
1757     if (isa<PHINode>(Op0))
1758       if (Instruction *NV = FoldOpIntoPhi(I))
1759         return NV;
1760   }
1761
1762   if (Value *X = dyn_castNotVal(Op0))   // ~A ^ A == -1
1763     if (X == Op1)
1764       return ReplaceInstUsesWith(I,
1765                                 ConstantIntegral::getAllOnesValue(I.getType()));
1766
1767   if (Value *X = dyn_castNotVal(Op1))   // A ^ ~A == -1
1768     if (X == Op0)
1769       return ReplaceInstUsesWith(I,
1770                                 ConstantIntegral::getAllOnesValue(I.getType()));
1771
1772   if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1773     if (Op1I->getOpcode() == Instruction::Or) {
1774       if (Op1I->getOperand(0) == Op0) {              // B^(B|A) == (A|B)^B
1775         cast<BinaryOperator>(Op1I)->swapOperands();
1776         I.swapOperands();
1777         std::swap(Op0, Op1);
1778       } else if (Op1I->getOperand(1) == Op0) {       // B^(A|B) == (A|B)^B
1779         I.swapOperands();
1780         std::swap(Op0, Op1);
1781       }      
1782     } else if (Op1I->getOpcode() == Instruction::Xor) {
1783       if (Op0 == Op1I->getOperand(0))                        // A^(A^B) == B
1784         return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1785       else if (Op0 == Op1I->getOperand(1))                   // A^(B^A) == B
1786         return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1787     }
1788
1789   if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1790     if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1791       if (Op0I->getOperand(0) == Op1)                // (B|A)^B == (A|B)^B
1792         cast<BinaryOperator>(Op0I)->swapOperands();
1793       if (Op0I->getOperand(1) == Op1) {              // (A|B)^B == A & ~B
1794         Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1795                                                      Op1->getName()+".not"), I);
1796         return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
1797       }
1798     } else if (Op0I->getOpcode() == Instruction::Xor) {
1799       if (Op1 == Op0I->getOperand(0))                        // (A^B)^A == B
1800         return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1801       else if (Op1 == Op0I->getOperand(1))                   // (B^A)^A == B
1802         return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1803     }
1804
1805   // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1806   Value *A, *B; ConstantInt *C1, *C2;
1807   if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1808       match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
1809       ConstantExpr::getAnd(C1, C2)->isNullValue())
1810     return BinaryOperator::createOr(Op0, Op1);
1811
1812   // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1813   if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1814     if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1815       return R;
1816
1817   return Changed ? &I : 0;
1818 }
1819
1820 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1821 /// overflowed for this type.
1822 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1823                             ConstantInt *In2) {
1824   Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1825   return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1826 }
1827
1828 static bool isPositive(ConstantInt *C) {
1829   return cast<ConstantSInt>(C)->getValue() >= 0;
1830 }
1831
1832 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1833 /// overflowed for this type.
1834 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1835                             ConstantInt *In2) {
1836   Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1837
1838   if (In1->getType()->isUnsigned())
1839     return cast<ConstantUInt>(Result)->getValue() <
1840            cast<ConstantUInt>(In1)->getValue();
1841   if (isPositive(In1) != isPositive(In2))
1842     return false;
1843   if (isPositive(In1))
1844     return cast<ConstantSInt>(Result)->getValue() <
1845            cast<ConstantSInt>(In1)->getValue();
1846   return cast<ConstantSInt>(Result)->getValue() >
1847          cast<ConstantSInt>(In1)->getValue();
1848 }
1849
1850 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1851   bool Changed = SimplifyCommutative(I);
1852   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1853   const Type *Ty = Op0->getType();
1854
1855   // setcc X, X
1856   if (Op0 == Op1)
1857     return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1858
1859   if (isa<UndefValue>(Op1))                  // X setcc undef -> undef
1860     return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1861
1862   // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1863   if (isa<ConstantPointerNull>(Op1) && 
1864       (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1865     return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1866
1867
1868   // setcc's with boolean values can always be turned into bitwise operations
1869   if (Ty == Type::BoolTy) {
1870     switch (I.getOpcode()) {
1871     default: assert(0 && "Invalid setcc instruction!");
1872     case Instruction::SetEQ: {     //  seteq bool %A, %B -> ~(A^B)
1873       Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
1874       InsertNewInstBefore(Xor, I);
1875       return BinaryOperator::createNot(Xor);
1876     }
1877     case Instruction::SetNE:
1878       return BinaryOperator::createXor(Op0, Op1);
1879
1880     case Instruction::SetGT:
1881       std::swap(Op0, Op1);                   // Change setgt -> setlt
1882       // FALL THROUGH
1883     case Instruction::SetLT: {               // setlt bool A, B -> ~X & Y
1884       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1885       InsertNewInstBefore(Not, I);
1886       return BinaryOperator::createAnd(Not, Op1);
1887     }
1888     case Instruction::SetGE:
1889       std::swap(Op0, Op1);                   // Change setge -> setle
1890       // FALL THROUGH
1891     case Instruction::SetLE: {     //  setle bool %A, %B -> ~A | B
1892       Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1893       InsertNewInstBefore(Not, I);
1894       return BinaryOperator::createOr(Not, Op1);
1895     }
1896     }
1897   }
1898
1899   // See if we are doing a comparison between a constant and an instruction that
1900   // can be folded into the comparison.
1901   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1902     // Check to see if we are comparing against the minimum or maximum value...
1903     if (CI->isMinValue()) {
1904       if (I.getOpcode() == Instruction::SetLT)       // A < MIN -> FALSE
1905         return ReplaceInstUsesWith(I, ConstantBool::False);
1906       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN -> TRUE
1907         return ReplaceInstUsesWith(I, ConstantBool::True);
1908       if (I.getOpcode() == Instruction::SetLE)       // A <= MIN -> A == MIN
1909         return BinaryOperator::createSetEQ(Op0, Op1);
1910       if (I.getOpcode() == Instruction::SetGT)       // A > MIN -> A != MIN
1911         return BinaryOperator::createSetNE(Op0, Op1);
1912
1913     } else if (CI->isMaxValue()) {
1914       if (I.getOpcode() == Instruction::SetGT)       // A > MAX -> FALSE
1915         return ReplaceInstUsesWith(I, ConstantBool::False);
1916       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX -> TRUE
1917         return ReplaceInstUsesWith(I, ConstantBool::True);
1918       if (I.getOpcode() == Instruction::SetGE)       // A >= MAX -> A == MAX
1919         return BinaryOperator::createSetEQ(Op0, Op1);
1920       if (I.getOpcode() == Instruction::SetLT)       // A < MAX -> A != MAX
1921         return BinaryOperator::createSetNE(Op0, Op1);
1922
1923       // Comparing against a value really close to min or max?
1924     } else if (isMinValuePlusOne(CI)) {
1925       if (I.getOpcode() == Instruction::SetLT)       // A < MIN+1 -> A == MIN
1926         return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1927       if (I.getOpcode() == Instruction::SetGE)       // A >= MIN-1 -> A != MIN
1928         return BinaryOperator::createSetNE(Op0, SubOne(CI));
1929
1930     } else if (isMaxValueMinusOne(CI)) {
1931       if (I.getOpcode() == Instruction::SetGT)       // A > MAX-1 -> A == MAX
1932         return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1933       if (I.getOpcode() == Instruction::SetLE)       // A <= MAX-1 -> A != MAX
1934         return BinaryOperator::createSetNE(Op0, AddOne(CI));
1935     }
1936
1937     // If we still have a setle or setge instruction, turn it into the
1938     // appropriate setlt or setgt instruction.  Since the border cases have
1939     // already been handled above, this requires little checking.
1940     //
1941     if (I.getOpcode() == Instruction::SetLE)
1942       return BinaryOperator::createSetLT(Op0, AddOne(CI));
1943     if (I.getOpcode() == Instruction::SetGE)
1944       return BinaryOperator::createSetGT(Op0, SubOne(CI));
1945
1946     if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1947       switch (LHSI->getOpcode()) {
1948       case Instruction::PHI:
1949         if (Instruction *NV = FoldOpIntoPhi(I))
1950           return NV;
1951         break;
1952       case Instruction::And:
1953         if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1954             LHSI->getOperand(0)->hasOneUse()) {
1955           // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1956           // could exist), turn it into (X & (C2 << C1)) != (C3 << C1).  This
1957           // happens a LOT in code produced by the C front-end, for bitfield
1958           // access.
1959           ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1960           ConstantUInt *ShAmt;
1961           ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1962           ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1963           const Type *Ty = LHSI->getType();
1964           
1965           // We can fold this as long as we can't shift unknown bits
1966           // into the mask.  This can only happen with signed shift
1967           // rights, as they sign-extend.
1968           if (ShAmt) {
1969             bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1970                            Shift->getType()->isUnsigned();
1971             if (!CanFold) {
1972               // To test for the bad case of the signed shr, see if any
1973               // of the bits shifted in could be tested after the mask.
1974               Constant *OShAmt = ConstantUInt::get(Type::UByteTy, 
1975                                    Ty->getPrimitiveSize()*8-ShAmt->getValue());
1976               Constant *ShVal = 
1977                 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1978               if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1979                 CanFold = true;
1980             }
1981             
1982             if (CanFold) {
1983               Constant *NewCst;
1984               if (Shift->getOpcode() == Instruction::Shl)
1985                 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1986               else
1987                 NewCst = ConstantExpr::getShl(CI, ShAmt);
1988
1989               // Check to see if we are shifting out any of the bits being
1990               // compared.
1991               if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1992                 // If we shifted bits out, the fold is not going to work out.
1993                 // As a special case, check to see if this means that the
1994                 // result is always true or false now.
1995                 if (I.getOpcode() == Instruction::SetEQ)
1996                   return ReplaceInstUsesWith(I, ConstantBool::False);
1997                 if (I.getOpcode() == Instruction::SetNE)
1998                   return ReplaceInstUsesWith(I, ConstantBool::True);
1999               } else {
2000                 I.setOperand(1, NewCst);
2001                 Constant *NewAndCST;
2002                 if (Shift->getOpcode() == Instruction::Shl)
2003                   NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2004                 else
2005                   NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2006                 LHSI->setOperand(1, NewAndCST);
2007                 LHSI->setOperand(0, Shift->getOperand(0));
2008                 WorkList.push_back(Shift); // Shift is dead.
2009                 AddUsesToWorkList(I);
2010                 return &I;
2011               }
2012             }
2013           }
2014         }
2015         break;
2016
2017       case Instruction::Cast: {       // (setcc (cast X to larger), CI)
2018         const Type *SrcTy = LHSI->getOperand(0)->getType();
2019         if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
2020           unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2021           if (SrcTy == Type::BoolTy) SrcBits = 1;
2022           unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
2023           if (LHSI->getType() == Type::BoolTy) DestBits = 1;
2024           if (SrcBits < DestBits) {
2025             // Check to see if the comparison is always true or false.
2026             Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2027             if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
2028               Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2029               Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2030               Min = ConstantExpr::getCast(Min, LHSI->getType());
2031               Max = ConstantExpr::getCast(Max, LHSI->getType());
2032               switch (I.getOpcode()) {
2033               default: assert(0 && "unknown integer comparison");
2034               case Instruction::SetEQ:
2035                 return ReplaceInstUsesWith(I, ConstantBool::False);
2036               case Instruction::SetNE:
2037                 return ReplaceInstUsesWith(I, ConstantBool::True);
2038               case Instruction::SetLT:
2039                 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2040               case Instruction::SetGT:
2041                 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2042               }
2043             }
2044
2045             return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2046                                    ConstantExpr::getCast(CI, SrcTy));
2047           }
2048         }
2049         break;
2050       }
2051       case Instruction::Shl:         // (setcc (shl X, ShAmt), CI)
2052         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2053           switch (I.getOpcode()) {
2054           default: break;
2055           case Instruction::SetEQ:
2056           case Instruction::SetNE: {
2057             // If we are comparing against bits always shifted out, the
2058             // comparison cannot succeed.
2059             Constant *Comp = 
2060               ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2061             if (Comp != CI) {// Comparing against a bit that we know is zero.
2062               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2063               Constant *Cst = ConstantBool::get(IsSetNE);
2064               return ReplaceInstUsesWith(I, Cst);
2065             }
2066
2067             if (LHSI->hasOneUse()) {
2068               // Otherwise strength reduce the shift into an and.
2069               unsigned ShAmtVal = ShAmt->getValue();
2070               unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2071               uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2072
2073               Constant *Mask;
2074               if (CI->getType()->isUnsigned()) {
2075                 Mask = ConstantUInt::get(CI->getType(), Val);
2076               } else if (ShAmtVal != 0) {
2077                 Mask = ConstantSInt::get(CI->getType(), Val);
2078               } else {
2079                 Mask = ConstantInt::getAllOnesValue(CI->getType());
2080               }
2081               
2082               Instruction *AndI =
2083                 BinaryOperator::createAnd(LHSI->getOperand(0),
2084                                           Mask, LHSI->getName()+".mask");
2085               Value *And = InsertNewInstBefore(AndI, I);
2086               return new SetCondInst(I.getOpcode(), And,
2087                                      ConstantExpr::getUShr(CI, ShAmt));
2088             }
2089           }
2090           }
2091         }
2092         break;
2093
2094       case Instruction::Shr:         // (setcc (shr X, ShAmt), CI)
2095         if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2096           switch (I.getOpcode()) {
2097           default: break;
2098           case Instruction::SetEQ:
2099           case Instruction::SetNE: {
2100             // If we are comparing against bits always shifted out, the
2101             // comparison cannot succeed.
2102             Constant *Comp = 
2103               ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2104             
2105             if (Comp != CI) {// Comparing against a bit that we know is zero.
2106               bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2107               Constant *Cst = ConstantBool::get(IsSetNE);
2108               return ReplaceInstUsesWith(I, Cst);
2109             }
2110               
2111             if (LHSI->hasOneUse() || CI->isNullValue()) {
2112               unsigned ShAmtVal = ShAmt->getValue();
2113
2114               // Otherwise strength reduce the shift into an and.
2115               uint64_t Val = ~0ULL;          // All ones.
2116               Val <<= ShAmtVal;              // Shift over to the right spot.
2117
2118               Constant *Mask;
2119               if (CI->getType()->isUnsigned()) {
2120                 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2121                 Val &= (1ULL << TypeBits)-1;
2122                 Mask = ConstantUInt::get(CI->getType(), Val);
2123               } else {
2124                 Mask = ConstantSInt::get(CI->getType(), Val);
2125               }
2126               
2127               Instruction *AndI =
2128                 BinaryOperator::createAnd(LHSI->getOperand(0),
2129                                           Mask, LHSI->getName()+".mask");
2130               Value *And = InsertNewInstBefore(AndI, I);
2131               return new SetCondInst(I.getOpcode(), And,
2132                                      ConstantExpr::getShl(CI, ShAmt));
2133             }
2134             break;
2135           }
2136           }
2137         }
2138         break;
2139
2140       case Instruction::Div:
2141         // Fold: (div X, C1) op C2 -> range check
2142         if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2143           // Fold this div into the comparison, producing a range check.
2144           // Determine, based on the divide type, what the range is being
2145           // checked.  If there is an overflow on the low or high side, remember
2146           // it, otherwise compute the range [low, hi) bounding the new value.
2147           bool LoOverflow = false, HiOverflow = 0;
2148           ConstantInt *LoBound = 0, *HiBound = 0;
2149
2150           ConstantInt *Prod;
2151           bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2152
2153           Instruction::BinaryOps Opcode = I.getOpcode();
2154
2155           if (DivRHS->isNullValue()) {  // Don't hack on divide by zeros.
2156           } else if (LHSI->getType()->isUnsigned()) {  // udiv
2157             LoBound = Prod;
2158             LoOverflow = ProdOV;
2159             HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2160           } else if (isPositive(DivRHS)) {             // Divisor is > 0.
2161             if (CI->isNullValue()) {       // (X / pos) op 0
2162               // Can't overflow.
2163               LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2164               HiBound = DivRHS;
2165             } else if (isPositive(CI)) {   // (X / pos) op pos
2166               LoBound = Prod;
2167               LoOverflow = ProdOV;
2168               HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2169             } else {                       // (X / pos) op neg
2170               Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2171               LoOverflow = AddWithOverflow(LoBound, Prod,
2172                                            cast<ConstantInt>(DivRHSH));
2173               HiBound = Prod;
2174               HiOverflow = ProdOV;
2175             }
2176           } else {                                     // Divisor is < 0.
2177             if (CI->isNullValue()) {       // (X / neg) op 0
2178               LoBound = AddOne(DivRHS);
2179               HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2180             } else if (isPositive(CI)) {   // (X / neg) op pos
2181               HiOverflow = LoOverflow = ProdOV;
2182               if (!LoOverflow)
2183                 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2184               HiBound = AddOne(Prod);
2185             } else {                       // (X / neg) op neg
2186               LoBound = Prod;
2187               LoOverflow = HiOverflow = ProdOV;
2188               HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2189             }
2190
2191             // Dividing by a negate swaps the condition.
2192             Opcode = SetCondInst::getSwappedCondition(Opcode);
2193           }
2194
2195           if (LoBound) {
2196             Value *X = LHSI->getOperand(0);
2197             switch (Opcode) {
2198             default: assert(0 && "Unhandled setcc opcode!");
2199             case Instruction::SetEQ:
2200               if (LoOverflow && HiOverflow)
2201                 return ReplaceInstUsesWith(I, ConstantBool::False);
2202               else if (HiOverflow)
2203                 return new SetCondInst(Instruction::SetGE, X, LoBound);
2204               else if (LoOverflow)
2205                 return new SetCondInst(Instruction::SetLT, X, HiBound);
2206               else
2207                 return InsertRangeTest(X, LoBound, HiBound, true, I);
2208             case Instruction::SetNE:
2209               if (LoOverflow && HiOverflow)
2210                 return ReplaceInstUsesWith(I, ConstantBool::True);
2211               else if (HiOverflow)
2212                 return new SetCondInst(Instruction::SetLT, X, LoBound);
2213               else if (LoOverflow)
2214                 return new SetCondInst(Instruction::SetGE, X, HiBound);
2215               else
2216                 return InsertRangeTest(X, LoBound, HiBound, false, I);
2217             case Instruction::SetLT:
2218               if (LoOverflow)
2219                 return ReplaceInstUsesWith(I, ConstantBool::False);
2220               return new SetCondInst(Instruction::SetLT, X, LoBound);
2221             case Instruction::SetGT:
2222               if (HiOverflow)
2223                 return ReplaceInstUsesWith(I, ConstantBool::False);
2224               return new SetCondInst(Instruction::SetGE, X, HiBound);
2225             }
2226           }
2227         }
2228         break;
2229       case Instruction::Select:
2230         // If either operand of the select is a constant, we can fold the
2231         // comparison into the select arms, which will cause one to be
2232         // constant folded and the select turned into a bitwise or.
2233         Value *Op1 = 0, *Op2 = 0;
2234         if (LHSI->hasOneUse()) {
2235           if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2236             // Fold the known value into the constant operand.
2237             Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2238             // Insert a new SetCC of the other select operand.
2239             Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2240                                                       LHSI->getOperand(2), CI,
2241                                                       I.getName()), I);
2242           } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2243             // Fold the known value into the constant operand.
2244             Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2245             // Insert a new SetCC of the other select operand.
2246             Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2247                                                       LHSI->getOperand(1), CI,
2248                                                       I.getName()), I);
2249           }
2250         }
2251         
2252         if (Op1)
2253           return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2254         break;
2255       }
2256     
2257     // Simplify seteq and setne instructions...
2258     if (I.getOpcode() == Instruction::SetEQ ||
2259         I.getOpcode() == Instruction::SetNE) {
2260       bool isSetNE = I.getOpcode() == Instruction::SetNE;
2261
2262       // If the first operand is (and|or|xor) with a constant, and the second
2263       // operand is a constant, simplify a bit.
2264       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2265         switch (BO->getOpcode()) {
2266         case Instruction::Rem:
2267           // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2268           if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2269               BO->hasOneUse() &&
2270               cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2271             if (unsigned L2 =
2272                 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2273               const Type *UTy = BO->getType()->getUnsignedVersion();
2274               Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2275                                                              UTy, "tmp"), I);
2276               Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2277               Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2278                                                     RHSCst, BO->getName()), I);
2279               return BinaryOperator::create(I.getOpcode(), NewRem,
2280                                             Constant::getNullValue(UTy));
2281             }
2282           break;          
2283
2284         case Instruction::Add:
2285           // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2286           if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2287             if (BO->hasOneUse())
2288               return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2289                                      ConstantExpr::getSub(CI, BOp1C));
2290           } else if (CI->isNullValue()) {
2291             // Replace ((add A, B) != 0) with (A != -B) if A or B is
2292             // efficiently invertible, or if the add has just this one use.
2293             Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2294             
2295             if (Value *NegVal = dyn_castNegVal(BOp1))
2296               return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2297             else if (Value *NegVal = dyn_castNegVal(BOp0))
2298               return new SetCondInst(I.getOpcode(), NegVal, BOp1);
2299             else if (BO->hasOneUse()) {
2300               Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2301               BO->setName("");
2302               InsertNewInstBefore(Neg, I);
2303               return new SetCondInst(I.getOpcode(), BOp0, Neg);
2304             }
2305           }
2306           break;
2307         case Instruction::Xor:
2308           // For the xor case, we can xor two constants together, eliminating
2309           // the explicit xor.
2310           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2311             return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
2312                                   ConstantExpr::getXor(CI, BOC));
2313
2314           // FALLTHROUGH
2315         case Instruction::Sub:
2316           // Replace (([sub|xor] A, B) != 0) with (A != B)
2317           if (CI->isNullValue())
2318             return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2319                                    BO->getOperand(1));
2320           break;
2321
2322         case Instruction::Or:
2323           // If bits are being or'd in that are not present in the constant we
2324           // are comparing against, then the comparison could never succeed!
2325           if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2326             Constant *NotCI = ConstantExpr::getNot(CI);
2327             if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2328               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2329           }
2330           break;
2331
2332         case Instruction::And:
2333           if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2334             // If bits are being compared against that are and'd out, then the
2335             // comparison can never succeed!
2336             if (!ConstantExpr::getAnd(CI,
2337                                       ConstantExpr::getNot(BOC))->isNullValue())
2338               return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2339
2340             // If we have ((X & C) == C), turn it into ((X & C) != 0).
2341             if (CI == BOC && isOneBitSet(CI))
2342               return new SetCondInst(isSetNE ? Instruction::SetEQ :
2343                                      Instruction::SetNE, Op0,
2344                                      Constant::getNullValue(CI->getType()));
2345
2346             // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2347             // to be a signed value as appropriate.
2348             if (isSignBit(BOC)) {
2349               Value *X = BO->getOperand(0);
2350               // If 'X' is not signed, insert a cast now...
2351               if (!BOC->getType()->isSigned()) {
2352                 const Type *DestTy = BOC->getType()->getSignedVersion();
2353                 X = InsertCastBefore(X, DestTy, I);
2354               }
2355               return new SetCondInst(isSetNE ? Instruction::SetLT :
2356                                          Instruction::SetGE, X,
2357                                      Constant::getNullValue(X->getType()));
2358             }
2359             
2360             // ((X & ~7) == 0) --> X < 8
2361             if (CI->isNullValue() && isHighOnes(BOC)) {
2362               Value *X = BO->getOperand(0);
2363               Constant *NegX = ConstantExpr::getNeg(BOC);
2364
2365               // If 'X' is signed, insert a cast now.
2366               if (NegX->getType()->isSigned()) {
2367                 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2368                 X = InsertCastBefore(X, DestTy, I);
2369                 NegX = ConstantExpr::getCast(NegX, DestTy);
2370               }
2371
2372               return new SetCondInst(isSetNE ? Instruction::SetGE :
2373                                      Instruction::SetLT, X, NegX);
2374             }
2375
2376           }
2377         default: break;
2378         }
2379       }
2380     } else {  // Not a SetEQ/SetNE
2381       // If the LHS is a cast from an integral value of the same size, 
2382       if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2383         Value *CastOp = Cast->getOperand(0);
2384         const Type *SrcTy = CastOp->getType();
2385         unsigned SrcTySize = SrcTy->getPrimitiveSize();
2386         if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2387             SrcTySize == Cast->getType()->getPrimitiveSize()) {
2388           assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) && 
2389                  "Source and destination signednesses should differ!");
2390           if (Cast->getType()->isSigned()) {
2391             // If this is a signed comparison, check for comparisons in the
2392             // vicinity of zero.
2393             if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2394               // X < 0  => x > 127
2395               return BinaryOperator::createSetGT(CastOp,
2396                          ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2397             else if (I.getOpcode() == Instruction::SetGT &&
2398                      cast<ConstantSInt>(CI)->getValue() == -1)
2399               // X > -1  => x < 128
2400               return BinaryOperator::createSetLT(CastOp,
2401                          ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2402           } else {
2403             ConstantUInt *CUI = cast<ConstantUInt>(CI);
2404             if (I.getOpcode() == Instruction::SetLT &&
2405                 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2406               // X < 128 => X > -1
2407               return BinaryOperator::createSetGT(CastOp,
2408                                                  ConstantSInt::get(SrcTy, -1));
2409             else if (I.getOpcode() == Instruction::SetGT &&
2410                      CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2411               // X > 127 => X < 0
2412               return BinaryOperator::createSetLT(CastOp,
2413                                                  Constant::getNullValue(SrcTy));
2414           }
2415         }
2416       }
2417     }
2418   }
2419
2420   // Test to see if the operands of the setcc are casted versions of other
2421   // values.  If the cast can be stripped off both arguments, we do so now.
2422   if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2423     Value *CastOp0 = CI->getOperand(0);
2424     if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
2425         (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
2426         (I.getOpcode() == Instruction::SetEQ ||
2427          I.getOpcode() == Instruction::SetNE)) {
2428       // We keep moving the cast from the left operand over to the right
2429       // operand, where it can often be eliminated completely.
2430       Op0 = CastOp0;
2431       
2432       // If operand #1 is a cast instruction, see if we can eliminate it as
2433       // well.
2434       if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2435         if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
2436                                                                Op0->getType()))
2437           Op1 = CI2->getOperand(0);
2438       
2439       // If Op1 is a constant, we can fold the cast into the constant.
2440       if (Op1->getType() != Op0->getType())
2441         if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2442           Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2443         } else {
2444           // Otherwise, cast the RHS right before the setcc
2445           Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2446           InsertNewInstBefore(cast<Instruction>(Op1), I);
2447         }
2448       return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2449     }
2450
2451     // Handle the special case of: setcc (cast bool to X), <cst>
2452     // This comes up when you have code like
2453     //   int X = A < B;
2454     //   if (X) ...
2455     // For generality, we handle any zero-extension of any operand comparison
2456     // with a constant.
2457     if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2458       const Type *SrcTy = CastOp0->getType();
2459       const Type *DestTy = Op0->getType();
2460       if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2461           (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2462         // Ok, we have an expansion of operand 0 into a new type.  Get the
2463         // constant value, masink off bits which are not set in the RHS.  These
2464         // could be set if the destination value is signed.
2465         uint64_t ConstVal = ConstantRHS->getRawValue();
2466         ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2467
2468         // If the constant we are comparing it with has high bits set, which
2469         // don't exist in the original value, the values could never be equal,
2470         // because the source would be zero extended.
2471         unsigned SrcBits =
2472           SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
2473         bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2474         if (ConstVal & ~((1ULL << SrcBits)-1)) {
2475           switch (I.getOpcode()) {
2476           default: assert(0 && "Unknown comparison type!");
2477           case Instruction::SetEQ:
2478             return ReplaceInstUsesWith(I, ConstantBool::False);
2479           case Instruction::SetNE:
2480             return ReplaceInstUsesWith(I, ConstantBool::True);
2481           case Instruction::SetLT:
2482           case Instruction::SetLE:
2483             if (DestTy->isSigned() && HasSignBit)
2484               return ReplaceInstUsesWith(I, ConstantBool::False);
2485             return ReplaceInstUsesWith(I, ConstantBool::True);
2486           case Instruction::SetGT:
2487           case Instruction::SetGE:
2488             if (DestTy->isSigned() && HasSignBit)
2489               return ReplaceInstUsesWith(I, ConstantBool::True);
2490             return ReplaceInstUsesWith(I, ConstantBool::False);
2491           }
2492         }
2493         
2494         // Otherwise, we can replace the setcc with a setcc of the smaller
2495         // operand value.
2496         Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2497         return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2498       }
2499     }
2500   }
2501   return Changed ? &I : 0;
2502 }
2503
2504
2505
2506 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
2507   assert(I.getOperand(1)->getType() == Type::UByteTy);
2508   Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2509   bool isLeftShift = I.getOpcode() == Instruction::Shl;
2510
2511   // shl X, 0 == X and shr X, 0 == X
2512   // shl 0, X == 0 and shr 0, X == 0
2513   if (Op1 == Constant::getNullValue(Type::UByteTy) ||
2514       Op0 == Constant::getNullValue(Op0->getType()))
2515     return ReplaceInstUsesWith(I, Op0);
2516
2517   if (isa<UndefValue>(Op0)) {            // undef >>s X -> undef
2518     if (!isLeftShift && I.getType()->isSigned())
2519       return ReplaceInstUsesWith(I, Op1);
2520     else                         // undef << X -> 0   AND  undef >>u X -> 0
2521       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2522   }
2523   if (isa<UndefValue>(Op1)) {
2524     if (isLeftShift || I.getType()->isUnsigned())
2525       return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2526     else
2527       return ReplaceInstUsesWith(I, Op0);          // X >>s undef -> X
2528   }
2529
2530   // shr int -1, X = -1   (for any arithmetic shift rights of ~0)
2531   if (!isLeftShift)
2532     if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2533       if (CSI->isAllOnesValue())
2534         return ReplaceInstUsesWith(I, CSI);
2535
2536   // Try to fold constant and into select arguments.
2537   if (isa<Constant>(Op0))
2538     if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2539       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2540         return R;
2541
2542   if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
2543     // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2544     // of a signed value.
2545     //
2546     unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
2547     if (CUI->getValue() >= TypeBits) {
2548       if (!Op0->getType()->isSigned() || isLeftShift)
2549         return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2550       else {
2551         I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2552         return &I;
2553       }
2554     }
2555
2556     // ((X*C1) << C2) == (X * (C1 << C2))
2557     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2558       if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2559         if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
2560           return BinaryOperator::createMul(BO->getOperand(0),
2561                                            ConstantExpr::getShl(BOOp, CUI));
2562     
2563     // Try to fold constant and into select arguments.
2564     if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2565       if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2566         return R;
2567     if (isa<PHINode>(Op0))
2568       if (Instruction *NV = FoldOpIntoPhi(I))
2569         return NV;
2570
2571     // If the operand is an bitwise operator with a constant RHS, and the
2572     // shift is the only use, we can pull it out of the shift.
2573     if (Op0->hasOneUse())
2574       if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2575         if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2576           bool isValid = true;     // Valid only for And, Or, Xor
2577           bool highBitSet = false; // Transform if high bit of constant set?
2578
2579           switch (Op0BO->getOpcode()) {
2580           default: isValid = false; break;   // Do not perform transform!
2581           case Instruction::Add:
2582             isValid = isLeftShift;
2583             break;
2584           case Instruction::Or:
2585           case Instruction::Xor:
2586             highBitSet = false;
2587             break;
2588           case Instruction::And:
2589             highBitSet = true;
2590             break;
2591           }
2592
2593           // If this is a signed shift right, and the high bit is modified
2594           // by the logical operation, do not perform the transformation.
2595           // The highBitSet boolean indicates the value of the high bit of
2596           // the constant which would cause it to be modified for this
2597           // operation.
2598           //
2599           if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2600             uint64_t Val = Op0C->getRawValue();
2601             isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2602           }
2603
2604           if (isValid) {
2605             Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
2606
2607             Instruction *NewShift =
2608               new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2609                             Op0BO->getName());
2610             Op0BO->setName("");
2611             InsertNewInstBefore(NewShift, I);
2612
2613             return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2614                                           NewRHS);
2615           }
2616         }
2617
2618     // If this is a shift of a shift, see if we can fold the two together...
2619     if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
2620       if (ConstantUInt *ShiftAmt1C =
2621                                  dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
2622         unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2623         unsigned ShiftAmt2 = CUI->getValue();
2624         
2625         // Check for (A << c1) << c2   and   (A >> c1) >> c2
2626         if (I.getOpcode() == Op0SI->getOpcode()) {
2627           unsigned Amt = ShiftAmt1+ShiftAmt2;   // Fold into one big shift...
2628           if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2629             Amt = Op0->getType()->getPrimitiveSize()*8;
2630           return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2631                                ConstantUInt::get(Type::UByteTy, Amt));
2632         }
2633         
2634         // Check for (A << c1) >> c2 or visaversa.  If we are dealing with
2635         // signed types, we can only support the (A >> c1) << c2 configuration,
2636         // because it can not turn an arbitrary bit of A into a sign bit.
2637         if (I.getType()->isUnsigned() || isLeftShift) {
2638           // Calculate bitmask for what gets shifted off the edge...
2639           Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
2640           if (isLeftShift)
2641             C = ConstantExpr::getShl(C, ShiftAmt1C);
2642           else
2643             C = ConstantExpr::getShr(C, ShiftAmt1C);
2644           
2645           Instruction *Mask =
2646             BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2647                                       Op0SI->getOperand(0)->getName()+".mask");
2648           InsertNewInstBefore(Mask, I);
2649           
2650           // Figure out what flavor of shift we should use...
2651           if (ShiftAmt1 == ShiftAmt2)
2652             return ReplaceInstUsesWith(I, Mask);  // (A << c) >> c  === A & c2
2653           else if (ShiftAmt1 < ShiftAmt2) {
2654             return new ShiftInst(I.getOpcode(), Mask,
2655                          ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2656           } else {
2657             return new ShiftInst(Op0SI->getOpcode(), Mask,
2658                          ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2659           }
2660         }
2661       }
2662   }
2663
2664   return 0;
2665 }
2666
2667 enum CastType {
2668   Noop     = 0,
2669   Truncate = 1,
2670   Signext  = 2,
2671   Zeroext  = 3
2672 };
2673
2674 /// getCastType - In the future, we will split the cast instruction into these
2675 /// various types.  Until then, we have to do the analysis here.
2676 static CastType getCastType(const Type *Src, const Type *Dest) {
2677   assert(Src->isIntegral() && Dest->isIntegral() &&
2678          "Only works on integral types!");
2679   unsigned SrcSize = Src->getPrimitiveSize()*8;
2680   if (Src == Type::BoolTy) SrcSize = 1;
2681   unsigned DestSize = Dest->getPrimitiveSize()*8;
2682   if (Dest == Type::BoolTy) DestSize = 1;
2683
2684   if (SrcSize == DestSize) return Noop;
2685   if (SrcSize > DestSize)  return Truncate;
2686   if (Src->isSigned()) return Signext;
2687   return Zeroext;
2688 }
2689
2690
2691 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2692 // instruction.
2693 //
2694 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
2695                                           const Type *DstTy, TargetData *TD) {
2696
2697   // It is legal to eliminate the instruction if casting A->B->A if the sizes
2698   // are identical and the bits don't get reinterpreted (for example 
2699   // int->float->int would not be allowed).
2700   if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
2701     return true;
2702
2703   // If we are casting between pointer and integer types, treat pointers as
2704   // integers of the appropriate size for the code below.
2705   if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2706   if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2707   if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
2708
2709   // Allow free casting and conversion of sizes as long as the sign doesn't
2710   // change...
2711   if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
2712     CastType FirstCast = getCastType(SrcTy, MidTy);
2713     CastType SecondCast = getCastType(MidTy, DstTy);
2714
2715     // Capture the effect of these two casts.  If the result is a legal cast,
2716     // the CastType is stored here, otherwise a special code is used.
2717     static const unsigned CastResult[] = {
2718       // First cast is noop
2719       0, 1, 2, 3,
2720       // First cast is a truncate
2721       1, 1, 4, 4,         // trunc->extend is not safe to eliminate
2722       // First cast is a sign ext
2723       2, 5, 2, 4,         // signext->zeroext never ok
2724       // First cast is a zero ext
2725       3, 5, 3, 3,
2726     };
2727
2728     unsigned Result = CastResult[FirstCast*4+SecondCast];
2729     switch (Result) {
2730     default: assert(0 && "Illegal table value!");
2731     case 0:
2732     case 1:
2733     case 2:
2734     case 3:
2735       // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2736       // truncates, we could eliminate more casts.
2737       return (unsigned)getCastType(SrcTy, DstTy) == Result;
2738     case 4:
2739       return false;  // Not possible to eliminate this here.
2740     case 5:
2741       // Sign or zero extend followed by truncate is always ok if the result
2742       // is a truncate or noop.
2743       CastType ResultCast = getCastType(SrcTy, DstTy);
2744       if (ResultCast == Noop || ResultCast == Truncate)
2745         return true;
2746       // Otherwise we are still growing the value, we are only safe if the 
2747       // result will match the sign/zeroextendness of the result.
2748       return ResultCast == FirstCast;
2749     }
2750   }
2751   return false;
2752 }
2753
2754 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
2755   if (V->getType() == Ty || isa<Constant>(V)) return false;
2756   if (const CastInst *CI = dyn_cast<CastInst>(V))
2757     if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2758                                TD))
2759       return false;
2760   return true;
2761 }
2762
2763 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2764 /// InsertBefore instruction.  This is specialized a bit to avoid inserting
2765 /// casts that are known to not do anything...
2766 ///
2767 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2768                                              Instruction *InsertBefore) {
2769   if (V->getType() == DestTy) return V;
2770   if (Constant *C = dyn_cast<Constant>(V))
2771     return ConstantExpr::getCast(C, DestTy);
2772
2773   CastInst *CI = new CastInst(V, DestTy, V->getName());
2774   InsertNewInstBefore(CI, *InsertBefore);
2775   return CI;
2776 }
2777
2778 // CastInst simplification
2779 //
2780 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
2781   Value *Src = CI.getOperand(0);
2782
2783   // If the user is casting a value to the same type, eliminate this cast
2784   // instruction...
2785   if (CI.getType() == Src->getType())
2786     return ReplaceInstUsesWith(CI, Src);
2787
2788   if (isa<UndefValue>(Src))   // cast undef -> undef
2789     return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2790
2791   // If casting the result of another cast instruction, try to eliminate this
2792   // one!
2793   //
2794   if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
2795     if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2796                                CSrc->getType(), CI.getType(), TD)) {
2797       // This instruction now refers directly to the cast's src operand.  This
2798       // has a good chance of making CSrc dead.
2799       CI.setOperand(0, CSrc->getOperand(0));
2800       return &CI;
2801     }
2802
2803     // If this is an A->B->A cast, and we are dealing with integral types, try
2804     // to convert this into a logical 'and' instruction.
2805     //
2806     if (CSrc->getOperand(0)->getType() == CI.getType() &&
2807         CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
2808         CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2809         CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2810       assert(CSrc->getType() != Type::ULongTy &&
2811              "Cannot have type bigger than ulong!");
2812       uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
2813       Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
2814       return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
2815     }
2816   }
2817
2818   // If this is a cast to bool, turn it into the appropriate setne instruction.
2819   if (CI.getType() == Type::BoolTy)
2820     return BinaryOperator::createSetNE(CI.getOperand(0),
2821                        Constant::getNullValue(CI.getOperand(0)->getType()));
2822
2823   // If casting the result of a getelementptr instruction with no offset, turn
2824   // this into a cast of the original pointer!
2825   //
2826   if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2827     bool AllZeroOperands = true;
2828     for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2829       if (!isa<Constant>(GEP->getOperand(i)) ||
2830           !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2831         AllZeroOperands = false;
2832         break;
2833       }
2834     if (AllZeroOperands) {
2835       CI.setOperand(0, GEP->getOperand(0));
2836       return &CI;
2837     }
2838   }
2839
2840   // If we are casting a malloc or alloca to a pointer to a type of the same
2841   // size, rewrite the allocation instruction to allocate the "right" type.
2842   //
2843   if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
2844     if (AI->hasOneUse() && !AI->isArrayAllocation())
2845       if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2846         // Get the type really allocated and the type casted to...
2847         const Type *AllocElTy = AI->getAllocatedType();
2848         const Type *CastElTy = PTy->getElementType();
2849         if (AllocElTy->isSized() && CastElTy->isSized()) {
2850           unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2851           unsigned CastElTySize = TD->getTypeSize(CastElTy);
2852
2853           // If the allocation is for an even multiple of the cast type size
2854           if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2855             Value *Amt = ConstantUInt::get(Type::UIntTy, 
2856                                          AllocElTySize/CastElTySize);
2857             std::string Name = AI->getName(); AI->setName("");
2858             AllocationInst *New;
2859             if (isa<MallocInst>(AI))
2860               New = new MallocInst(CastElTy, Amt, Name);
2861             else
2862               New = new AllocaInst(CastElTy, Amt, Name);
2863             InsertNewInstBefore(New, *AI);
2864             return ReplaceInstUsesWith(CI, New);
2865           }
2866         }
2867       }
2868
2869   if (isa<PHINode>(Src))
2870     if (Instruction *NV = FoldOpIntoPhi(CI))
2871       return NV;
2872
2873   // If the source value is an instruction with only this use, we can attempt to
2874   // propagate the cast into the instruction.  Also, only handle integral types
2875   // for now.
2876   if (Instruction *SrcI = dyn_cast<Instruction>(Src))
2877     if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
2878         CI.getType()->isInteger()) {  // Don't mess with casts to bool here
2879       const Type *DestTy = CI.getType();
2880       unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2881       unsigned DestBitSize = getTypeSizeInBits(DestTy);
2882
2883       Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2884       Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2885
2886       switch (SrcI->getOpcode()) {
2887       case Instruction::Add:
2888       case Instruction::Mul:
2889       case Instruction::And:
2890       case Instruction::Or:
2891       case Instruction::Xor:
2892         // If we are discarding information, or just changing the sign, rewrite.
2893         if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2894           // Don't insert two casts if they cannot be eliminated.  We allow two
2895           // casts to be inserted if the sizes are the same.  This could only be
2896           // converting signedness, which is a noop.
2897           if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2898               !ValueRequiresCast(Op0, DestTy, TD)) {
2899             Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2900             Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2901             return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2902                              ->getOpcode(), Op0c, Op1c);
2903           }
2904         }
2905         break;
2906       case Instruction::Shl:
2907         // Allow changing the sign of the source operand.  Do not allow changing
2908         // the size of the shift, UNLESS the shift amount is a constant.  We
2909         // mush not change variable sized shifts to a smaller size, because it
2910         // is undefined to shift more bits out than exist in the value.
2911         if (DestBitSize == SrcBitSize ||
2912             (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2913           Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2914           return new ShiftInst(Instruction::Shl, Op0c, Op1);
2915         }
2916         break;
2917       }
2918     }
2919   
2920   return 0;
2921 }
2922
2923 /// GetSelectFoldableOperands - We want to turn code that looks like this:
2924 ///   %C = or %A, %B
2925 ///   %D = select %cond, %C, %A
2926 /// into:
2927 ///   %C = select %cond, %B, 0
2928 ///   %D = or %A, %C
2929 ///
2930 /// Assuming that the specified instruction is an operand to the select, return
2931 /// a bitmask indicating which operands of this instruction are foldable if they
2932 /// equal the other incoming value of the select.
2933 ///
2934 static unsigned GetSelectFoldableOperands(Instruction *I) {
2935   switch (I->getOpcode()) {
2936   case Instruction::Add:
2937   case Instruction::Mul:
2938   case Instruction::And:
2939   case Instruction::Or:
2940   case Instruction::Xor:
2941     return 3;              // Can fold through either operand.
2942   case Instruction::Sub:   // Can only fold on the amount subtracted.
2943   case Instruction::Shl:   // Can only fold on the shift amount.
2944   case Instruction::Shr:
2945     return 1;           
2946   default:
2947     return 0;              // Cannot fold
2948   }
2949 }
2950
2951 /// GetSelectFoldableConstant - For the same transformation as the previous
2952 /// function, return the identity constant that goes into the select.
2953 static Constant *GetSelectFoldableConstant(Instruction *I) {
2954   switch (I->getOpcode()) {
2955   default: assert(0 && "This cannot happen!"); abort();
2956   case Instruction::Add:
2957   case Instruction::Sub:
2958   case Instruction::Or:
2959   case Instruction::Xor:
2960     return Constant::getNullValue(I->getType());
2961   case Instruction::Shl:
2962   case Instruction::Shr:
2963     return Constant::getNullValue(Type::UByteTy);
2964   case Instruction::And:
2965     return ConstantInt::getAllOnesValue(I->getType());
2966   case Instruction::Mul:
2967     return ConstantInt::get(I->getType(), 1);
2968   }
2969 }
2970
2971 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2972   Value *CondVal = SI.getCondition();
2973   Value *TrueVal = SI.getTrueValue();
2974   Value *FalseVal = SI.getFalseValue();
2975
2976   // select true, X, Y  -> X
2977   // select false, X, Y -> Y
2978   if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
2979     if (C == ConstantBool::True)
2980       return ReplaceInstUsesWith(SI, TrueVal);
2981     else {
2982       assert(C == ConstantBool::False);
2983       return ReplaceInstUsesWith(SI, FalseVal);
2984     }
2985
2986   // select C, X, X -> X
2987   if (TrueVal == FalseVal)
2988     return ReplaceInstUsesWith(SI, TrueVal);
2989
2990   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2991     return ReplaceInstUsesWith(SI, FalseVal);
2992   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2993     return ReplaceInstUsesWith(SI, TrueVal);
2994   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2995     if (isa<Constant>(TrueVal))
2996       return ReplaceInstUsesWith(SI, TrueVal);
2997     else
2998       return ReplaceInstUsesWith(SI, FalseVal);
2999   }
3000
3001   if (SI.getType() == Type::BoolTy)
3002     if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3003       if (C == ConstantBool::True) {
3004         // Change: A = select B, true, C --> A = or B, C
3005         return BinaryOperator::createOr(CondVal, FalseVal);
3006       } else {
3007         // Change: A = select B, false, C --> A = and !B, C
3008         Value *NotCond =
3009           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3010                                              "not."+CondVal->getName()), SI);
3011         return BinaryOperator::createAnd(NotCond, FalseVal);
3012       }
3013     } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3014       if (C == ConstantBool::False) {
3015         // Change: A = select B, C, false --> A = and B, C
3016         return BinaryOperator::createAnd(CondVal, TrueVal);
3017       } else {
3018         // Change: A = select B, C, true --> A = or !B, C
3019         Value *NotCond =
3020           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3021                                              "not."+CondVal->getName()), SI);
3022         return BinaryOperator::createOr(NotCond, TrueVal);
3023       }
3024     }
3025
3026   // Selecting between two integer constants?
3027   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3028     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3029       // select C, 1, 0 -> cast C to int
3030       if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3031         return new CastInst(CondVal, SI.getType());
3032       } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3033         // select C, 0, 1 -> cast !C to int
3034         Value *NotCond =
3035           InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3036                                                "not."+CondVal->getName()), SI);
3037         return new CastInst(NotCond, SI.getType());
3038       }
3039
3040       // If one of the constants is zero (we know they can't both be) and we
3041       // have a setcc instruction with zero, and we have an 'and' with the
3042       // non-constant value, eliminate this whole mess.  This corresponds to
3043       // cases like this: ((X & 27) ? 27 : 0)
3044       if (TrueValC->isNullValue() || FalseValC->isNullValue())
3045         if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3046           if ((IC->getOpcode() == Instruction::SetEQ ||
3047                IC->getOpcode() == Instruction::SetNE) &&
3048               isa<ConstantInt>(IC->getOperand(1)) &&
3049               cast<Constant>(IC->getOperand(1))->isNullValue())
3050             if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3051               if (ICA->getOpcode() == Instruction::And &&
3052                   isa<ConstantInt>(ICA->getOperand(1)) && 
3053                   (ICA->getOperand(1) == TrueValC || 
3054                    ICA->getOperand(1) == FalseValC) && 
3055                   isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3056                 // Okay, now we know that everything is set up, we just don't
3057                 // know whether we have a setne or seteq and whether the true or
3058                 // false val is the zero.
3059                 bool ShouldNotVal = !TrueValC->isNullValue();
3060                 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3061                 Value *V = ICA;
3062                 if (ShouldNotVal)
3063                   V = InsertNewInstBefore(BinaryOperator::create(
3064                                   Instruction::Xor, V, ICA->getOperand(1)), SI);
3065                 return ReplaceInstUsesWith(SI, V);
3066               }
3067     }
3068
3069   // See if we are selecting two values based on a comparison of the two values.
3070   if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3071     if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3072       // Transform (X == Y) ? X : Y  -> Y
3073       if (SCI->getOpcode() == Instruction::SetEQ)
3074         return ReplaceInstUsesWith(SI, FalseVal);
3075       // Transform (X != Y) ? X : Y  -> X
3076       if (SCI->getOpcode() == Instruction::SetNE)
3077         return ReplaceInstUsesWith(SI, TrueVal);
3078       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3079
3080     } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3081       // Transform (X == Y) ? Y : X  -> X
3082       if (SCI->getOpcode() == Instruction::SetEQ)
3083         return ReplaceInstUsesWith(SI, FalseVal);
3084       // Transform (X != Y) ? Y : X  -> Y
3085       if (SCI->getOpcode() == Instruction::SetNE)
3086         return ReplaceInstUsesWith(SI, TrueVal);
3087       // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3088     }
3089   }
3090   
3091   // See if we can fold the select into one of our operands.
3092   if (SI.getType()->isInteger()) {
3093     // See the comment above GetSelectFoldableOperands for a description of the
3094     // transformation we are doing here.
3095     if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3096       if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3097           !isa<Constant>(FalseVal))
3098         if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3099           unsigned OpToFold = 0;
3100           if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3101             OpToFold = 1;
3102           } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3103             OpToFold = 2;
3104           }
3105
3106           if (OpToFold) {
3107             Constant *C = GetSelectFoldableConstant(TVI);
3108             std::string Name = TVI->getName(); TVI->setName("");
3109             Instruction *NewSel =
3110               new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3111                              Name);
3112             InsertNewInstBefore(NewSel, SI);
3113             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3114               return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3115             else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3116               return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3117             else {
3118               assert(0 && "Unknown instruction!!");
3119             }
3120           }
3121         }
3122
3123     if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3124       if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3125           !isa<Constant>(TrueVal))
3126         if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3127           unsigned OpToFold = 0;
3128           if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3129             OpToFold = 1;
3130           } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3131             OpToFold = 2;
3132           }
3133
3134           if (OpToFold) {
3135             Constant *C = GetSelectFoldableConstant(FVI);
3136             std::string Name = FVI->getName(); FVI->setName("");
3137             Instruction *NewSel =
3138               new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3139                              Name);
3140             InsertNewInstBefore(NewSel, SI);
3141             if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3142               return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3143             else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3144               return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3145             else {
3146               assert(0 && "Unknown instruction!!");
3147             }
3148           }
3149         }
3150   }
3151   return 0;
3152 }
3153
3154
3155 // CallInst simplification
3156 //
3157 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
3158   // Intrinsics cannot occur in an invoke, so handle them here instead of in
3159   // visitCallSite.
3160   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3161     bool Changed = false;
3162
3163     // memmove/cpy/set of zero bytes is a noop.
3164     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3165       if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3166
3167       // FIXME: Increase alignment here.
3168       
3169       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3170         if (CI->getRawValue() == 1) {
3171           // Replace the instruction with just byte operations.  We would
3172           // transform other cases to loads/stores, but we don't know if
3173           // alignment is sufficient.
3174         }
3175     }
3176
3177     // If we have a memmove and the source operation is a constant global,
3178     // then the source and dest pointers can't alias, so we can change this
3179     // into a call to memcpy.
3180     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3181       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3182         if (GVSrc->isConstant()) {
3183           Module *M = CI.getParent()->getParent()->getParent();
3184           Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3185                                      CI.getCalledFunction()->getFunctionType());
3186           CI.setOperand(0, MemCpy);
3187           Changed = true;
3188         }
3189
3190     if (Changed) return &CI;
3191   }
3192
3193   return visitCallSite(&CI);
3194 }
3195
3196 // InvokeInst simplification
3197 //
3198 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3199   return visitCallSite(&II);
3200 }
3201
3202 // visitCallSite - Improvements for call and invoke instructions.
3203 //
3204 Instruction *InstCombiner::visitCallSite(CallSite CS) {
3205   bool Changed = false;
3206
3207   // If the callee is a constexpr cast of a function, attempt to move the cast
3208   // to the arguments of the call/invoke.
3209   if (transformConstExprCastCall(CS)) return 0;
3210
3211   Value *Callee = CS.getCalledValue();
3212
3213   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee))
3214     // This instruction is not reachable, just remove it.  Eventually, this
3215     // should get turned into an unreachable instruction.
3216     if (!isa<InvokeInst>(CS.getInstruction())) {    // Don't hack the CFG!
3217       if (!CS.getInstruction()->use_empty())
3218         CS.getInstruction()->
3219           replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3220       return EraseInstFromFunction(*CS.getInstruction());
3221     }
3222
3223   const PointerType *PTy = cast<PointerType>(Callee->getType());
3224   const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3225   if (FTy->isVarArg()) {
3226     // See if we can optimize any arguments passed through the varargs area of
3227     // the call.
3228     for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3229            E = CS.arg_end(); I != E; ++I)
3230       if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3231         // If this cast does not effect the value passed through the varargs
3232         // area, we can eliminate the use of the cast.
3233         Value *Op = CI->getOperand(0);
3234         if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3235           *I = Op;
3236           Changed = true;
3237         }
3238       }
3239   }
3240   
3241   return Changed ? CS.getInstruction() : 0;
3242 }
3243
3244 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
3245 // attempt to move the cast to the arguments of the call/invoke.
3246 //
3247 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3248   if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3249   ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
3250   if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
3251     return false;
3252   Function *Callee = cast<Function>(CE->getOperand(0));
3253   Instruction *Caller = CS.getInstruction();
3254
3255   // Okay, this is a cast from a function to a different type.  Unless doing so
3256   // would cause a type conversion of one of our arguments, change this call to
3257   // be a direct call with arguments casted to the appropriate types.
3258   //
3259   const FunctionType *FT = Callee->getFunctionType();
3260   const Type *OldRetTy = Caller->getType();
3261
3262   // Check to see if we are changing the return type...
3263   if (OldRetTy != FT->getReturnType()) {
3264     if (Callee->isExternal() &&
3265         !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3266         !Caller->use_empty())
3267       return false;   // Cannot transform this return value...
3268
3269     // If the callsite is an invoke instruction, and the return value is used by
3270     // a PHI node in a successor, we cannot change the return type of the call
3271     // because there is no place to put the cast instruction (without breaking
3272     // the critical edge).  Bail out in this case.
3273     if (!Caller->use_empty())
3274       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3275         for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3276              UI != E; ++UI)
3277           if (PHINode *PN = dyn_cast<PHINode>(*UI))
3278             if (PN->getParent() == II->getNormalDest() ||
3279                 PN->getParent() == II->getUnwindDest())
3280               return false;
3281   }
3282
3283   unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3284   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3285                                     
3286   CallSite::arg_iterator AI = CS.arg_begin();
3287   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3288     const Type *ParamTy = FT->getParamType(i);
3289     bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3290     if (Callee->isExternal() && !isConvertible) return false;    
3291   }
3292
3293   if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3294       Callee->isExternal())
3295     return false;   // Do not delete arguments unless we have a function body...
3296
3297   // Okay, we decided that this is a safe thing to do: go ahead and start
3298   // inserting cast instructions as necessary...
3299   std::vector<Value*> Args;
3300   Args.reserve(NumActualArgs);
3301
3302   AI = CS.arg_begin();
3303   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3304     const Type *ParamTy = FT->getParamType(i);
3305     if ((*AI)->getType() == ParamTy) {
3306       Args.push_back(*AI);
3307     } else {
3308       Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3309                                          *Caller));
3310     }
3311   }
3312
3313   // If the function takes more arguments than the call was taking, add them
3314   // now...
3315   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3316     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3317
3318   // If we are removing arguments to the function, emit an obnoxious warning...
3319   if (FT->getNumParams() < NumActualArgs)
3320     if (!FT->isVarArg()) {
3321       std::cerr << "WARNING: While resolving call to function '"
3322                 << Callee->getName() << "' arguments were dropped!\n";
3323     } else {
3324       // Add all of the arguments in their promoted form to the arg list...
3325       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3326         const Type *PTy = getPromotedType((*AI)->getType());
3327         if (PTy != (*AI)->getType()) {
3328           // Must promote to pass through va_arg area!
3329           Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3330           InsertNewInstBefore(Cast, *Caller);
3331           Args.push_back(Cast);
3332         } else {
3333           Args.push_back(*AI);
3334         }
3335       }
3336     }
3337
3338   if (FT->getReturnType() == Type::VoidTy)
3339     Caller->setName("");   // Void type should not have a name...
3340
3341   Instruction *NC;
3342   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3343     NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
3344                         Args, Caller->getName(), Caller);
3345   } else {
3346     NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3347   }
3348
3349   // Insert a cast of the return type as necessary...
3350   Value *NV = NC;
3351   if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3352     if (NV->getType() != Type::VoidTy) {
3353       NV = NC = new CastInst(NC, Caller->getType(), "tmp");
3354
3355       // If this is an invoke instruction, we should insert it after the first
3356       // non-phi, instruction in the normal successor block.
3357       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3358         BasicBlock::iterator I = II->getNormalDest()->begin();
3359         while (isa<PHINode>(I)) ++I;
3360         InsertNewInstBefore(NC, *I);
3361       } else {
3362         // Otherwise, it's a call, just insert cast right after the call instr
3363         InsertNewInstBefore(NC, *Caller);
3364       }
3365       AddUsersToWorkList(*Caller);
3366     } else {
3367       NV = Constant::getNullValue(Caller->getType());
3368     }
3369   }
3370
3371   if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3372     Caller->replaceAllUsesWith(NV);
3373   Caller->getParent()->getInstList().erase(Caller);
3374   removeFromWorkList(Caller);
3375   return true;
3376 }
3377
3378
3379
3380 // PHINode simplification
3381 //
3382 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
3383   // FIXME: hasConstantValue should ignore undef values!
3384   if (Value *V = hasConstantValue(&PN))
3385     return ReplaceInstUsesWith(PN, V);
3386
3387   // If the only user of this instruction is a cast instruction, and all of the
3388   // incoming values are constants, change this PHI to merge together the casted
3389   // constants.
3390   if (PN.hasOneUse())
3391     if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3392       if (CI->getType() != PN.getType()) {  // noop casts will be folded
3393         bool AllConstant = true;
3394         for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3395           if (!isa<Constant>(PN.getIncomingValue(i))) {
3396             AllConstant = false;
3397             break;
3398           }
3399         if (AllConstant) {
3400           // Make a new PHI with all casted values.
3401           PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3402           for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3403             Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3404             New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3405                              PN.getIncomingBlock(i));
3406           }
3407
3408           // Update the cast instruction.
3409           CI->setOperand(0, New);
3410           WorkList.push_back(CI);    // revisit the cast instruction to fold.
3411           WorkList.push_back(New);   // Make sure to revisit the new Phi
3412           return &PN;                // PN is now dead!
3413         }
3414       }
3415   return 0;
3416 }
3417
3418 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3419                                       Instruction *InsertPoint,
3420                                       InstCombiner *IC) {
3421   unsigned PS = IC->getTargetData().getPointerSize();
3422   const Type *VTy = V->getType();
3423   Instruction *Cast;
3424   if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3425     // We must insert a cast to ensure we sign-extend.
3426     V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3427                                              V->getName()), *InsertPoint);
3428   return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3429                                  *InsertPoint);
3430 }
3431
3432
3433 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3434   Value *PtrOp = GEP.getOperand(0);
3435   // Is it 'getelementptr %P, long 0'  or 'getelementptr %P'
3436   // If so, eliminate the noop.
3437   if (GEP.getNumOperands() == 1)
3438     return ReplaceInstUsesWith(GEP, PtrOp);
3439
3440   if (isa<UndefValue>(GEP.getOperand(0)))
3441     return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3442
3443   bool HasZeroPointerIndex = false;
3444   if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3445     HasZeroPointerIndex = C->isNullValue();
3446
3447   if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
3448     return ReplaceInstUsesWith(GEP, PtrOp);
3449
3450   // Eliminate unneeded casts for indices.
3451   bool MadeChange = false;
3452   gep_type_iterator GTI = gep_type_begin(GEP);
3453   for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3454     if (isa<SequentialType>(*GTI)) {
3455       if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3456         Value *Src = CI->getOperand(0);
3457         const Type *SrcTy = Src->getType();
3458         const Type *DestTy = CI->getType();
3459         if (Src->getType()->isInteger()) {
3460           if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3461             // We can always eliminate a cast from ulong or long to the other.
3462             // We can always eliminate a cast from uint to int or the other on
3463             // 32-bit pointer platforms.
3464             if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3465               MadeChange = true;
3466               GEP.setOperand(i, Src);
3467             }
3468           } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3469                      SrcTy->getPrimitiveSize() == 4) {
3470             // We can always eliminate a cast from int to [u]long.  We can
3471             // eliminate a cast from uint to [u]long iff the target is a 32-bit
3472             // pointer target.
3473             if (SrcTy->isSigned() || 
3474                 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3475               MadeChange = true;
3476               GEP.setOperand(i, Src);
3477             }
3478           }
3479         }
3480       }
3481       // If we are using a wider index than needed for this platform, shrink it
3482       // to what we need.  If the incoming value needs a cast instruction,
3483       // insert it.  This explicit cast can make subsequent optimizations more
3484       // obvious.
3485       Value *Op = GEP.getOperand(i);
3486       if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
3487         if (Constant *C = dyn_cast<Constant>(Op)) {
3488           GEP.setOperand(i, ConstantExpr::getCast(C,
3489                                      TD->getIntPtrType()->getSignedVersion()));
3490           MadeChange = true;
3491         } else {
3492           Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3493                                                 Op->getName()), GEP);
3494           GEP.setOperand(i, Op);
3495           MadeChange = true;
3496         }
3497
3498       // If this is a constant idx, make sure to canonicalize it to be a signed
3499       // operand, otherwise CSE and other optimizations are pessimized.
3500       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3501         GEP.setOperand(i, ConstantExpr::getCast(CUI,
3502                                           CUI->getType()->getSignedVersion()));
3503         MadeChange = true;
3504       }
3505     }
3506   if (MadeChange) return &GEP;
3507
3508   // Combine Indices - If the source pointer to this getelementptr instruction
3509   // is a getelementptr instruction, combine the indices of the two
3510   // getelementptr instructions into a single instruction.
3511   //
3512   std::vector<Value*> SrcGEPOperands;
3513   if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
3514     SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
3515   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3516     if (CE->getOpcode() == Instruction::GetElementPtr)
3517       SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3518   }
3519
3520   if (!SrcGEPOperands.empty()) {
3521     // Note that if our source is a gep chain itself that we wait for that
3522     // chain to be resolved before we perform this transformation.  This
3523     // avoids us creating a TON of code in some cases.
3524     //
3525     if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3526         cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3527       return 0;   // Wait until our source is folded to completion.
3528
3529     std::vector<Value *> Indices;
3530
3531     // Find out whether the last index in the source GEP is a sequential idx.
3532     bool EndsWithSequential = false;
3533     for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3534            E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
3535       EndsWithSequential = !isa<StructType>(*I);
3536   
3537     // Can we combine the two pointer arithmetics offsets?
3538     if (EndsWithSequential) {
3539       // Replace: gep (gep %P, long B), long A, ...
3540       // With:    T = long A+B; gep %P, T, ...
3541       //
3542       Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
3543       if (SO1 == Constant::getNullValue(SO1->getType())) {
3544         Sum = GO1;
3545       } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3546         Sum = SO1;
3547       } else {
3548         // If they aren't the same type, convert both to an integer of the
3549         // target's pointer size.
3550         if (SO1->getType() != GO1->getType()) {
3551           if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3552             SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3553           } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3554             GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3555           } else {
3556             unsigned PS = TD->getPointerSize();
3557             Instruction *Cast;
3558             if (SO1->getType()->getPrimitiveSize() == PS) {
3559               // Convert GO1 to SO1's type.
3560               GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3561
3562             } else if (GO1->getType()->getPrimitiveSize() == PS) {
3563               // Convert SO1 to GO1's type.
3564               SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3565             } else {
3566               const Type *PT = TD->getIntPtrType();
3567               SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3568               GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3569             }
3570           }
3571         }
3572         if (isa<Constant>(SO1) && isa<Constant>(GO1))
3573           Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3574         else {
3575           Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3576           InsertNewInstBefore(cast<Instruction>(Sum), GEP);
3577         }
3578       }
3579
3580       // Recycle the GEP we already have if possible.
3581       if (SrcGEPOperands.size() == 2) {
3582         GEP.setOperand(0, SrcGEPOperands[0]);
3583         GEP.setOperand(1, Sum);
3584         return &GEP;
3585       } else {
3586         Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3587                        SrcGEPOperands.end()-1);
3588         Indices.push_back(Sum);
3589         Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3590       }
3591     } else if (isa<Constant>(*GEP.idx_begin()) && 
3592                cast<Constant>(*GEP.idx_begin())->isNullValue() &&
3593                SrcGEPOperands.size() != 1) { 
3594       // Otherwise we can do the fold if the first index of the GEP is a zero
3595       Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3596                      SrcGEPOperands.end());
3597       Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3598     }
3599
3600     if (!Indices.empty())
3601       return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
3602
3603   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
3604     // GEP of global variable.  If all of the indices for this GEP are
3605     // constants, we can promote this to a constexpr instead of an instruction.
3606
3607     // Scan for nonconstants...
3608     std::vector<Constant*> Indices;
3609     User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3610     for (; I != E && isa<Constant>(*I); ++I)
3611       Indices.push_back(cast<Constant>(*I));
3612
3613     if (I == E) {  // If they are all constants...
3614       Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
3615
3616       // Replace all uses of the GEP with the new constexpr...
3617       return ReplaceInstUsesWith(GEP, CE);
3618     }
3619   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3620     if (CE->getOpcode() == Instruction::Cast) {
3621       if (HasZeroPointerIndex) {
3622         // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3623         // into     : GEP [10 x ubyte]* X, long 0, ...
3624         //
3625         // This occurs when the program declares an array extern like "int X[];"
3626         //
3627         Constant *X = CE->getOperand(0);
3628         const PointerType *CPTy = cast<PointerType>(CE->getType());
3629         if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3630           if (const ArrayType *XATy =
3631               dyn_cast<ArrayType>(XTy->getElementType()))
3632             if (const ArrayType *CATy =
3633                 dyn_cast<ArrayType>(CPTy->getElementType()))
3634               if (CATy->getElementType() == XATy->getElementType()) {
3635                 // At this point, we know that the cast source type is a pointer
3636                 // to an array of the same type as the destination pointer
3637                 // array.  Because the array type is never stepped over (there
3638                 // is a leading zero) we can fold the cast into this GEP.
3639                 GEP.setOperand(0, X);
3640                 return &GEP;
3641               }
3642       }
3643     }
3644   }
3645
3646   return 0;
3647 }
3648
3649 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3650   // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3651   if (AI.isArrayAllocation())    // Check C != 1
3652     if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3653       const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
3654       AllocationInst *New = 0;
3655
3656       // Create and insert the replacement instruction...
3657       if (isa<MallocInst>(AI))
3658         New = new MallocInst(NewTy, 0, AI.getName());
3659       else {
3660         assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
3661         New = new AllocaInst(NewTy, 0, AI.getName());
3662       }
3663
3664       InsertNewInstBefore(New, AI);
3665       
3666       // Scan to the end of the allocation instructions, to skip over a block of
3667       // allocas if possible...
3668       //
3669       BasicBlock::iterator It = New;
3670       while (isa<AllocationInst>(*It)) ++It;
3671
3672       // Now that I is pointing to the first non-allocation-inst in the block,
3673       // insert our getelementptr instruction...
3674       //
3675       std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
3676       Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3677
3678       // Now make everything use the getelementptr instead of the original
3679       // allocation.
3680       return ReplaceInstUsesWith(AI, V);
3681     } else if (isa<UndefValue>(AI.getArraySize())) {
3682       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3683     }
3684
3685   // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3686   // Note that we only do this for alloca's, because malloc should allocate and
3687   // return a unique pointer, even for a zero byte allocation.
3688   if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() && 
3689       TD->getTypeSize(AI.getAllocatedType()) == 0)
3690     return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3691
3692   return 0;
3693 }
3694
3695 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3696   Value *Op = FI.getOperand(0);
3697
3698   // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3699   if (CastInst *CI = dyn_cast<CastInst>(Op))
3700     if (isa<PointerType>(CI->getOperand(0)->getType())) {
3701       FI.setOperand(0, CI->getOperand(0));
3702       return &FI;
3703     }
3704
3705   // If we have 'free null' delete the instruction.  This can happen in stl code
3706   // when lots of inlining happens.
3707   // FIXME: free undef should be xformed into an 'unreachable' instruction.
3708   if (isa<ConstantPointerNull>(Op) || isa<UndefValue>(Op))
3709     return EraseInstFromFunction(FI);
3710
3711   return 0;
3712 }
3713
3714
3715 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3716 /// constantexpr, return the constant value being addressed by the constant
3717 /// expression, or null if something is funny.
3718 ///
3719 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
3720   if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
3721     return 0;  // Do not allow stepping over the value!
3722
3723   // Loop over all of the operands, tracking down which value we are
3724   // addressing...
3725   gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3726   for (++I; I != E; ++I)
3727     if (const StructType *STy = dyn_cast<StructType>(*I)) {
3728       ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3729       assert(CU->getValue() < STy->getNumElements() &&
3730              "Struct index out of range!");
3731       if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
3732         C = CS->getOperand(CU->getValue());
3733       } else if (isa<ConstantAggregateZero>(C)) {
3734         C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3735       } else if (isa<UndefValue>(C)) {
3736         C = UndefValue::get(STy->getElementType(CU->getValue()));
3737       } else {
3738         return 0;
3739       }
3740     } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3741       const ArrayType *ATy = cast<ArrayType>(*I);
3742       if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3743       if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
3744         C = CA->getOperand(CI->getRawValue());
3745       else if (isa<ConstantAggregateZero>(C))
3746         C = Constant::getNullValue(ATy->getElementType());
3747       else if (isa<UndefValue>(C))
3748         C = UndefValue::get(ATy->getElementType());
3749       else
3750         return 0;
3751     } else {
3752       return 0;
3753     }
3754   return C;
3755 }
3756
3757 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3758   User *CI = cast<User>(LI.getOperand(0));
3759
3760   const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3761   if (const PointerType *SrcTy =
3762       dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3763     const Type *SrcPTy = SrcTy->getElementType();
3764     if (SrcPTy->isSized() && DestPTy->isSized() &&
3765         IC.getTargetData().getTypeSize(SrcPTy) == 
3766             IC.getTargetData().getTypeSize(DestPTy) &&
3767         (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3768         (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3769       // Okay, we are casting from one integer or pointer type to another of
3770       // the same size.  Instead of casting the pointer before the load, cast
3771       // the result of the loaded value.
3772       Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
3773                                                            CI->getName(),
3774                                                            LI.isVolatile()),LI);
3775       // Now cast the result of the load.
3776       return new CastInst(NewLoad, LI.getType());
3777     }
3778   }
3779   return 0;
3780 }
3781
3782 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
3783 /// from this value cannot trap.  If it is not obviously safe to load from the
3784 /// specified pointer, we do a quick local scan of the basic block containing
3785 /// ScanFrom, to determine if the address is already accessed.
3786 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3787   // If it is an alloca or global variable, it is always safe to load from.
3788   if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3789
3790   // Otherwise, be a little bit agressive by scanning the local block where we
3791   // want to check to see if the pointer is already being loaded or stored
3792   // from/to.  If so, the previous load or store would have already trapped,
3793   // so there is no harm doing an extra load (also, CSE will later eliminate
3794   // the load entirely).
3795   BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3796
3797   while (BBI != E) {
3798     --BBI;
3799
3800     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3801       if (LI->getOperand(0) == V) return true;
3802     } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3803       if (SI->getOperand(1) == V) return true;
3804     
3805   }
3806   return false;
3807 }
3808
3809 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3810   Value *Op = LI.getOperand(0);
3811
3812   if (Constant *C = dyn_cast<Constant>(Op)) {
3813     if ((C->isNullValue() || isa<UndefValue>(C)) &&
3814         !LI.isVolatile())                           // load null -> undef
3815       // FIXME: this should become an unreachable instruction
3816       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
3817
3818     // Instcombine load (constant global) into the value loaded.
3819     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3820       if (GV->isConstant() && !GV->isExternal())
3821         return ReplaceInstUsesWith(LI, GV->getInitializer());
3822     
3823     // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3824     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3825       if (CE->getOpcode() == Instruction::GetElementPtr) {
3826         if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3827           if (GV->isConstant() && !GV->isExternal())
3828             if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3829               return ReplaceInstUsesWith(LI, V);
3830       } else if (CE->getOpcode() == Instruction::Cast) {
3831         if (Instruction *Res = InstCombineLoadCast(*this, LI))
3832           return Res;
3833       }
3834   }
3835
3836   // load (cast X) --> cast (load X) iff safe
3837   if (CastInst *CI = dyn_cast<CastInst>(Op))
3838     if (Instruction *Res = InstCombineLoadCast(*this, LI))
3839       return Res;
3840
3841   if (!LI.isVolatile() && Op->hasOneUse()) {
3842     // Change select and PHI nodes to select values instead of addresses: this
3843     // helps alias analysis out a lot, allows many others simplifications, and
3844     // exposes redundancy in the code.
3845     //
3846     // Note that we cannot do the transformation unless we know that the
3847     // introduced loads cannot trap!  Something like this is valid as long as
3848     // the condition is always false: load (select bool %C, int* null, int* %G),
3849     // but it would not be valid if we transformed it to load from null
3850     // unconditionally.
3851     //
3852     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3853       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
3854       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3855           isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
3856         Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
3857                                      SI->getOperand(1)->getName()+".val"), LI);
3858         Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
3859                                      SI->getOperand(2)->getName()+".val"), LI);
3860         return new SelectInst(SI->getCondition(), V1, V2);
3861       }
3862
3863       // load (select (cond, null, P)) -> load P
3864       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3865         if (C->isNullValue()) {
3866           LI.setOperand(0, SI->getOperand(2));
3867           return &LI;
3868         }
3869
3870       // load (select (cond, P, null)) -> load P
3871       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3872         if (C->isNullValue()) {
3873           LI.setOperand(0, SI->getOperand(1));
3874           return &LI;
3875         }
3876
3877     } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3878       // load (phi (&V1, &V2, &V3))  --> phi(load &V1, load &V2, load &V3)
3879       bool Safe = PN->getParent() == LI.getParent();
3880
3881       // Scan all of the instructions between the PHI and the load to make
3882       // sure there are no instructions that might possibly alter the value
3883       // loaded from the PHI.
3884       if (Safe) {
3885         BasicBlock::iterator I = &LI;
3886         for (--I; !isa<PHINode>(I); --I)
3887           if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3888             Safe = false;
3889             break;
3890           }
3891       }
3892
3893       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
3894         if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
3895                                     PN->getIncomingBlock(i)->getTerminator()))
3896           Safe = false;
3897
3898       if (Safe) {
3899         // Create the PHI.
3900         PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3901         InsertNewInstBefore(NewPN, *PN);
3902         std::map<BasicBlock*,Value*> LoadMap;  // Don't insert duplicate loads
3903
3904         for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3905           BasicBlock *BB = PN->getIncomingBlock(i);
3906           Value *&TheLoad = LoadMap[BB];
3907           if (TheLoad == 0) {
3908             Value *InVal = PN->getIncomingValue(i);
3909             TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3910                                                        InVal->getName()+".val"),
3911                                           *BB->getTerminator());
3912           }
3913           NewPN->addIncoming(TheLoad, BB);
3914         }
3915         return ReplaceInstUsesWith(LI, NewPN);
3916       }
3917     }
3918   }
3919   return 0;
3920 }
3921
3922 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
3923   if (isa<ConstantPointerNull>(SI.getOperand(1)) ||
3924       isa<UndefValue>(SI.getOperand(1))) {
3925     // FIXME: This should become an unreachable instruction.
3926     return EraseInstFromFunction(SI);
3927   }
3928
3929
3930   return 0;
3931 }
3932
3933
3934 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3935   // Change br (not X), label True, label False to: br X, label False, True
3936   Value *X;
3937   BasicBlock *TrueDest;
3938   BasicBlock *FalseDest;
3939   if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3940       !isa<Constant>(X)) {
3941     // Swap Destinations and condition...
3942     BI.setCondition(X);
3943     BI.setSuccessor(0, FalseDest);
3944     BI.setSuccessor(1, TrueDest);
3945     return &BI;
3946   }
3947
3948   // Cannonicalize setne -> seteq
3949   Instruction::BinaryOps Op; Value *Y;
3950   if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3951                       TrueDest, FalseDest)))
3952     if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3953          Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3954       SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3955       std::string Name = I->getName(); I->setName("");
3956       Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3957       Value *NewSCC =  BinaryOperator::create(NewOpcode, X, Y, Name, I);
3958       // Swap Destinations and condition...
3959       BI.setCondition(NewSCC);
3960       BI.setSuccessor(0, FalseDest);
3961       BI.setSuccessor(1, TrueDest);
3962       removeFromWorkList(I);
3963       I->getParent()->getInstList().erase(I);
3964       WorkList.push_back(cast<Instruction>(NewSCC));
3965       return &BI;
3966     }
3967   
3968   return 0;
3969 }
3970
3971 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3972   Value *Cond = SI.getCondition();
3973   if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3974     if (I->getOpcode() == Instruction::Add)
3975       if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3976         // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3977         for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3978           SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3979                                                 AddRHS));
3980         SI.setOperand(0, I->getOperand(0));
3981         WorkList.push_back(I);
3982         return &SI;
3983       }
3984   }
3985   return 0;
3986 }
3987
3988
3989 void InstCombiner::removeFromWorkList(Instruction *I) {
3990   WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3991                  WorkList.end());
3992 }
3993
3994 bool InstCombiner::runOnFunction(Function &F) {
3995   bool Changed = false;
3996   TD = &getAnalysis<TargetData>();
3997
3998   for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3999     WorkList.push_back(&*i);
4000
4001
4002   while (!WorkList.empty()) {
4003     Instruction *I = WorkList.back();  // Get an instruction from the worklist
4004     WorkList.pop_back();
4005
4006     // Check to see if we can DCE or ConstantPropagate the instruction...
4007     // Check to see if we can DIE the instruction...
4008     if (isInstructionTriviallyDead(I)) {
4009       // Add operands to the worklist...
4010       if (I->getNumOperands() < 4)
4011         AddUsesToWorkList(*I);
4012       ++NumDeadInst;
4013
4014       I->getParent()->getInstList().erase(I);
4015       removeFromWorkList(I);
4016       continue;
4017     }
4018
4019     // Instruction isn't dead, see if we can constant propagate it...
4020     if (Constant *C = ConstantFoldInstruction(I)) {
4021       // Add operands to the worklist...
4022       AddUsesToWorkList(*I);
4023       ReplaceInstUsesWith(*I, C);
4024
4025       ++NumConstProp;
4026       I->getParent()->getInstList().erase(I);
4027       removeFromWorkList(I);
4028       continue;
4029     }
4030
4031     // Now that we have an instruction, try combining it to simplify it...
4032     if (Instruction *Result = visit(*I)) {
4033       ++NumCombined;
4034       // Should we replace the old instruction with a new one?
4035       if (Result != I) {
4036         DEBUG(std::cerr << "IC: Old = " << *I
4037                         << "    New = " << *Result);
4038
4039         // Everything uses the new instruction now.
4040         I->replaceAllUsesWith(Result);
4041
4042         // Push the new instruction and any users onto the worklist.
4043         WorkList.push_back(Result);
4044         AddUsersToWorkList(*Result);
4045
4046         // Move the name to the new instruction first...
4047         std::string OldName = I->getName(); I->setName("");
4048         Result->setName(OldName);
4049
4050         // Insert the new instruction into the basic block...
4051         BasicBlock *InstParent = I->getParent();
4052         InstParent->getInstList().insert(I, Result);
4053
4054         // Make sure that we reprocess all operands now that we reduced their
4055         // use counts.
4056         for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4057           if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4058             WorkList.push_back(OpI);
4059
4060         // Instructions can end up on the worklist more than once.  Make sure
4061         // we do not process an instruction that has been deleted.
4062         removeFromWorkList(I);
4063
4064         // Erase the old instruction.
4065         InstParent->getInstList().erase(I);
4066       } else {
4067         DEBUG(std::cerr << "IC: MOD = " << *I);
4068
4069         // If the instruction was modified, it's possible that it is now dead.
4070         // if so, remove it.
4071         if (isInstructionTriviallyDead(I)) {
4072           // Make sure we process all operands now that we are reducing their
4073           // use counts.
4074           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4075             if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4076               WorkList.push_back(OpI);
4077           
4078           // Instructions may end up in the worklist more than once.  Erase all
4079           // occurrances of this instruction.
4080           removeFromWorkList(I);
4081           I->getParent()->getInstList().erase(I);
4082         } else {
4083           WorkList.push_back(Result);
4084           AddUsersToWorkList(*Result);
4085         }
4086       }
4087       Changed = true;
4088     }
4089   }
4090
4091   return Changed;
4092 }
4093
4094 FunctionPass *llvm::createInstructionCombiningPass() {
4095   return new InstCombiner();
4096 }
4097