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