InstructionSimplify.cpp revision 0b8c9a80f20772c3793201ab5b251d3520b9cea3
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/Analysis/InstructionSimplify.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/ConstantFolding.h"
26#include "llvm/Analysis/Dominators.h"
27#include "llvm/Analysis/ValueTracking.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/GlobalAlias.h"
30#include "llvm/IR/Operator.h"
31#include "llvm/Support/ConstantRange.h"
32#include "llvm/Support/GetElementPtrTypeIterator.h"
33#include "llvm/Support/PatternMatch.h"
34#include "llvm/Support/ValueHandle.h"
35using namespace llvm;
36using namespace llvm::PatternMatch;
37
38enum { RecursionLimit = 3 };
39
40STATISTIC(NumExpand,  "Number of expansions");
41STATISTIC(NumFactor , "Number of factorizations");
42STATISTIC(NumReassoc, "Number of reassociations");
43
44struct Query {
45  const DataLayout *TD;
46  const TargetLibraryInfo *TLI;
47  const DominatorTree *DT;
48
49  Query(const DataLayout *td, const TargetLibraryInfo *tli,
50        const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {}
51};
52
53static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
55                            unsigned);
56static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
57                              unsigned);
58static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
60static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
61
62/// getFalse - For a boolean type, or a vector of boolean type, return false, or
63/// a vector with every element false, as appropriate for the type.
64static Constant *getFalse(Type *Ty) {
65  assert(Ty->getScalarType()->isIntegerTy(1) &&
66         "Expected i1 type or a vector of i1!");
67  return Constant::getNullValue(Ty);
68}
69
70/// getTrue - For a boolean type, or a vector of boolean type, return true, or
71/// a vector with every element true, as appropriate for the type.
72static Constant *getTrue(Type *Ty) {
73  assert(Ty->getScalarType()->isIntegerTy(1) &&
74         "Expected i1 type or a vector of i1!");
75  return Constant::getAllOnesValue(Ty);
76}
77
78/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
80                          Value *RHS) {
81  CmpInst *Cmp = dyn_cast<CmpInst>(V);
82  if (!Cmp)
83    return false;
84  CmpInst::Predicate CPred = Cmp->getPredicate();
85  Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86  if (CPred == Pred && CLHS == LHS && CRHS == RHS)
87    return true;
88  return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89    CRHS == LHS;
90}
91
92/// ValueDominatesPHI - Does the given value dominate the specified phi node?
93static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94  Instruction *I = dyn_cast<Instruction>(V);
95  if (!I)
96    // Arguments and constants dominate all instructions.
97    return true;
98
99  // If we are processing instructions (and/or basic blocks) that have not been
100  // fully added to a function, the parent nodes may still be null. Simply
101  // return the conservative answer in these cases.
102  if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
103    return false;
104
105  // If we have a DominatorTree then do a precise test.
106  if (DT) {
107    if (!DT->isReachableFromEntry(P->getParent()))
108      return true;
109    if (!DT->isReachableFromEntry(I->getParent()))
110      return false;
111    return DT->dominates(I, P);
112  }
113
114  // Otherwise, if the instruction is in the entry block, and is not an invoke,
115  // then it obviously dominates all phi nodes.
116  if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
117      !isa<InvokeInst>(I))
118    return true;
119
120  return false;
121}
122
123/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124/// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
125/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127/// Returns the simplified value, or null if no simplification was performed.
128static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
129                          unsigned OpcToExpand, const Query &Q,
130                          unsigned MaxRecurse) {
131  Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
132  // Recursion is always used, so bail out at once if we already hit the limit.
133  if (!MaxRecurse--)
134    return 0;
135
136  // Check whether the expression has the form "(A op' B) op C".
137  if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138    if (Op0->getOpcode() == OpcodeToExpand) {
139      // It does!  Try turning it into "(A op C) op' (B op C)".
140      Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141      // Do "A op C" and "B op C" both simplify?
142      if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143        if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
144          // They do! Return "L op' R" if it simplifies or is already available.
145          // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
146          if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147                                     && L == B && R == A)) {
148            ++NumExpand;
149            return LHS;
150          }
151          // Otherwise return "L op' R" if it simplifies.
152          if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
153            ++NumExpand;
154            return V;
155          }
156        }
157    }
158
159  // Check whether the expression has the form "A op (B op' C)".
160  if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161    if (Op1->getOpcode() == OpcodeToExpand) {
162      // It does!  Try turning it into "(A op B) op' (A op C)".
163      Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164      // Do "A op B" and "A op C" both simplify?
165      if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166        if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
167          // They do! Return "L op' R" if it simplifies or is already available.
168          // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
169          if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170                                     && L == C && R == B)) {
171            ++NumExpand;
172            return RHS;
173          }
174          // Otherwise return "L op' R" if it simplifies.
175          if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
176            ++NumExpand;
177            return V;
178          }
179        }
180    }
181
182  return 0;
183}
184
185/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
186/// using the operation OpCodeToExtract.  For example, when Opcode is Add and
187/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
188/// Returns the simplified value, or null if no simplification was performed.
189static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
190                             unsigned OpcToExtract, const Query &Q,
191                             unsigned MaxRecurse) {
192  Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
193  // Recursion is always used, so bail out at once if we already hit the limit.
194  if (!MaxRecurse--)
195    return 0;
196
197  BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
198  BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
199
200  if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
201      !Op1 || Op1->getOpcode() != OpcodeToExtract)
202    return 0;
203
204  // The expression has the form "(A op' B) op (C op' D)".
205  Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
206  Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
207
208  // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
209  // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
210  // commutative case, "(A op' B) op (C op' A)"?
211  if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
212    Value *DD = A == C ? D : C;
213    // Form "A op' (B op DD)" if it simplifies completely.
214    // Does "B op DD" simplify?
215    if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
216      // It does!  Return "A op' V" if it simplifies or is already available.
217      // If V equals B then "A op' V" is just the LHS.  If V equals DD then
218      // "A op' V" is just the RHS.
219      if (V == B || V == DD) {
220        ++NumFactor;
221        return V == B ? LHS : RHS;
222      }
223      // Otherwise return "A op' V" if it simplifies.
224      if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
225        ++NumFactor;
226        return W;
227      }
228    }
229  }
230
231  // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
232  // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
233  // commutative case, "(A op' B) op (B op' D)"?
234  if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
235    Value *CC = B == D ? C : D;
236    // Form "(A op CC) op' B" if it simplifies completely..
237    // Does "A op CC" simplify?
238    if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
239      // It does!  Return "V op' B" if it simplifies or is already available.
240      // If V equals A then "V op' B" is just the LHS.  If V equals CC then
241      // "V op' B" is just the RHS.
242      if (V == A || V == CC) {
243        ++NumFactor;
244        return V == A ? LHS : RHS;
245      }
246      // Otherwise return "V op' B" if it simplifies.
247      if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
248        ++NumFactor;
249        return W;
250      }
251    }
252  }
253
254  return 0;
255}
256
257/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
258/// operations.  Returns the simpler value, or null if none was found.
259static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
260                                       const Query &Q, unsigned MaxRecurse) {
261  Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
262  assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
263
264  // Recursion is always used, so bail out at once if we already hit the limit.
265  if (!MaxRecurse--)
266    return 0;
267
268  BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
269  BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
270
271  // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
272  if (Op0 && Op0->getOpcode() == Opcode) {
273    Value *A = Op0->getOperand(0);
274    Value *B = Op0->getOperand(1);
275    Value *C = RHS;
276
277    // Does "B op C" simplify?
278    if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
279      // It does!  Return "A op V" if it simplifies or is already available.
280      // If V equals B then "A op V" is just the LHS.
281      if (V == B) return LHS;
282      // Otherwise return "A op V" if it simplifies.
283      if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
284        ++NumReassoc;
285        return W;
286      }
287    }
288  }
289
290  // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
291  if (Op1 && Op1->getOpcode() == Opcode) {
292    Value *A = LHS;
293    Value *B = Op1->getOperand(0);
294    Value *C = Op1->getOperand(1);
295
296    // Does "A op B" simplify?
297    if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
298      // It does!  Return "V op C" if it simplifies or is already available.
299      // If V equals B then "V op C" is just the RHS.
300      if (V == B) return RHS;
301      // Otherwise return "V op C" if it simplifies.
302      if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
303        ++NumReassoc;
304        return W;
305      }
306    }
307  }
308
309  // The remaining transforms require commutativity as well as associativity.
310  if (!Instruction::isCommutative(Opcode))
311    return 0;
312
313  // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
314  if (Op0 && Op0->getOpcode() == Opcode) {
315    Value *A = Op0->getOperand(0);
316    Value *B = Op0->getOperand(1);
317    Value *C = RHS;
318
319    // Does "C op A" simplify?
320    if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
321      // It does!  Return "V op B" if it simplifies or is already available.
322      // If V equals A then "V op B" is just the LHS.
323      if (V == A) return LHS;
324      // Otherwise return "V op B" if it simplifies.
325      if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
326        ++NumReassoc;
327        return W;
328      }
329    }
330  }
331
332  // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
333  if (Op1 && Op1->getOpcode() == Opcode) {
334    Value *A = LHS;
335    Value *B = Op1->getOperand(0);
336    Value *C = Op1->getOperand(1);
337
338    // Does "C op A" simplify?
339    if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
340      // It does!  Return "B op V" if it simplifies or is already available.
341      // If V equals C then "B op V" is just the RHS.
342      if (V == C) return RHS;
343      // Otherwise return "B op V" if it simplifies.
344      if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
345        ++NumReassoc;
346        return W;
347      }
348    }
349  }
350
351  return 0;
352}
353
354/// ThreadBinOpOverSelect - In the case of a binary operation with a select
355/// instruction as an operand, try to simplify the binop by seeing whether
356/// evaluating it on both branches of the select results in the same value.
357/// Returns the common value if so, otherwise returns null.
358static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
359                                    const Query &Q, unsigned MaxRecurse) {
360  // Recursion is always used, so bail out at once if we already hit the limit.
361  if (!MaxRecurse--)
362    return 0;
363
364  SelectInst *SI;
365  if (isa<SelectInst>(LHS)) {
366    SI = cast<SelectInst>(LHS);
367  } else {
368    assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369    SI = cast<SelectInst>(RHS);
370  }
371
372  // Evaluate the BinOp on the true and false branches of the select.
373  Value *TV;
374  Value *FV;
375  if (SI == LHS) {
376    TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
377    FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
378  } else {
379    TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
380    FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
381  }
382
383  // If they simplified to the same value, then return the common value.
384  // If they both failed to simplify then return null.
385  if (TV == FV)
386    return TV;
387
388  // If one branch simplified to undef, return the other one.
389  if (TV && isa<UndefValue>(TV))
390    return FV;
391  if (FV && isa<UndefValue>(FV))
392    return TV;
393
394  // If applying the operation did not change the true and false select values,
395  // then the result of the binop is the select itself.
396  if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
397    return SI;
398
399  // If one branch simplified and the other did not, and the simplified
400  // value is equal to the unsimplified one, return the simplified value.
401  // For example, select (cond, X, X & Z) & Z -> X & Z.
402  if ((FV && !TV) || (TV && !FV)) {
403    // Check that the simplified value has the form "X op Y" where "op" is the
404    // same as the original operation.
405    Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406    if (Simplified && Simplified->getOpcode() == Opcode) {
407      // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408      // We already know that "op" is the same as for the simplified value.  See
409      // if the operands match too.  If so, return the simplified value.
410      Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411      Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412      Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
413      if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414          Simplified->getOperand(1) == UnsimplifiedRHS)
415        return Simplified;
416      if (Simplified->isCommutative() &&
417          Simplified->getOperand(1) == UnsimplifiedLHS &&
418          Simplified->getOperand(0) == UnsimplifiedRHS)
419        return Simplified;
420    }
421  }
422
423  return 0;
424}
425
426/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427/// try to simplify the comparison by seeing whether both branches of the select
428/// result in the same value.  Returns the common value if so, otherwise returns
429/// null.
430static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
431                                  Value *RHS, const Query &Q,
432                                  unsigned MaxRecurse) {
433  // Recursion is always used, so bail out at once if we already hit the limit.
434  if (!MaxRecurse--)
435    return 0;
436
437  // Make sure the select is on the LHS.
438  if (!isa<SelectInst>(LHS)) {
439    std::swap(LHS, RHS);
440    Pred = CmpInst::getSwappedPredicate(Pred);
441  }
442  assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443  SelectInst *SI = cast<SelectInst>(LHS);
444  Value *Cond = SI->getCondition();
445  Value *TV = SI->getTrueValue();
446  Value *FV = SI->getFalseValue();
447
448  // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
449  // Does "cmp TV, RHS" simplify?
450  Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
451  if (TCmp == Cond) {
452    // It not only simplified, it simplified to the select condition.  Replace
453    // it with 'true'.
454    TCmp = getTrue(Cond->getType());
455  } else if (!TCmp) {
456    // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
457    // condition then we can replace it with 'true'.  Otherwise give up.
458    if (!isSameCompare(Cond, Pred, TV, RHS))
459      return 0;
460    TCmp = getTrue(Cond->getType());
461  }
462
463  // Does "cmp FV, RHS" simplify?
464  Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
465  if (FCmp == Cond) {
466    // It not only simplified, it simplified to the select condition.  Replace
467    // it with 'false'.
468    FCmp = getFalse(Cond->getType());
469  } else if (!FCmp) {
470    // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
471    // condition then we can replace it with 'false'.  Otherwise give up.
472    if (!isSameCompare(Cond, Pred, FV, RHS))
473      return 0;
474    FCmp = getFalse(Cond->getType());
475  }
476
477  // If both sides simplified to the same value, then use it as the result of
478  // the original comparison.
479  if (TCmp == FCmp)
480    return TCmp;
481
482  // The remaining cases only make sense if the select condition has the same
483  // type as the result of the comparison, so bail out if this is not so.
484  if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
485    return 0;
486  // If the false value simplified to false, then the result of the compare
487  // is equal to "Cond && TCmp".  This also catches the case when the false
488  // value simplified to false and the true value to true, returning "Cond".
489  if (match(FCmp, m_Zero()))
490    if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
491      return V;
492  // If the true value simplified to true, then the result of the compare
493  // is equal to "Cond || FCmp".
494  if (match(TCmp, m_One()))
495    if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
496      return V;
497  // Finally, if the false value simplified to true and the true value to
498  // false, then the result of the compare is equal to "!Cond".
499  if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
500    if (Value *V =
501        SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
502                        Q, MaxRecurse))
503      return V;
504
505  return 0;
506}
507
508/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510/// it on the incoming phi values yields the same result for every value.  If so
511/// returns the common value, otherwise returns null.
512static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
513                                 const Query &Q, unsigned MaxRecurse) {
514  // Recursion is always used, so bail out at once if we already hit the limit.
515  if (!MaxRecurse--)
516    return 0;
517
518  PHINode *PI;
519  if (isa<PHINode>(LHS)) {
520    PI = cast<PHINode>(LHS);
521    // Bail out if RHS and the phi may be mutually interdependent due to a loop.
522    if (!ValueDominatesPHI(RHS, PI, Q.DT))
523      return 0;
524  } else {
525    assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
526    PI = cast<PHINode>(RHS);
527    // Bail out if LHS and the phi may be mutually interdependent due to a loop.
528    if (!ValueDominatesPHI(LHS, PI, Q.DT))
529      return 0;
530  }
531
532  // Evaluate the BinOp on the incoming phi values.
533  Value *CommonValue = 0;
534  for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
535    Value *Incoming = PI->getIncomingValue(i);
536    // If the incoming value is the phi node itself, it can safely be skipped.
537    if (Incoming == PI) continue;
538    Value *V = PI == LHS ?
539      SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
540      SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
541    // If the operation failed to simplify, or simplified to a different value
542    // to previously, then give up.
543    if (!V || (CommonValue && V != CommonValue))
544      return 0;
545    CommonValue = V;
546  }
547
548  return CommonValue;
549}
550
551/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
552/// try to simplify the comparison by seeing whether comparing with all of the
553/// incoming phi values yields the same result every time.  If so returns the
554/// common result, otherwise returns null.
555static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
556                               const Query &Q, unsigned MaxRecurse) {
557  // Recursion is always used, so bail out at once if we already hit the limit.
558  if (!MaxRecurse--)
559    return 0;
560
561  // Make sure the phi is on the LHS.
562  if (!isa<PHINode>(LHS)) {
563    std::swap(LHS, RHS);
564    Pred = CmpInst::getSwappedPredicate(Pred);
565  }
566  assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
567  PHINode *PI = cast<PHINode>(LHS);
568
569  // Bail out if RHS and the phi may be mutually interdependent due to a loop.
570  if (!ValueDominatesPHI(RHS, PI, Q.DT))
571    return 0;
572
573  // Evaluate the BinOp on the incoming phi values.
574  Value *CommonValue = 0;
575  for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
576    Value *Incoming = PI->getIncomingValue(i);
577    // If the incoming value is the phi node itself, it can safely be skipped.
578    if (Incoming == PI) continue;
579    Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
580    // If the operation failed to simplify, or simplified to a different value
581    // to previously, then give up.
582    if (!V || (CommonValue && V != CommonValue))
583      return 0;
584    CommonValue = V;
585  }
586
587  return CommonValue;
588}
589
590/// SimplifyAddInst - Given operands for an Add, see if we can
591/// fold the result.  If not, this returns null.
592static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
593                              const Query &Q, unsigned MaxRecurse) {
594  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
595    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596      Constant *Ops[] = { CLHS, CRHS };
597      return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
598                                      Q.TD, Q.TLI);
599    }
600
601    // Canonicalize the constant to the RHS.
602    std::swap(Op0, Op1);
603  }
604
605  // X + undef -> undef
606  if (match(Op1, m_Undef()))
607    return Op1;
608
609  // X + 0 -> X
610  if (match(Op1, m_Zero()))
611    return Op0;
612
613  // X + (Y - X) -> Y
614  // (Y - X) + X -> Y
615  // Eg: X + -X -> 0
616  Value *Y = 0;
617  if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
618      match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
619    return Y;
620
621  // X + ~X -> -1   since   ~X = -X-1
622  if (match(Op0, m_Not(m_Specific(Op1))) ||
623      match(Op1, m_Not(m_Specific(Op0))))
624    return Constant::getAllOnesValue(Op0->getType());
625
626  /// i1 add -> xor.
627  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
628    if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
629      return V;
630
631  // Try some generic simplifications for associative operations.
632  if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
633                                          MaxRecurse))
634    return V;
635
636  // Mul distributes over Add.  Try some generic simplifications based on this.
637  if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
638                                Q, MaxRecurse))
639    return V;
640
641  // Threading Add over selects and phi nodes is pointless, so don't bother.
642  // Threading over the select in "A + select(cond, B, C)" means evaluating
643  // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
644  // only if B and C are equal.  If B and C are equal then (since we assume
645  // that operands have already been simplified) "select(cond, B, C)" should
646  // have been simplified to the common value of B and C already.  Analysing
647  // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
648  // for threading over phi nodes.
649
650  return 0;
651}
652
653Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
654                             const DataLayout *TD, const TargetLibraryInfo *TLI,
655                             const DominatorTree *DT) {
656  return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
657                           RecursionLimit);
658}
659
660/// \brief Compute the base pointer and cumulative constant offsets for V.
661///
662/// This strips all constant offsets off of V, leaving it the base pointer, and
663/// accumulates the total constant offset applied in the returned constant. It
664/// returns 0 if V is not a pointer, and returns the constant '0' if there are
665/// no constant offsets applied.
666static Constant *stripAndComputeConstantOffsets(const DataLayout &TD,
667                                                Value *&V) {
668  if (!V->getType()->isPointerTy())
669    return 0;
670
671  unsigned IntPtrWidth = TD.getPointerSizeInBits();
672  APInt Offset = APInt::getNullValue(IntPtrWidth);
673
674  // Even though we don't look through PHI nodes, we could be called on an
675  // instruction in an unreachable block, which may be on a cycle.
676  SmallPtrSet<Value *, 4> Visited;
677  Visited.insert(V);
678  do {
679    if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
680      if (!GEP->isInBounds() || !GEP->accumulateConstantOffset(TD, Offset))
681        break;
682      V = GEP->getPointerOperand();
683    } else if (Operator::getOpcode(V) == Instruction::BitCast) {
684      V = cast<Operator>(V)->getOperand(0);
685    } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
686      if (GA->mayBeOverridden())
687        break;
688      V = GA->getAliasee();
689    } else {
690      break;
691    }
692    assert(V->getType()->isPointerTy() && "Unexpected operand type!");
693  } while (Visited.insert(V));
694
695  Type *IntPtrTy = TD.getIntPtrType(V->getContext());
696  return ConstantInt::get(IntPtrTy, Offset);
697}
698
699/// \brief Compute the constant difference between two pointer values.
700/// If the difference is not a constant, returns zero.
701static Constant *computePointerDifference(const DataLayout &TD,
702                                          Value *LHS, Value *RHS) {
703  Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
704  if (!LHSOffset)
705    return 0;
706  Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
707  if (!RHSOffset)
708    return 0;
709
710  // If LHS and RHS are not related via constant offsets to the same base
711  // value, there is nothing we can do here.
712  if (LHS != RHS)
713    return 0;
714
715  // Otherwise, the difference of LHS - RHS can be computed as:
716  //    LHS - RHS
717  //  = (LHSOffset + Base) - (RHSOffset + Base)
718  //  = LHSOffset - RHSOffset
719  return ConstantExpr::getSub(LHSOffset, RHSOffset);
720}
721
722/// SimplifySubInst - Given operands for a Sub, see if we can
723/// fold the result.  If not, this returns null.
724static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
725                              const Query &Q, unsigned MaxRecurse) {
726  if (Constant *CLHS = dyn_cast<Constant>(Op0))
727    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
728      Constant *Ops[] = { CLHS, CRHS };
729      return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
730                                      Ops, Q.TD, Q.TLI);
731    }
732
733  // X - undef -> undef
734  // undef - X -> undef
735  if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
736    return UndefValue::get(Op0->getType());
737
738  // X - 0 -> X
739  if (match(Op1, m_Zero()))
740    return Op0;
741
742  // X - X -> 0
743  if (Op0 == Op1)
744    return Constant::getNullValue(Op0->getType());
745
746  // (X*2) - X -> X
747  // (X<<1) - X -> X
748  Value *X = 0;
749  if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
750      match(Op0, m_Shl(m_Specific(Op1), m_One())))
751    return Op1;
752
753  // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
754  // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
755  Value *Y = 0, *Z = Op1;
756  if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
757    // See if "V === Y - Z" simplifies.
758    if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
759      // It does!  Now see if "X + V" simplifies.
760      if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
761        // It does, we successfully reassociated!
762        ++NumReassoc;
763        return W;
764      }
765    // See if "V === X - Z" simplifies.
766    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
767      // It does!  Now see if "Y + V" simplifies.
768      if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
769        // It does, we successfully reassociated!
770        ++NumReassoc;
771        return W;
772      }
773  }
774
775  // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
776  // For example, X - (X + 1) -> -1
777  X = Op0;
778  if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
779    // See if "V === X - Y" simplifies.
780    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
781      // It does!  Now see if "V - Z" simplifies.
782      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
783        // It does, we successfully reassociated!
784        ++NumReassoc;
785        return W;
786      }
787    // See if "V === X - Z" simplifies.
788    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
789      // It does!  Now see if "V - Y" simplifies.
790      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
791        // It does, we successfully reassociated!
792        ++NumReassoc;
793        return W;
794      }
795  }
796
797  // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
798  // For example, X - (X - Y) -> Y.
799  Z = Op0;
800  if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
801    // See if "V === Z - X" simplifies.
802    if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
803      // It does!  Now see if "V + Y" simplifies.
804      if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
805        // It does, we successfully reassociated!
806        ++NumReassoc;
807        return W;
808      }
809
810  // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
811  if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
812      match(Op1, m_Trunc(m_Value(Y))))
813    if (X->getType() == Y->getType())
814      // See if "V === X - Y" simplifies.
815      if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
816        // It does!  Now see if "trunc V" simplifies.
817        if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
818          // It does, return the simplified "trunc V".
819          return W;
820
821  // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
822  if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
823      match(Op1, m_PtrToInt(m_Value(Y))))
824    if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
825      return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
826
827  // Mul distributes over Sub.  Try some generic simplifications based on this.
828  if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
829                                Q, MaxRecurse))
830    return V;
831
832  // i1 sub -> xor.
833  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
834    if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
835      return V;
836
837  // Threading Sub over selects and phi nodes is pointless, so don't bother.
838  // Threading over the select in "A - select(cond, B, C)" means evaluating
839  // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
840  // only if B and C are equal.  If B and C are equal then (since we assume
841  // that operands have already been simplified) "select(cond, B, C)" should
842  // have been simplified to the common value of B and C already.  Analysing
843  // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
844  // for threading over phi nodes.
845
846  return 0;
847}
848
849Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
850                             const DataLayout *TD, const TargetLibraryInfo *TLI,
851                             const DominatorTree *DT) {
852  return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
853                           RecursionLimit);
854}
855
856/// Given operands for an FAdd, see if we can fold the result.  If not, this
857/// returns null.
858static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
859                              const Query &Q, unsigned MaxRecurse) {
860  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
861    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
862      Constant *Ops[] = { CLHS, CRHS };
863      return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
864                                      Ops, Q.TD, Q.TLI);
865    }
866
867    // Canonicalize the constant to the RHS.
868    std::swap(Op0, Op1);
869  }
870
871  // fadd X, -0 ==> X
872  if (match(Op1, m_NegZero()))
873    return Op0;
874
875  // fadd X, 0 ==> X, when we know X is not -0
876  if (match(Op1, m_Zero()) &&
877      (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
878    return Op0;
879
880  // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
881  //   where nnan and ninf have to occur at least once somewhere in this
882  //   expression
883  Value *SubOp = 0;
884  if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
885    SubOp = Op1;
886  else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
887    SubOp = Op0;
888  if (SubOp) {
889    Instruction *FSub = cast<Instruction>(SubOp);
890    if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
891        (FMF.noInfs() || FSub->hasNoInfs()))
892      return Constant::getNullValue(Op0->getType());
893  }
894
895  return 0;
896}
897
898/// Given operands for an FSub, see if we can fold the result.  If not, this
899/// returns null.
900static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
901                              const Query &Q, unsigned MaxRecurse) {
902  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
903    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
904      Constant *Ops[] = { CLHS, CRHS };
905      return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
906                                      Ops, Q.TD, Q.TLI);
907    }
908  }
909
910  // fsub X, 0 ==> X
911  if (match(Op1, m_Zero()))
912    return Op0;
913
914  // fsub X, -0 ==> X, when we know X is not -0
915  if (match(Op1, m_NegZero()) &&
916      (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
917    return Op0;
918
919  // fsub 0, (fsub -0.0, X) ==> X
920  Value *X;
921  if (match(Op0, m_AnyZero())) {
922    if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
923      return X;
924    if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
925      return X;
926  }
927
928  // fsub nnan ninf x, x ==> 0.0
929  if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
930    return Constant::getNullValue(Op0->getType());
931
932  return 0;
933}
934
935/// Given the operands for an FMul, see if we can fold the result
936static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
937                               FastMathFlags FMF,
938                               const Query &Q,
939                               unsigned MaxRecurse) {
940 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
941    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
942      Constant *Ops[] = { CLHS, CRHS };
943      return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
944                                      Ops, Q.TD, Q.TLI);
945    }
946
947    // Canonicalize the constant to the RHS.
948    std::swap(Op0, Op1);
949 }
950
951 // fmul X, 1.0 ==> X
952 if (match(Op1, m_FPOne()))
953   return Op0;
954
955 // fmul nnan nsz X, 0 ==> 0
956 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
957   return Op1;
958
959 return 0;
960}
961
962/// SimplifyMulInst - Given operands for a Mul, see if we can
963/// fold the result.  If not, this returns null.
964static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
965                              unsigned MaxRecurse) {
966  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
967    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
968      Constant *Ops[] = { CLHS, CRHS };
969      return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
970                                      Ops, Q.TD, Q.TLI);
971    }
972
973    // Canonicalize the constant to the RHS.
974    std::swap(Op0, Op1);
975  }
976
977  // X * undef -> 0
978  if (match(Op1, m_Undef()))
979    return Constant::getNullValue(Op0->getType());
980
981  // X * 0 -> 0
982  if (match(Op1, m_Zero()))
983    return Op1;
984
985  // X * 1 -> X
986  if (match(Op1, m_One()))
987    return Op0;
988
989  // (X / Y) * Y -> X if the division is exact.
990  Value *X = 0;
991  if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
992      match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
993    return X;
994
995  // i1 mul -> and.
996  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
997    if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
998      return V;
999
1000  // Try some generic simplifications for associative operations.
1001  if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
1002                                          MaxRecurse))
1003    return V;
1004
1005  // Mul distributes over Add.  Try some generic simplifications based on this.
1006  if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
1007                             Q, MaxRecurse))
1008    return V;
1009
1010  // If the operation is with the result of a select instruction, check whether
1011  // operating on either branch of the select always yields the same value.
1012  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1013    if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
1014                                         MaxRecurse))
1015      return V;
1016
1017  // If the operation is with the result of a phi instruction, check whether
1018  // operating on all incoming values of the phi always yields the same value.
1019  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1020    if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
1021                                      MaxRecurse))
1022      return V;
1023
1024  return 0;
1025}
1026
1027Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1028                             const DataLayout *TD, const TargetLibraryInfo *TLI,
1029                             const DominatorTree *DT) {
1030  return ::SimplifyFAddInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1031}
1032
1033Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1034                             const DataLayout *TD, const TargetLibraryInfo *TLI,
1035                             const DominatorTree *DT) {
1036  return ::SimplifyFSubInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1037}
1038
1039Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1040                              FastMathFlags FMF,
1041                              const DataLayout *TD,
1042                              const TargetLibraryInfo *TLI,
1043                              const DominatorTree *DT) {
1044  return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1045}
1046
1047Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
1048                             const TargetLibraryInfo *TLI,
1049                             const DominatorTree *DT) {
1050  return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1051}
1052
1053/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1054/// fold the result.  If not, this returns null.
1055static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1056                          const Query &Q, unsigned MaxRecurse) {
1057  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1058    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1059      Constant *Ops[] = { C0, C1 };
1060      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1061    }
1062  }
1063
1064  bool isSigned = Opcode == Instruction::SDiv;
1065
1066  // X / undef -> undef
1067  if (match(Op1, m_Undef()))
1068    return Op1;
1069
1070  // undef / X -> 0
1071  if (match(Op0, m_Undef()))
1072    return Constant::getNullValue(Op0->getType());
1073
1074  // 0 / X -> 0, we don't need to preserve faults!
1075  if (match(Op0, m_Zero()))
1076    return Op0;
1077
1078  // X / 1 -> X
1079  if (match(Op1, m_One()))
1080    return Op0;
1081
1082  if (Op0->getType()->isIntegerTy(1))
1083    // It can't be division by zero, hence it must be division by one.
1084    return Op0;
1085
1086  // X / X -> 1
1087  if (Op0 == Op1)
1088    return ConstantInt::get(Op0->getType(), 1);
1089
1090  // (X * Y) / Y -> X if the multiplication does not overflow.
1091  Value *X = 0, *Y = 0;
1092  if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1093    if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1094    OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1095    // If the Mul knows it does not overflow, then we are good to go.
1096    if ((isSigned && Mul->hasNoSignedWrap()) ||
1097        (!isSigned && Mul->hasNoUnsignedWrap()))
1098      return X;
1099    // If X has the form X = A / Y then X * Y cannot overflow.
1100    if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1101      if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1102        return X;
1103  }
1104
1105  // (X rem Y) / Y -> 0
1106  if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1107      (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1108    return Constant::getNullValue(Op0->getType());
1109
1110  // If the operation is with the result of a select instruction, check whether
1111  // operating on either branch of the select always yields the same value.
1112  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1113    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1114      return V;
1115
1116  // If the operation is with the result of a phi instruction, check whether
1117  // operating on all incoming values of the phi always yields the same value.
1118  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1119    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1120      return V;
1121
1122  return 0;
1123}
1124
1125/// SimplifySDivInst - Given operands for an SDiv, see if we can
1126/// fold the result.  If not, this returns null.
1127static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1128                               unsigned MaxRecurse) {
1129  if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1130    return V;
1131
1132  return 0;
1133}
1134
1135Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1136                              const TargetLibraryInfo *TLI,
1137                              const DominatorTree *DT) {
1138  return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1139}
1140
1141/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1142/// fold the result.  If not, this returns null.
1143static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1144                               unsigned MaxRecurse) {
1145  if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1146    return V;
1147
1148  return 0;
1149}
1150
1151Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1152                              const TargetLibraryInfo *TLI,
1153                              const DominatorTree *DT) {
1154  return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1155}
1156
1157static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1158                               unsigned) {
1159  // undef / X -> undef    (the undef could be a snan).
1160  if (match(Op0, m_Undef()))
1161    return Op0;
1162
1163  // X / undef -> undef
1164  if (match(Op1, m_Undef()))
1165    return Op1;
1166
1167  return 0;
1168}
1169
1170Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1171                              const TargetLibraryInfo *TLI,
1172                              const DominatorTree *DT) {
1173  return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1174}
1175
1176/// SimplifyRem - Given operands for an SRem or URem, see if we can
1177/// fold the result.  If not, this returns null.
1178static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1179                          const Query &Q, unsigned MaxRecurse) {
1180  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1181    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1182      Constant *Ops[] = { C0, C1 };
1183      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1184    }
1185  }
1186
1187  // X % undef -> undef
1188  if (match(Op1, m_Undef()))
1189    return Op1;
1190
1191  // undef % X -> 0
1192  if (match(Op0, m_Undef()))
1193    return Constant::getNullValue(Op0->getType());
1194
1195  // 0 % X -> 0, we don't need to preserve faults!
1196  if (match(Op0, m_Zero()))
1197    return Op0;
1198
1199  // X % 0 -> undef, we don't need to preserve faults!
1200  if (match(Op1, m_Zero()))
1201    return UndefValue::get(Op0->getType());
1202
1203  // X % 1 -> 0
1204  if (match(Op1, m_One()))
1205    return Constant::getNullValue(Op0->getType());
1206
1207  if (Op0->getType()->isIntegerTy(1))
1208    // It can't be remainder by zero, hence it must be remainder by one.
1209    return Constant::getNullValue(Op0->getType());
1210
1211  // X % X -> 0
1212  if (Op0 == Op1)
1213    return Constant::getNullValue(Op0->getType());
1214
1215  // If the operation is with the result of a select instruction, check whether
1216  // operating on either branch of the select always yields the same value.
1217  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1218    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1219      return V;
1220
1221  // If the operation is with the result of a phi instruction, check whether
1222  // operating on all incoming values of the phi always yields the same value.
1223  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1224    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1225      return V;
1226
1227  return 0;
1228}
1229
1230/// SimplifySRemInst - Given operands for an SRem, see if we can
1231/// fold the result.  If not, this returns null.
1232static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1233                               unsigned MaxRecurse) {
1234  if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1235    return V;
1236
1237  return 0;
1238}
1239
1240Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1241                              const TargetLibraryInfo *TLI,
1242                              const DominatorTree *DT) {
1243  return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1244}
1245
1246/// SimplifyURemInst - Given operands for a URem, see if we can
1247/// fold the result.  If not, this returns null.
1248static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1249                               unsigned MaxRecurse) {
1250  if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1251    return V;
1252
1253  return 0;
1254}
1255
1256Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1257                              const TargetLibraryInfo *TLI,
1258                              const DominatorTree *DT) {
1259  return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1260}
1261
1262static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1263                               unsigned) {
1264  // undef % X -> undef    (the undef could be a snan).
1265  if (match(Op0, m_Undef()))
1266    return Op0;
1267
1268  // X % undef -> undef
1269  if (match(Op1, m_Undef()))
1270    return Op1;
1271
1272  return 0;
1273}
1274
1275Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1276                              const TargetLibraryInfo *TLI,
1277                              const DominatorTree *DT) {
1278  return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1279}
1280
1281/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1282/// fold the result.  If not, this returns null.
1283static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1284                            const Query &Q, unsigned MaxRecurse) {
1285  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1286    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1287      Constant *Ops[] = { C0, C1 };
1288      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1289    }
1290  }
1291
1292  // 0 shift by X -> 0
1293  if (match(Op0, m_Zero()))
1294    return Op0;
1295
1296  // X shift by 0 -> X
1297  if (match(Op1, m_Zero()))
1298    return Op0;
1299
1300  // X shift by undef -> undef because it may shift by the bitwidth.
1301  if (match(Op1, m_Undef()))
1302    return Op1;
1303
1304  // Shifting by the bitwidth or more is undefined.
1305  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1306    if (CI->getValue().getLimitedValue() >=
1307        Op0->getType()->getScalarSizeInBits())
1308      return UndefValue::get(Op0->getType());
1309
1310  // If the operation is with the result of a select instruction, check whether
1311  // operating on either branch of the select always yields the same value.
1312  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1313    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1314      return V;
1315
1316  // If the operation is with the result of a phi instruction, check whether
1317  // operating on all incoming values of the phi always yields the same value.
1318  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1319    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1320      return V;
1321
1322  return 0;
1323}
1324
1325/// SimplifyShlInst - Given operands for an Shl, see if we can
1326/// fold the result.  If not, this returns null.
1327static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1328                              const Query &Q, unsigned MaxRecurse) {
1329  if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1330    return V;
1331
1332  // undef << X -> 0
1333  if (match(Op0, m_Undef()))
1334    return Constant::getNullValue(Op0->getType());
1335
1336  // (X >> A) << A -> X
1337  Value *X;
1338  if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1339    return X;
1340  return 0;
1341}
1342
1343Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1344                             const DataLayout *TD, const TargetLibraryInfo *TLI,
1345                             const DominatorTree *DT) {
1346  return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1347                           RecursionLimit);
1348}
1349
1350/// SimplifyLShrInst - Given operands for an LShr, see if we can
1351/// fold the result.  If not, this returns null.
1352static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1353                               const Query &Q, unsigned MaxRecurse) {
1354  if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1355    return V;
1356
1357  // undef >>l X -> 0
1358  if (match(Op0, m_Undef()))
1359    return Constant::getNullValue(Op0->getType());
1360
1361  // (X << A) >> A -> X
1362  Value *X;
1363  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1364      cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1365    return X;
1366
1367  return 0;
1368}
1369
1370Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1371                              const DataLayout *TD,
1372                              const TargetLibraryInfo *TLI,
1373                              const DominatorTree *DT) {
1374  return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1375                            RecursionLimit);
1376}
1377
1378/// SimplifyAShrInst - Given operands for an AShr, see if we can
1379/// fold the result.  If not, this returns null.
1380static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1381                               const Query &Q, unsigned MaxRecurse) {
1382  if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1383    return V;
1384
1385  // all ones >>a X -> all ones
1386  if (match(Op0, m_AllOnes()))
1387    return Op0;
1388
1389  // undef >>a X -> all ones
1390  if (match(Op0, m_Undef()))
1391    return Constant::getAllOnesValue(Op0->getType());
1392
1393  // (X << A) >> A -> X
1394  Value *X;
1395  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1396      cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1397    return X;
1398
1399  return 0;
1400}
1401
1402Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1403                              const DataLayout *TD,
1404                              const TargetLibraryInfo *TLI,
1405                              const DominatorTree *DT) {
1406  return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1407                            RecursionLimit);
1408}
1409
1410/// SimplifyAndInst - Given operands for an And, see if we can
1411/// fold the result.  If not, this returns null.
1412static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1413                              unsigned MaxRecurse) {
1414  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1415    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1416      Constant *Ops[] = { CLHS, CRHS };
1417      return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1418                                      Ops, Q.TD, Q.TLI);
1419    }
1420
1421    // Canonicalize the constant to the RHS.
1422    std::swap(Op0, Op1);
1423  }
1424
1425  // X & undef -> 0
1426  if (match(Op1, m_Undef()))
1427    return Constant::getNullValue(Op0->getType());
1428
1429  // X & X = X
1430  if (Op0 == Op1)
1431    return Op0;
1432
1433  // X & 0 = 0
1434  if (match(Op1, m_Zero()))
1435    return Op1;
1436
1437  // X & -1 = X
1438  if (match(Op1, m_AllOnes()))
1439    return Op0;
1440
1441  // A & ~A  =  ~A & A  =  0
1442  if (match(Op0, m_Not(m_Specific(Op1))) ||
1443      match(Op1, m_Not(m_Specific(Op0))))
1444    return Constant::getNullValue(Op0->getType());
1445
1446  // (A | ?) & A = A
1447  Value *A = 0, *B = 0;
1448  if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1449      (A == Op1 || B == Op1))
1450    return Op1;
1451
1452  // A & (A | ?) = A
1453  if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1454      (A == Op0 || B == Op0))
1455    return Op0;
1456
1457  // A & (-A) = A if A is a power of two or zero.
1458  if (match(Op0, m_Neg(m_Specific(Op1))) ||
1459      match(Op1, m_Neg(m_Specific(Op0)))) {
1460    if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
1461      return Op0;
1462    if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
1463      return Op1;
1464  }
1465
1466  // Try some generic simplifications for associative operations.
1467  if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1468                                          MaxRecurse))
1469    return V;
1470
1471  // And distributes over Or.  Try some generic simplifications based on this.
1472  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1473                             Q, MaxRecurse))
1474    return V;
1475
1476  // And distributes over Xor.  Try some generic simplifications based on this.
1477  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1478                             Q, MaxRecurse))
1479    return V;
1480
1481  // Or distributes over And.  Try some generic simplifications based on this.
1482  if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1483                                Q, MaxRecurse))
1484    return V;
1485
1486  // If the operation is with the result of a select instruction, check whether
1487  // operating on either branch of the select always yields the same value.
1488  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1489    if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1490                                         MaxRecurse))
1491      return V;
1492
1493  // If the operation is with the result of a phi instruction, check whether
1494  // operating on all incoming values of the phi always yields the same value.
1495  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1496    if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1497                                      MaxRecurse))
1498      return V;
1499
1500  return 0;
1501}
1502
1503Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
1504                             const TargetLibraryInfo *TLI,
1505                             const DominatorTree *DT) {
1506  return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1507}
1508
1509/// SimplifyOrInst - Given operands for an Or, see if we can
1510/// fold the result.  If not, this returns null.
1511static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1512                             unsigned MaxRecurse) {
1513  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1514    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1515      Constant *Ops[] = { CLHS, CRHS };
1516      return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1517                                      Ops, Q.TD, Q.TLI);
1518    }
1519
1520    // Canonicalize the constant to the RHS.
1521    std::swap(Op0, Op1);
1522  }
1523
1524  // X | undef -> -1
1525  if (match(Op1, m_Undef()))
1526    return Constant::getAllOnesValue(Op0->getType());
1527
1528  // X | X = X
1529  if (Op0 == Op1)
1530    return Op0;
1531
1532  // X | 0 = X
1533  if (match(Op1, m_Zero()))
1534    return Op0;
1535
1536  // X | -1 = -1
1537  if (match(Op1, m_AllOnes()))
1538    return Op1;
1539
1540  // A | ~A  =  ~A | A  =  -1
1541  if (match(Op0, m_Not(m_Specific(Op1))) ||
1542      match(Op1, m_Not(m_Specific(Op0))))
1543    return Constant::getAllOnesValue(Op0->getType());
1544
1545  // (A & ?) | A = A
1546  Value *A = 0, *B = 0;
1547  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1548      (A == Op1 || B == Op1))
1549    return Op1;
1550
1551  // A | (A & ?) = A
1552  if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1553      (A == Op0 || B == Op0))
1554    return Op0;
1555
1556  // ~(A & ?) | A = -1
1557  if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1558      (A == Op1 || B == Op1))
1559    return Constant::getAllOnesValue(Op1->getType());
1560
1561  // A | ~(A & ?) = -1
1562  if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1563      (A == Op0 || B == Op0))
1564    return Constant::getAllOnesValue(Op0->getType());
1565
1566  // Try some generic simplifications for associative operations.
1567  if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1568                                          MaxRecurse))
1569    return V;
1570
1571  // Or distributes over And.  Try some generic simplifications based on this.
1572  if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1573                             MaxRecurse))
1574    return V;
1575
1576  // And distributes over Or.  Try some generic simplifications based on this.
1577  if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1578                                Q, MaxRecurse))
1579    return V;
1580
1581  // If the operation is with the result of a select instruction, check whether
1582  // operating on either branch of the select always yields the same value.
1583  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1584    if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1585                                         MaxRecurse))
1586      return V;
1587
1588  // If the operation is with the result of a phi instruction, check whether
1589  // operating on all incoming values of the phi always yields the same value.
1590  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1591    if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1592      return V;
1593
1594  return 0;
1595}
1596
1597Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
1598                            const TargetLibraryInfo *TLI,
1599                            const DominatorTree *DT) {
1600  return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1601}
1602
1603/// SimplifyXorInst - Given operands for a Xor, see if we can
1604/// fold the result.  If not, this returns null.
1605static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1606                              unsigned MaxRecurse) {
1607  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1608    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1609      Constant *Ops[] = { CLHS, CRHS };
1610      return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1611                                      Ops, Q.TD, Q.TLI);
1612    }
1613
1614    // Canonicalize the constant to the RHS.
1615    std::swap(Op0, Op1);
1616  }
1617
1618  // A ^ undef -> undef
1619  if (match(Op1, m_Undef()))
1620    return Op1;
1621
1622  // A ^ 0 = A
1623  if (match(Op1, m_Zero()))
1624    return Op0;
1625
1626  // A ^ A = 0
1627  if (Op0 == Op1)
1628    return Constant::getNullValue(Op0->getType());
1629
1630  // A ^ ~A  =  ~A ^ A  =  -1
1631  if (match(Op0, m_Not(m_Specific(Op1))) ||
1632      match(Op1, m_Not(m_Specific(Op0))))
1633    return Constant::getAllOnesValue(Op0->getType());
1634
1635  // Try some generic simplifications for associative operations.
1636  if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1637                                          MaxRecurse))
1638    return V;
1639
1640  // And distributes over Xor.  Try some generic simplifications based on this.
1641  if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1642                                Q, MaxRecurse))
1643    return V;
1644
1645  // Threading Xor over selects and phi nodes is pointless, so don't bother.
1646  // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1647  // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1648  // only if B and C are equal.  If B and C are equal then (since we assume
1649  // that operands have already been simplified) "select(cond, B, C)" should
1650  // have been simplified to the common value of B and C already.  Analysing
1651  // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1652  // for threading over phi nodes.
1653
1654  return 0;
1655}
1656
1657Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
1658                             const TargetLibraryInfo *TLI,
1659                             const DominatorTree *DT) {
1660  return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1661}
1662
1663static Type *GetCompareTy(Value *Op) {
1664  return CmpInst::makeCmpResultType(Op->getType());
1665}
1666
1667/// ExtractEquivalentCondition - Rummage around inside V looking for something
1668/// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1669/// otherwise return null.  Helper function for analyzing max/min idioms.
1670static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1671                                         Value *LHS, Value *RHS) {
1672  SelectInst *SI = dyn_cast<SelectInst>(V);
1673  if (!SI)
1674    return 0;
1675  CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1676  if (!Cmp)
1677    return 0;
1678  Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1679  if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1680    return Cmp;
1681  if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1682      LHS == CmpRHS && RHS == CmpLHS)
1683    return Cmp;
1684  return 0;
1685}
1686
1687static Constant *computePointerICmp(const DataLayout &TD,
1688                                    CmpInst::Predicate Pred,
1689                                    Value *LHS, Value *RHS) {
1690  // We can only fold certain predicates on pointer comparisons.
1691  switch (Pred) {
1692  default:
1693    return 0;
1694
1695    // Equality comaprisons are easy to fold.
1696  case CmpInst::ICMP_EQ:
1697  case CmpInst::ICMP_NE:
1698    break;
1699
1700    // We can only handle unsigned relational comparisons because 'inbounds' on
1701    // a GEP only protects against unsigned wrapping.
1702  case CmpInst::ICMP_UGT:
1703  case CmpInst::ICMP_UGE:
1704  case CmpInst::ICMP_ULT:
1705  case CmpInst::ICMP_ULE:
1706    // However, we have to switch them to their signed variants to handle
1707    // negative indices from the base pointer.
1708    Pred = ICmpInst::getSignedPredicate(Pred);
1709    break;
1710  }
1711
1712  Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
1713  if (!LHSOffset)
1714    return 0;
1715  Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
1716  if (!RHSOffset)
1717    return 0;
1718
1719  // If LHS and RHS are not related via constant offsets to the same base
1720  // value, there is nothing we can do here.
1721  if (LHS != RHS)
1722    return 0;
1723
1724  return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1725}
1726
1727/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1728/// fold the result.  If not, this returns null.
1729static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1730                               const Query &Q, unsigned MaxRecurse) {
1731  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1732  assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1733
1734  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1735    if (Constant *CRHS = dyn_cast<Constant>(RHS))
1736      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
1737
1738    // If we have a constant, make sure it is on the RHS.
1739    std::swap(LHS, RHS);
1740    Pred = CmpInst::getSwappedPredicate(Pred);
1741  }
1742
1743  Type *ITy = GetCompareTy(LHS); // The return type.
1744  Type *OpTy = LHS->getType();   // The operand type.
1745
1746  // icmp X, X -> true/false
1747  // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1748  // because X could be 0.
1749  if (LHS == RHS || isa<UndefValue>(RHS))
1750    return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1751
1752  // Special case logic when the operands have i1 type.
1753  if (OpTy->getScalarType()->isIntegerTy(1)) {
1754    switch (Pred) {
1755    default: break;
1756    case ICmpInst::ICMP_EQ:
1757      // X == 1 -> X
1758      if (match(RHS, m_One()))
1759        return LHS;
1760      break;
1761    case ICmpInst::ICMP_NE:
1762      // X != 0 -> X
1763      if (match(RHS, m_Zero()))
1764        return LHS;
1765      break;
1766    case ICmpInst::ICMP_UGT:
1767      // X >u 0 -> X
1768      if (match(RHS, m_Zero()))
1769        return LHS;
1770      break;
1771    case ICmpInst::ICMP_UGE:
1772      // X >=u 1 -> X
1773      if (match(RHS, m_One()))
1774        return LHS;
1775      break;
1776    case ICmpInst::ICMP_SLT:
1777      // X <s 0 -> X
1778      if (match(RHS, m_Zero()))
1779        return LHS;
1780      break;
1781    case ICmpInst::ICMP_SLE:
1782      // X <=s -1 -> X
1783      if (match(RHS, m_One()))
1784        return LHS;
1785      break;
1786    }
1787  }
1788
1789  // icmp <object*>, <object*/null> - Different identified objects have
1790  // different addresses (unless null), and what's more the address of an
1791  // identified local is never equal to another argument (again, barring null).
1792  // Note that generalizing to the case where LHS is a global variable address
1793  // or null is pointless, since if both LHS and RHS are constants then we
1794  // already constant folded the compare, and if only one of them is then we
1795  // moved it to RHS already.
1796  Value *LHSPtr = LHS->stripPointerCasts();
1797  Value *RHSPtr = RHS->stripPointerCasts();
1798  if (LHSPtr == RHSPtr)
1799    return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1800
1801  // Be more aggressive about stripping pointer adjustments when checking a
1802  // comparison of an alloca address to another object.  We can rip off all
1803  // inbounds GEP operations, even if they are variable.
1804  LHSPtr = LHSPtr->stripInBoundsOffsets();
1805  if (llvm::isIdentifiedObject(LHSPtr)) {
1806    RHSPtr = RHSPtr->stripInBoundsOffsets();
1807    if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1808      // If both sides are different identified objects, they aren't equal
1809      // unless they're null.
1810      if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
1811          Pred == CmpInst::ICMP_EQ)
1812        return ConstantInt::get(ITy, false);
1813
1814      // A local identified object (alloca or noalias call) can't equal any
1815      // incoming argument, unless they're both null or they belong to
1816      // different functions. The latter happens during inlining.
1817      if (Instruction *LHSInst = dyn_cast<Instruction>(LHSPtr))
1818        if (Argument *RHSArg = dyn_cast<Argument>(RHSPtr))
1819          if (LHSInst->getParent()->getParent() == RHSArg->getParent() &&
1820              Pred == CmpInst::ICMP_EQ)
1821            return ConstantInt::get(ITy, false);
1822    }
1823
1824    // Assume that the constant null is on the right.
1825    if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
1826      if (Pred == CmpInst::ICMP_EQ)
1827        return ConstantInt::get(ITy, false);
1828      else if (Pred == CmpInst::ICMP_NE)
1829        return ConstantInt::get(ITy, true);
1830    }
1831  } else if (Argument *LHSArg = dyn_cast<Argument>(LHSPtr)) {
1832    RHSPtr = RHSPtr->stripInBoundsOffsets();
1833    // An alloca can't be equal to an argument unless they come from separate
1834    // functions via inlining.
1835    if (AllocaInst *RHSInst = dyn_cast<AllocaInst>(RHSPtr)) {
1836      if (LHSArg->getParent() == RHSInst->getParent()->getParent()) {
1837        if (Pred == CmpInst::ICMP_EQ)
1838          return ConstantInt::get(ITy, false);
1839        else if (Pred == CmpInst::ICMP_NE)
1840          return ConstantInt::get(ITy, true);
1841      }
1842    }
1843  }
1844
1845  // If we are comparing with zero then try hard since this is a common case.
1846  if (match(RHS, m_Zero())) {
1847    bool LHSKnownNonNegative, LHSKnownNegative;
1848    switch (Pred) {
1849    default: llvm_unreachable("Unknown ICmp predicate!");
1850    case ICmpInst::ICMP_ULT:
1851      return getFalse(ITy);
1852    case ICmpInst::ICMP_UGE:
1853      return getTrue(ITy);
1854    case ICmpInst::ICMP_EQ:
1855    case ICmpInst::ICMP_ULE:
1856      if (isKnownNonZero(LHS, Q.TD))
1857        return getFalse(ITy);
1858      break;
1859    case ICmpInst::ICMP_NE:
1860    case ICmpInst::ICMP_UGT:
1861      if (isKnownNonZero(LHS, Q.TD))
1862        return getTrue(ITy);
1863      break;
1864    case ICmpInst::ICMP_SLT:
1865      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1866      if (LHSKnownNegative)
1867        return getTrue(ITy);
1868      if (LHSKnownNonNegative)
1869        return getFalse(ITy);
1870      break;
1871    case ICmpInst::ICMP_SLE:
1872      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1873      if (LHSKnownNegative)
1874        return getTrue(ITy);
1875      if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1876        return getFalse(ITy);
1877      break;
1878    case ICmpInst::ICMP_SGE:
1879      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1880      if (LHSKnownNegative)
1881        return getFalse(ITy);
1882      if (LHSKnownNonNegative)
1883        return getTrue(ITy);
1884      break;
1885    case ICmpInst::ICMP_SGT:
1886      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1887      if (LHSKnownNegative)
1888        return getFalse(ITy);
1889      if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1890        return getTrue(ITy);
1891      break;
1892    }
1893  }
1894
1895  // See if we are doing a comparison with a constant integer.
1896  if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1897    // Rule out tautological comparisons (eg., ult 0 or uge 0).
1898    ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1899    if (RHS_CR.isEmptySet())
1900      return ConstantInt::getFalse(CI->getContext());
1901    if (RHS_CR.isFullSet())
1902      return ConstantInt::getTrue(CI->getContext());
1903
1904    // Many binary operators with constant RHS have easy to compute constant
1905    // range.  Use them to check whether the comparison is a tautology.
1906    uint32_t Width = CI->getBitWidth();
1907    APInt Lower = APInt(Width, 0);
1908    APInt Upper = APInt(Width, 0);
1909    ConstantInt *CI2;
1910    if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1911      // 'urem x, CI2' produces [0, CI2).
1912      Upper = CI2->getValue();
1913    } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1914      // 'srem x, CI2' produces (-|CI2|, |CI2|).
1915      Upper = CI2->getValue().abs();
1916      Lower = (-Upper) + 1;
1917    } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1918      // 'udiv CI2, x' produces [0, CI2].
1919      Upper = CI2->getValue() + 1;
1920    } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1921      // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1922      APInt NegOne = APInt::getAllOnesValue(Width);
1923      if (!CI2->isZero())
1924        Upper = NegOne.udiv(CI2->getValue()) + 1;
1925    } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1926      // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1927      APInt IntMin = APInt::getSignedMinValue(Width);
1928      APInt IntMax = APInt::getSignedMaxValue(Width);
1929      APInt Val = CI2->getValue().abs();
1930      if (!Val.isMinValue()) {
1931        Lower = IntMin.sdiv(Val);
1932        Upper = IntMax.sdiv(Val) + 1;
1933      }
1934    } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1935      // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1936      APInt NegOne = APInt::getAllOnesValue(Width);
1937      if (CI2->getValue().ult(Width))
1938        Upper = NegOne.lshr(CI2->getValue()) + 1;
1939    } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1940      // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1941      APInt IntMin = APInt::getSignedMinValue(Width);
1942      APInt IntMax = APInt::getSignedMaxValue(Width);
1943      if (CI2->getValue().ult(Width)) {
1944        Lower = IntMin.ashr(CI2->getValue());
1945        Upper = IntMax.ashr(CI2->getValue()) + 1;
1946      }
1947    } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1948      // 'or x, CI2' produces [CI2, UINT_MAX].
1949      Lower = CI2->getValue();
1950    } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1951      // 'and x, CI2' produces [0, CI2].
1952      Upper = CI2->getValue() + 1;
1953    }
1954    if (Lower != Upper) {
1955      ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1956      if (RHS_CR.contains(LHS_CR))
1957        return ConstantInt::getTrue(RHS->getContext());
1958      if (RHS_CR.inverse().contains(LHS_CR))
1959        return ConstantInt::getFalse(RHS->getContext());
1960    }
1961  }
1962
1963  // Compare of cast, for example (zext X) != 0 -> X != 0
1964  if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1965    Instruction *LI = cast<CastInst>(LHS);
1966    Value *SrcOp = LI->getOperand(0);
1967    Type *SrcTy = SrcOp->getType();
1968    Type *DstTy = LI->getType();
1969
1970    // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1971    // if the integer type is the same size as the pointer type.
1972    if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
1973        Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1974      if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1975        // Transfer the cast to the constant.
1976        if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1977                                        ConstantExpr::getIntToPtr(RHSC, SrcTy),
1978                                        Q, MaxRecurse-1))
1979          return V;
1980      } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1981        if (RI->getOperand(0)->getType() == SrcTy)
1982          // Compare without the cast.
1983          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1984                                          Q, MaxRecurse-1))
1985            return V;
1986      }
1987    }
1988
1989    if (isa<ZExtInst>(LHS)) {
1990      // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1991      // same type.
1992      if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1993        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1994          // Compare X and Y.  Note that signed predicates become unsigned.
1995          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1996                                          SrcOp, RI->getOperand(0), Q,
1997                                          MaxRecurse-1))
1998            return V;
1999      }
2000      // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2001      // too.  If not, then try to deduce the result of the comparison.
2002      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2003        // Compute the constant that would happen if we truncated to SrcTy then
2004        // reextended to DstTy.
2005        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2006        Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2007
2008        // If the re-extended constant didn't change then this is effectively
2009        // also a case of comparing two zero-extended values.
2010        if (RExt == CI && MaxRecurse)
2011          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2012                                        SrcOp, Trunc, Q, MaxRecurse-1))
2013            return V;
2014
2015        // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2016        // there.  Use this to work out the result of the comparison.
2017        if (RExt != CI) {
2018          switch (Pred) {
2019          default: llvm_unreachable("Unknown ICmp predicate!");
2020          // LHS <u RHS.
2021          case ICmpInst::ICMP_EQ:
2022          case ICmpInst::ICMP_UGT:
2023          case ICmpInst::ICMP_UGE:
2024            return ConstantInt::getFalse(CI->getContext());
2025
2026          case ICmpInst::ICMP_NE:
2027          case ICmpInst::ICMP_ULT:
2028          case ICmpInst::ICMP_ULE:
2029            return ConstantInt::getTrue(CI->getContext());
2030
2031          // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2032          // is non-negative then LHS <s RHS.
2033          case ICmpInst::ICMP_SGT:
2034          case ICmpInst::ICMP_SGE:
2035            return CI->getValue().isNegative() ?
2036              ConstantInt::getTrue(CI->getContext()) :
2037              ConstantInt::getFalse(CI->getContext());
2038
2039          case ICmpInst::ICMP_SLT:
2040          case ICmpInst::ICMP_SLE:
2041            return CI->getValue().isNegative() ?
2042              ConstantInt::getFalse(CI->getContext()) :
2043              ConstantInt::getTrue(CI->getContext());
2044          }
2045        }
2046      }
2047    }
2048
2049    if (isa<SExtInst>(LHS)) {
2050      // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2051      // same type.
2052      if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2053        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2054          // Compare X and Y.  Note that the predicate does not change.
2055          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2056                                          Q, MaxRecurse-1))
2057            return V;
2058      }
2059      // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2060      // too.  If not, then try to deduce the result of the comparison.
2061      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2062        // Compute the constant that would happen if we truncated to SrcTy then
2063        // reextended to DstTy.
2064        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2065        Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2066
2067        // If the re-extended constant didn't change then this is effectively
2068        // also a case of comparing two sign-extended values.
2069        if (RExt == CI && MaxRecurse)
2070          if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2071            return V;
2072
2073        // Otherwise the upper bits of LHS are all equal, while RHS has varying
2074        // bits there.  Use this to work out the result of the comparison.
2075        if (RExt != CI) {
2076          switch (Pred) {
2077          default: llvm_unreachable("Unknown ICmp predicate!");
2078          case ICmpInst::ICMP_EQ:
2079            return ConstantInt::getFalse(CI->getContext());
2080          case ICmpInst::ICMP_NE:
2081            return ConstantInt::getTrue(CI->getContext());
2082
2083          // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2084          // LHS >s RHS.
2085          case ICmpInst::ICMP_SGT:
2086          case ICmpInst::ICMP_SGE:
2087            return CI->getValue().isNegative() ?
2088              ConstantInt::getTrue(CI->getContext()) :
2089              ConstantInt::getFalse(CI->getContext());
2090          case ICmpInst::ICMP_SLT:
2091          case ICmpInst::ICMP_SLE:
2092            return CI->getValue().isNegative() ?
2093              ConstantInt::getFalse(CI->getContext()) :
2094              ConstantInt::getTrue(CI->getContext());
2095
2096          // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2097          // LHS >u RHS.
2098          case ICmpInst::ICMP_UGT:
2099          case ICmpInst::ICMP_UGE:
2100            // Comparison is true iff the LHS <s 0.
2101            if (MaxRecurse)
2102              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2103                                              Constant::getNullValue(SrcTy),
2104                                              Q, MaxRecurse-1))
2105                return V;
2106            break;
2107          case ICmpInst::ICMP_ULT:
2108          case ICmpInst::ICMP_ULE:
2109            // Comparison is true iff the LHS >=s 0.
2110            if (MaxRecurse)
2111              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2112                                              Constant::getNullValue(SrcTy),
2113                                              Q, MaxRecurse-1))
2114                return V;
2115            break;
2116          }
2117        }
2118      }
2119    }
2120  }
2121
2122  // Special logic for binary operators.
2123  BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2124  BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2125  if (MaxRecurse && (LBO || RBO)) {
2126    // Analyze the case when either LHS or RHS is an add instruction.
2127    Value *A = 0, *B = 0, *C = 0, *D = 0;
2128    // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2129    bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2130    if (LBO && LBO->getOpcode() == Instruction::Add) {
2131      A = LBO->getOperand(0); B = LBO->getOperand(1);
2132      NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2133        (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2134        (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2135    }
2136    if (RBO && RBO->getOpcode() == Instruction::Add) {
2137      C = RBO->getOperand(0); D = RBO->getOperand(1);
2138      NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2139        (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2140        (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2141    }
2142
2143    // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2144    if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2145      if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2146                                      Constant::getNullValue(RHS->getType()),
2147                                      Q, MaxRecurse-1))
2148        return V;
2149
2150    // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2151    if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2152      if (Value *V = SimplifyICmpInst(Pred,
2153                                      Constant::getNullValue(LHS->getType()),
2154                                      C == LHS ? D : C, Q, MaxRecurse-1))
2155        return V;
2156
2157    // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2158    if (A && C && (A == C || A == D || B == C || B == D) &&
2159        NoLHSWrapProblem && NoRHSWrapProblem) {
2160      // Determine Y and Z in the form icmp (X+Y), (X+Z).
2161      Value *Y, *Z;
2162      if (A == C) {
2163        // C + B == C + D  ->  B == D
2164        Y = B;
2165        Z = D;
2166      } else if (A == D) {
2167        // D + B == C + D  ->  B == C
2168        Y = B;
2169        Z = C;
2170      } else if (B == C) {
2171        // A + C == C + D  ->  A == D
2172        Y = A;
2173        Z = D;
2174      } else {
2175        assert(B == D);
2176        // A + D == C + D  ->  A == C
2177        Y = A;
2178        Z = C;
2179      }
2180      if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2181        return V;
2182    }
2183  }
2184
2185  if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2186    bool KnownNonNegative, KnownNegative;
2187    switch (Pred) {
2188    default:
2189      break;
2190    case ICmpInst::ICMP_SGT:
2191    case ICmpInst::ICMP_SGE:
2192      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2193      if (!KnownNonNegative)
2194        break;
2195      // fall-through
2196    case ICmpInst::ICMP_EQ:
2197    case ICmpInst::ICMP_UGT:
2198    case ICmpInst::ICMP_UGE:
2199      return getFalse(ITy);
2200    case ICmpInst::ICMP_SLT:
2201    case ICmpInst::ICMP_SLE:
2202      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2203      if (!KnownNonNegative)
2204        break;
2205      // fall-through
2206    case ICmpInst::ICMP_NE:
2207    case ICmpInst::ICMP_ULT:
2208    case ICmpInst::ICMP_ULE:
2209      return getTrue(ITy);
2210    }
2211  }
2212  if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2213    bool KnownNonNegative, KnownNegative;
2214    switch (Pred) {
2215    default:
2216      break;
2217    case ICmpInst::ICMP_SGT:
2218    case ICmpInst::ICMP_SGE:
2219      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2220      if (!KnownNonNegative)
2221        break;
2222      // fall-through
2223    case ICmpInst::ICMP_NE:
2224    case ICmpInst::ICMP_UGT:
2225    case ICmpInst::ICMP_UGE:
2226      return getTrue(ITy);
2227    case ICmpInst::ICMP_SLT:
2228    case ICmpInst::ICMP_SLE:
2229      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2230      if (!KnownNonNegative)
2231        break;
2232      // fall-through
2233    case ICmpInst::ICMP_EQ:
2234    case ICmpInst::ICMP_ULT:
2235    case ICmpInst::ICMP_ULE:
2236      return getFalse(ITy);
2237    }
2238  }
2239
2240  // x udiv y <=u x.
2241  if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2242    // icmp pred (X /u Y), X
2243    if (Pred == ICmpInst::ICMP_UGT)
2244      return getFalse(ITy);
2245    if (Pred == ICmpInst::ICMP_ULE)
2246      return getTrue(ITy);
2247  }
2248
2249  if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2250      LBO->getOperand(1) == RBO->getOperand(1)) {
2251    switch (LBO->getOpcode()) {
2252    default: break;
2253    case Instruction::UDiv:
2254    case Instruction::LShr:
2255      if (ICmpInst::isSigned(Pred))
2256        break;
2257      // fall-through
2258    case Instruction::SDiv:
2259    case Instruction::AShr:
2260      if (!LBO->isExact() || !RBO->isExact())
2261        break;
2262      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2263                                      RBO->getOperand(0), Q, MaxRecurse-1))
2264        return V;
2265      break;
2266    case Instruction::Shl: {
2267      bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2268      bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2269      if (!NUW && !NSW)
2270        break;
2271      if (!NSW && ICmpInst::isSigned(Pred))
2272        break;
2273      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2274                                      RBO->getOperand(0), Q, MaxRecurse-1))
2275        return V;
2276      break;
2277    }
2278    }
2279  }
2280
2281  // Simplify comparisons involving max/min.
2282  Value *A, *B;
2283  CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2284  CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2285
2286  // Signed variants on "max(a,b)>=a -> true".
2287  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2288    if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2289    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2290    // We analyze this as smax(A, B) pred A.
2291    P = Pred;
2292  } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2293             (A == LHS || B == LHS)) {
2294    if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2295    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2296    // We analyze this as smax(A, B) swapped-pred A.
2297    P = CmpInst::getSwappedPredicate(Pred);
2298  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2299             (A == RHS || B == RHS)) {
2300    if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2301    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2302    // We analyze this as smax(-A, -B) swapped-pred -A.
2303    // Note that we do not need to actually form -A or -B thanks to EqP.
2304    P = CmpInst::getSwappedPredicate(Pred);
2305  } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2306             (A == LHS || B == LHS)) {
2307    if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2308    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2309    // We analyze this as smax(-A, -B) pred -A.
2310    // Note that we do not need to actually form -A or -B thanks to EqP.
2311    P = Pred;
2312  }
2313  if (P != CmpInst::BAD_ICMP_PREDICATE) {
2314    // Cases correspond to "max(A, B) p A".
2315    switch (P) {
2316    default:
2317      break;
2318    case CmpInst::ICMP_EQ:
2319    case CmpInst::ICMP_SLE:
2320      // Equivalent to "A EqP B".  This may be the same as the condition tested
2321      // in the max/min; if so, we can just return that.
2322      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2323        return V;
2324      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2325        return V;
2326      // Otherwise, see if "A EqP B" simplifies.
2327      if (MaxRecurse)
2328        if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2329          return V;
2330      break;
2331    case CmpInst::ICMP_NE:
2332    case CmpInst::ICMP_SGT: {
2333      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2334      // Equivalent to "A InvEqP B".  This may be the same as the condition
2335      // tested in the max/min; if so, we can just return that.
2336      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2337        return V;
2338      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2339        return V;
2340      // Otherwise, see if "A InvEqP B" simplifies.
2341      if (MaxRecurse)
2342        if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2343          return V;
2344      break;
2345    }
2346    case CmpInst::ICMP_SGE:
2347      // Always true.
2348      return getTrue(ITy);
2349    case CmpInst::ICMP_SLT:
2350      // Always false.
2351      return getFalse(ITy);
2352    }
2353  }
2354
2355  // Unsigned variants on "max(a,b)>=a -> true".
2356  P = CmpInst::BAD_ICMP_PREDICATE;
2357  if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2358    if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2359    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2360    // We analyze this as umax(A, B) pred A.
2361    P = Pred;
2362  } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2363             (A == LHS || B == LHS)) {
2364    if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2365    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2366    // We analyze this as umax(A, B) swapped-pred A.
2367    P = CmpInst::getSwappedPredicate(Pred);
2368  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2369             (A == RHS || B == RHS)) {
2370    if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2371    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2372    // We analyze this as umax(-A, -B) swapped-pred -A.
2373    // Note that we do not need to actually form -A or -B thanks to EqP.
2374    P = CmpInst::getSwappedPredicate(Pred);
2375  } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2376             (A == LHS || B == LHS)) {
2377    if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2378    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2379    // We analyze this as umax(-A, -B) pred -A.
2380    // Note that we do not need to actually form -A or -B thanks to EqP.
2381    P = Pred;
2382  }
2383  if (P != CmpInst::BAD_ICMP_PREDICATE) {
2384    // Cases correspond to "max(A, B) p A".
2385    switch (P) {
2386    default:
2387      break;
2388    case CmpInst::ICMP_EQ:
2389    case CmpInst::ICMP_ULE:
2390      // Equivalent to "A EqP B".  This may be the same as the condition tested
2391      // in the max/min; if so, we can just return that.
2392      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2393        return V;
2394      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2395        return V;
2396      // Otherwise, see if "A EqP B" simplifies.
2397      if (MaxRecurse)
2398        if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2399          return V;
2400      break;
2401    case CmpInst::ICMP_NE:
2402    case CmpInst::ICMP_UGT: {
2403      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2404      // Equivalent to "A InvEqP B".  This may be the same as the condition
2405      // tested in the max/min; if so, we can just return that.
2406      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2407        return V;
2408      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2409        return V;
2410      // Otherwise, see if "A InvEqP B" simplifies.
2411      if (MaxRecurse)
2412        if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2413          return V;
2414      break;
2415    }
2416    case CmpInst::ICMP_UGE:
2417      // Always true.
2418      return getTrue(ITy);
2419    case CmpInst::ICMP_ULT:
2420      // Always false.
2421      return getFalse(ITy);
2422    }
2423  }
2424
2425  // Variants on "max(x,y) >= min(x,z)".
2426  Value *C, *D;
2427  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2428      match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2429      (A == C || A == D || B == C || B == D)) {
2430    // max(x, ?) pred min(x, ?).
2431    if (Pred == CmpInst::ICMP_SGE)
2432      // Always true.
2433      return getTrue(ITy);
2434    if (Pred == CmpInst::ICMP_SLT)
2435      // Always false.
2436      return getFalse(ITy);
2437  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2438             match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2439             (A == C || A == D || B == C || B == D)) {
2440    // min(x, ?) pred max(x, ?).
2441    if (Pred == CmpInst::ICMP_SLE)
2442      // Always true.
2443      return getTrue(ITy);
2444    if (Pred == CmpInst::ICMP_SGT)
2445      // Always false.
2446      return getFalse(ITy);
2447  } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2448             match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2449             (A == C || A == D || B == C || B == D)) {
2450    // max(x, ?) pred min(x, ?).
2451    if (Pred == CmpInst::ICMP_UGE)
2452      // Always true.
2453      return getTrue(ITy);
2454    if (Pred == CmpInst::ICMP_ULT)
2455      // Always false.
2456      return getFalse(ITy);
2457  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2458             match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2459             (A == C || A == D || B == C || B == D)) {
2460    // min(x, ?) pred max(x, ?).
2461    if (Pred == CmpInst::ICMP_ULE)
2462      // Always true.
2463      return getTrue(ITy);
2464    if (Pred == CmpInst::ICMP_UGT)
2465      // Always false.
2466      return getFalse(ITy);
2467  }
2468
2469  // Simplify comparisons of related pointers using a powerful, recursive
2470  // GEP-walk when we have target data available..
2471  if (Q.TD && LHS->getType()->isPointerTy() && RHS->getType()->isPointerTy())
2472    if (Constant *C = computePointerICmp(*Q.TD, Pred, LHS, RHS))
2473      return C;
2474
2475  if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2476    if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2477      if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2478          GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2479          (ICmpInst::isEquality(Pred) ||
2480           (GLHS->isInBounds() && GRHS->isInBounds() &&
2481            Pred == ICmpInst::getSignedPredicate(Pred)))) {
2482        // The bases are equal and the indices are constant.  Build a constant
2483        // expression GEP with the same indices and a null base pointer to see
2484        // what constant folding can make out of it.
2485        Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2486        SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2487        Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2488
2489        SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2490        Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2491        return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2492      }
2493    }
2494  }
2495
2496  // If the comparison is with the result of a select instruction, check whether
2497  // comparing with either branch of the select always yields the same value.
2498  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2499    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2500      return V;
2501
2502  // If the comparison is with the result of a phi instruction, check whether
2503  // doing the compare with each incoming phi value yields a common result.
2504  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2505    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2506      return V;
2507
2508  return 0;
2509}
2510
2511Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2512                              const DataLayout *TD,
2513                              const TargetLibraryInfo *TLI,
2514                              const DominatorTree *DT) {
2515  return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2516                            RecursionLimit);
2517}
2518
2519/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2520/// fold the result.  If not, this returns null.
2521static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2522                               const Query &Q, unsigned MaxRecurse) {
2523  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2524  assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2525
2526  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2527    if (Constant *CRHS = dyn_cast<Constant>(RHS))
2528      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
2529
2530    // If we have a constant, make sure it is on the RHS.
2531    std::swap(LHS, RHS);
2532    Pred = CmpInst::getSwappedPredicate(Pred);
2533  }
2534
2535  // Fold trivial predicates.
2536  if (Pred == FCmpInst::FCMP_FALSE)
2537    return ConstantInt::get(GetCompareTy(LHS), 0);
2538  if (Pred == FCmpInst::FCMP_TRUE)
2539    return ConstantInt::get(GetCompareTy(LHS), 1);
2540
2541  if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2542    return UndefValue::get(GetCompareTy(LHS));
2543
2544  // fcmp x,x -> true/false.  Not all compares are foldable.
2545  if (LHS == RHS) {
2546    if (CmpInst::isTrueWhenEqual(Pred))
2547      return ConstantInt::get(GetCompareTy(LHS), 1);
2548    if (CmpInst::isFalseWhenEqual(Pred))
2549      return ConstantInt::get(GetCompareTy(LHS), 0);
2550  }
2551
2552  // Handle fcmp with constant RHS
2553  if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2554    // If the constant is a nan, see if we can fold the comparison based on it.
2555    if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2556      if (CFP->getValueAPF().isNaN()) {
2557        if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2558          return ConstantInt::getFalse(CFP->getContext());
2559        assert(FCmpInst::isUnordered(Pred) &&
2560               "Comparison must be either ordered or unordered!");
2561        // True if unordered.
2562        return ConstantInt::getTrue(CFP->getContext());
2563      }
2564      // Check whether the constant is an infinity.
2565      if (CFP->getValueAPF().isInfinity()) {
2566        if (CFP->getValueAPF().isNegative()) {
2567          switch (Pred) {
2568          case FCmpInst::FCMP_OLT:
2569            // No value is ordered and less than negative infinity.
2570            return ConstantInt::getFalse(CFP->getContext());
2571          case FCmpInst::FCMP_UGE:
2572            // All values are unordered with or at least negative infinity.
2573            return ConstantInt::getTrue(CFP->getContext());
2574          default:
2575            break;
2576          }
2577        } else {
2578          switch (Pred) {
2579          case FCmpInst::FCMP_OGT:
2580            // No value is ordered and greater than infinity.
2581            return ConstantInt::getFalse(CFP->getContext());
2582          case FCmpInst::FCMP_ULE:
2583            // All values are unordered with and at most infinity.
2584            return ConstantInt::getTrue(CFP->getContext());
2585          default:
2586            break;
2587          }
2588        }
2589      }
2590    }
2591  }
2592
2593  // If the comparison is with the result of a select instruction, check whether
2594  // comparing with either branch of the select always yields the same value.
2595  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2596    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2597      return V;
2598
2599  // If the comparison is with the result of a phi instruction, check whether
2600  // doing the compare with each incoming phi value yields a common result.
2601  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2602    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2603      return V;
2604
2605  return 0;
2606}
2607
2608Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2609                              const DataLayout *TD,
2610                              const TargetLibraryInfo *TLI,
2611                              const DominatorTree *DT) {
2612  return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2613                            RecursionLimit);
2614}
2615
2616/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2617/// the result.  If not, this returns null.
2618static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2619                                 Value *FalseVal, const Query &Q,
2620                                 unsigned MaxRecurse) {
2621  // select true, X, Y  -> X
2622  // select false, X, Y -> Y
2623  if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2624    return CB->getZExtValue() ? TrueVal : FalseVal;
2625
2626  // select C, X, X -> X
2627  if (TrueVal == FalseVal)
2628    return TrueVal;
2629
2630  if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2631    if (isa<Constant>(TrueVal))
2632      return TrueVal;
2633    return FalseVal;
2634  }
2635  if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2636    return FalseVal;
2637  if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2638    return TrueVal;
2639
2640  return 0;
2641}
2642
2643Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2644                                const DataLayout *TD,
2645                                const TargetLibraryInfo *TLI,
2646                                const DominatorTree *DT) {
2647  return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2648                              RecursionLimit);
2649}
2650
2651/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2652/// fold the result.  If not, this returns null.
2653static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2654  // The type of the GEP pointer operand.
2655  PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2656  // The GEP pointer operand is not a pointer, it's a vector of pointers.
2657  if (!PtrTy)
2658    return 0;
2659
2660  // getelementptr P -> P.
2661  if (Ops.size() == 1)
2662    return Ops[0];
2663
2664  if (isa<UndefValue>(Ops[0])) {
2665    // Compute the (pointer) type returned by the GEP instruction.
2666    Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2667    Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2668    return UndefValue::get(GEPTy);
2669  }
2670
2671  if (Ops.size() == 2) {
2672    // getelementptr P, 0 -> P.
2673    if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2674      if (C->isZero())
2675        return Ops[0];
2676    // getelementptr P, N -> P if P points to a type of zero size.
2677    if (Q.TD) {
2678      Type *Ty = PtrTy->getElementType();
2679      if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
2680        return Ops[0];
2681    }
2682  }
2683
2684  // Check to see if this is constant foldable.
2685  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2686    if (!isa<Constant>(Ops[i]))
2687      return 0;
2688
2689  return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2690}
2691
2692Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
2693                             const TargetLibraryInfo *TLI,
2694                             const DominatorTree *DT) {
2695  return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2696}
2697
2698/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2699/// can fold the result.  If not, this returns null.
2700static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2701                                      ArrayRef<unsigned> Idxs, const Query &Q,
2702                                      unsigned) {
2703  if (Constant *CAgg = dyn_cast<Constant>(Agg))
2704    if (Constant *CVal = dyn_cast<Constant>(Val))
2705      return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2706
2707  // insertvalue x, undef, n -> x
2708  if (match(Val, m_Undef()))
2709    return Agg;
2710
2711  // insertvalue x, (extractvalue y, n), n
2712  if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2713    if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2714        EV->getIndices() == Idxs) {
2715      // insertvalue undef, (extractvalue y, n), n -> y
2716      if (match(Agg, m_Undef()))
2717        return EV->getAggregateOperand();
2718
2719      // insertvalue y, (extractvalue y, n), n -> y
2720      if (Agg == EV->getAggregateOperand())
2721        return Agg;
2722    }
2723
2724  return 0;
2725}
2726
2727Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2728                                     ArrayRef<unsigned> Idxs,
2729                                     const DataLayout *TD,
2730                                     const TargetLibraryInfo *TLI,
2731                                     const DominatorTree *DT) {
2732  return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2733                                   RecursionLimit);
2734}
2735
2736/// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2737static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
2738  // If all of the PHI's incoming values are the same then replace the PHI node
2739  // with the common value.
2740  Value *CommonValue = 0;
2741  bool HasUndefInput = false;
2742  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2743    Value *Incoming = PN->getIncomingValue(i);
2744    // If the incoming value is the phi node itself, it can safely be skipped.
2745    if (Incoming == PN) continue;
2746    if (isa<UndefValue>(Incoming)) {
2747      // Remember that we saw an undef value, but otherwise ignore them.
2748      HasUndefInput = true;
2749      continue;
2750    }
2751    if (CommonValue && Incoming != CommonValue)
2752      return 0;  // Not the same, bail out.
2753    CommonValue = Incoming;
2754  }
2755
2756  // If CommonValue is null then all of the incoming values were either undef or
2757  // equal to the phi node itself.
2758  if (!CommonValue)
2759    return UndefValue::get(PN->getType());
2760
2761  // If we have a PHI node like phi(X, undef, X), where X is defined by some
2762  // instruction, we cannot return X as the result of the PHI node unless it
2763  // dominates the PHI block.
2764  if (HasUndefInput)
2765    return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
2766
2767  return CommonValue;
2768}
2769
2770static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2771  if (Constant *C = dyn_cast<Constant>(Op))
2772    return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2773
2774  return 0;
2775}
2776
2777Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
2778                               const TargetLibraryInfo *TLI,
2779                               const DominatorTree *DT) {
2780  return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2781}
2782
2783//=== Helper functions for higher up the class hierarchy.
2784
2785/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2786/// fold the result.  If not, this returns null.
2787static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2788                            const Query &Q, unsigned MaxRecurse) {
2789  switch (Opcode) {
2790  case Instruction::Add:
2791    return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2792                           Q, MaxRecurse);
2793  case Instruction::FAdd:
2794    return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2795
2796  case Instruction::Sub:
2797    return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2798                           Q, MaxRecurse);
2799  case Instruction::FSub:
2800    return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2801
2802  case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2803  case Instruction::FMul:
2804    return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2805  case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2806  case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2807  case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2808  case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2809  case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2810  case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
2811  case Instruction::Shl:
2812    return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2813                           Q, MaxRecurse);
2814  case Instruction::LShr:
2815    return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2816  case Instruction::AShr:
2817    return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2818  case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2819  case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2820  case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
2821  default:
2822    if (Constant *CLHS = dyn_cast<Constant>(LHS))
2823      if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2824        Constant *COps[] = {CLHS, CRHS};
2825        return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2826                                        Q.TLI);
2827      }
2828
2829    // If the operation is associative, try some generic simplifications.
2830    if (Instruction::isAssociative(Opcode))
2831      if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
2832        return V;
2833
2834    // If the operation is with the result of a select instruction check whether
2835    // operating on either branch of the select always yields the same value.
2836    if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2837      if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
2838        return V;
2839
2840    // If the operation is with the result of a phi instruction, check whether
2841    // operating on all incoming values of the phi always yields the same value.
2842    if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2843      if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
2844        return V;
2845
2846    return 0;
2847  }
2848}
2849
2850Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2851                           const DataLayout *TD, const TargetLibraryInfo *TLI,
2852                           const DominatorTree *DT) {
2853  return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
2854}
2855
2856/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2857/// fold the result.
2858static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2859                              const Query &Q, unsigned MaxRecurse) {
2860  if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2861    return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2862  return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2863}
2864
2865Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2866                             const DataLayout *TD, const TargetLibraryInfo *TLI,
2867                             const DominatorTree *DT) {
2868  return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2869                           RecursionLimit);
2870}
2871
2872template <typename IterTy>
2873static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
2874                           const Query &Q, unsigned MaxRecurse) {
2875  Type *Ty = V->getType();
2876  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
2877    Ty = PTy->getElementType();
2878  FunctionType *FTy = cast<FunctionType>(Ty);
2879
2880  // call undef -> undef
2881  if (isa<UndefValue>(V))
2882    return UndefValue::get(FTy->getReturnType());
2883
2884  Function *F = dyn_cast<Function>(V);
2885  if (!F)
2886    return 0;
2887
2888  if (!canConstantFoldCallTo(F))
2889    return 0;
2890
2891  SmallVector<Constant *, 4> ConstantArgs;
2892  ConstantArgs.reserve(ArgEnd - ArgBegin);
2893  for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
2894    Constant *C = dyn_cast<Constant>(*I);
2895    if (!C)
2896      return 0;
2897    ConstantArgs.push_back(C);
2898  }
2899
2900  return ConstantFoldCall(F, ConstantArgs, Q.TLI);
2901}
2902
2903Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
2904                          User::op_iterator ArgEnd, const DataLayout *TD,
2905                          const TargetLibraryInfo *TLI,
2906                          const DominatorTree *DT) {
2907  return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(TD, TLI, DT),
2908                        RecursionLimit);
2909}
2910
2911Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
2912                          const DataLayout *TD, const TargetLibraryInfo *TLI,
2913                          const DominatorTree *DT) {
2914  return ::SimplifyCall(V, Args.begin(), Args.end(), Query(TD, TLI, DT),
2915                        RecursionLimit);
2916}
2917
2918/// SimplifyInstruction - See if we can compute a simplified version of this
2919/// instruction.  If not, this returns null.
2920Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
2921                                 const TargetLibraryInfo *TLI,
2922                                 const DominatorTree *DT) {
2923  Value *Result;
2924
2925  switch (I->getOpcode()) {
2926  default:
2927    Result = ConstantFoldInstruction(I, TD, TLI);
2928    break;
2929  case Instruction::FAdd:
2930    Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
2931                              I->getFastMathFlags(), TD, TLI, DT);
2932    break;
2933  case Instruction::Add:
2934    Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2935                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2936                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2937                             TD, TLI, DT);
2938    break;
2939  case Instruction::FSub:
2940    Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
2941                              I->getFastMathFlags(), TD, TLI, DT);
2942    break;
2943  case Instruction::Sub:
2944    Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2945                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2946                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2947                             TD, TLI, DT);
2948    break;
2949  case Instruction::FMul:
2950    Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
2951                              I->getFastMathFlags(), TD, TLI, DT);
2952    break;
2953  case Instruction::Mul:
2954    Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2955    break;
2956  case Instruction::SDiv:
2957    Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2958    break;
2959  case Instruction::UDiv:
2960    Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2961    break;
2962  case Instruction::FDiv:
2963    Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2964    break;
2965  case Instruction::SRem:
2966    Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2967    break;
2968  case Instruction::URem:
2969    Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2970    break;
2971  case Instruction::FRem:
2972    Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2973    break;
2974  case Instruction::Shl:
2975    Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2976                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2977                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2978                             TD, TLI, DT);
2979    break;
2980  case Instruction::LShr:
2981    Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2982                              cast<BinaryOperator>(I)->isExact(),
2983                              TD, TLI, DT);
2984    break;
2985  case Instruction::AShr:
2986    Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2987                              cast<BinaryOperator>(I)->isExact(),
2988                              TD, TLI, DT);
2989    break;
2990  case Instruction::And:
2991    Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2992    break;
2993  case Instruction::Or:
2994    Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2995    break;
2996  case Instruction::Xor:
2997    Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2998    break;
2999  case Instruction::ICmp:
3000    Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
3001                              I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3002    break;
3003  case Instruction::FCmp:
3004    Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
3005                              I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3006    break;
3007  case Instruction::Select:
3008    Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
3009                                I->getOperand(2), TD, TLI, DT);
3010    break;
3011  case Instruction::GetElementPtr: {
3012    SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
3013    Result = SimplifyGEPInst(Ops, TD, TLI, DT);
3014    break;
3015  }
3016  case Instruction::InsertValue: {
3017    InsertValueInst *IV = cast<InsertValueInst>(I);
3018    Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3019                                     IV->getInsertedValueOperand(),
3020                                     IV->getIndices(), TD, TLI, DT);
3021    break;
3022  }
3023  case Instruction::PHI:
3024    Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
3025    break;
3026  case Instruction::Call: {
3027    CallSite CS(cast<CallInst>(I));
3028    Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3029                          TD, TLI, DT);
3030    break;
3031  }
3032  case Instruction::Trunc:
3033    Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
3034    break;
3035  }
3036
3037  /// If called on unreachable code, the above logic may report that the
3038  /// instruction simplified to itself.  Make life easier for users by
3039  /// detecting that case here, returning a safe value instead.
3040  return Result == I ? UndefValue::get(I->getType()) : Result;
3041}
3042
3043/// \brief Implementation of recursive simplification through an instructions
3044/// uses.
3045///
3046/// This is the common implementation of the recursive simplification routines.
3047/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3048/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3049/// instructions to process and attempt to simplify it using
3050/// InstructionSimplify.
3051///
3052/// This routine returns 'true' only when *it* simplifies something. The passed
3053/// in simplified value does not count toward this.
3054static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
3055                                              const DataLayout *TD,
3056                                              const TargetLibraryInfo *TLI,
3057                                              const DominatorTree *DT) {
3058  bool Simplified = false;
3059  SmallSetVector<Instruction *, 8> Worklist;
3060
3061  // If we have an explicit value to collapse to, do that round of the
3062  // simplification loop by hand initially.
3063  if (SimpleV) {
3064    for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3065         ++UI)
3066      if (*UI != I)
3067        Worklist.insert(cast<Instruction>(*UI));
3068
3069    // Replace the instruction with its simplified value.
3070    I->replaceAllUsesWith(SimpleV);
3071
3072    // Gracefully handle edge cases where the instruction is not wired into any
3073    // parent block.
3074    if (I->getParent())
3075      I->eraseFromParent();
3076  } else {
3077    Worklist.insert(I);
3078  }
3079
3080  // Note that we must test the size on each iteration, the worklist can grow.
3081  for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3082    I = Worklist[Idx];
3083
3084    // See if this instruction simplifies.
3085    SimpleV = SimplifyInstruction(I, TD, TLI, DT);
3086    if (!SimpleV)
3087      continue;
3088
3089    Simplified = true;
3090
3091    // Stash away all the uses of the old instruction so we can check them for
3092    // recursive simplifications after a RAUW. This is cheaper than checking all
3093    // uses of To on the recursive step in most cases.
3094    for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3095         ++UI)
3096      Worklist.insert(cast<Instruction>(*UI));
3097
3098    // Replace the instruction with its simplified value.
3099    I->replaceAllUsesWith(SimpleV);
3100
3101    // Gracefully handle edge cases where the instruction is not wired into any
3102    // parent block.
3103    if (I->getParent())
3104      I->eraseFromParent();
3105  }
3106  return Simplified;
3107}
3108
3109bool llvm::recursivelySimplifyInstruction(Instruction *I,
3110                                          const DataLayout *TD,
3111                                          const TargetLibraryInfo *TLI,
3112                                          const DominatorTree *DT) {
3113  return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
3114}
3115
3116bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
3117                                         const DataLayout *TD,
3118                                         const TargetLibraryInfo *TLI,
3119                                         const DominatorTree *DT) {
3120  assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3121  assert(SimpleV && "Must provide a simplified value.");
3122  return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
3123}
3124