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