InstructionSimplify.cpp revision 263508
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/ConstantFolding.h"
25#include "llvm/Analysis/Dominators.h"
26#include "llvm/Analysis/ValueTracking.h"
27#include "llvm/Analysis/MemoryBuiltins.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.
666///
667/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
668/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
669/// folding.
670static Constant *stripAndComputeConstantOffsets(const DataLayout *TD,
671                                                Value *&V,
672                                                bool AllowNonInbounds = false) {
673  assert(V->getType()->getScalarType()->isPointerTy());
674
675  // Without DataLayout, just be conservative for now. Theoretically, more could
676  // be done in this case.
677  if (!TD)
678    return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
679
680  Type *IntPtrTy = TD->getIntPtrType(V->getType())->getScalarType();
681  APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
682
683  // Even though we don't look through PHI nodes, we could be called on an
684  // instruction in an unreachable block, which may be on a cycle.
685  SmallPtrSet<Value *, 4> Visited;
686  Visited.insert(V);
687  do {
688    if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
689      if ((!AllowNonInbounds && !GEP->isInBounds()) ||
690          !GEP->accumulateConstantOffset(*TD, Offset))
691        break;
692      V = GEP->getPointerOperand();
693    } else if (Operator::getOpcode(V) == Instruction::BitCast) {
694      V = cast<Operator>(V)->getOperand(0);
695    } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
696      if (GA->mayBeOverridden())
697        break;
698      V = GA->getAliasee();
699    } else {
700      break;
701    }
702    assert(V->getType()->getScalarType()->isPointerTy() &&
703           "Unexpected operand type!");
704  } while (Visited.insert(V));
705
706  Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
707  if (V->getType()->isVectorTy())
708    return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
709                                    OffsetIntPtr);
710  return OffsetIntPtr;
711}
712
713/// \brief Compute the constant difference between two pointer values.
714/// If the difference is not a constant, returns zero.
715static Constant *computePointerDifference(const DataLayout *TD,
716                                          Value *LHS, Value *RHS) {
717  Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
718  Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
719
720  // If LHS and RHS are not related via constant offsets to the same base
721  // value, there is nothing we can do here.
722  if (LHS != RHS)
723    return 0;
724
725  // Otherwise, the difference of LHS - RHS can be computed as:
726  //    LHS - RHS
727  //  = (LHSOffset + Base) - (RHSOffset + Base)
728  //  = LHSOffset - RHSOffset
729  return ConstantExpr::getSub(LHSOffset, RHSOffset);
730}
731
732/// SimplifySubInst - Given operands for a Sub, see if we can
733/// fold the result.  If not, this returns null.
734static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
735                              const Query &Q, unsigned MaxRecurse) {
736  if (Constant *CLHS = dyn_cast<Constant>(Op0))
737    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
738      Constant *Ops[] = { CLHS, CRHS };
739      return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
740                                      Ops, Q.TD, Q.TLI);
741    }
742
743  // X - undef -> undef
744  // undef - X -> undef
745  if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
746    return UndefValue::get(Op0->getType());
747
748  // X - 0 -> X
749  if (match(Op1, m_Zero()))
750    return Op0;
751
752  // X - X -> 0
753  if (Op0 == Op1)
754    return Constant::getNullValue(Op0->getType());
755
756  // (X*2) - X -> X
757  // (X<<1) - X -> X
758  Value *X = 0;
759  if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
760      match(Op0, m_Shl(m_Specific(Op1), m_One())))
761    return Op1;
762
763  // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
764  // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
765  Value *Y = 0, *Z = Op1;
766  if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
767    // See if "V === Y - Z" simplifies.
768    if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
769      // It does!  Now see if "X + V" simplifies.
770      if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
771        // It does, we successfully reassociated!
772        ++NumReassoc;
773        return W;
774      }
775    // See if "V === X - Z" simplifies.
776    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
777      // It does!  Now see if "Y + V" simplifies.
778      if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
779        // It does, we successfully reassociated!
780        ++NumReassoc;
781        return W;
782      }
783  }
784
785  // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
786  // For example, X - (X + 1) -> -1
787  X = Op0;
788  if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
789    // See if "V === X - Y" simplifies.
790    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
791      // It does!  Now see if "V - Z" simplifies.
792      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
793        // It does, we successfully reassociated!
794        ++NumReassoc;
795        return W;
796      }
797    // See if "V === X - Z" simplifies.
798    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
799      // It does!  Now see if "V - Y" simplifies.
800      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
801        // It does, we successfully reassociated!
802        ++NumReassoc;
803        return W;
804      }
805  }
806
807  // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
808  // For example, X - (X - Y) -> Y.
809  Z = Op0;
810  if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
811    // See if "V === Z - X" simplifies.
812    if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
813      // It does!  Now see if "V + Y" simplifies.
814      if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
815        // It does, we successfully reassociated!
816        ++NumReassoc;
817        return W;
818      }
819
820  // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
821  if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
822      match(Op1, m_Trunc(m_Value(Y))))
823    if (X->getType() == Y->getType())
824      // See if "V === X - Y" simplifies.
825      if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
826        // It does!  Now see if "trunc V" simplifies.
827        if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
828          // It does, return the simplified "trunc V".
829          return W;
830
831  // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
832  if (match(Op0, m_PtrToInt(m_Value(X))) &&
833      match(Op1, m_PtrToInt(m_Value(Y))))
834    if (Constant *Result = computePointerDifference(Q.TD, X, Y))
835      return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
836
837  // Mul distributes over Sub.  Try some generic simplifications based on this.
838  if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
839                                Q, MaxRecurse))
840    return V;
841
842  // i1 sub -> xor.
843  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
844    if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
845      return V;
846
847  // Threading Sub over selects and phi nodes is pointless, so don't bother.
848  // Threading over the select in "A - select(cond, B, C)" means evaluating
849  // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
850  // only if B and C are equal.  If B and C are equal then (since we assume
851  // that operands have already been simplified) "select(cond, B, C)" should
852  // have been simplified to the common value of B and C already.  Analysing
853  // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
854  // for threading over phi nodes.
855
856  return 0;
857}
858
859Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
860                             const DataLayout *TD, const TargetLibraryInfo *TLI,
861                             const DominatorTree *DT) {
862  return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
863                           RecursionLimit);
864}
865
866/// Given operands for an FAdd, see if we can fold the result.  If not, this
867/// returns null.
868static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
869                              const Query &Q, unsigned MaxRecurse) {
870  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
871    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
872      Constant *Ops[] = { CLHS, CRHS };
873      return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
874                                      Ops, Q.TD, Q.TLI);
875    }
876
877    // Canonicalize the constant to the RHS.
878    std::swap(Op0, Op1);
879  }
880
881  // fadd X, -0 ==> X
882  if (match(Op1, m_NegZero()))
883    return Op0;
884
885  // fadd X, 0 ==> X, when we know X is not -0
886  if (match(Op1, m_Zero()) &&
887      (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
888    return Op0;
889
890  // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
891  //   where nnan and ninf have to occur at least once somewhere in this
892  //   expression
893  Value *SubOp = 0;
894  if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
895    SubOp = Op1;
896  else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
897    SubOp = Op0;
898  if (SubOp) {
899    Instruction *FSub = cast<Instruction>(SubOp);
900    if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
901        (FMF.noInfs() || FSub->hasNoInfs()))
902      return Constant::getNullValue(Op0->getType());
903  }
904
905  return 0;
906}
907
908/// Given operands for an FSub, see if we can fold the result.  If not, this
909/// returns null.
910static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
911                              const Query &Q, unsigned MaxRecurse) {
912  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
913    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
914      Constant *Ops[] = { CLHS, CRHS };
915      return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
916                                      Ops, Q.TD, Q.TLI);
917    }
918  }
919
920  // fsub X, 0 ==> X
921  if (match(Op1, m_Zero()))
922    return Op0;
923
924  // fsub X, -0 ==> X, when we know X is not -0
925  if (match(Op1, m_NegZero()) &&
926      (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
927    return Op0;
928
929  // fsub 0, (fsub -0.0, X) ==> X
930  Value *X;
931  if (match(Op0, m_AnyZero())) {
932    if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
933      return X;
934    if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
935      return X;
936  }
937
938  // fsub nnan ninf x, x ==> 0.0
939  if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
940    return Constant::getNullValue(Op0->getType());
941
942  return 0;
943}
944
945/// Given the operands for an FMul, see if we can fold the result
946static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
947                               FastMathFlags FMF,
948                               const Query &Q,
949                               unsigned MaxRecurse) {
950 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
951    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
952      Constant *Ops[] = { CLHS, CRHS };
953      return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
954                                      Ops, Q.TD, Q.TLI);
955    }
956
957    // Canonicalize the constant to the RHS.
958    std::swap(Op0, Op1);
959 }
960
961 // fmul X, 1.0 ==> X
962 if (match(Op1, m_FPOne()))
963   return Op0;
964
965 // fmul nnan nsz X, 0 ==> 0
966 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
967   return Op1;
968
969 return 0;
970}
971
972/// SimplifyMulInst - Given operands for a Mul, see if we can
973/// fold the result.  If not, this returns null.
974static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
975                              unsigned MaxRecurse) {
976  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
977    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
978      Constant *Ops[] = { CLHS, CRHS };
979      return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
980                                      Ops, Q.TD, Q.TLI);
981    }
982
983    // Canonicalize the constant to the RHS.
984    std::swap(Op0, Op1);
985  }
986
987  // X * undef -> 0
988  if (match(Op1, m_Undef()))
989    return Constant::getNullValue(Op0->getType());
990
991  // X * 0 -> 0
992  if (match(Op1, m_Zero()))
993    return Op1;
994
995  // X * 1 -> X
996  if (match(Op1, m_One()))
997    return Op0;
998
999  // (X / Y) * Y -> X if the division is exact.
1000  Value *X = 0;
1001  if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
1002      match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
1003    return X;
1004
1005  // i1 mul -> and.
1006  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
1007    if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
1008      return V;
1009
1010  // Try some generic simplifications for associative operations.
1011  if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
1012                                          MaxRecurse))
1013    return V;
1014
1015  // Mul distributes over Add.  Try some generic simplifications based on this.
1016  if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
1017                             Q, MaxRecurse))
1018    return V;
1019
1020  // If the operation is with the result of a select instruction, check whether
1021  // operating on either branch of the select always yields the same value.
1022  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1023    if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
1024                                         MaxRecurse))
1025      return V;
1026
1027  // If the operation is with the result of a phi instruction, check whether
1028  // operating on all incoming values of the phi always yields the same value.
1029  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1030    if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
1031                                      MaxRecurse))
1032      return V;
1033
1034  return 0;
1035}
1036
1037Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1038                             const DataLayout *TD, const TargetLibraryInfo *TLI,
1039                             const DominatorTree *DT) {
1040  return ::SimplifyFAddInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1041}
1042
1043Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1044                             const DataLayout *TD, const TargetLibraryInfo *TLI,
1045                             const DominatorTree *DT) {
1046  return ::SimplifyFSubInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1047}
1048
1049Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1050                              FastMathFlags FMF,
1051                              const DataLayout *TD,
1052                              const TargetLibraryInfo *TLI,
1053                              const DominatorTree *DT) {
1054  return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1055}
1056
1057Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
1058                             const TargetLibraryInfo *TLI,
1059                             const DominatorTree *DT) {
1060  return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1061}
1062
1063/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1064/// fold the result.  If not, this returns null.
1065static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1066                          const Query &Q, unsigned MaxRecurse) {
1067  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1068    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1069      Constant *Ops[] = { C0, C1 };
1070      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1071    }
1072  }
1073
1074  bool isSigned = Opcode == Instruction::SDiv;
1075
1076  // X / undef -> undef
1077  if (match(Op1, m_Undef()))
1078    return Op1;
1079
1080  // undef / X -> 0
1081  if (match(Op0, m_Undef()))
1082    return Constant::getNullValue(Op0->getType());
1083
1084  // 0 / X -> 0, we don't need to preserve faults!
1085  if (match(Op0, m_Zero()))
1086    return Op0;
1087
1088  // X / 1 -> X
1089  if (match(Op1, m_One()))
1090    return Op0;
1091
1092  if (Op0->getType()->isIntegerTy(1))
1093    // It can't be division by zero, hence it must be division by one.
1094    return Op0;
1095
1096  // X / X -> 1
1097  if (Op0 == Op1)
1098    return ConstantInt::get(Op0->getType(), 1);
1099
1100  // (X * Y) / Y -> X if the multiplication does not overflow.
1101  Value *X = 0, *Y = 0;
1102  if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1103    if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1104    OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1105    // If the Mul knows it does not overflow, then we are good to go.
1106    if ((isSigned && Mul->hasNoSignedWrap()) ||
1107        (!isSigned && Mul->hasNoUnsignedWrap()))
1108      return X;
1109    // If X has the form X = A / Y then X * Y cannot overflow.
1110    if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1111      if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1112        return X;
1113  }
1114
1115  // (X rem Y) / Y -> 0
1116  if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1117      (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1118    return Constant::getNullValue(Op0->getType());
1119
1120  // If the operation is with the result of a select instruction, check whether
1121  // operating on either branch of the select always yields the same value.
1122  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1123    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1124      return V;
1125
1126  // If the operation is with the result of a phi instruction, check whether
1127  // operating on all incoming values of the phi always yields the same value.
1128  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1129    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1130      return V;
1131
1132  return 0;
1133}
1134
1135/// SimplifySDivInst - Given operands for an SDiv, see if we can
1136/// fold the result.  If not, this returns null.
1137static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1138                               unsigned MaxRecurse) {
1139  if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1140    return V;
1141
1142  return 0;
1143}
1144
1145Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1146                              const TargetLibraryInfo *TLI,
1147                              const DominatorTree *DT) {
1148  return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1149}
1150
1151/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1152/// fold the result.  If not, this returns null.
1153static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1154                               unsigned MaxRecurse) {
1155  if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1156    return V;
1157
1158  return 0;
1159}
1160
1161Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1162                              const TargetLibraryInfo *TLI,
1163                              const DominatorTree *DT) {
1164  return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1165}
1166
1167static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1168                               unsigned) {
1169  // undef / X -> undef    (the undef could be a snan).
1170  if (match(Op0, m_Undef()))
1171    return Op0;
1172
1173  // X / undef -> undef
1174  if (match(Op1, m_Undef()))
1175    return Op1;
1176
1177  return 0;
1178}
1179
1180Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1181                              const TargetLibraryInfo *TLI,
1182                              const DominatorTree *DT) {
1183  return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1184}
1185
1186/// SimplifyRem - Given operands for an SRem or URem, see if we can
1187/// fold the result.  If not, this returns null.
1188static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1189                          const Query &Q, unsigned MaxRecurse) {
1190  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1191    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1192      Constant *Ops[] = { C0, C1 };
1193      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1194    }
1195  }
1196
1197  // X % undef -> undef
1198  if (match(Op1, m_Undef()))
1199    return Op1;
1200
1201  // undef % X -> 0
1202  if (match(Op0, m_Undef()))
1203    return Constant::getNullValue(Op0->getType());
1204
1205  // 0 % X -> 0, we don't need to preserve faults!
1206  if (match(Op0, m_Zero()))
1207    return Op0;
1208
1209  // X % 0 -> undef, we don't need to preserve faults!
1210  if (match(Op1, m_Zero()))
1211    return UndefValue::get(Op0->getType());
1212
1213  // X % 1 -> 0
1214  if (match(Op1, m_One()))
1215    return Constant::getNullValue(Op0->getType());
1216
1217  if (Op0->getType()->isIntegerTy(1))
1218    // It can't be remainder by zero, hence it must be remainder by one.
1219    return Constant::getNullValue(Op0->getType());
1220
1221  // X % X -> 0
1222  if (Op0 == Op1)
1223    return Constant::getNullValue(Op0->getType());
1224
1225  // If the operation is with the result of a select instruction, check whether
1226  // operating on either branch of the select always yields the same value.
1227  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1228    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1229      return V;
1230
1231  // If the operation is with the result of a phi instruction, check whether
1232  // operating on all incoming values of the phi always yields the same value.
1233  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1234    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1235      return V;
1236
1237  return 0;
1238}
1239
1240/// SimplifySRemInst - Given operands for an SRem, see if we can
1241/// fold the result.  If not, this returns null.
1242static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1243                               unsigned MaxRecurse) {
1244  if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1245    return V;
1246
1247  return 0;
1248}
1249
1250Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1251                              const TargetLibraryInfo *TLI,
1252                              const DominatorTree *DT) {
1253  return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1254}
1255
1256/// SimplifyURemInst - Given operands for a URem, see if we can
1257/// fold the result.  If not, this returns null.
1258static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1259                               unsigned MaxRecurse) {
1260  if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1261    return V;
1262
1263  return 0;
1264}
1265
1266Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1267                              const TargetLibraryInfo *TLI,
1268                              const DominatorTree *DT) {
1269  return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1270}
1271
1272static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1273                               unsigned) {
1274  // undef % X -> undef    (the undef could be a snan).
1275  if (match(Op0, m_Undef()))
1276    return Op0;
1277
1278  // X % undef -> undef
1279  if (match(Op1, m_Undef()))
1280    return Op1;
1281
1282  return 0;
1283}
1284
1285Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1286                              const TargetLibraryInfo *TLI,
1287                              const DominatorTree *DT) {
1288  return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1289}
1290
1291/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1292/// fold the result.  If not, this returns null.
1293static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1294                            const Query &Q, unsigned MaxRecurse) {
1295  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1296    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1297      Constant *Ops[] = { C0, C1 };
1298      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1299    }
1300  }
1301
1302  // 0 shift by X -> 0
1303  if (match(Op0, m_Zero()))
1304    return Op0;
1305
1306  // X shift by 0 -> X
1307  if (match(Op1, m_Zero()))
1308    return Op0;
1309
1310  // X shift by undef -> undef because it may shift by the bitwidth.
1311  if (match(Op1, m_Undef()))
1312    return Op1;
1313
1314  // Shifting by the bitwidth or more is undefined.
1315  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1316    if (CI->getValue().getLimitedValue() >=
1317        Op0->getType()->getScalarSizeInBits())
1318      return UndefValue::get(Op0->getType());
1319
1320  // If the operation is with the result of a select instruction, check whether
1321  // operating on either branch of the select always yields the same value.
1322  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1323    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1324      return V;
1325
1326  // If the operation is with the result of a phi instruction, check whether
1327  // operating on all incoming values of the phi always yields the same value.
1328  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1329    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1330      return V;
1331
1332  return 0;
1333}
1334
1335/// SimplifyShlInst - Given operands for an Shl, see if we can
1336/// fold the result.  If not, this returns null.
1337static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1338                              const Query &Q, unsigned MaxRecurse) {
1339  if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1340    return V;
1341
1342  // undef << X -> 0
1343  if (match(Op0, m_Undef()))
1344    return Constant::getNullValue(Op0->getType());
1345
1346  // (X >> A) << A -> X
1347  Value *X;
1348  if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1349    return X;
1350  return 0;
1351}
1352
1353Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1354                             const DataLayout *TD, const TargetLibraryInfo *TLI,
1355                             const DominatorTree *DT) {
1356  return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1357                           RecursionLimit);
1358}
1359
1360/// SimplifyLShrInst - Given operands for an LShr, see if we can
1361/// fold the result.  If not, this returns null.
1362static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1363                               const Query &Q, unsigned MaxRecurse) {
1364  if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1365    return V;
1366
1367  // X >> X -> 0
1368  if (Op0 == Op1)
1369    return Constant::getNullValue(Op0->getType());
1370
1371  // undef >>l X -> 0
1372  if (match(Op0, m_Undef()))
1373    return Constant::getNullValue(Op0->getType());
1374
1375  // (X << A) >> A -> X
1376  Value *X;
1377  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1378      cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1379    return X;
1380
1381  return 0;
1382}
1383
1384Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1385                              const DataLayout *TD,
1386                              const TargetLibraryInfo *TLI,
1387                              const DominatorTree *DT) {
1388  return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1389                            RecursionLimit);
1390}
1391
1392/// SimplifyAShrInst - Given operands for an AShr, see if we can
1393/// fold the result.  If not, this returns null.
1394static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1395                               const Query &Q, unsigned MaxRecurse) {
1396  if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1397    return V;
1398
1399  // X >> X -> 0
1400  if (Op0 == Op1)
1401    return Constant::getNullValue(Op0->getType());
1402
1403  // all ones >>a X -> all ones
1404  if (match(Op0, m_AllOnes()))
1405    return Op0;
1406
1407  // undef >>a X -> all ones
1408  if (match(Op0, m_Undef()))
1409    return Constant::getAllOnesValue(Op0->getType());
1410
1411  // (X << A) >> A -> X
1412  Value *X;
1413  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1414      cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1415    return X;
1416
1417  return 0;
1418}
1419
1420Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1421                              const DataLayout *TD,
1422                              const TargetLibraryInfo *TLI,
1423                              const DominatorTree *DT) {
1424  return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1425                            RecursionLimit);
1426}
1427
1428/// SimplifyAndInst - Given operands for an And, see if we can
1429/// fold the result.  If not, this returns null.
1430static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1431                              unsigned MaxRecurse) {
1432  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1433    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1434      Constant *Ops[] = { CLHS, CRHS };
1435      return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1436                                      Ops, Q.TD, Q.TLI);
1437    }
1438
1439    // Canonicalize the constant to the RHS.
1440    std::swap(Op0, Op1);
1441  }
1442
1443  // X & undef -> 0
1444  if (match(Op1, m_Undef()))
1445    return Constant::getNullValue(Op0->getType());
1446
1447  // X & X = X
1448  if (Op0 == Op1)
1449    return Op0;
1450
1451  // X & 0 = 0
1452  if (match(Op1, m_Zero()))
1453    return Op1;
1454
1455  // X & -1 = X
1456  if (match(Op1, m_AllOnes()))
1457    return Op0;
1458
1459  // A & ~A  =  ~A & A  =  0
1460  if (match(Op0, m_Not(m_Specific(Op1))) ||
1461      match(Op1, m_Not(m_Specific(Op0))))
1462    return Constant::getNullValue(Op0->getType());
1463
1464  // (A | ?) & A = A
1465  Value *A = 0, *B = 0;
1466  if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1467      (A == Op1 || B == Op1))
1468    return Op1;
1469
1470  // A & (A | ?) = A
1471  if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1472      (A == Op0 || B == Op0))
1473    return Op0;
1474
1475  // A & (-A) = A if A is a power of two or zero.
1476  if (match(Op0, m_Neg(m_Specific(Op1))) ||
1477      match(Op1, m_Neg(m_Specific(Op0)))) {
1478    if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
1479      return Op0;
1480    if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
1481      return Op1;
1482  }
1483
1484  // Try some generic simplifications for associative operations.
1485  if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1486                                          MaxRecurse))
1487    return V;
1488
1489  // And distributes over Or.  Try some generic simplifications based on this.
1490  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1491                             Q, MaxRecurse))
1492    return V;
1493
1494  // And distributes over Xor.  Try some generic simplifications based on this.
1495  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1496                             Q, MaxRecurse))
1497    return V;
1498
1499  // Or distributes over And.  Try some generic simplifications based on this.
1500  if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1501                                Q, MaxRecurse))
1502    return V;
1503
1504  // If the operation is with the result of a select instruction, check whether
1505  // operating on either branch of the select always yields the same value.
1506  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1507    if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1508                                         MaxRecurse))
1509      return V;
1510
1511  // If the operation is with the result of a phi instruction, check whether
1512  // operating on all incoming values of the phi always yields the same value.
1513  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1514    if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1515                                      MaxRecurse))
1516      return V;
1517
1518  return 0;
1519}
1520
1521Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
1522                             const TargetLibraryInfo *TLI,
1523                             const DominatorTree *DT) {
1524  return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1525}
1526
1527/// SimplifyOrInst - Given operands for an Or, see if we can
1528/// fold the result.  If not, this returns null.
1529static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1530                             unsigned MaxRecurse) {
1531  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1532    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1533      Constant *Ops[] = { CLHS, CRHS };
1534      return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1535                                      Ops, Q.TD, Q.TLI);
1536    }
1537
1538    // Canonicalize the constant to the RHS.
1539    std::swap(Op0, Op1);
1540  }
1541
1542  // X | undef -> -1
1543  if (match(Op1, m_Undef()))
1544    return Constant::getAllOnesValue(Op0->getType());
1545
1546  // X | X = X
1547  if (Op0 == Op1)
1548    return Op0;
1549
1550  // X | 0 = X
1551  if (match(Op1, m_Zero()))
1552    return Op0;
1553
1554  // X | -1 = -1
1555  if (match(Op1, m_AllOnes()))
1556    return Op1;
1557
1558  // A | ~A  =  ~A | A  =  -1
1559  if (match(Op0, m_Not(m_Specific(Op1))) ||
1560      match(Op1, m_Not(m_Specific(Op0))))
1561    return Constant::getAllOnesValue(Op0->getType());
1562
1563  // (A & ?) | A = A
1564  Value *A = 0, *B = 0;
1565  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1566      (A == Op1 || B == Op1))
1567    return Op1;
1568
1569  // A | (A & ?) = A
1570  if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1571      (A == Op0 || B == Op0))
1572    return Op0;
1573
1574  // ~(A & ?) | A = -1
1575  if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1576      (A == Op1 || B == Op1))
1577    return Constant::getAllOnesValue(Op1->getType());
1578
1579  // A | ~(A & ?) = -1
1580  if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1581      (A == Op0 || B == Op0))
1582    return Constant::getAllOnesValue(Op0->getType());
1583
1584  // Try some generic simplifications for associative operations.
1585  if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1586                                          MaxRecurse))
1587    return V;
1588
1589  // Or distributes over And.  Try some generic simplifications based on this.
1590  if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1591                             MaxRecurse))
1592    return V;
1593
1594  // And distributes over Or.  Try some generic simplifications based on this.
1595  if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1596                                Q, MaxRecurse))
1597    return V;
1598
1599  // If the operation is with the result of a select instruction, check whether
1600  // operating on either branch of the select always yields the same value.
1601  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1602    if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1603                                         MaxRecurse))
1604      return V;
1605
1606  // If the operation is with the result of a phi instruction, check whether
1607  // operating on all incoming values of the phi always yields the same value.
1608  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1609    if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1610      return V;
1611
1612  return 0;
1613}
1614
1615Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
1616                            const TargetLibraryInfo *TLI,
1617                            const DominatorTree *DT) {
1618  return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1619}
1620
1621/// SimplifyXorInst - Given operands for a Xor, see if we can
1622/// fold the result.  If not, this returns null.
1623static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1624                              unsigned MaxRecurse) {
1625  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1626    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1627      Constant *Ops[] = { CLHS, CRHS };
1628      return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1629                                      Ops, Q.TD, Q.TLI);
1630    }
1631
1632    // Canonicalize the constant to the RHS.
1633    std::swap(Op0, Op1);
1634  }
1635
1636  // A ^ undef -> undef
1637  if (match(Op1, m_Undef()))
1638    return Op1;
1639
1640  // A ^ 0 = A
1641  if (match(Op1, m_Zero()))
1642    return Op0;
1643
1644  // A ^ A = 0
1645  if (Op0 == Op1)
1646    return Constant::getNullValue(Op0->getType());
1647
1648  // A ^ ~A  =  ~A ^ A  =  -1
1649  if (match(Op0, m_Not(m_Specific(Op1))) ||
1650      match(Op1, m_Not(m_Specific(Op0))))
1651    return Constant::getAllOnesValue(Op0->getType());
1652
1653  // Try some generic simplifications for associative operations.
1654  if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1655                                          MaxRecurse))
1656    return V;
1657
1658  // And distributes over Xor.  Try some generic simplifications based on this.
1659  if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1660                                Q, MaxRecurse))
1661    return V;
1662
1663  // Threading Xor over selects and phi nodes is pointless, so don't bother.
1664  // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1665  // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1666  // only if B and C are equal.  If B and C are equal then (since we assume
1667  // that operands have already been simplified) "select(cond, B, C)" should
1668  // have been simplified to the common value of B and C already.  Analysing
1669  // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1670  // for threading over phi nodes.
1671
1672  return 0;
1673}
1674
1675Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
1676                             const TargetLibraryInfo *TLI,
1677                             const DominatorTree *DT) {
1678  return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1679}
1680
1681static Type *GetCompareTy(Value *Op) {
1682  return CmpInst::makeCmpResultType(Op->getType());
1683}
1684
1685/// ExtractEquivalentCondition - Rummage around inside V looking for something
1686/// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1687/// otherwise return null.  Helper function for analyzing max/min idioms.
1688static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1689                                         Value *LHS, Value *RHS) {
1690  SelectInst *SI = dyn_cast<SelectInst>(V);
1691  if (!SI)
1692    return 0;
1693  CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1694  if (!Cmp)
1695    return 0;
1696  Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1697  if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1698    return Cmp;
1699  if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1700      LHS == CmpRHS && RHS == CmpLHS)
1701    return Cmp;
1702  return 0;
1703}
1704
1705// A significant optimization not implemented here is assuming that alloca
1706// addresses are not equal to incoming argument values. They don't *alias*,
1707// as we say, but that doesn't mean they aren't equal, so we take a
1708// conservative approach.
1709//
1710// This is inspired in part by C++11 5.10p1:
1711//   "Two pointers of the same type compare equal if and only if they are both
1712//    null, both point to the same function, or both represent the same
1713//    address."
1714//
1715// This is pretty permissive.
1716//
1717// It's also partly due to C11 6.5.9p6:
1718//   "Two pointers compare equal if and only if both are null pointers, both are
1719//    pointers to the same object (including a pointer to an object and a
1720//    subobject at its beginning) or function, both are pointers to one past the
1721//    last element of the same array object, or one is a pointer to one past the
1722//    end of one array object and the other is a pointer to the start of a
1723//    different array object that happens to immediately follow the first array
1724//    object in the address space.)
1725//
1726// C11's version is more restrictive, however there's no reason why an argument
1727// couldn't be a one-past-the-end value for a stack object in the caller and be
1728// equal to the beginning of a stack object in the callee.
1729//
1730// If the C and C++ standards are ever made sufficiently restrictive in this
1731// area, it may be possible to update LLVM's semantics accordingly and reinstate
1732// this optimization.
1733static Constant *computePointerICmp(const DataLayout *TD,
1734                                    const TargetLibraryInfo *TLI,
1735                                    CmpInst::Predicate Pred,
1736                                    Value *LHS, Value *RHS) {
1737  // First, skip past any trivial no-ops.
1738  LHS = LHS->stripPointerCasts();
1739  RHS = RHS->stripPointerCasts();
1740
1741  // A non-null pointer is not equal to a null pointer.
1742  if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1743      (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1744    return ConstantInt::get(GetCompareTy(LHS),
1745                            !CmpInst::isTrueWhenEqual(Pred));
1746
1747  // We can only fold certain predicates on pointer comparisons.
1748  switch (Pred) {
1749  default:
1750    return 0;
1751
1752    // Equality comaprisons are easy to fold.
1753  case CmpInst::ICMP_EQ:
1754  case CmpInst::ICMP_NE:
1755    break;
1756
1757    // We can only handle unsigned relational comparisons because 'inbounds' on
1758    // a GEP only protects against unsigned wrapping.
1759  case CmpInst::ICMP_UGT:
1760  case CmpInst::ICMP_UGE:
1761  case CmpInst::ICMP_ULT:
1762  case CmpInst::ICMP_ULE:
1763    // However, we have to switch them to their signed variants to handle
1764    // negative indices from the base pointer.
1765    Pred = ICmpInst::getSignedPredicate(Pred);
1766    break;
1767  }
1768
1769  // Strip off any constant offsets so that we can reason about them.
1770  // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1771  // here and compare base addresses like AliasAnalysis does, however there are
1772  // numerous hazards. AliasAnalysis and its utilities rely on special rules
1773  // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1774  // doesn't need to guarantee pointer inequality when it says NoAlias.
1775  Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
1776  Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
1777
1778  // If LHS and RHS are related via constant offsets to the same base
1779  // value, we can replace it with an icmp which just compares the offsets.
1780  if (LHS == RHS)
1781    return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1782
1783  // Various optimizations for (in)equality comparisons.
1784  if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1785    // Different non-empty allocations that exist at the same time have
1786    // different addresses (if the program can tell). Global variables always
1787    // exist, so they always exist during the lifetime of each other and all
1788    // allocas. Two different allocas usually have different addresses...
1789    //
1790    // However, if there's an @llvm.stackrestore dynamically in between two
1791    // allocas, they may have the same address. It's tempting to reduce the
1792    // scope of the problem by only looking at *static* allocas here. That would
1793    // cover the majority of allocas while significantly reducing the likelihood
1794    // of having an @llvm.stackrestore pop up in the middle. However, it's not
1795    // actually impossible for an @llvm.stackrestore to pop up in the middle of
1796    // an entry block. Also, if we have a block that's not attached to a
1797    // function, we can't tell if it's "static" under the current definition.
1798    // Theoretically, this problem could be fixed by creating a new kind of
1799    // instruction kind specifically for static allocas. Such a new instruction
1800    // could be required to be at the top of the entry block, thus preventing it
1801    // from being subject to a @llvm.stackrestore. Instcombine could even
1802    // convert regular allocas into these special allocas. It'd be nifty.
1803    // However, until then, this problem remains open.
1804    //
1805    // So, we'll assume that two non-empty allocas have different addresses
1806    // for now.
1807    //
1808    // With all that, if the offsets are within the bounds of their allocations
1809    // (and not one-past-the-end! so we can't use inbounds!), and their
1810    // allocations aren't the same, the pointers are not equal.
1811    //
1812    // Note that it's not necessary to check for LHS being a global variable
1813    // address, due to canonicalization and constant folding.
1814    if (isa<AllocaInst>(LHS) &&
1815        (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
1816      ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1817      ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
1818      uint64_t LHSSize, RHSSize;
1819      if (LHSOffsetCI && RHSOffsetCI &&
1820          getObjectSize(LHS, LHSSize, TD, TLI) &&
1821          getObjectSize(RHS, RHSSize, TD, TLI)) {
1822        const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1823        const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
1824        if (!LHSOffsetValue.isNegative() &&
1825            !RHSOffsetValue.isNegative() &&
1826            LHSOffsetValue.ult(LHSSize) &&
1827            RHSOffsetValue.ult(RHSSize)) {
1828          return ConstantInt::get(GetCompareTy(LHS),
1829                                  !CmpInst::isTrueWhenEqual(Pred));
1830        }
1831      }
1832
1833      // Repeat the above check but this time without depending on DataLayout
1834      // or being able to compute a precise size.
1835      if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1836          !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1837          LHSOffset->isNullValue() &&
1838          RHSOffset->isNullValue())
1839        return ConstantInt::get(GetCompareTy(LHS),
1840                                !CmpInst::isTrueWhenEqual(Pred));
1841    }
1842
1843    // Even if an non-inbounds GEP occurs along the path we can still optimize
1844    // equality comparisons concerning the result. We avoid walking the whole
1845    // chain again by starting where the last calls to
1846    // stripAndComputeConstantOffsets left off and accumulate the offsets.
1847    Constant *LHSNoBound = stripAndComputeConstantOffsets(TD, LHS, true);
1848    Constant *RHSNoBound = stripAndComputeConstantOffsets(TD, RHS, true);
1849    if (LHS == RHS)
1850      return ConstantExpr::getICmp(Pred,
1851                                   ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1852                                   ConstantExpr::getAdd(RHSOffset, RHSNoBound));
1853  }
1854
1855  // Otherwise, fail.
1856  return 0;
1857}
1858
1859/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1860/// fold the result.  If not, this returns null.
1861static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1862                               const Query &Q, unsigned MaxRecurse) {
1863  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1864  assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1865
1866  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1867    if (Constant *CRHS = dyn_cast<Constant>(RHS))
1868      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
1869
1870    // If we have a constant, make sure it is on the RHS.
1871    std::swap(LHS, RHS);
1872    Pred = CmpInst::getSwappedPredicate(Pred);
1873  }
1874
1875  Type *ITy = GetCompareTy(LHS); // The return type.
1876  Type *OpTy = LHS->getType();   // The operand type.
1877
1878  // icmp X, X -> true/false
1879  // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1880  // because X could be 0.
1881  if (LHS == RHS || isa<UndefValue>(RHS))
1882    return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1883
1884  // Special case logic when the operands have i1 type.
1885  if (OpTy->getScalarType()->isIntegerTy(1)) {
1886    switch (Pred) {
1887    default: break;
1888    case ICmpInst::ICMP_EQ:
1889      // X == 1 -> X
1890      if (match(RHS, m_One()))
1891        return LHS;
1892      break;
1893    case ICmpInst::ICMP_NE:
1894      // X != 0 -> X
1895      if (match(RHS, m_Zero()))
1896        return LHS;
1897      break;
1898    case ICmpInst::ICMP_UGT:
1899      // X >u 0 -> X
1900      if (match(RHS, m_Zero()))
1901        return LHS;
1902      break;
1903    case ICmpInst::ICMP_UGE:
1904      // X >=u 1 -> X
1905      if (match(RHS, m_One()))
1906        return LHS;
1907      break;
1908    case ICmpInst::ICMP_SLT:
1909      // X <s 0 -> X
1910      if (match(RHS, m_Zero()))
1911        return LHS;
1912      break;
1913    case ICmpInst::ICMP_SLE:
1914      // X <=s -1 -> X
1915      if (match(RHS, m_One()))
1916        return LHS;
1917      break;
1918    }
1919  }
1920
1921  // If we are comparing with zero then try hard since this is a common case.
1922  if (match(RHS, m_Zero())) {
1923    bool LHSKnownNonNegative, LHSKnownNegative;
1924    switch (Pred) {
1925    default: llvm_unreachable("Unknown ICmp predicate!");
1926    case ICmpInst::ICMP_ULT:
1927      return getFalse(ITy);
1928    case ICmpInst::ICMP_UGE:
1929      return getTrue(ITy);
1930    case ICmpInst::ICMP_EQ:
1931    case ICmpInst::ICMP_ULE:
1932      if (isKnownNonZero(LHS, Q.TD))
1933        return getFalse(ITy);
1934      break;
1935    case ICmpInst::ICMP_NE:
1936    case ICmpInst::ICMP_UGT:
1937      if (isKnownNonZero(LHS, Q.TD))
1938        return getTrue(ITy);
1939      break;
1940    case ICmpInst::ICMP_SLT:
1941      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1942      if (LHSKnownNegative)
1943        return getTrue(ITy);
1944      if (LHSKnownNonNegative)
1945        return getFalse(ITy);
1946      break;
1947    case ICmpInst::ICMP_SLE:
1948      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1949      if (LHSKnownNegative)
1950        return getTrue(ITy);
1951      if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1952        return getFalse(ITy);
1953      break;
1954    case ICmpInst::ICMP_SGE:
1955      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1956      if (LHSKnownNegative)
1957        return getFalse(ITy);
1958      if (LHSKnownNonNegative)
1959        return getTrue(ITy);
1960      break;
1961    case ICmpInst::ICMP_SGT:
1962      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1963      if (LHSKnownNegative)
1964        return getFalse(ITy);
1965      if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1966        return getTrue(ITy);
1967      break;
1968    }
1969  }
1970
1971  // See if we are doing a comparison with a constant integer.
1972  if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1973    // Rule out tautological comparisons (eg., ult 0 or uge 0).
1974    ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1975    if (RHS_CR.isEmptySet())
1976      return ConstantInt::getFalse(CI->getContext());
1977    if (RHS_CR.isFullSet())
1978      return ConstantInt::getTrue(CI->getContext());
1979
1980    // Many binary operators with constant RHS have easy to compute constant
1981    // range.  Use them to check whether the comparison is a tautology.
1982    uint32_t Width = CI->getBitWidth();
1983    APInt Lower = APInt(Width, 0);
1984    APInt Upper = APInt(Width, 0);
1985    ConstantInt *CI2;
1986    if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1987      // 'urem x, CI2' produces [0, CI2).
1988      Upper = CI2->getValue();
1989    } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1990      // 'srem x, CI2' produces (-|CI2|, |CI2|).
1991      Upper = CI2->getValue().abs();
1992      Lower = (-Upper) + 1;
1993    } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1994      // 'udiv CI2, x' produces [0, CI2].
1995      Upper = CI2->getValue() + 1;
1996    } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1997      // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1998      APInt NegOne = APInt::getAllOnesValue(Width);
1999      if (!CI2->isZero())
2000        Upper = NegOne.udiv(CI2->getValue()) + 1;
2001    } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2002      // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
2003      APInt IntMin = APInt::getSignedMinValue(Width);
2004      APInt IntMax = APInt::getSignedMaxValue(Width);
2005      APInt Val = CI2->getValue().abs();
2006      if (!Val.isMinValue()) {
2007        Lower = IntMin.sdiv(Val);
2008        Upper = IntMax.sdiv(Val) + 1;
2009      }
2010    } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2011      // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2012      APInt NegOne = APInt::getAllOnesValue(Width);
2013      if (CI2->getValue().ult(Width))
2014        Upper = NegOne.lshr(CI2->getValue()) + 1;
2015    } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2016      // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2017      APInt IntMin = APInt::getSignedMinValue(Width);
2018      APInt IntMax = APInt::getSignedMaxValue(Width);
2019      if (CI2->getValue().ult(Width)) {
2020        Lower = IntMin.ashr(CI2->getValue());
2021        Upper = IntMax.ashr(CI2->getValue()) + 1;
2022      }
2023    } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2024      // 'or x, CI2' produces [CI2, UINT_MAX].
2025      Lower = CI2->getValue();
2026    } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2027      // 'and x, CI2' produces [0, CI2].
2028      Upper = CI2->getValue() + 1;
2029    }
2030    if (Lower != Upper) {
2031      ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2032      if (RHS_CR.contains(LHS_CR))
2033        return ConstantInt::getTrue(RHS->getContext());
2034      if (RHS_CR.inverse().contains(LHS_CR))
2035        return ConstantInt::getFalse(RHS->getContext());
2036    }
2037  }
2038
2039  // Compare of cast, for example (zext X) != 0 -> X != 0
2040  if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2041    Instruction *LI = cast<CastInst>(LHS);
2042    Value *SrcOp = LI->getOperand(0);
2043    Type *SrcTy = SrcOp->getType();
2044    Type *DstTy = LI->getType();
2045
2046    // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2047    // if the integer type is the same size as the pointer type.
2048    if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
2049        Q.TD->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2050      if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2051        // Transfer the cast to the constant.
2052        if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2053                                        ConstantExpr::getIntToPtr(RHSC, SrcTy),
2054                                        Q, MaxRecurse-1))
2055          return V;
2056      } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2057        if (RI->getOperand(0)->getType() == SrcTy)
2058          // Compare without the cast.
2059          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2060                                          Q, MaxRecurse-1))
2061            return V;
2062      }
2063    }
2064
2065    if (isa<ZExtInst>(LHS)) {
2066      // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2067      // same type.
2068      if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2069        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2070          // Compare X and Y.  Note that signed predicates become unsigned.
2071          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2072                                          SrcOp, RI->getOperand(0), Q,
2073                                          MaxRecurse-1))
2074            return V;
2075      }
2076      // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2077      // too.  If not, then try to deduce the result of the comparison.
2078      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2079        // Compute the constant that would happen if we truncated to SrcTy then
2080        // reextended to DstTy.
2081        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2082        Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2083
2084        // If the re-extended constant didn't change then this is effectively
2085        // also a case of comparing two zero-extended values.
2086        if (RExt == CI && MaxRecurse)
2087          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2088                                        SrcOp, Trunc, Q, MaxRecurse-1))
2089            return V;
2090
2091        // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2092        // there.  Use this to work out the result of the comparison.
2093        if (RExt != CI) {
2094          switch (Pred) {
2095          default: llvm_unreachable("Unknown ICmp predicate!");
2096          // LHS <u RHS.
2097          case ICmpInst::ICMP_EQ:
2098          case ICmpInst::ICMP_UGT:
2099          case ICmpInst::ICMP_UGE:
2100            return ConstantInt::getFalse(CI->getContext());
2101
2102          case ICmpInst::ICMP_NE:
2103          case ICmpInst::ICMP_ULT:
2104          case ICmpInst::ICMP_ULE:
2105            return ConstantInt::getTrue(CI->getContext());
2106
2107          // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2108          // is non-negative then LHS <s RHS.
2109          case ICmpInst::ICMP_SGT:
2110          case ICmpInst::ICMP_SGE:
2111            return CI->getValue().isNegative() ?
2112              ConstantInt::getTrue(CI->getContext()) :
2113              ConstantInt::getFalse(CI->getContext());
2114
2115          case ICmpInst::ICMP_SLT:
2116          case ICmpInst::ICMP_SLE:
2117            return CI->getValue().isNegative() ?
2118              ConstantInt::getFalse(CI->getContext()) :
2119              ConstantInt::getTrue(CI->getContext());
2120          }
2121        }
2122      }
2123    }
2124
2125    if (isa<SExtInst>(LHS)) {
2126      // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2127      // same type.
2128      if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2129        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2130          // Compare X and Y.  Note that the predicate does not change.
2131          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2132                                          Q, MaxRecurse-1))
2133            return V;
2134      }
2135      // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2136      // too.  If not, then try to deduce the result of the comparison.
2137      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2138        // Compute the constant that would happen if we truncated to SrcTy then
2139        // reextended to DstTy.
2140        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2141        Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2142
2143        // If the re-extended constant didn't change then this is effectively
2144        // also a case of comparing two sign-extended values.
2145        if (RExt == CI && MaxRecurse)
2146          if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2147            return V;
2148
2149        // Otherwise the upper bits of LHS are all equal, while RHS has varying
2150        // bits there.  Use this to work out the result of the comparison.
2151        if (RExt != CI) {
2152          switch (Pred) {
2153          default: llvm_unreachable("Unknown ICmp predicate!");
2154          case ICmpInst::ICMP_EQ:
2155            return ConstantInt::getFalse(CI->getContext());
2156          case ICmpInst::ICMP_NE:
2157            return ConstantInt::getTrue(CI->getContext());
2158
2159          // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2160          // LHS >s RHS.
2161          case ICmpInst::ICMP_SGT:
2162          case ICmpInst::ICMP_SGE:
2163            return CI->getValue().isNegative() ?
2164              ConstantInt::getTrue(CI->getContext()) :
2165              ConstantInt::getFalse(CI->getContext());
2166          case ICmpInst::ICMP_SLT:
2167          case ICmpInst::ICMP_SLE:
2168            return CI->getValue().isNegative() ?
2169              ConstantInt::getFalse(CI->getContext()) :
2170              ConstantInt::getTrue(CI->getContext());
2171
2172          // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2173          // LHS >u RHS.
2174          case ICmpInst::ICMP_UGT:
2175          case ICmpInst::ICMP_UGE:
2176            // Comparison is true iff the LHS <s 0.
2177            if (MaxRecurse)
2178              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2179                                              Constant::getNullValue(SrcTy),
2180                                              Q, MaxRecurse-1))
2181                return V;
2182            break;
2183          case ICmpInst::ICMP_ULT:
2184          case ICmpInst::ICMP_ULE:
2185            // Comparison is true iff the LHS >=s 0.
2186            if (MaxRecurse)
2187              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2188                                              Constant::getNullValue(SrcTy),
2189                                              Q, MaxRecurse-1))
2190                return V;
2191            break;
2192          }
2193        }
2194      }
2195    }
2196  }
2197
2198  // Special logic for binary operators.
2199  BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2200  BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2201  if (MaxRecurse && (LBO || RBO)) {
2202    // Analyze the case when either LHS or RHS is an add instruction.
2203    Value *A = 0, *B = 0, *C = 0, *D = 0;
2204    // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2205    bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2206    if (LBO && LBO->getOpcode() == Instruction::Add) {
2207      A = LBO->getOperand(0); B = LBO->getOperand(1);
2208      NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2209        (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2210        (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2211    }
2212    if (RBO && RBO->getOpcode() == Instruction::Add) {
2213      C = RBO->getOperand(0); D = RBO->getOperand(1);
2214      NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2215        (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2216        (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2217    }
2218
2219    // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2220    if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2221      if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2222                                      Constant::getNullValue(RHS->getType()),
2223                                      Q, MaxRecurse-1))
2224        return V;
2225
2226    // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2227    if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2228      if (Value *V = SimplifyICmpInst(Pred,
2229                                      Constant::getNullValue(LHS->getType()),
2230                                      C == LHS ? D : C, Q, MaxRecurse-1))
2231        return V;
2232
2233    // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2234    if (A && C && (A == C || A == D || B == C || B == D) &&
2235        NoLHSWrapProblem && NoRHSWrapProblem) {
2236      // Determine Y and Z in the form icmp (X+Y), (X+Z).
2237      Value *Y, *Z;
2238      if (A == C) {
2239        // C + B == C + D  ->  B == D
2240        Y = B;
2241        Z = D;
2242      } else if (A == D) {
2243        // D + B == C + D  ->  B == C
2244        Y = B;
2245        Z = C;
2246      } else if (B == C) {
2247        // A + C == C + D  ->  A == D
2248        Y = A;
2249        Z = D;
2250      } else {
2251        assert(B == D);
2252        // A + D == C + D  ->  A == C
2253        Y = A;
2254        Z = C;
2255      }
2256      if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2257        return V;
2258    }
2259  }
2260
2261  // icmp pred (urem X, Y), Y
2262  if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2263    bool KnownNonNegative, KnownNegative;
2264    switch (Pred) {
2265    default:
2266      break;
2267    case ICmpInst::ICMP_SGT:
2268    case ICmpInst::ICMP_SGE:
2269      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2270      if (!KnownNonNegative)
2271        break;
2272      // fall-through
2273    case ICmpInst::ICMP_EQ:
2274    case ICmpInst::ICMP_UGT:
2275    case ICmpInst::ICMP_UGE:
2276      return getFalse(ITy);
2277    case ICmpInst::ICMP_SLT:
2278    case ICmpInst::ICMP_SLE:
2279      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2280      if (!KnownNonNegative)
2281        break;
2282      // fall-through
2283    case ICmpInst::ICMP_NE:
2284    case ICmpInst::ICMP_ULT:
2285    case ICmpInst::ICMP_ULE:
2286      return getTrue(ITy);
2287    }
2288  }
2289
2290  // icmp pred X, (urem Y, X)
2291  if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2292    bool KnownNonNegative, KnownNegative;
2293    switch (Pred) {
2294    default:
2295      break;
2296    case ICmpInst::ICMP_SGT:
2297    case ICmpInst::ICMP_SGE:
2298      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2299      if (!KnownNonNegative)
2300        break;
2301      // fall-through
2302    case ICmpInst::ICMP_NE:
2303    case ICmpInst::ICMP_UGT:
2304    case ICmpInst::ICMP_UGE:
2305      return getTrue(ITy);
2306    case ICmpInst::ICMP_SLT:
2307    case ICmpInst::ICMP_SLE:
2308      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2309      if (!KnownNonNegative)
2310        break;
2311      // fall-through
2312    case ICmpInst::ICMP_EQ:
2313    case ICmpInst::ICMP_ULT:
2314    case ICmpInst::ICMP_ULE:
2315      return getFalse(ITy);
2316    }
2317  }
2318
2319  // x udiv y <=u x.
2320  if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2321    // icmp pred (X /u Y), X
2322    if (Pred == ICmpInst::ICMP_UGT)
2323      return getFalse(ITy);
2324    if (Pred == ICmpInst::ICMP_ULE)
2325      return getTrue(ITy);
2326  }
2327
2328  if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2329      LBO->getOperand(1) == RBO->getOperand(1)) {
2330    switch (LBO->getOpcode()) {
2331    default: break;
2332    case Instruction::UDiv:
2333    case Instruction::LShr:
2334      if (ICmpInst::isSigned(Pred))
2335        break;
2336      // fall-through
2337    case Instruction::SDiv:
2338    case Instruction::AShr:
2339      if (!LBO->isExact() || !RBO->isExact())
2340        break;
2341      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2342                                      RBO->getOperand(0), Q, MaxRecurse-1))
2343        return V;
2344      break;
2345    case Instruction::Shl: {
2346      bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2347      bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2348      if (!NUW && !NSW)
2349        break;
2350      if (!NSW && ICmpInst::isSigned(Pred))
2351        break;
2352      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2353                                      RBO->getOperand(0), Q, MaxRecurse-1))
2354        return V;
2355      break;
2356    }
2357    }
2358  }
2359
2360  // Simplify comparisons involving max/min.
2361  Value *A, *B;
2362  CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2363  CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2364
2365  // Signed variants on "max(a,b)>=a -> true".
2366  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2367    if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2368    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2369    // We analyze this as smax(A, B) pred A.
2370    P = Pred;
2371  } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2372             (A == LHS || B == LHS)) {
2373    if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2374    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2375    // We analyze this as smax(A, B) swapped-pred A.
2376    P = CmpInst::getSwappedPredicate(Pred);
2377  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2378             (A == RHS || B == RHS)) {
2379    if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2380    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2381    // We analyze this as smax(-A, -B) swapped-pred -A.
2382    // Note that we do not need to actually form -A or -B thanks to EqP.
2383    P = CmpInst::getSwappedPredicate(Pred);
2384  } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2385             (A == LHS || B == LHS)) {
2386    if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2387    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2388    // We analyze this as smax(-A, -B) pred -A.
2389    // Note that we do not need to actually form -A or -B thanks to EqP.
2390    P = Pred;
2391  }
2392  if (P != CmpInst::BAD_ICMP_PREDICATE) {
2393    // Cases correspond to "max(A, B) p A".
2394    switch (P) {
2395    default:
2396      break;
2397    case CmpInst::ICMP_EQ:
2398    case CmpInst::ICMP_SLE:
2399      // Equivalent to "A EqP B".  This may be the same as the condition tested
2400      // in the max/min; if so, we can just return that.
2401      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2402        return V;
2403      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2404        return V;
2405      // Otherwise, see if "A EqP B" simplifies.
2406      if (MaxRecurse)
2407        if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2408          return V;
2409      break;
2410    case CmpInst::ICMP_NE:
2411    case CmpInst::ICMP_SGT: {
2412      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2413      // Equivalent to "A InvEqP B".  This may be the same as the condition
2414      // tested in the max/min; if so, we can just return that.
2415      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2416        return V;
2417      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2418        return V;
2419      // Otherwise, see if "A InvEqP B" simplifies.
2420      if (MaxRecurse)
2421        if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2422          return V;
2423      break;
2424    }
2425    case CmpInst::ICMP_SGE:
2426      // Always true.
2427      return getTrue(ITy);
2428    case CmpInst::ICMP_SLT:
2429      // Always false.
2430      return getFalse(ITy);
2431    }
2432  }
2433
2434  // Unsigned variants on "max(a,b)>=a -> true".
2435  P = CmpInst::BAD_ICMP_PREDICATE;
2436  if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2437    if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2438    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2439    // We analyze this as umax(A, B) pred A.
2440    P = Pred;
2441  } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2442             (A == LHS || B == LHS)) {
2443    if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2444    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2445    // We analyze this as umax(A, B) swapped-pred A.
2446    P = CmpInst::getSwappedPredicate(Pred);
2447  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2448             (A == RHS || B == RHS)) {
2449    if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2450    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2451    // We analyze this as umax(-A, -B) swapped-pred -A.
2452    // Note that we do not need to actually form -A or -B thanks to EqP.
2453    P = CmpInst::getSwappedPredicate(Pred);
2454  } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2455             (A == LHS || B == LHS)) {
2456    if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2457    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2458    // We analyze this as umax(-A, -B) pred -A.
2459    // Note that we do not need to actually form -A or -B thanks to EqP.
2460    P = Pred;
2461  }
2462  if (P != CmpInst::BAD_ICMP_PREDICATE) {
2463    // Cases correspond to "max(A, B) p A".
2464    switch (P) {
2465    default:
2466      break;
2467    case CmpInst::ICMP_EQ:
2468    case CmpInst::ICMP_ULE:
2469      // Equivalent to "A EqP B".  This may be the same as the condition tested
2470      // in the max/min; if so, we can just return that.
2471      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2472        return V;
2473      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2474        return V;
2475      // Otherwise, see if "A EqP B" simplifies.
2476      if (MaxRecurse)
2477        if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2478          return V;
2479      break;
2480    case CmpInst::ICMP_NE:
2481    case CmpInst::ICMP_UGT: {
2482      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2483      // Equivalent to "A InvEqP B".  This may be the same as the condition
2484      // tested in the max/min; if so, we can just return that.
2485      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2486        return V;
2487      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2488        return V;
2489      // Otherwise, see if "A InvEqP B" simplifies.
2490      if (MaxRecurse)
2491        if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2492          return V;
2493      break;
2494    }
2495    case CmpInst::ICMP_UGE:
2496      // Always true.
2497      return getTrue(ITy);
2498    case CmpInst::ICMP_ULT:
2499      // Always false.
2500      return getFalse(ITy);
2501    }
2502  }
2503
2504  // Variants on "max(x,y) >= min(x,z)".
2505  Value *C, *D;
2506  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2507      match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2508      (A == C || A == D || B == C || B == D)) {
2509    // max(x, ?) pred min(x, ?).
2510    if (Pred == CmpInst::ICMP_SGE)
2511      // Always true.
2512      return getTrue(ITy);
2513    if (Pred == CmpInst::ICMP_SLT)
2514      // Always false.
2515      return getFalse(ITy);
2516  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2517             match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2518             (A == C || A == D || B == C || B == D)) {
2519    // min(x, ?) pred max(x, ?).
2520    if (Pred == CmpInst::ICMP_SLE)
2521      // Always true.
2522      return getTrue(ITy);
2523    if (Pred == CmpInst::ICMP_SGT)
2524      // Always false.
2525      return getFalse(ITy);
2526  } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2527             match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2528             (A == C || A == D || B == C || B == D)) {
2529    // max(x, ?) pred min(x, ?).
2530    if (Pred == CmpInst::ICMP_UGE)
2531      // Always true.
2532      return getTrue(ITy);
2533    if (Pred == CmpInst::ICMP_ULT)
2534      // Always false.
2535      return getFalse(ITy);
2536  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2537             match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2538             (A == C || A == D || B == C || B == D)) {
2539    // min(x, ?) pred max(x, ?).
2540    if (Pred == CmpInst::ICMP_ULE)
2541      // Always true.
2542      return getTrue(ITy);
2543    if (Pred == CmpInst::ICMP_UGT)
2544      // Always false.
2545      return getFalse(ITy);
2546  }
2547
2548  // Simplify comparisons of related pointers using a powerful, recursive
2549  // GEP-walk when we have target data available..
2550  if (LHS->getType()->isPointerTy())
2551    if (Constant *C = computePointerICmp(Q.TD, Q.TLI, Pred, LHS, RHS))
2552      return C;
2553
2554  if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2555    if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2556      if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2557          GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2558          (ICmpInst::isEquality(Pred) ||
2559           (GLHS->isInBounds() && GRHS->isInBounds() &&
2560            Pred == ICmpInst::getSignedPredicate(Pred)))) {
2561        // The bases are equal and the indices are constant.  Build a constant
2562        // expression GEP with the same indices and a null base pointer to see
2563        // what constant folding can make out of it.
2564        Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2565        SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2566        Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2567
2568        SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2569        Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2570        return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2571      }
2572    }
2573  }
2574
2575  // If the comparison is with the result of a select instruction, check whether
2576  // comparing with either branch of the select always yields the same value.
2577  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2578    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2579      return V;
2580
2581  // If the comparison is with the result of a phi instruction, check whether
2582  // doing the compare with each incoming phi value yields a common result.
2583  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2584    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2585      return V;
2586
2587  return 0;
2588}
2589
2590Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2591                              const DataLayout *TD,
2592                              const TargetLibraryInfo *TLI,
2593                              const DominatorTree *DT) {
2594  return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2595                            RecursionLimit);
2596}
2597
2598/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2599/// fold the result.  If not, this returns null.
2600static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2601                               const Query &Q, unsigned MaxRecurse) {
2602  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2603  assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2604
2605  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2606    if (Constant *CRHS = dyn_cast<Constant>(RHS))
2607      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
2608
2609    // If we have a constant, make sure it is on the RHS.
2610    std::swap(LHS, RHS);
2611    Pred = CmpInst::getSwappedPredicate(Pred);
2612  }
2613
2614  // Fold trivial predicates.
2615  if (Pred == FCmpInst::FCMP_FALSE)
2616    return ConstantInt::get(GetCompareTy(LHS), 0);
2617  if (Pred == FCmpInst::FCMP_TRUE)
2618    return ConstantInt::get(GetCompareTy(LHS), 1);
2619
2620  if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2621    return UndefValue::get(GetCompareTy(LHS));
2622
2623  // fcmp x,x -> true/false.  Not all compares are foldable.
2624  if (LHS == RHS) {
2625    if (CmpInst::isTrueWhenEqual(Pred))
2626      return ConstantInt::get(GetCompareTy(LHS), 1);
2627    if (CmpInst::isFalseWhenEqual(Pred))
2628      return ConstantInt::get(GetCompareTy(LHS), 0);
2629  }
2630
2631  // Handle fcmp with constant RHS
2632  if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2633    // If the constant is a nan, see if we can fold the comparison based on it.
2634    if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2635      if (CFP->getValueAPF().isNaN()) {
2636        if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2637          return ConstantInt::getFalse(CFP->getContext());
2638        assert(FCmpInst::isUnordered(Pred) &&
2639               "Comparison must be either ordered or unordered!");
2640        // True if unordered.
2641        return ConstantInt::getTrue(CFP->getContext());
2642      }
2643      // Check whether the constant is an infinity.
2644      if (CFP->getValueAPF().isInfinity()) {
2645        if (CFP->getValueAPF().isNegative()) {
2646          switch (Pred) {
2647          case FCmpInst::FCMP_OLT:
2648            // No value is ordered and less than negative infinity.
2649            return ConstantInt::getFalse(CFP->getContext());
2650          case FCmpInst::FCMP_UGE:
2651            // All values are unordered with or at least negative infinity.
2652            return ConstantInt::getTrue(CFP->getContext());
2653          default:
2654            break;
2655          }
2656        } else {
2657          switch (Pred) {
2658          case FCmpInst::FCMP_OGT:
2659            // No value is ordered and greater than infinity.
2660            return ConstantInt::getFalse(CFP->getContext());
2661          case FCmpInst::FCMP_ULE:
2662            // All values are unordered with and at most infinity.
2663            return ConstantInt::getTrue(CFP->getContext());
2664          default:
2665            break;
2666          }
2667        }
2668      }
2669    }
2670  }
2671
2672  // If the comparison is with the result of a select instruction, check whether
2673  // comparing with either branch of the select always yields the same value.
2674  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2675    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2676      return V;
2677
2678  // If the comparison is with the result of a phi instruction, check whether
2679  // doing the compare with each incoming phi value yields a common result.
2680  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2681    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2682      return V;
2683
2684  return 0;
2685}
2686
2687Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2688                              const DataLayout *TD,
2689                              const TargetLibraryInfo *TLI,
2690                              const DominatorTree *DT) {
2691  return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2692                            RecursionLimit);
2693}
2694
2695/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2696/// the result.  If not, this returns null.
2697static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2698                                 Value *FalseVal, const Query &Q,
2699                                 unsigned MaxRecurse) {
2700  // select true, X, Y  -> X
2701  // select false, X, Y -> Y
2702  if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2703    return CB->getZExtValue() ? TrueVal : FalseVal;
2704
2705  // select C, X, X -> X
2706  if (TrueVal == FalseVal)
2707    return TrueVal;
2708
2709  if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2710    if (isa<Constant>(TrueVal))
2711      return TrueVal;
2712    return FalseVal;
2713  }
2714  if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2715    return FalseVal;
2716  if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2717    return TrueVal;
2718
2719  return 0;
2720}
2721
2722Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2723                                const DataLayout *TD,
2724                                const TargetLibraryInfo *TLI,
2725                                const DominatorTree *DT) {
2726  return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2727                              RecursionLimit);
2728}
2729
2730/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2731/// fold the result.  If not, this returns null.
2732static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2733  // The type of the GEP pointer operand.
2734  PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2735  // The GEP pointer operand is not a pointer, it's a vector of pointers.
2736  if (!PtrTy)
2737    return 0;
2738
2739  // getelementptr P -> P.
2740  if (Ops.size() == 1)
2741    return Ops[0];
2742
2743  if (isa<UndefValue>(Ops[0])) {
2744    // Compute the (pointer) type returned by the GEP instruction.
2745    Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2746    Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2747    return UndefValue::get(GEPTy);
2748  }
2749
2750  if (Ops.size() == 2) {
2751    // getelementptr P, 0 -> P.
2752    if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2753      if (C->isZero())
2754        return Ops[0];
2755    // getelementptr P, N -> P if P points to a type of zero size.
2756    if (Q.TD) {
2757      Type *Ty = PtrTy->getElementType();
2758      if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
2759        return Ops[0];
2760    }
2761  }
2762
2763  // Check to see if this is constant foldable.
2764  for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2765    if (!isa<Constant>(Ops[i]))
2766      return 0;
2767
2768  return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2769}
2770
2771Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
2772                             const TargetLibraryInfo *TLI,
2773                             const DominatorTree *DT) {
2774  return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2775}
2776
2777/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2778/// can fold the result.  If not, this returns null.
2779static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2780                                      ArrayRef<unsigned> Idxs, const Query &Q,
2781                                      unsigned) {
2782  if (Constant *CAgg = dyn_cast<Constant>(Agg))
2783    if (Constant *CVal = dyn_cast<Constant>(Val))
2784      return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2785
2786  // insertvalue x, undef, n -> x
2787  if (match(Val, m_Undef()))
2788    return Agg;
2789
2790  // insertvalue x, (extractvalue y, n), n
2791  if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2792    if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2793        EV->getIndices() == Idxs) {
2794      // insertvalue undef, (extractvalue y, n), n -> y
2795      if (match(Agg, m_Undef()))
2796        return EV->getAggregateOperand();
2797
2798      // insertvalue y, (extractvalue y, n), n -> y
2799      if (Agg == EV->getAggregateOperand())
2800        return Agg;
2801    }
2802
2803  return 0;
2804}
2805
2806Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2807                                     ArrayRef<unsigned> Idxs,
2808                                     const DataLayout *TD,
2809                                     const TargetLibraryInfo *TLI,
2810                                     const DominatorTree *DT) {
2811  return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2812                                   RecursionLimit);
2813}
2814
2815/// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2816static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
2817  // If all of the PHI's incoming values are the same then replace the PHI node
2818  // with the common value.
2819  Value *CommonValue = 0;
2820  bool HasUndefInput = false;
2821  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2822    Value *Incoming = PN->getIncomingValue(i);
2823    // If the incoming value is the phi node itself, it can safely be skipped.
2824    if (Incoming == PN) continue;
2825    if (isa<UndefValue>(Incoming)) {
2826      // Remember that we saw an undef value, but otherwise ignore them.
2827      HasUndefInput = true;
2828      continue;
2829    }
2830    if (CommonValue && Incoming != CommonValue)
2831      return 0;  // Not the same, bail out.
2832    CommonValue = Incoming;
2833  }
2834
2835  // If CommonValue is null then all of the incoming values were either undef or
2836  // equal to the phi node itself.
2837  if (!CommonValue)
2838    return UndefValue::get(PN->getType());
2839
2840  // If we have a PHI node like phi(X, undef, X), where X is defined by some
2841  // instruction, we cannot return X as the result of the PHI node unless it
2842  // dominates the PHI block.
2843  if (HasUndefInput)
2844    return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
2845
2846  return CommonValue;
2847}
2848
2849static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2850  if (Constant *C = dyn_cast<Constant>(Op))
2851    return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2852
2853  return 0;
2854}
2855
2856Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
2857                               const TargetLibraryInfo *TLI,
2858                               const DominatorTree *DT) {
2859  return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2860}
2861
2862//=== Helper functions for higher up the class hierarchy.
2863
2864/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2865/// fold the result.  If not, this returns null.
2866static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2867                            const Query &Q, unsigned MaxRecurse) {
2868  switch (Opcode) {
2869  case Instruction::Add:
2870    return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2871                           Q, MaxRecurse);
2872  case Instruction::FAdd:
2873    return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2874
2875  case Instruction::Sub:
2876    return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2877                           Q, MaxRecurse);
2878  case Instruction::FSub:
2879    return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2880
2881  case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2882  case Instruction::FMul:
2883    return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2884  case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2885  case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2886  case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2887  case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2888  case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2889  case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
2890  case Instruction::Shl:
2891    return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2892                           Q, MaxRecurse);
2893  case Instruction::LShr:
2894    return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2895  case Instruction::AShr:
2896    return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2897  case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2898  case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2899  case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
2900  default:
2901    if (Constant *CLHS = dyn_cast<Constant>(LHS))
2902      if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2903        Constant *COps[] = {CLHS, CRHS};
2904        return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2905                                        Q.TLI);
2906      }
2907
2908    // If the operation is associative, try some generic simplifications.
2909    if (Instruction::isAssociative(Opcode))
2910      if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
2911        return V;
2912
2913    // If the operation is with the result of a select instruction check whether
2914    // operating on either branch of the select always yields the same value.
2915    if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2916      if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
2917        return V;
2918
2919    // If the operation is with the result of a phi instruction, check whether
2920    // operating on all incoming values of the phi always yields the same value.
2921    if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2922      if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
2923        return V;
2924
2925    return 0;
2926  }
2927}
2928
2929Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2930                           const DataLayout *TD, const TargetLibraryInfo *TLI,
2931                           const DominatorTree *DT) {
2932  return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
2933}
2934
2935/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2936/// fold the result.
2937static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2938                              const Query &Q, unsigned MaxRecurse) {
2939  if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2940    return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2941  return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2942}
2943
2944Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2945                             const DataLayout *TD, const TargetLibraryInfo *TLI,
2946                             const DominatorTree *DT) {
2947  return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2948                           RecursionLimit);
2949}
2950
2951static bool IsIdempotent(Intrinsic::ID ID) {
2952  switch (ID) {
2953  default: return false;
2954
2955  // Unary idempotent: f(f(x)) = f(x)
2956  case Intrinsic::fabs:
2957  case Intrinsic::floor:
2958  case Intrinsic::ceil:
2959  case Intrinsic::trunc:
2960  case Intrinsic::rint:
2961  case Intrinsic::nearbyint:
2962  case Intrinsic::round:
2963    return true;
2964  }
2965}
2966
2967template <typename IterTy>
2968static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
2969                                const Query &Q, unsigned MaxRecurse) {
2970  // Perform idempotent optimizations
2971  if (!IsIdempotent(IID))
2972    return 0;
2973
2974  // Unary Ops
2975  if (std::distance(ArgBegin, ArgEnd) == 1)
2976    if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
2977      if (II->getIntrinsicID() == IID)
2978        return II;
2979
2980  return 0;
2981}
2982
2983template <typename IterTy>
2984static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
2985                           const Query &Q, unsigned MaxRecurse) {
2986  Type *Ty = V->getType();
2987  if (PointerType *PTy = dyn_cast<PointerType>(Ty))
2988    Ty = PTy->getElementType();
2989  FunctionType *FTy = cast<FunctionType>(Ty);
2990
2991  // call undef -> undef
2992  if (isa<UndefValue>(V))
2993    return UndefValue::get(FTy->getReturnType());
2994
2995  Function *F = dyn_cast<Function>(V);
2996  if (!F)
2997    return 0;
2998
2999  if (unsigned IID = F->getIntrinsicID())
3000    if (Value *Ret =
3001        SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3002      return Ret;
3003
3004  if (!canConstantFoldCallTo(F))
3005    return 0;
3006
3007  SmallVector<Constant *, 4> ConstantArgs;
3008  ConstantArgs.reserve(ArgEnd - ArgBegin);
3009  for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3010    Constant *C = dyn_cast<Constant>(*I);
3011    if (!C)
3012      return 0;
3013    ConstantArgs.push_back(C);
3014  }
3015
3016  return ConstantFoldCall(F, ConstantArgs, Q.TLI);
3017}
3018
3019Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
3020                          User::op_iterator ArgEnd, const DataLayout *TD,
3021                          const TargetLibraryInfo *TLI,
3022                          const DominatorTree *DT) {
3023  return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(TD, TLI, DT),
3024                        RecursionLimit);
3025}
3026
3027Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
3028                          const DataLayout *TD, const TargetLibraryInfo *TLI,
3029                          const DominatorTree *DT) {
3030  return ::SimplifyCall(V, Args.begin(), Args.end(), Query(TD, TLI, DT),
3031                        RecursionLimit);
3032}
3033
3034/// SimplifyInstruction - See if we can compute a simplified version of this
3035/// instruction.  If not, this returns null.
3036Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
3037                                 const TargetLibraryInfo *TLI,
3038                                 const DominatorTree *DT) {
3039  Value *Result;
3040
3041  switch (I->getOpcode()) {
3042  default:
3043    Result = ConstantFoldInstruction(I, TD, TLI);
3044    break;
3045  case Instruction::FAdd:
3046    Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3047                              I->getFastMathFlags(), TD, TLI, DT);
3048    break;
3049  case Instruction::Add:
3050    Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3051                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
3052                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3053                             TD, TLI, DT);
3054    break;
3055  case Instruction::FSub:
3056    Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3057                              I->getFastMathFlags(), TD, TLI, DT);
3058    break;
3059  case Instruction::Sub:
3060    Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3061                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
3062                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3063                             TD, TLI, DT);
3064    break;
3065  case Instruction::FMul:
3066    Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3067                              I->getFastMathFlags(), TD, TLI, DT);
3068    break;
3069  case Instruction::Mul:
3070    Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3071    break;
3072  case Instruction::SDiv:
3073    Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3074    break;
3075  case Instruction::UDiv:
3076    Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3077    break;
3078  case Instruction::FDiv:
3079    Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3080    break;
3081  case Instruction::SRem:
3082    Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3083    break;
3084  case Instruction::URem:
3085    Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3086    break;
3087  case Instruction::FRem:
3088    Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3089    break;
3090  case Instruction::Shl:
3091    Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3092                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
3093                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3094                             TD, TLI, DT);
3095    break;
3096  case Instruction::LShr:
3097    Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3098                              cast<BinaryOperator>(I)->isExact(),
3099                              TD, TLI, DT);
3100    break;
3101  case Instruction::AShr:
3102    Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3103                              cast<BinaryOperator>(I)->isExact(),
3104                              TD, TLI, DT);
3105    break;
3106  case Instruction::And:
3107    Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3108    break;
3109  case Instruction::Or:
3110    Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3111    break;
3112  case Instruction::Xor:
3113    Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3114    break;
3115  case Instruction::ICmp:
3116    Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
3117                              I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3118    break;
3119  case Instruction::FCmp:
3120    Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
3121                              I->getOperand(0), I->getOperand(1), TD, TLI, DT);
3122    break;
3123  case Instruction::Select:
3124    Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
3125                                I->getOperand(2), TD, TLI, DT);
3126    break;
3127  case Instruction::GetElementPtr: {
3128    SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
3129    Result = SimplifyGEPInst(Ops, TD, TLI, DT);
3130    break;
3131  }
3132  case Instruction::InsertValue: {
3133    InsertValueInst *IV = cast<InsertValueInst>(I);
3134    Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3135                                     IV->getInsertedValueOperand(),
3136                                     IV->getIndices(), TD, TLI, DT);
3137    break;
3138  }
3139  case Instruction::PHI:
3140    Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
3141    break;
3142  case Instruction::Call: {
3143    CallSite CS(cast<CallInst>(I));
3144    Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3145                          TD, TLI, DT);
3146    break;
3147  }
3148  case Instruction::Trunc:
3149    Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
3150    break;
3151  }
3152
3153  /// If called on unreachable code, the above logic may report that the
3154  /// instruction simplified to itself.  Make life easier for users by
3155  /// detecting that case here, returning a safe value instead.
3156  return Result == I ? UndefValue::get(I->getType()) : Result;
3157}
3158
3159/// \brief Implementation of recursive simplification through an instructions
3160/// uses.
3161///
3162/// This is the common implementation of the recursive simplification routines.
3163/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3164/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3165/// instructions to process and attempt to simplify it using
3166/// InstructionSimplify.
3167///
3168/// This routine returns 'true' only when *it* simplifies something. The passed
3169/// in simplified value does not count toward this.
3170static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
3171                                              const DataLayout *TD,
3172                                              const TargetLibraryInfo *TLI,
3173                                              const DominatorTree *DT) {
3174  bool Simplified = false;
3175  SmallSetVector<Instruction *, 8> Worklist;
3176
3177  // If we have an explicit value to collapse to, do that round of the
3178  // simplification loop by hand initially.
3179  if (SimpleV) {
3180    for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3181         ++UI)
3182      if (*UI != I)
3183        Worklist.insert(cast<Instruction>(*UI));
3184
3185    // Replace the instruction with its simplified value.
3186    I->replaceAllUsesWith(SimpleV);
3187
3188    // Gracefully handle edge cases where the instruction is not wired into any
3189    // parent block.
3190    if (I->getParent())
3191      I->eraseFromParent();
3192  } else {
3193    Worklist.insert(I);
3194  }
3195
3196  // Note that we must test the size on each iteration, the worklist can grow.
3197  for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3198    I = Worklist[Idx];
3199
3200    // See if this instruction simplifies.
3201    SimpleV = SimplifyInstruction(I, TD, TLI, DT);
3202    if (!SimpleV)
3203      continue;
3204
3205    Simplified = true;
3206
3207    // Stash away all the uses of the old instruction so we can check them for
3208    // recursive simplifications after a RAUW. This is cheaper than checking all
3209    // uses of To on the recursive step in most cases.
3210    for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3211         ++UI)
3212      Worklist.insert(cast<Instruction>(*UI));
3213
3214    // Replace the instruction with its simplified value.
3215    I->replaceAllUsesWith(SimpleV);
3216
3217    // Gracefully handle edge cases where the instruction is not wired into any
3218    // parent block.
3219    if (I->getParent())
3220      I->eraseFromParent();
3221  }
3222  return Simplified;
3223}
3224
3225bool llvm::recursivelySimplifyInstruction(Instruction *I,
3226                                          const DataLayout *TD,
3227                                          const TargetLibraryInfo *TLI,
3228                                          const DominatorTree *DT) {
3229  return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
3230}
3231
3232bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
3233                                         const DataLayout *TD,
3234                                         const TargetLibraryInfo *TLI,
3235                                         const DominatorTree *DT) {
3236  assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3237  assert(SimpleV && "Must provide a simplified value.");
3238  return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
3239}
3240