f737354b36a6c62a453a296eefe63bd461528fb9
[oota-llvm.git] / lib / Analysis / InstructionSimplify.cpp
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions.  This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "instsimplify"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/ConstantFolding.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Support/PatternMatch.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Target/TargetData.h"
28 using namespace llvm;
29 using namespace llvm::PatternMatch;
30
31 #define RecursionLimit 3
32
33 STATISTIC(NumExpand,  "Number of expansions");
34 STATISTIC(NumFactor , "Number of factorizations");
35 STATISTIC(NumReassoc, "Number of reassociations");
36
37 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
38                               const DominatorTree *, unsigned);
39 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
40                             const DominatorTree *, unsigned);
41 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
42                               const DominatorTree *, unsigned);
43 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
44                              const DominatorTree *, unsigned);
45 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
46                               const DominatorTree *, unsigned);
47
48 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
49 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
50   Instruction *I = dyn_cast<Instruction>(V);
51   if (!I)
52     // Arguments and constants dominate all instructions.
53     return true;
54
55   // If we have a DominatorTree then do a precise test.
56   if (DT)
57     return DT->dominates(I, P);
58
59   // Otherwise, if the instruction is in the entry block, and is not an invoke,
60   // then it obviously dominates all phi nodes.
61   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
62       !isa<InvokeInst>(I))
63     return true;
64
65   return false;
66 }
67
68 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
69 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
70 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
71 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
72 /// Returns the simplified value, or null if no simplification was performed.
73 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
74                           unsigned OpcToExpand, const TargetData *TD,
75                           const DominatorTree *DT, unsigned MaxRecurse) {
76   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
77   // Recursion is always used, so bail out at once if we already hit the limit.
78   if (!MaxRecurse--)
79     return 0;
80
81   // Check whether the expression has the form "(A op' B) op C".
82   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
83     if (Op0->getOpcode() == OpcodeToExpand) {
84       // It does!  Try turning it into "(A op C) op' (B op C)".
85       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
86       // Do "A op C" and "B op C" both simplify?
87       if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
88         if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
89           // They do! Return "L op' R" if it simplifies or is already available.
90           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
91           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
92                                      && L == B && R == A)) {
93             ++NumExpand;
94             return LHS;
95           }
96           // Otherwise return "L op' R" if it simplifies.
97           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
98                                        MaxRecurse)) {
99             ++NumExpand;
100             return V;
101           }
102         }
103     }
104
105   // Check whether the expression has the form "A op (B op' C)".
106   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
107     if (Op1->getOpcode() == OpcodeToExpand) {
108       // It does!  Try turning it into "(A op B) op' (A op C)".
109       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
110       // Do "A op B" and "A op C" both simplify?
111       if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
112         if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
113           // They do! Return "L op' R" if it simplifies or is already available.
114           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
115           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
116                                      && L == C && R == B)) {
117             ++NumExpand;
118             return RHS;
119           }
120           // Otherwise return "L op' R" if it simplifies.
121           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
122                                        MaxRecurse)) {
123             ++NumExpand;
124             return V;
125           }
126         }
127     }
128
129   return 0;
130 }
131
132 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
133 /// using the operation OpCodeToExtract.  For example, when Opcode is Add and
134 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
135 /// Returns the simplified value, or null if no simplification was performed.
136 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
137                              unsigned OpcToExtract, const TargetData *TD,
138                              const DominatorTree *DT, unsigned MaxRecurse) {
139   Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
140   // Recursion is always used, so bail out at once if we already hit the limit.
141   if (!MaxRecurse--)
142     return 0;
143
144   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
145   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
146
147   if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
148       !Op1 || Op1->getOpcode() != OpcodeToExtract)
149     return 0;
150
151   // The expression has the form "(A op' B) op (C op' D)".
152   Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
153   Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
154
155   // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
156   // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
157   // commutative case, "(A op' B) op (C op' A)"?
158   if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
159     Value *DD = A == C ? D : C;
160     // Form "A op' (B op DD)" if it simplifies completely.
161     // Does "B op DD" simplify?
162     if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
163       // It does!  Return "A op' V" if it simplifies or is already available.
164       // If V equals B then "A op' V" is just the LHS.  If V equals DD then
165       // "A op' V" is just the RHS.
166       if (V == B || V == DD) {
167         ++NumFactor;
168         return V == B ? LHS : RHS;
169       }
170       // Otherwise return "A op' V" if it simplifies.
171       if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
172         ++NumFactor;
173         return W;
174       }
175     }
176   }
177
178   // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
179   // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
180   // commutative case, "(A op' B) op (B op' D)"?
181   if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
182     Value *CC = B == D ? C : D;
183     // Form "(A op CC) op' B" if it simplifies completely..
184     // Does "A op CC" simplify?
185     if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
186       // It does!  Return "V op' B" if it simplifies or is already available.
187       // If V equals A then "V op' B" is just the LHS.  If V equals CC then
188       // "V op' B" is just the RHS.
189       if (V == A || V == CC) {
190         ++NumFactor;
191         return V == A ? LHS : RHS;
192       }
193       // Otherwise return "V op' B" if it simplifies.
194       if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
195         ++NumFactor;
196         return W;
197       }
198     }
199   }
200
201   return 0;
202 }
203
204 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
205 /// operations.  Returns the simpler value, or null if none was found.
206 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
207                                        const TargetData *TD,
208                                        const DominatorTree *DT,
209                                        unsigned MaxRecurse) {
210   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
211   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
212
213   // Recursion is always used, so bail out at once if we already hit the limit.
214   if (!MaxRecurse--)
215     return 0;
216
217   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
218   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
219
220   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
221   if (Op0 && Op0->getOpcode() == Opcode) {
222     Value *A = Op0->getOperand(0);
223     Value *B = Op0->getOperand(1);
224     Value *C = RHS;
225
226     // Does "B op C" simplify?
227     if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
228       // It does!  Return "A op V" if it simplifies or is already available.
229       // If V equals B then "A op V" is just the LHS.
230       if (V == B) return LHS;
231       // Otherwise return "A op V" if it simplifies.
232       if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
233         ++NumReassoc;
234         return W;
235       }
236     }
237   }
238
239   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
240   if (Op1 && Op1->getOpcode() == Opcode) {
241     Value *A = LHS;
242     Value *B = Op1->getOperand(0);
243     Value *C = Op1->getOperand(1);
244
245     // Does "A op B" simplify?
246     if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
247       // It does!  Return "V op C" if it simplifies or is already available.
248       // If V equals B then "V op C" is just the RHS.
249       if (V == B) return RHS;
250       // Otherwise return "V op C" if it simplifies.
251       if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
252         ++NumReassoc;
253         return W;
254       }
255     }
256   }
257
258   // The remaining transforms require commutativity as well as associativity.
259   if (!Instruction::isCommutative(Opcode))
260     return 0;
261
262   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
263   if (Op0 && Op0->getOpcode() == Opcode) {
264     Value *A = Op0->getOperand(0);
265     Value *B = Op0->getOperand(1);
266     Value *C = RHS;
267
268     // Does "C op A" simplify?
269     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
270       // It does!  Return "V op B" if it simplifies or is already available.
271       // If V equals A then "V op B" is just the LHS.
272       if (V == A) return LHS;
273       // Otherwise return "V op B" if it simplifies.
274       if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
275         ++NumReassoc;
276         return W;
277       }
278     }
279   }
280
281   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
282   if (Op1 && Op1->getOpcode() == Opcode) {
283     Value *A = LHS;
284     Value *B = Op1->getOperand(0);
285     Value *C = Op1->getOperand(1);
286
287     // Does "C op A" simplify?
288     if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
289       // It does!  Return "B op V" if it simplifies or is already available.
290       // If V equals C then "B op V" is just the RHS.
291       if (V == C) return RHS;
292       // Otherwise return "B op V" if it simplifies.
293       if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
294         ++NumReassoc;
295         return W;
296       }
297     }
298   }
299
300   return 0;
301 }
302
303 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
304 /// instruction as an operand, try to simplify the binop by seeing whether
305 /// evaluating it on both branches of the select results in the same value.
306 /// Returns the common value if so, otherwise returns null.
307 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
308                                     const TargetData *TD,
309                                     const DominatorTree *DT,
310                                     unsigned MaxRecurse) {
311   // Recursion is always used, so bail out at once if we already hit the limit.
312   if (!MaxRecurse--)
313     return 0;
314
315   SelectInst *SI;
316   if (isa<SelectInst>(LHS)) {
317     SI = cast<SelectInst>(LHS);
318   } else {
319     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
320     SI = cast<SelectInst>(RHS);
321   }
322
323   // Evaluate the BinOp on the true and false branches of the select.
324   Value *TV;
325   Value *FV;
326   if (SI == LHS) {
327     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
328     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
329   } else {
330     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
331     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
332   }
333
334   // If they simplified to the same value, then return the common value.
335   // If they both failed to simplify then return null.
336   if (TV == FV)
337     return TV;
338
339   // If one branch simplified to undef, return the other one.
340   if (TV && isa<UndefValue>(TV))
341     return FV;
342   if (FV && isa<UndefValue>(FV))
343     return TV;
344
345   // If applying the operation did not change the true and false select values,
346   // then the result of the binop is the select itself.
347   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
348     return SI;
349
350   // If one branch simplified and the other did not, and the simplified
351   // value is equal to the unsimplified one, return the simplified value.
352   // For example, select (cond, X, X & Z) & Z -> X & Z.
353   if ((FV && !TV) || (TV && !FV)) {
354     // Check that the simplified value has the form "X op Y" where "op" is the
355     // same as the original operation.
356     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
357     if (Simplified && Simplified->getOpcode() == Opcode) {
358       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
359       // We already know that "op" is the same as for the simplified value.  See
360       // if the operands match too.  If so, return the simplified value.
361       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
362       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
363       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
364       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
365           Simplified->getOperand(1) == UnsimplifiedRHS)
366         return Simplified;
367       if (Simplified->isCommutative() &&
368           Simplified->getOperand(1) == UnsimplifiedLHS &&
369           Simplified->getOperand(0) == UnsimplifiedRHS)
370         return Simplified;
371     }
372   }
373
374   return 0;
375 }
376
377 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
378 /// try to simplify the comparison by seeing whether both branches of the select
379 /// result in the same value.  Returns the common value if so, otherwise returns
380 /// null.
381 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
382                                   Value *RHS, const TargetData *TD,
383                                   const DominatorTree *DT,
384                                   unsigned MaxRecurse) {
385   // Recursion is always used, so bail out at once if we already hit the limit.
386   if (!MaxRecurse--)
387     return 0;
388
389   // Make sure the select is on the LHS.
390   if (!isa<SelectInst>(LHS)) {
391     std::swap(LHS, RHS);
392     Pred = CmpInst::getSwappedPredicate(Pred);
393   }
394   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
395   SelectInst *SI = cast<SelectInst>(LHS);
396
397   // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
398   // Does "cmp TV, RHS" simplify?
399   if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
400                                     MaxRecurse))
401     // It does!  Does "cmp FV, RHS" simplify?
402     if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
403                                       MaxRecurse))
404       // It does!  If they simplified to the same value, then use it as the
405       // result of the original comparison.
406       if (TCmp == FCmp)
407         return TCmp;
408   return 0;
409 }
410
411 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
412 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
413 /// it on the incoming phi values yields the same result for every value.  If so
414 /// returns the common value, otherwise returns null.
415 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
416                                  const TargetData *TD, const DominatorTree *DT,
417                                  unsigned MaxRecurse) {
418   // Recursion is always used, so bail out at once if we already hit the limit.
419   if (!MaxRecurse--)
420     return 0;
421
422   PHINode *PI;
423   if (isa<PHINode>(LHS)) {
424     PI = cast<PHINode>(LHS);
425     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
426     if (!ValueDominatesPHI(RHS, PI, DT))
427       return 0;
428   } else {
429     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
430     PI = cast<PHINode>(RHS);
431     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
432     if (!ValueDominatesPHI(LHS, PI, DT))
433       return 0;
434   }
435
436   // Evaluate the BinOp on the incoming phi values.
437   Value *CommonValue = 0;
438   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
439     Value *Incoming = PI->getIncomingValue(i);
440     // If the incoming value is the phi node itself, it can safely be skipped.
441     if (Incoming == PI) continue;
442     Value *V = PI == LHS ?
443       SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
444       SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
445     // If the operation failed to simplify, or simplified to a different value
446     // to previously, then give up.
447     if (!V || (CommonValue && V != CommonValue))
448       return 0;
449     CommonValue = V;
450   }
451
452   return CommonValue;
453 }
454
455 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
456 /// try to simplify the comparison by seeing whether comparing with all of the
457 /// incoming phi values yields the same result every time.  If so returns the
458 /// common result, otherwise returns null.
459 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
460                                const TargetData *TD, const DominatorTree *DT,
461                                unsigned MaxRecurse) {
462   // Recursion is always used, so bail out at once if we already hit the limit.
463   if (!MaxRecurse--)
464     return 0;
465
466   // Make sure the phi is on the LHS.
467   if (!isa<PHINode>(LHS)) {
468     std::swap(LHS, RHS);
469     Pred = CmpInst::getSwappedPredicate(Pred);
470   }
471   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
472   PHINode *PI = cast<PHINode>(LHS);
473
474   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
475   if (!ValueDominatesPHI(RHS, PI, DT))
476     return 0;
477
478   // Evaluate the BinOp on the incoming phi values.
479   Value *CommonValue = 0;
480   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
481     Value *Incoming = PI->getIncomingValue(i);
482     // If the incoming value is the phi node itself, it can safely be skipped.
483     if (Incoming == PI) continue;
484     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
485     // If the operation failed to simplify, or simplified to a different value
486     // to previously, then give up.
487     if (!V || (CommonValue && V != CommonValue))
488       return 0;
489     CommonValue = V;
490   }
491
492   return CommonValue;
493 }
494
495 /// SimplifyAddInst - Given operands for an Add, see if we can
496 /// fold the result.  If not, this returns null.
497 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
498                               const TargetData *TD, const DominatorTree *DT,
499                               unsigned MaxRecurse) {
500   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
501     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
502       Constant *Ops[] = { CLHS, CRHS };
503       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
504                                       Ops, 2, TD);
505     }
506
507     // Canonicalize the constant to the RHS.
508     std::swap(Op0, Op1);
509   }
510
511   // X + undef -> undef
512   if (isa<UndefValue>(Op1))
513     return Op1;
514
515   // X + 0 -> X
516   if (match(Op1, m_Zero()))
517     return Op0;
518
519   // X + (Y - X) -> Y
520   // (Y - X) + X -> Y
521   // Eg: X + -X -> 0
522   Value *Y = 0;
523   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
524       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
525     return Y;
526
527   // X + ~X -> -1   since   ~X = -X-1
528   if (match(Op0, m_Not(m_Specific(Op1))) ||
529       match(Op1, m_Not(m_Specific(Op0))))
530     return Constant::getAllOnesValue(Op0->getType());
531
532   /// i1 add -> xor.
533   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
534     if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
535       return V;
536
537   // Try some generic simplifications for associative operations.
538   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
539                                           MaxRecurse))
540     return V;
541
542   // Mul distributes over Add.  Try some generic simplifications based on this.
543   if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
544                                 TD, DT, MaxRecurse))
545     return V;
546
547   // Threading Add over selects and phi nodes is pointless, so don't bother.
548   // Threading over the select in "A + select(cond, B, C)" means evaluating
549   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
550   // only if B and C are equal.  If B and C are equal then (since we assume
551   // that operands have already been simplified) "select(cond, B, C)" should
552   // have been simplified to the common value of B and C already.  Analysing
553   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
554   // for threading over phi nodes.
555
556   return 0;
557 }
558
559 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
560                              const TargetData *TD, const DominatorTree *DT) {
561   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
562 }
563
564 /// SimplifySubInst - Given operands for a Sub, see if we can
565 /// fold the result.  If not, this returns null.
566 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
567                               const TargetData *TD, const DominatorTree *DT,
568                               unsigned MaxRecurse) {
569   if (Constant *CLHS = dyn_cast<Constant>(Op0))
570     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
571       Constant *Ops[] = { CLHS, CRHS };
572       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
573                                       Ops, 2, TD);
574     }
575
576   // X - undef -> undef
577   // undef - X -> undef
578   if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
579     return UndefValue::get(Op0->getType());
580
581   // X - 0 -> X
582   if (match(Op1, m_Zero()))
583     return Op0;
584
585   // X - X -> 0
586   if (Op0 == Op1)
587     return Constant::getNullValue(Op0->getType());
588
589   // (X + Y) - Y -> X
590   // (Y + X) - Y -> X
591   Value *X = 0;
592   if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
593       match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
594     return X;
595
596   // (X*2) - X -> X
597   // (X<<1) - X -> X
598   if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
599       match(Op0, m_Shl(m_Specific(Op1), m_One())))
600     return Op1;
601
602   // i1 sub -> xor.
603   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
604     if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
605       return V;
606
607   // X - (X - Y) -> Y.  More generally Z - (X - Y) -> (Z - X) + Y if everything
608   // simplifies.
609   Value *Y = 0, *Z = Op0;
610   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
611     // See if "V === Z - X" simplifies.
612     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
613       // It does!  Now see if "W === V + Y" simplifies.
614       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
615                                    MaxRecurse-1)) {
616         // It does, we successfully reassociated!
617         ++NumReassoc;
618         return W;
619       }
620
621   // Mul distributes over Sub.  Try some generic simplifications based on this.
622   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
623                                 TD, DT, MaxRecurse))
624     return V;
625
626   // Threading Sub over selects and phi nodes is pointless, so don't bother.
627   // Threading over the select in "A - select(cond, B, C)" means evaluating
628   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
629   // only if B and C are equal.  If B and C are equal then (since we assume
630   // that operands have already been simplified) "select(cond, B, C)" should
631   // have been simplified to the common value of B and C already.  Analysing
632   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
633   // for threading over phi nodes.
634
635   return 0;
636 }
637
638 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
639                              const TargetData *TD, const DominatorTree *DT) {
640   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
641 }
642
643 /// SimplifyMulInst - Given operands for a Mul, see if we can
644 /// fold the result.  If not, this returns null.
645 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
646                               const DominatorTree *DT, unsigned MaxRecurse) {
647   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
648     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
649       Constant *Ops[] = { CLHS, CRHS };
650       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
651                                       Ops, 2, TD);
652     }
653
654     // Canonicalize the constant to the RHS.
655     std::swap(Op0, Op1);
656   }
657
658   // X * undef -> 0
659   if (isa<UndefValue>(Op1))
660     return Constant::getNullValue(Op0->getType());
661
662   // X * 0 -> 0
663   if (match(Op1, m_Zero()))
664     return Op1;
665
666   // X * 1 -> X
667   if (match(Op1, m_One()))
668     return Op0;
669
670   /// i1 mul -> and.
671   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
672     if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
673       return V;
674
675   // Try some generic simplifications for associative operations.
676   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
677                                           MaxRecurse))
678     return V;
679
680   // Mul distributes over Add.  Try some generic simplifications based on this.
681   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
682                              TD, DT, MaxRecurse))
683     return V;
684
685   // If the operation is with the result of a select instruction, check whether
686   // operating on either branch of the select always yields the same value.
687   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
688     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
689                                          MaxRecurse))
690       return V;
691
692   // If the operation is with the result of a phi instruction, check whether
693   // operating on all incoming values of the phi always yields the same value.
694   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
695     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
696                                       MaxRecurse))
697       return V;
698
699   return 0;
700 }
701
702 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
703                              const DominatorTree *DT) {
704   return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
705 }
706
707 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
708 /// fold the result.  If not, this returns null.
709 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
710                             const TargetData *TD, const DominatorTree *DT,
711                             unsigned MaxRecurse) {
712   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
713     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
714       Constant *Ops[] = { C0, C1 };
715       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
716     }
717   }
718
719   // 0 shift by X -> 0
720   if (match(Op0, m_Zero()))
721     return Op0;
722
723   // X shift by 0 -> X
724   if (match(Op1, m_Zero()))
725     return Op0;
726
727   // X shift by undef -> undef because it may shift by the bitwidth.
728   if (isa<UndefValue>(Op1))
729     return Op1;
730
731   // Shifting by the bitwidth or more is undefined.
732   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
733     if (CI->getValue().getLimitedValue() >=
734         Op0->getType()->getScalarSizeInBits())
735       return UndefValue::get(Op0->getType());
736
737   // If the operation is with the result of a select instruction, check whether
738   // operating on either branch of the select always yields the same value.
739   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
740     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
741       return V;
742
743   // If the operation is with the result of a phi instruction, check whether
744   // operating on all incoming values of the phi always yields the same value.
745   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
746     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
747       return V;
748
749   return 0;
750 }
751
752 /// SimplifyShlInst - Given operands for an Shl, see if we can
753 /// fold the result.  If not, this returns null.
754 static Value *SimplifyShlInst(Value *Op0, Value *Op1, const TargetData *TD,
755                               const DominatorTree *DT, unsigned MaxRecurse) {
756   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
757     return V;
758
759   // undef << X -> 0
760   if (isa<UndefValue>(Op0))
761     return Constant::getNullValue(Op0->getType());
762
763   return 0;
764 }
765
766 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, const TargetData *TD,
767                              const DominatorTree *DT) {
768   return ::SimplifyShlInst(Op0, Op1, TD, DT, RecursionLimit);
769 }
770
771 /// SimplifyLShrInst - Given operands for an LShr, see if we can
772 /// fold the result.  If not, this returns null.
773 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, const TargetData *TD,
774                                const DominatorTree *DT, unsigned MaxRecurse) {
775   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
776     return V;
777
778   // undef >>l X -> 0
779   if (isa<UndefValue>(Op0))
780     return Constant::getNullValue(Op0->getType());
781
782   return 0;
783 }
784
785 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, const TargetData *TD,
786                               const DominatorTree *DT) {
787   return ::SimplifyLShrInst(Op0, Op1, TD, DT, RecursionLimit);
788 }
789
790 /// SimplifyAShrInst - Given operands for an AShr, see if we can
791 /// fold the result.  If not, this returns null.
792 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, const TargetData *TD,
793                               const DominatorTree *DT, unsigned MaxRecurse) {
794   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
795     return V;
796
797   // all ones >>a X -> all ones
798   if (match(Op0, m_AllOnes()))
799     return Op0;
800
801   // undef >>a X -> all ones
802   if (isa<UndefValue>(Op0))
803     return Constant::getAllOnesValue(Op0->getType());
804
805   return 0;
806 }
807
808 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, const TargetData *TD,
809                               const DominatorTree *DT) {
810   return ::SimplifyAShrInst(Op0, Op1, TD, DT, RecursionLimit);
811 }
812
813 /// SimplifyAndInst - Given operands for an And, see if we can
814 /// fold the result.  If not, this returns null.
815 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
816                               const DominatorTree *DT, unsigned MaxRecurse) {
817   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
818     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
819       Constant *Ops[] = { CLHS, CRHS };
820       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
821                                       Ops, 2, TD);
822     }
823
824     // Canonicalize the constant to the RHS.
825     std::swap(Op0, Op1);
826   }
827
828   // X & undef -> 0
829   if (isa<UndefValue>(Op1))
830     return Constant::getNullValue(Op0->getType());
831
832   // X & X = X
833   if (Op0 == Op1)
834     return Op0;
835
836   // X & 0 = 0
837   if (match(Op1, m_Zero()))
838     return Op1;
839
840   // X & -1 = X
841   if (match(Op1, m_AllOnes()))
842     return Op0;
843
844   // A & ~A  =  ~A & A  =  0
845   Value *A = 0, *B = 0;
846   if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
847       (match(Op1, m_Not(m_Value(A))) && A == Op0))
848     return Constant::getNullValue(Op0->getType());
849
850   // (A | ?) & A = A
851   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
852       (A == Op1 || B == Op1))
853     return Op1;
854
855   // A & (A | ?) = A
856   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
857       (A == Op0 || B == Op0))
858     return Op0;
859
860   // Try some generic simplifications for associative operations.
861   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
862                                           MaxRecurse))
863     return V;
864
865   // And distributes over Or.  Try some generic simplifications based on this.
866   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
867                              TD, DT, MaxRecurse))
868     return V;
869
870   // And distributes over Xor.  Try some generic simplifications based on this.
871   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
872                              TD, DT, MaxRecurse))
873     return V;
874
875   // Or distributes over And.  Try some generic simplifications based on this.
876   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
877                                 TD, DT, MaxRecurse))
878     return V;
879
880   // If the operation is with the result of a select instruction, check whether
881   // operating on either branch of the select always yields the same value.
882   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
883     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
884                                          MaxRecurse))
885       return V;
886
887   // If the operation is with the result of a phi instruction, check whether
888   // operating on all incoming values of the phi always yields the same value.
889   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
890     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
891                                       MaxRecurse))
892       return V;
893
894   return 0;
895 }
896
897 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
898                              const DominatorTree *DT) {
899   return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
900 }
901
902 /// SimplifyOrInst - Given operands for an Or, see if we can
903 /// fold the result.  If not, this returns null.
904 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
905                              const DominatorTree *DT, unsigned MaxRecurse) {
906   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
907     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
908       Constant *Ops[] = { CLHS, CRHS };
909       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
910                                       Ops, 2, TD);
911     }
912
913     // Canonicalize the constant to the RHS.
914     std::swap(Op0, Op1);
915   }
916
917   // X | undef -> -1
918   if (isa<UndefValue>(Op1))
919     return Constant::getAllOnesValue(Op0->getType());
920
921   // X | X = X
922   if (Op0 == Op1)
923     return Op0;
924
925   // X | 0 = X
926   if (match(Op1, m_Zero()))
927     return Op0;
928
929   // X | -1 = -1
930   if (match(Op1, m_AllOnes()))
931     return Op1;
932
933   // A | ~A  =  ~A | A  =  -1
934   Value *A = 0, *B = 0;
935   if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
936       (match(Op1, m_Not(m_Value(A))) && A == Op0))
937     return Constant::getAllOnesValue(Op0->getType());
938
939   // (A & ?) | A = A
940   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
941       (A == Op1 || B == Op1))
942     return Op1;
943
944   // A | (A & ?) = A
945   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
946       (A == Op0 || B == Op0))
947     return Op0;
948
949   // Try some generic simplifications for associative operations.
950   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
951                                           MaxRecurse))
952     return V;
953
954   // Or distributes over And.  Try some generic simplifications based on this.
955   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
956                              TD, DT, MaxRecurse))
957     return V;
958
959   // And distributes over Or.  Try some generic simplifications based on this.
960   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
961                                 TD, DT, MaxRecurse))
962     return V;
963
964   // If the operation is with the result of a select instruction, check whether
965   // operating on either branch of the select always yields the same value.
966   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
967     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
968                                          MaxRecurse))
969       return V;
970
971   // If the operation is with the result of a phi instruction, check whether
972   // operating on all incoming values of the phi always yields the same value.
973   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
974     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
975                                       MaxRecurse))
976       return V;
977
978   return 0;
979 }
980
981 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
982                             const DominatorTree *DT) {
983   return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
984 }
985
986 /// SimplifyXorInst - Given operands for a Xor, see if we can
987 /// fold the result.  If not, this returns null.
988 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
989                               const DominatorTree *DT, unsigned MaxRecurse) {
990   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
991     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
992       Constant *Ops[] = { CLHS, CRHS };
993       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
994                                       Ops, 2, TD);
995     }
996
997     // Canonicalize the constant to the RHS.
998     std::swap(Op0, Op1);
999   }
1000
1001   // A ^ undef -> undef
1002   if (isa<UndefValue>(Op1))
1003     return Op1;
1004
1005   // A ^ 0 = A
1006   if (match(Op1, m_Zero()))
1007     return Op0;
1008
1009   // A ^ A = 0
1010   if (Op0 == Op1)
1011     return Constant::getNullValue(Op0->getType());
1012
1013   // A ^ ~A  =  ~A ^ A  =  -1
1014   Value *A = 0;
1015   if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
1016       (match(Op1, m_Not(m_Value(A))) && A == Op0))
1017     return Constant::getAllOnesValue(Op0->getType());
1018
1019   // Try some generic simplifications for associative operations.
1020   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1021                                           MaxRecurse))
1022     return V;
1023
1024   // And distributes over Xor.  Try some generic simplifications based on this.
1025   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1026                                 TD, DT, MaxRecurse))
1027     return V;
1028
1029   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1030   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1031   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1032   // only if B and C are equal.  If B and C are equal then (since we assume
1033   // that operands have already been simplified) "select(cond, B, C)" should
1034   // have been simplified to the common value of B and C already.  Analysing
1035   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1036   // for threading over phi nodes.
1037
1038   return 0;
1039 }
1040
1041 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1042                              const DominatorTree *DT) {
1043   return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1044 }
1045
1046 static const Type *GetCompareTy(Value *Op) {
1047   return CmpInst::makeCmpResultType(Op->getType());
1048 }
1049
1050 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1051 /// fold the result.  If not, this returns null.
1052 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1053                                const TargetData *TD, const DominatorTree *DT,
1054                                unsigned MaxRecurse) {
1055   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1056   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1057
1058   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1059     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1060       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1061
1062     // If we have a constant, make sure it is on the RHS.
1063     std::swap(LHS, RHS);
1064     Pred = CmpInst::getSwappedPredicate(Pred);
1065   }
1066
1067   const Type *ITy = GetCompareTy(LHS); // The return type.
1068   const Type *OpTy = LHS->getType();   // The operand type.
1069
1070   // icmp X, X -> true/false
1071   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1072   // because X could be 0.
1073   if (LHS == RHS || isa<UndefValue>(RHS))
1074     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1075
1076   // Special case logic when the operands have i1 type.
1077   if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1078        cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1079     switch (Pred) {
1080     default: break;
1081     case ICmpInst::ICMP_EQ:
1082       // X == 1 -> X
1083       if (match(RHS, m_One()))
1084         return LHS;
1085       break;
1086     case ICmpInst::ICMP_NE:
1087       // X != 0 -> X
1088       if (match(RHS, m_Zero()))
1089         return LHS;
1090       break;
1091     case ICmpInst::ICMP_UGT:
1092       // X >u 0 -> X
1093       if (match(RHS, m_Zero()))
1094         return LHS;
1095       break;
1096     case ICmpInst::ICMP_UGE:
1097       // X >=u 1 -> X
1098       if (match(RHS, m_One()))
1099         return LHS;
1100       break;
1101     case ICmpInst::ICMP_SLT:
1102       // X <s 0 -> X
1103       if (match(RHS, m_Zero()))
1104         return LHS;
1105       break;
1106     case ICmpInst::ICMP_SLE:
1107       // X <=s -1 -> X
1108       if (match(RHS, m_One()))
1109         return LHS;
1110       break;
1111     }
1112   }
1113
1114   // See if we are doing a comparison with a constant.
1115   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1116     switch (Pred) {
1117     default: break;
1118     case ICmpInst::ICMP_UGT:
1119       if (CI->isMaxValue(false))                 // A >u MAX -> FALSE
1120         return ConstantInt::getFalse(CI->getContext());
1121       break;
1122     case ICmpInst::ICMP_UGE:
1123       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
1124         return ConstantInt::getTrue(CI->getContext());
1125       break;
1126     case ICmpInst::ICMP_ULT:
1127       if (CI->isMinValue(false))                 // A <u MIN -> FALSE
1128         return ConstantInt::getFalse(CI->getContext());
1129       break;
1130     case ICmpInst::ICMP_ULE:
1131       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
1132         return ConstantInt::getTrue(CI->getContext());
1133       break;
1134     case ICmpInst::ICMP_SGT:
1135       if (CI->isMaxValue(true))                  // A >s MAX -> FALSE
1136         return ConstantInt::getFalse(CI->getContext());
1137       break;
1138     case ICmpInst::ICMP_SGE:
1139       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
1140         return ConstantInt::getTrue(CI->getContext());
1141       break;
1142     case ICmpInst::ICMP_SLT:
1143       if (CI->isMinValue(true))                  // A <s MIN -> FALSE
1144         return ConstantInt::getFalse(CI->getContext());
1145       break;
1146     case ICmpInst::ICMP_SLE:
1147       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
1148         return ConstantInt::getTrue(CI->getContext());
1149       break;
1150     }
1151   }
1152
1153   // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1154   // different addresses, and what's more the address of a stack variable is
1155   // never null or equal to the address of a global.  Note that generalizing
1156   // to the case where LHS is a global variable address or null is pointless,
1157   // since if both LHS and RHS are constants then we already constant folded
1158   // the compare, and if only one of them is then we moved it to RHS already.
1159   if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1160                                isa<ConstantPointerNull>(RHS)))
1161     // We already know that LHS != LHS.
1162     return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1163
1164   // If the comparison is with the result of a select instruction, check whether
1165   // comparing with either branch of the select always yields the same value.
1166   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1167     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1168       return V;
1169
1170   // If the comparison is with the result of a phi instruction, check whether
1171   // doing the compare with each incoming phi value yields a common result.
1172   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1173     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1174       return V;
1175
1176   return 0;
1177 }
1178
1179 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1180                               const TargetData *TD, const DominatorTree *DT) {
1181   return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1182 }
1183
1184 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1185 /// fold the result.  If not, this returns null.
1186 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1187                                const TargetData *TD, const DominatorTree *DT,
1188                                unsigned MaxRecurse) {
1189   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1190   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1191
1192   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1193     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1194       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1195
1196     // If we have a constant, make sure it is on the RHS.
1197     std::swap(LHS, RHS);
1198     Pred = CmpInst::getSwappedPredicate(Pred);
1199   }
1200
1201   // Fold trivial predicates.
1202   if (Pred == FCmpInst::FCMP_FALSE)
1203     return ConstantInt::get(GetCompareTy(LHS), 0);
1204   if (Pred == FCmpInst::FCMP_TRUE)
1205     return ConstantInt::get(GetCompareTy(LHS), 1);
1206
1207   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
1208     return UndefValue::get(GetCompareTy(LHS));
1209
1210   // fcmp x,x -> true/false.  Not all compares are foldable.
1211   if (LHS == RHS) {
1212     if (CmpInst::isTrueWhenEqual(Pred))
1213       return ConstantInt::get(GetCompareTy(LHS), 1);
1214     if (CmpInst::isFalseWhenEqual(Pred))
1215       return ConstantInt::get(GetCompareTy(LHS), 0);
1216   }
1217
1218   // Handle fcmp with constant RHS
1219   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1220     // If the constant is a nan, see if we can fold the comparison based on it.
1221     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1222       if (CFP->getValueAPF().isNaN()) {
1223         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
1224           return ConstantInt::getFalse(CFP->getContext());
1225         assert(FCmpInst::isUnordered(Pred) &&
1226                "Comparison must be either ordered or unordered!");
1227         // True if unordered.
1228         return ConstantInt::getTrue(CFP->getContext());
1229       }
1230       // Check whether the constant is an infinity.
1231       if (CFP->getValueAPF().isInfinity()) {
1232         if (CFP->getValueAPF().isNegative()) {
1233           switch (Pred) {
1234           case FCmpInst::FCMP_OLT:
1235             // No value is ordered and less than negative infinity.
1236             return ConstantInt::getFalse(CFP->getContext());
1237           case FCmpInst::FCMP_UGE:
1238             // All values are unordered with or at least negative infinity.
1239             return ConstantInt::getTrue(CFP->getContext());
1240           default:
1241             break;
1242           }
1243         } else {
1244           switch (Pred) {
1245           case FCmpInst::FCMP_OGT:
1246             // No value is ordered and greater than infinity.
1247             return ConstantInt::getFalse(CFP->getContext());
1248           case FCmpInst::FCMP_ULE:
1249             // All values are unordered with and at most infinity.
1250             return ConstantInt::getTrue(CFP->getContext());
1251           default:
1252             break;
1253           }
1254         }
1255       }
1256     }
1257   }
1258
1259   // If the comparison is with the result of a select instruction, check whether
1260   // comparing with either branch of the select always yields the same value.
1261   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1262     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1263       return V;
1264
1265   // If the comparison is with the result of a phi instruction, check whether
1266   // doing the compare with each incoming phi value yields a common result.
1267   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1268     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1269       return V;
1270
1271   return 0;
1272 }
1273
1274 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1275                               const TargetData *TD, const DominatorTree *DT) {
1276   return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1277 }
1278
1279 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1280 /// the result.  If not, this returns null.
1281 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1282                                 const TargetData *TD, const DominatorTree *) {
1283   // select true, X, Y  -> X
1284   // select false, X, Y -> Y
1285   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1286     return CB->getZExtValue() ? TrueVal : FalseVal;
1287
1288   // select C, X, X -> X
1289   if (TrueVal == FalseVal)
1290     return TrueVal;
1291
1292   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
1293     return FalseVal;
1294   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
1295     return TrueVal;
1296   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
1297     if (isa<Constant>(TrueVal))
1298       return TrueVal;
1299     return FalseVal;
1300   }
1301
1302   return 0;
1303 }
1304
1305 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1306 /// fold the result.  If not, this returns null.
1307 Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
1308                              const TargetData *TD, const DominatorTree *) {
1309   // The type of the GEP pointer operand.
1310   const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1311
1312   // getelementptr P -> P.
1313   if (NumOps == 1)
1314     return Ops[0];
1315
1316   if (isa<UndefValue>(Ops[0])) {
1317     // Compute the (pointer) type returned by the GEP instruction.
1318     const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1319                                                              NumOps-1);
1320     const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1321     return UndefValue::get(GEPTy);
1322   }
1323
1324   if (NumOps == 2) {
1325     // getelementptr P, 0 -> P.
1326     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1327       if (C->isZero())
1328         return Ops[0];
1329     // getelementptr P, N -> P if P points to a type of zero size.
1330     if (TD) {
1331       const Type *Ty = PtrTy->getElementType();
1332       if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
1333         return Ops[0];
1334     }
1335   }
1336
1337   // Check to see if this is constant foldable.
1338   for (unsigned i = 0; i != NumOps; ++i)
1339     if (!isa<Constant>(Ops[i]))
1340       return 0;
1341
1342   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1343                                         (Constant *const*)Ops+1, NumOps-1);
1344 }
1345
1346 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
1347 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1348   // If all of the PHI's incoming values are the same then replace the PHI node
1349   // with the common value.
1350   Value *CommonValue = 0;
1351   bool HasUndefInput = false;
1352   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1353     Value *Incoming = PN->getIncomingValue(i);
1354     // If the incoming value is the phi node itself, it can safely be skipped.
1355     if (Incoming == PN) continue;
1356     if (isa<UndefValue>(Incoming)) {
1357       // Remember that we saw an undef value, but otherwise ignore them.
1358       HasUndefInput = true;
1359       continue;
1360     }
1361     if (CommonValue && Incoming != CommonValue)
1362       return 0;  // Not the same, bail out.
1363     CommonValue = Incoming;
1364   }
1365
1366   // If CommonValue is null then all of the incoming values were either undef or
1367   // equal to the phi node itself.
1368   if (!CommonValue)
1369     return UndefValue::get(PN->getType());
1370
1371   // If we have a PHI node like phi(X, undef, X), where X is defined by some
1372   // instruction, we cannot return X as the result of the PHI node unless it
1373   // dominates the PHI block.
1374   if (HasUndefInput)
1375     return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1376
1377   return CommonValue;
1378 }
1379
1380
1381 //=== Helper functions for higher up the class hierarchy.
1382
1383 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1384 /// fold the result.  If not, this returns null.
1385 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
1386                             const TargetData *TD, const DominatorTree *DT,
1387                             unsigned MaxRecurse) {
1388   switch (Opcode) {
1389   case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1390                                                 /* isNUW */ false, TD, DT,
1391                                                 MaxRecurse);
1392   case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1393                                                 /* isNUW */ false, TD, DT,
1394                                                 MaxRecurse);
1395   case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
1396   case Instruction::Shl: return SimplifyShlInst(LHS, RHS, TD, DT, MaxRecurse);
1397   case Instruction::LShr: return SimplifyLShrInst(LHS, RHS, TD, DT, MaxRecurse);
1398   case Instruction::AShr: return SimplifyAShrInst(LHS, RHS, TD, DT, MaxRecurse);
1399   case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1400   case Instruction::Or:  return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1401   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
1402   default:
1403     if (Constant *CLHS = dyn_cast<Constant>(LHS))
1404       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1405         Constant *COps[] = {CLHS, CRHS};
1406         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1407       }
1408
1409     // If the operation is associative, try some generic simplifications.
1410     if (Instruction::isAssociative(Opcode))
1411       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1412                                               MaxRecurse))
1413         return V;
1414
1415     // If the operation is with the result of a select instruction, check whether
1416     // operating on either branch of the select always yields the same value.
1417     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1418       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
1419                                            MaxRecurse))
1420         return V;
1421
1422     // If the operation is with the result of a phi instruction, check whether
1423     // operating on all incoming values of the phi always yields the same value.
1424     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1425       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
1426         return V;
1427
1428     return 0;
1429   }
1430 }
1431
1432 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
1433                            const TargetData *TD, const DominatorTree *DT) {
1434   return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
1435 }
1436
1437 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1438 /// fold the result.
1439 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1440                               const TargetData *TD, const DominatorTree *DT,
1441                               unsigned MaxRecurse) {
1442   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
1443     return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1444   return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1445 }
1446
1447 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1448                              const TargetData *TD, const DominatorTree *DT) {
1449   return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1450 }
1451
1452 /// SimplifyInstruction - See if we can compute a simplified version of this
1453 /// instruction.  If not, this returns null.
1454 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1455                                  const DominatorTree *DT) {
1456   Value *Result;
1457
1458   switch (I->getOpcode()) {
1459   default:
1460     Result = ConstantFoldInstruction(I, TD);
1461     break;
1462   case Instruction::Add:
1463     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1464                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
1465                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1466                              TD, DT);
1467     break;
1468   case Instruction::Sub:
1469     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1470                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
1471                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1472                              TD, DT);
1473     break;
1474   case Instruction::Mul:
1475     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1476     break;
1477   case Instruction::Shl:
1478     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1), TD, DT);
1479     break;
1480   case Instruction::LShr:
1481     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1482     break;
1483   case Instruction::AShr:
1484     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1485     break;
1486   case Instruction::And:
1487     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1488     break;
1489   case Instruction::Or:
1490     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1491     break;
1492   case Instruction::Xor:
1493     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1494     break;
1495   case Instruction::ICmp:
1496     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1497                               I->getOperand(0), I->getOperand(1), TD, DT);
1498     break;
1499   case Instruction::FCmp:
1500     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1501                               I->getOperand(0), I->getOperand(1), TD, DT);
1502     break;
1503   case Instruction::Select:
1504     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1505                                 I->getOperand(2), TD, DT);
1506     break;
1507   case Instruction::GetElementPtr: {
1508     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1509     Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1510     break;
1511   }
1512   case Instruction::PHI:
1513     Result = SimplifyPHINode(cast<PHINode>(I), DT);
1514     break;
1515   }
1516
1517   /// If called on unreachable code, the above logic may report that the
1518   /// instruction simplified to itself.  Make life easier for users by
1519   /// detecting that case here, returning a safe value instead.
1520   return Result == I ? UndefValue::get(I->getType()) : Result;
1521 }
1522
1523 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1524 /// delete the From instruction.  In addition to a basic RAUW, this does a
1525 /// recursive simplification of the newly formed instructions.  This catches
1526 /// things where one simplification exposes other opportunities.  This only
1527 /// simplifies and deletes scalar operations, it does not change the CFG.
1528 ///
1529 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
1530                                      const TargetData *TD,
1531                                      const DominatorTree *DT) {
1532   assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
1533
1534   // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1535   // we can know if it gets deleted out from under us or replaced in a
1536   // recursive simplification.
1537   WeakVH FromHandle(From);
1538   WeakVH ToHandle(To);
1539
1540   while (!From->use_empty()) {
1541     // Update the instruction to use the new value.
1542     Use &TheUse = From->use_begin().getUse();
1543     Instruction *User = cast<Instruction>(TheUse.getUser());
1544     TheUse = To;
1545
1546     // Check to see if the instruction can be folded due to the operand
1547     // replacement.  For example changing (or X, Y) into (or X, -1) can replace
1548     // the 'or' with -1.
1549     Value *SimplifiedVal;
1550     {
1551       // Sanity check to make sure 'User' doesn't dangle across
1552       // SimplifyInstruction.
1553       AssertingVH<> UserHandle(User);
1554
1555       SimplifiedVal = SimplifyInstruction(User, TD, DT);
1556       if (SimplifiedVal == 0) continue;
1557     }
1558
1559     // Recursively simplify this user to the new value.
1560     ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
1561     From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1562     To = ToHandle;
1563
1564     assert(ToHandle && "To value deleted by recursive simplification?");
1565
1566     // If the recursive simplification ended up revisiting and deleting
1567     // 'From' then we're done.
1568     if (From == 0)
1569       return;
1570   }
1571
1572   // If 'From' has value handles referring to it, do a real RAUW to update them.
1573   From->replaceAllUsesWith(To);
1574
1575   From->eraseFromParent();
1576 }