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