InstructionSimplify.cpp revision 223017
1199481Srdivacky//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2199481Srdivacky//
3199481Srdivacky//                     The LLVM Compiler Infrastructure
4199481Srdivacky//
5199481Srdivacky// This file is distributed under the University of Illinois Open Source
6199481Srdivacky// License. See LICENSE.TXT for details.
7199481Srdivacky//
8199481Srdivacky//===----------------------------------------------------------------------===//
9199481Srdivacky//
10199481Srdivacky// This file implements routines for folding instructions into simpler forms
11218893Sdim// that do not require creating new instructions.  This does constant folding
12218893Sdim// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13218893Sdim// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14218893Sdim// ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15218893Sdim// simplified: This is usually true and assuming it simplifies the logic (if
16218893Sdim// they have not been simplified then results are correct but maybe suboptimal).
17199481Srdivacky//
18199481Srdivacky//===----------------------------------------------------------------------===//
19199481Srdivacky
20218893Sdim#define DEBUG_TYPE "instsimplify"
21221345Sdim#include "llvm/Operator.h"
22218893Sdim#include "llvm/ADT/Statistic.h"
23199481Srdivacky#include "llvm/Analysis/InstructionSimplify.h"
24199481Srdivacky#include "llvm/Analysis/ConstantFolding.h"
25218893Sdim#include "llvm/Analysis/Dominators.h"
26218893Sdim#include "llvm/Analysis/ValueTracking.h"
27221345Sdim#include "llvm/Support/ConstantRange.h"
28218893Sdim#include "llvm/Support/PatternMatch.h"
29199481Srdivacky#include "llvm/Support/ValueHandle.h"
30218893Sdim#include "llvm/Target/TargetData.h"
31199481Srdivackyusing namespace llvm;
32199481Srdivackyusing namespace llvm::PatternMatch;
33199481Srdivacky
34218893Sdimenum { RecursionLimit = 3 };
35218893Sdim
36218893SdimSTATISTIC(NumExpand,  "Number of expansions");
37218893SdimSTATISTIC(NumFactor , "Number of factorizations");
38218893SdimSTATISTIC(NumReassoc, "Number of reassociations");
39218893Sdim
40218893Sdimstatic Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41218893Sdim                              const DominatorTree *, unsigned);
42218893Sdimstatic Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
43218893Sdim                            const DominatorTree *, unsigned);
44218893Sdimstatic Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
45218893Sdim                              const DominatorTree *, unsigned);
46218893Sdimstatic Value *SimplifyOrInst(Value *, Value *, const TargetData *,
47218893Sdim                             const DominatorTree *, unsigned);
48218893Sdimstatic Value *SimplifyXorInst(Value *, Value *, const TargetData *,
49218893Sdim                              const DominatorTree *, unsigned);
50218893Sdim
51218893Sdim/// ValueDominatesPHI - Does the given value dominate the specified phi node?
52218893Sdimstatic bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
53218893Sdim  Instruction *I = dyn_cast<Instruction>(V);
54218893Sdim  if (!I)
55218893Sdim    // Arguments and constants dominate all instructions.
56218893Sdim    return true;
57218893Sdim
58218893Sdim  // If we have a DominatorTree then do a precise test.
59218893Sdim  if (DT)
60218893Sdim    return DT->dominates(I, P);
61218893Sdim
62218893Sdim  // Otherwise, if the instruction is in the entry block, and is not an invoke,
63218893Sdim  // then it obviously dominates all phi nodes.
64218893Sdim  if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
65218893Sdim      !isa<InvokeInst>(I))
66218893Sdim    return true;
67218893Sdim
68218893Sdim  return false;
69218893Sdim}
70218893Sdim
71218893Sdim/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
72218893Sdim/// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
73218893Sdim/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
74218893Sdim/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
75218893Sdim/// Returns the simplified value, or null if no simplification was performed.
76218893Sdimstatic Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
77218893Sdim                          unsigned OpcToExpand, const TargetData *TD,
78218893Sdim                          const DominatorTree *DT, unsigned MaxRecurse) {
79218893Sdim  Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
80218893Sdim  // Recursion is always used, so bail out at once if we already hit the limit.
81218893Sdim  if (!MaxRecurse--)
82218893Sdim    return 0;
83218893Sdim
84218893Sdim  // Check whether the expression has the form "(A op' B) op C".
85218893Sdim  if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
86218893Sdim    if (Op0->getOpcode() == OpcodeToExpand) {
87218893Sdim      // It does!  Try turning it into "(A op C) op' (B op C)".
88218893Sdim      Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
89218893Sdim      // Do "A op C" and "B op C" both simplify?
90218893Sdim      if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
91218893Sdim        if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
92218893Sdim          // They do! Return "L op' R" if it simplifies or is already available.
93218893Sdim          // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
94218893Sdim          if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
95218893Sdim                                     && L == B && R == A)) {
96218893Sdim            ++NumExpand;
97218893Sdim            return LHS;
98218893Sdim          }
99218893Sdim          // Otherwise return "L op' R" if it simplifies.
100218893Sdim          if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
101218893Sdim                                       MaxRecurse)) {
102218893Sdim            ++NumExpand;
103218893Sdim            return V;
104218893Sdim          }
105218893Sdim        }
106218893Sdim    }
107218893Sdim
108218893Sdim  // Check whether the expression has the form "A op (B op' C)".
109218893Sdim  if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
110218893Sdim    if (Op1->getOpcode() == OpcodeToExpand) {
111218893Sdim      // It does!  Try turning it into "(A op B) op' (A op C)".
112218893Sdim      Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
113218893Sdim      // Do "A op B" and "A op C" both simplify?
114218893Sdim      if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
115218893Sdim        if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
116218893Sdim          // They do! Return "L op' R" if it simplifies or is already available.
117218893Sdim          // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
118218893Sdim          if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
119218893Sdim                                     && L == C && R == B)) {
120218893Sdim            ++NumExpand;
121218893Sdim            return RHS;
122218893Sdim          }
123218893Sdim          // Otherwise return "L op' R" if it simplifies.
124218893Sdim          if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
125218893Sdim                                       MaxRecurse)) {
126218893Sdim            ++NumExpand;
127218893Sdim            return V;
128218893Sdim          }
129218893Sdim        }
130218893Sdim    }
131218893Sdim
132218893Sdim  return 0;
133218893Sdim}
134218893Sdim
135218893Sdim/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
136218893Sdim/// using the operation OpCodeToExtract.  For example, when Opcode is Add and
137218893Sdim/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
138218893Sdim/// Returns the simplified value, or null if no simplification was performed.
139218893Sdimstatic Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
140218893Sdim                             unsigned OpcToExtract, const TargetData *TD,
141218893Sdim                             const DominatorTree *DT, unsigned MaxRecurse) {
142218893Sdim  Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
143218893Sdim  // Recursion is always used, so bail out at once if we already hit the limit.
144218893Sdim  if (!MaxRecurse--)
145218893Sdim    return 0;
146218893Sdim
147218893Sdim  BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
148218893Sdim  BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
149218893Sdim
150218893Sdim  if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
151218893Sdim      !Op1 || Op1->getOpcode() != OpcodeToExtract)
152218893Sdim    return 0;
153218893Sdim
154218893Sdim  // The expression has the form "(A op' B) op (C op' D)".
155218893Sdim  Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
156218893Sdim  Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
157218893Sdim
158218893Sdim  // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
159218893Sdim  // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
160218893Sdim  // commutative case, "(A op' B) op (C op' A)"?
161218893Sdim  if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
162218893Sdim    Value *DD = A == C ? D : C;
163218893Sdim    // Form "A op' (B op DD)" if it simplifies completely.
164218893Sdim    // Does "B op DD" simplify?
165218893Sdim    if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
166218893Sdim      // It does!  Return "A op' V" if it simplifies or is already available.
167218893Sdim      // If V equals B then "A op' V" is just the LHS.  If V equals DD then
168218893Sdim      // "A op' V" is just the RHS.
169218893Sdim      if (V == B || V == DD) {
170218893Sdim        ++NumFactor;
171218893Sdim        return V == B ? LHS : RHS;
172218893Sdim      }
173218893Sdim      // Otherwise return "A op' V" if it simplifies.
174218893Sdim      if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
175218893Sdim        ++NumFactor;
176218893Sdim        return W;
177218893Sdim      }
178218893Sdim    }
179218893Sdim  }
180218893Sdim
181218893Sdim  // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
182218893Sdim  // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
183218893Sdim  // commutative case, "(A op' B) op (B op' D)"?
184218893Sdim  if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
185218893Sdim    Value *CC = B == D ? C : D;
186218893Sdim    // Form "(A op CC) op' B" if it simplifies completely..
187218893Sdim    // Does "A op CC" simplify?
188218893Sdim    if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
189218893Sdim      // It does!  Return "V op' B" if it simplifies or is already available.
190218893Sdim      // If V equals A then "V op' B" is just the LHS.  If V equals CC then
191218893Sdim      // "V op' B" is just the RHS.
192218893Sdim      if (V == A || V == CC) {
193218893Sdim        ++NumFactor;
194218893Sdim        return V == A ? LHS : RHS;
195218893Sdim      }
196218893Sdim      // Otherwise return "V op' B" if it simplifies.
197218893Sdim      if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
198218893Sdim        ++NumFactor;
199218893Sdim        return W;
200218893Sdim      }
201218893Sdim    }
202218893Sdim  }
203218893Sdim
204218893Sdim  return 0;
205218893Sdim}
206218893Sdim
207218893Sdim/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
208218893Sdim/// operations.  Returns the simpler value, or null if none was found.
209218893Sdimstatic Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
210218893Sdim                                       const TargetData *TD,
211218893Sdim                                       const DominatorTree *DT,
212218893Sdim                                       unsigned MaxRecurse) {
213218893Sdim  Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
214218893Sdim  assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
215218893Sdim
216218893Sdim  // Recursion is always used, so bail out at once if we already hit the limit.
217218893Sdim  if (!MaxRecurse--)
218218893Sdim    return 0;
219218893Sdim
220218893Sdim  BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
221218893Sdim  BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
222218893Sdim
223218893Sdim  // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
224218893Sdim  if (Op0 && Op0->getOpcode() == Opcode) {
225218893Sdim    Value *A = Op0->getOperand(0);
226218893Sdim    Value *B = Op0->getOperand(1);
227218893Sdim    Value *C = RHS;
228218893Sdim
229218893Sdim    // Does "B op C" simplify?
230218893Sdim    if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
231218893Sdim      // It does!  Return "A op V" if it simplifies or is already available.
232218893Sdim      // If V equals B then "A op V" is just the LHS.
233218893Sdim      if (V == B) return LHS;
234218893Sdim      // Otherwise return "A op V" if it simplifies.
235218893Sdim      if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
236218893Sdim        ++NumReassoc;
237218893Sdim        return W;
238218893Sdim      }
239218893Sdim    }
240218893Sdim  }
241218893Sdim
242218893Sdim  // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
243218893Sdim  if (Op1 && Op1->getOpcode() == Opcode) {
244218893Sdim    Value *A = LHS;
245218893Sdim    Value *B = Op1->getOperand(0);
246218893Sdim    Value *C = Op1->getOperand(1);
247218893Sdim
248218893Sdim    // Does "A op B" simplify?
249218893Sdim    if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
250218893Sdim      // It does!  Return "V op C" if it simplifies or is already available.
251218893Sdim      // If V equals B then "V op C" is just the RHS.
252218893Sdim      if (V == B) return RHS;
253218893Sdim      // Otherwise return "V op C" if it simplifies.
254218893Sdim      if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
255218893Sdim        ++NumReassoc;
256218893Sdim        return W;
257218893Sdim      }
258218893Sdim    }
259218893Sdim  }
260218893Sdim
261218893Sdim  // The remaining transforms require commutativity as well as associativity.
262218893Sdim  if (!Instruction::isCommutative(Opcode))
263218893Sdim    return 0;
264218893Sdim
265218893Sdim  // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
266218893Sdim  if (Op0 && Op0->getOpcode() == Opcode) {
267218893Sdim    Value *A = Op0->getOperand(0);
268218893Sdim    Value *B = Op0->getOperand(1);
269218893Sdim    Value *C = RHS;
270218893Sdim
271218893Sdim    // Does "C op A" simplify?
272218893Sdim    if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
273218893Sdim      // It does!  Return "V op B" if it simplifies or is already available.
274218893Sdim      // If V equals A then "V op B" is just the LHS.
275218893Sdim      if (V == A) return LHS;
276218893Sdim      // Otherwise return "V op B" if it simplifies.
277218893Sdim      if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
278218893Sdim        ++NumReassoc;
279218893Sdim        return W;
280218893Sdim      }
281218893Sdim    }
282218893Sdim  }
283218893Sdim
284218893Sdim  // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
285218893Sdim  if (Op1 && Op1->getOpcode() == Opcode) {
286218893Sdim    Value *A = LHS;
287218893Sdim    Value *B = Op1->getOperand(0);
288218893Sdim    Value *C = Op1->getOperand(1);
289218893Sdim
290218893Sdim    // Does "C op A" simplify?
291218893Sdim    if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
292218893Sdim      // It does!  Return "B op V" if it simplifies or is already available.
293218893Sdim      // If V equals C then "B op V" is just the RHS.
294218893Sdim      if (V == C) return RHS;
295218893Sdim      // Otherwise return "B op V" if it simplifies.
296218893Sdim      if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
297218893Sdim        ++NumReassoc;
298218893Sdim        return W;
299218893Sdim      }
300218893Sdim    }
301218893Sdim  }
302218893Sdim
303218893Sdim  return 0;
304218893Sdim}
305218893Sdim
306218893Sdim/// ThreadBinOpOverSelect - In the case of a binary operation with a select
307218893Sdim/// instruction as an operand, try to simplify the binop by seeing whether
308218893Sdim/// evaluating it on both branches of the select results in the same value.
309218893Sdim/// Returns the common value if so, otherwise returns null.
310218893Sdimstatic Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
311218893Sdim                                    const TargetData *TD,
312218893Sdim                                    const DominatorTree *DT,
313218893Sdim                                    unsigned MaxRecurse) {
314218893Sdim  // Recursion is always used, so bail out at once if we already hit the limit.
315218893Sdim  if (!MaxRecurse--)
316218893Sdim    return 0;
317218893Sdim
318218893Sdim  SelectInst *SI;
319218893Sdim  if (isa<SelectInst>(LHS)) {
320218893Sdim    SI = cast<SelectInst>(LHS);
321218893Sdim  } else {
322218893Sdim    assert(isa<SelectInst>(RHS) && "No select instruction operand!");
323218893Sdim    SI = cast<SelectInst>(RHS);
324218893Sdim  }
325218893Sdim
326218893Sdim  // Evaluate the BinOp on the true and false branches of the select.
327218893Sdim  Value *TV;
328218893Sdim  Value *FV;
329218893Sdim  if (SI == LHS) {
330218893Sdim    TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
331218893Sdim    FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
332218893Sdim  } else {
333218893Sdim    TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
334218893Sdim    FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
335218893Sdim  }
336218893Sdim
337218893Sdim  // If they simplified to the same value, then return the common value.
338218893Sdim  // If they both failed to simplify then return null.
339218893Sdim  if (TV == FV)
340218893Sdim    return TV;
341218893Sdim
342218893Sdim  // If one branch simplified to undef, return the other one.
343218893Sdim  if (TV && isa<UndefValue>(TV))
344218893Sdim    return FV;
345218893Sdim  if (FV && isa<UndefValue>(FV))
346218893Sdim    return TV;
347218893Sdim
348218893Sdim  // If applying the operation did not change the true and false select values,
349218893Sdim  // then the result of the binop is the select itself.
350218893Sdim  if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
351218893Sdim    return SI;
352218893Sdim
353218893Sdim  // If one branch simplified and the other did not, and the simplified
354218893Sdim  // value is equal to the unsimplified one, return the simplified value.
355218893Sdim  // For example, select (cond, X, X & Z) & Z -> X & Z.
356218893Sdim  if ((FV && !TV) || (TV && !FV)) {
357218893Sdim    // Check that the simplified value has the form "X op Y" where "op" is the
358218893Sdim    // same as the original operation.
359218893Sdim    Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
360218893Sdim    if (Simplified && Simplified->getOpcode() == Opcode) {
361218893Sdim      // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
362218893Sdim      // We already know that "op" is the same as for the simplified value.  See
363218893Sdim      // if the operands match too.  If so, return the simplified value.
364218893Sdim      Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
365218893Sdim      Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
366218893Sdim      Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
367218893Sdim      if (Simplified->getOperand(0) == UnsimplifiedLHS &&
368218893Sdim          Simplified->getOperand(1) == UnsimplifiedRHS)
369218893Sdim        return Simplified;
370218893Sdim      if (Simplified->isCommutative() &&
371218893Sdim          Simplified->getOperand(1) == UnsimplifiedLHS &&
372218893Sdim          Simplified->getOperand(0) == UnsimplifiedRHS)
373218893Sdim        return Simplified;
374218893Sdim    }
375218893Sdim  }
376218893Sdim
377218893Sdim  return 0;
378218893Sdim}
379218893Sdim
380218893Sdim/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
381218893Sdim/// try to simplify the comparison by seeing whether both branches of the select
382218893Sdim/// result in the same value.  Returns the common value if so, otherwise returns
383218893Sdim/// null.
384218893Sdimstatic Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
385218893Sdim                                  Value *RHS, const TargetData *TD,
386218893Sdim                                  const DominatorTree *DT,
387218893Sdim                                  unsigned MaxRecurse) {
388218893Sdim  // Recursion is always used, so bail out at once if we already hit the limit.
389218893Sdim  if (!MaxRecurse--)
390218893Sdim    return 0;
391218893Sdim
392218893Sdim  // Make sure the select is on the LHS.
393218893Sdim  if (!isa<SelectInst>(LHS)) {
394218893Sdim    std::swap(LHS, RHS);
395218893Sdim    Pred = CmpInst::getSwappedPredicate(Pred);
396218893Sdim  }
397218893Sdim  assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
398218893Sdim  SelectInst *SI = cast<SelectInst>(LHS);
399218893Sdim
400218893Sdim  // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
401218893Sdim  // Does "cmp TV, RHS" simplify?
402218893Sdim  if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
403218893Sdim                                    MaxRecurse)) {
404218893Sdim    // It does!  Does "cmp FV, RHS" simplify?
405218893Sdim    if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
406218893Sdim                                      MaxRecurse)) {
407218893Sdim      // It does!  If they simplified to the same value, then use it as the
408218893Sdim      // result of the original comparison.
409218893Sdim      if (TCmp == FCmp)
410218893Sdim        return TCmp;
411218893Sdim      Value *Cond = SI->getCondition();
412218893Sdim      // If the false value simplified to false, then the result of the compare
413218893Sdim      // is equal to "Cond && TCmp".  This also catches the case when the false
414218893Sdim      // value simplified to false and the true value to true, returning "Cond".
415218893Sdim      if (match(FCmp, m_Zero()))
416218893Sdim        if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
417218893Sdim          return V;
418218893Sdim      // If the true value simplified to true, then the result of the compare
419218893Sdim      // is equal to "Cond || FCmp".
420218893Sdim      if (match(TCmp, m_One()))
421218893Sdim        if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
422218893Sdim          return V;
423218893Sdim      // Finally, if the false value simplified to true and the true value to
424218893Sdim      // false, then the result of the compare is equal to "!Cond".
425218893Sdim      if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
426218893Sdim        if (Value *V =
427218893Sdim            SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
428218893Sdim                            TD, DT, MaxRecurse))
429218893Sdim          return V;
430218893Sdim    }
431218893Sdim  }
432218893Sdim
433218893Sdim  return 0;
434218893Sdim}
435218893Sdim
436218893Sdim/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
437218893Sdim/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
438218893Sdim/// it on the incoming phi values yields the same result for every value.  If so
439218893Sdim/// returns the common value, otherwise returns null.
440218893Sdimstatic Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
441218893Sdim                                 const TargetData *TD, const DominatorTree *DT,
442218893Sdim                                 unsigned MaxRecurse) {
443218893Sdim  // Recursion is always used, so bail out at once if we already hit the limit.
444218893Sdim  if (!MaxRecurse--)
445218893Sdim    return 0;
446218893Sdim
447218893Sdim  PHINode *PI;
448218893Sdim  if (isa<PHINode>(LHS)) {
449218893Sdim    PI = cast<PHINode>(LHS);
450218893Sdim    // Bail out if RHS and the phi may be mutually interdependent due to a loop.
451218893Sdim    if (!ValueDominatesPHI(RHS, PI, DT))
452218893Sdim      return 0;
453218893Sdim  } else {
454218893Sdim    assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
455218893Sdim    PI = cast<PHINode>(RHS);
456218893Sdim    // Bail out if LHS and the phi may be mutually interdependent due to a loop.
457218893Sdim    if (!ValueDominatesPHI(LHS, PI, DT))
458218893Sdim      return 0;
459218893Sdim  }
460218893Sdim
461218893Sdim  // Evaluate the BinOp on the incoming phi values.
462218893Sdim  Value *CommonValue = 0;
463218893Sdim  for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
464218893Sdim    Value *Incoming = PI->getIncomingValue(i);
465218893Sdim    // If the incoming value is the phi node itself, it can safely be skipped.
466218893Sdim    if (Incoming == PI) continue;
467218893Sdim    Value *V = PI == LHS ?
468218893Sdim      SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
469218893Sdim      SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
470218893Sdim    // If the operation failed to simplify, or simplified to a different value
471218893Sdim    // to previously, then give up.
472218893Sdim    if (!V || (CommonValue && V != CommonValue))
473218893Sdim      return 0;
474218893Sdim    CommonValue = V;
475218893Sdim  }
476218893Sdim
477218893Sdim  return CommonValue;
478218893Sdim}
479218893Sdim
480218893Sdim/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
481218893Sdim/// try to simplify the comparison by seeing whether comparing with all of the
482218893Sdim/// incoming phi values yields the same result every time.  If so returns the
483218893Sdim/// common result, otherwise returns null.
484218893Sdimstatic Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
485218893Sdim                               const TargetData *TD, const DominatorTree *DT,
486218893Sdim                               unsigned MaxRecurse) {
487218893Sdim  // Recursion is always used, so bail out at once if we already hit the limit.
488218893Sdim  if (!MaxRecurse--)
489218893Sdim    return 0;
490218893Sdim
491218893Sdim  // Make sure the phi is on the LHS.
492218893Sdim  if (!isa<PHINode>(LHS)) {
493218893Sdim    std::swap(LHS, RHS);
494218893Sdim    Pred = CmpInst::getSwappedPredicate(Pred);
495218893Sdim  }
496218893Sdim  assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
497218893Sdim  PHINode *PI = cast<PHINode>(LHS);
498218893Sdim
499218893Sdim  // Bail out if RHS and the phi may be mutually interdependent due to a loop.
500218893Sdim  if (!ValueDominatesPHI(RHS, PI, DT))
501218893Sdim    return 0;
502218893Sdim
503218893Sdim  // Evaluate the BinOp on the incoming phi values.
504218893Sdim  Value *CommonValue = 0;
505218893Sdim  for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
506218893Sdim    Value *Incoming = PI->getIncomingValue(i);
507218893Sdim    // If the incoming value is the phi node itself, it can safely be skipped.
508218893Sdim    if (Incoming == PI) continue;
509218893Sdim    Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
510218893Sdim    // If the operation failed to simplify, or simplified to a different value
511218893Sdim    // to previously, then give up.
512218893Sdim    if (!V || (CommonValue && V != CommonValue))
513218893Sdim      return 0;
514218893Sdim    CommonValue = V;
515218893Sdim  }
516218893Sdim
517218893Sdim  return CommonValue;
518218893Sdim}
519218893Sdim
520199989Srdivacky/// SimplifyAddInst - Given operands for an Add, see if we can
521199481Srdivacky/// fold the result.  If not, this returns null.
522218893Sdimstatic Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
523218893Sdim                              const TargetData *TD, const DominatorTree *DT,
524218893Sdim                              unsigned MaxRecurse) {
525199481Srdivacky  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
526199481Srdivacky    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
527199481Srdivacky      Constant *Ops[] = { CLHS, CRHS };
528199989Srdivacky      return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
529199989Srdivacky                                      Ops, 2, TD);
530199989Srdivacky    }
531218893Sdim
532199989Srdivacky    // Canonicalize the constant to the RHS.
533199989Srdivacky    std::swap(Op0, Op1);
534199989Srdivacky  }
535218893Sdim
536218893Sdim  // X + undef -> undef
537218893Sdim  if (match(Op1, m_Undef()))
538218893Sdim    return Op1;
539218893Sdim
540218893Sdim  // X + 0 -> X
541218893Sdim  if (match(Op1, m_Zero()))
542218893Sdim    return Op0;
543218893Sdim
544218893Sdim  // X + (Y - X) -> Y
545218893Sdim  // (Y - X) + X -> Y
546218893Sdim  // Eg: X + -X -> 0
547218893Sdim  Value *Y = 0;
548218893Sdim  if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
549218893Sdim      match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
550218893Sdim    return Y;
551218893Sdim
552218893Sdim  // X + ~X -> -1   since   ~X = -X-1
553218893Sdim  if (match(Op0, m_Not(m_Specific(Op1))) ||
554218893Sdim      match(Op1, m_Not(m_Specific(Op0))))
555218893Sdim    return Constant::getAllOnesValue(Op0->getType());
556218893Sdim
557218893Sdim  /// i1 add -> xor.
558218893Sdim  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
559218893Sdim    if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
560218893Sdim      return V;
561218893Sdim
562218893Sdim  // Try some generic simplifications for associative operations.
563218893Sdim  if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
564218893Sdim                                          MaxRecurse))
565218893Sdim    return V;
566218893Sdim
567218893Sdim  // Mul distributes over Add.  Try some generic simplifications based on this.
568218893Sdim  if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
569218893Sdim                                TD, DT, MaxRecurse))
570218893Sdim    return V;
571218893Sdim
572218893Sdim  // Threading Add over selects and phi nodes is pointless, so don't bother.
573218893Sdim  // Threading over the select in "A + select(cond, B, C)" means evaluating
574218893Sdim  // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
575218893Sdim  // only if B and C are equal.  If B and C are equal then (since we assume
576218893Sdim  // that operands have already been simplified) "select(cond, B, C)" should
577218893Sdim  // have been simplified to the common value of B and C already.  Analysing
578218893Sdim  // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
579218893Sdim  // for threading over phi nodes.
580218893Sdim
581218893Sdim  return 0;
582218893Sdim}
583218893Sdim
584218893SdimValue *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
585218893Sdim                             const TargetData *TD, const DominatorTree *DT) {
586218893Sdim  return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
587218893Sdim}
588218893Sdim
589218893Sdim/// SimplifySubInst - Given operands for a Sub, see if we can
590218893Sdim/// fold the result.  If not, this returns null.
591218893Sdimstatic Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
592218893Sdim                              const TargetData *TD, const DominatorTree *DT,
593218893Sdim                              unsigned MaxRecurse) {
594218893Sdim  if (Constant *CLHS = dyn_cast<Constant>(Op0))
595218893Sdim    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596218893Sdim      Constant *Ops[] = { CLHS, CRHS };
597218893Sdim      return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
598218893Sdim                                      Ops, 2, TD);
599218893Sdim    }
600218893Sdim
601218893Sdim  // X - undef -> undef
602218893Sdim  // undef - X -> undef
603218893Sdim  if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
604218893Sdim    return UndefValue::get(Op0->getType());
605218893Sdim
606218893Sdim  // X - 0 -> X
607218893Sdim  if (match(Op1, m_Zero()))
608218893Sdim    return Op0;
609218893Sdim
610218893Sdim  // X - X -> 0
611218893Sdim  if (Op0 == Op1)
612218893Sdim    return Constant::getNullValue(Op0->getType());
613218893Sdim
614218893Sdim  // (X*2) - X -> X
615218893Sdim  // (X<<1) - X -> X
616218893Sdim  Value *X = 0;
617218893Sdim  if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
618218893Sdim      match(Op0, m_Shl(m_Specific(Op1), m_One())))
619218893Sdim    return Op1;
620218893Sdim
621218893Sdim  // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
622218893Sdim  // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
623218893Sdim  Value *Y = 0, *Z = Op1;
624218893Sdim  if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
625218893Sdim    // See if "V === Y - Z" simplifies.
626218893Sdim    if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
627218893Sdim      // It does!  Now see if "X + V" simplifies.
628218893Sdim      if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
629218893Sdim                                   MaxRecurse-1)) {
630218893Sdim        // It does, we successfully reassociated!
631218893Sdim        ++NumReassoc;
632218893Sdim        return W;
633218893Sdim      }
634218893Sdim    // See if "V === X - Z" simplifies.
635218893Sdim    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
636218893Sdim      // It does!  Now see if "Y + V" simplifies.
637218893Sdim      if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
638218893Sdim                                   MaxRecurse-1)) {
639218893Sdim        // It does, we successfully reassociated!
640218893Sdim        ++NumReassoc;
641218893Sdim        return W;
642218893Sdim      }
643199989Srdivacky  }
644218893Sdim
645218893Sdim  // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
646218893Sdim  // For example, X - (X + 1) -> -1
647218893Sdim  X = Op0;
648218893Sdim  if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
649218893Sdim    // See if "V === X - Y" simplifies.
650218893Sdim    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
651218893Sdim      // It does!  Now see if "V - Z" simplifies.
652218893Sdim      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
653218893Sdim                                   MaxRecurse-1)) {
654218893Sdim        // It does, we successfully reassociated!
655218893Sdim        ++NumReassoc;
656218893Sdim        return W;
657218893Sdim      }
658218893Sdim    // See if "V === X - Z" simplifies.
659218893Sdim    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
660218893Sdim      // It does!  Now see if "V - Y" simplifies.
661218893Sdim      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
662218893Sdim                                   MaxRecurse-1)) {
663218893Sdim        // It does, we successfully reassociated!
664218893Sdim        ++NumReassoc;
665218893Sdim        return W;
666218893Sdim      }
667218893Sdim  }
668218893Sdim
669218893Sdim  // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
670218893Sdim  // For example, X - (X - Y) -> Y.
671218893Sdim  Z = Op0;
672218893Sdim  if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
673218893Sdim    // See if "V === Z - X" simplifies.
674218893Sdim    if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
675218893Sdim      // It does!  Now see if "V + Y" simplifies.
676218893Sdim      if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
677218893Sdim                                   MaxRecurse-1)) {
678218893Sdim        // It does, we successfully reassociated!
679218893Sdim        ++NumReassoc;
680218893Sdim        return W;
681218893Sdim      }
682218893Sdim
683218893Sdim  // Mul distributes over Sub.  Try some generic simplifications based on this.
684218893Sdim  if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
685218893Sdim                                TD, DT, MaxRecurse))
686218893Sdim    return V;
687218893Sdim
688218893Sdim  // i1 sub -> xor.
689218893Sdim  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
690218893Sdim    if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
691218893Sdim      return V;
692218893Sdim
693218893Sdim  // Threading Sub over selects and phi nodes is pointless, so don't bother.
694218893Sdim  // Threading over the select in "A - select(cond, B, C)" means evaluating
695218893Sdim  // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
696218893Sdim  // only if B and C are equal.  If B and C are equal then (since we assume
697218893Sdim  // that operands have already been simplified) "select(cond, B, C)" should
698218893Sdim  // have been simplified to the common value of B and C already.  Analysing
699218893Sdim  // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
700218893Sdim  // for threading over phi nodes.
701218893Sdim
702199989Srdivacky  return 0;
703199989Srdivacky}
704199989Srdivacky
705218893SdimValue *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
706218893Sdim                             const TargetData *TD, const DominatorTree *DT) {
707218893Sdim  return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
708218893Sdim}
709218893Sdim
710218893Sdim/// SimplifyMulInst - Given operands for a Mul, see if we can
711218893Sdim/// fold the result.  If not, this returns null.
712218893Sdimstatic Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
713218893Sdim                              const DominatorTree *DT, unsigned MaxRecurse) {
714218893Sdim  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
715218893Sdim    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
716218893Sdim      Constant *Ops[] = { CLHS, CRHS };
717218893Sdim      return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
718218893Sdim                                      Ops, 2, TD);
719218893Sdim    }
720218893Sdim
721218893Sdim    // Canonicalize the constant to the RHS.
722218893Sdim    std::swap(Op0, Op1);
723218893Sdim  }
724218893Sdim
725218893Sdim  // X * undef -> 0
726218893Sdim  if (match(Op1, m_Undef()))
727218893Sdim    return Constant::getNullValue(Op0->getType());
728218893Sdim
729218893Sdim  // X * 0 -> 0
730218893Sdim  if (match(Op1, m_Zero()))
731218893Sdim    return Op1;
732218893Sdim
733218893Sdim  // X * 1 -> X
734218893Sdim  if (match(Op1, m_One()))
735218893Sdim    return Op0;
736218893Sdim
737218893Sdim  // (X / Y) * Y -> X if the division is exact.
738218893Sdim  Value *X = 0, *Y = 0;
739218893Sdim  if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
740218893Sdim      (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
741218893Sdim    BinaryOperator *Div = cast<BinaryOperator>(Y == Op1 ? Op0 : Op1);
742218893Sdim    if (Div->isExact())
743218893Sdim      return X;
744218893Sdim  }
745218893Sdim
746218893Sdim  // i1 mul -> and.
747218893Sdim  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
748218893Sdim    if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
749218893Sdim      return V;
750218893Sdim
751218893Sdim  // Try some generic simplifications for associative operations.
752218893Sdim  if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
753218893Sdim                                          MaxRecurse))
754218893Sdim    return V;
755218893Sdim
756218893Sdim  // Mul distributes over Add.  Try some generic simplifications based on this.
757218893Sdim  if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
758218893Sdim                             TD, DT, MaxRecurse))
759218893Sdim    return V;
760218893Sdim
761218893Sdim  // If the operation is with the result of a select instruction, check whether
762218893Sdim  // operating on either branch of the select always yields the same value.
763218893Sdim  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
764218893Sdim    if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
765218893Sdim                                         MaxRecurse))
766218893Sdim      return V;
767218893Sdim
768218893Sdim  // If the operation is with the result of a phi instruction, check whether
769218893Sdim  // operating on all incoming values of the phi always yields the same value.
770218893Sdim  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
771218893Sdim    if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
772218893Sdim                                      MaxRecurse))
773218893Sdim      return V;
774218893Sdim
775218893Sdim  return 0;
776218893Sdim}
777218893Sdim
778218893SdimValue *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
779218893Sdim                             const DominatorTree *DT) {
780218893Sdim  return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
781218893Sdim}
782218893Sdim
783218893Sdim/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
784218893Sdim/// fold the result.  If not, this returns null.
785218893Sdimstatic Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
786218893Sdim                          const TargetData *TD, const DominatorTree *DT,
787218893Sdim                          unsigned MaxRecurse) {
788218893Sdim  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
789218893Sdim    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
790218893Sdim      Constant *Ops[] = { C0, C1 };
791218893Sdim      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
792218893Sdim    }
793218893Sdim  }
794218893Sdim
795218893Sdim  bool isSigned = Opcode == Instruction::SDiv;
796218893Sdim
797218893Sdim  // X / undef -> undef
798218893Sdim  if (match(Op1, m_Undef()))
799218893Sdim    return Op1;
800218893Sdim
801218893Sdim  // undef / X -> 0
802218893Sdim  if (match(Op0, m_Undef()))
803218893Sdim    return Constant::getNullValue(Op0->getType());
804218893Sdim
805218893Sdim  // 0 / X -> 0, we don't need to preserve faults!
806218893Sdim  if (match(Op0, m_Zero()))
807218893Sdim    return Op0;
808218893Sdim
809218893Sdim  // X / 1 -> X
810218893Sdim  if (match(Op1, m_One()))
811218893Sdim    return Op0;
812218893Sdim
813218893Sdim  if (Op0->getType()->isIntegerTy(1))
814218893Sdim    // It can't be division by zero, hence it must be division by one.
815218893Sdim    return Op0;
816218893Sdim
817218893Sdim  // X / X -> 1
818218893Sdim  if (Op0 == Op1)
819218893Sdim    return ConstantInt::get(Op0->getType(), 1);
820218893Sdim
821218893Sdim  // (X * Y) / Y -> X if the multiplication does not overflow.
822218893Sdim  Value *X = 0, *Y = 0;
823218893Sdim  if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
824218893Sdim    if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
825218893Sdim    BinaryOperator *Mul = cast<BinaryOperator>(Op0);
826218893Sdim    // If the Mul knows it does not overflow, then we are good to go.
827218893Sdim    if ((isSigned && Mul->hasNoSignedWrap()) ||
828218893Sdim        (!isSigned && Mul->hasNoUnsignedWrap()))
829218893Sdim      return X;
830218893Sdim    // If X has the form X = A / Y then X * Y cannot overflow.
831218893Sdim    if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
832218893Sdim      if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
833218893Sdim        return X;
834218893Sdim  }
835218893Sdim
836218893Sdim  // (X rem Y) / Y -> 0
837218893Sdim  if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
838218893Sdim      (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
839218893Sdim    return Constant::getNullValue(Op0->getType());
840218893Sdim
841218893Sdim  // If the operation is with the result of a select instruction, check whether
842218893Sdim  // operating on either branch of the select always yields the same value.
843218893Sdim  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
844218893Sdim    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
845218893Sdim      return V;
846218893Sdim
847218893Sdim  // If the operation is with the result of a phi instruction, check whether
848218893Sdim  // operating on all incoming values of the phi always yields the same value.
849218893Sdim  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
850218893Sdim    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
851218893Sdim      return V;
852218893Sdim
853218893Sdim  return 0;
854218893Sdim}
855218893Sdim
856218893Sdim/// SimplifySDivInst - Given operands for an SDiv, see if we can
857218893Sdim/// fold the result.  If not, this returns null.
858218893Sdimstatic Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
859218893Sdim                               const DominatorTree *DT, unsigned MaxRecurse) {
860218893Sdim  if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
861218893Sdim    return V;
862218893Sdim
863218893Sdim  return 0;
864218893Sdim}
865218893Sdim
866218893SdimValue *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
867218893Sdim                              const DominatorTree *DT) {
868218893Sdim  return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
869218893Sdim}
870218893Sdim
871218893Sdim/// SimplifyUDivInst - Given operands for a UDiv, see if we can
872218893Sdim/// fold the result.  If not, this returns null.
873218893Sdimstatic Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
874218893Sdim                               const DominatorTree *DT, unsigned MaxRecurse) {
875218893Sdim  if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
876218893Sdim    return V;
877218893Sdim
878218893Sdim  return 0;
879218893Sdim}
880218893Sdim
881218893SdimValue *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
882218893Sdim                              const DominatorTree *DT) {
883218893Sdim  return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
884218893Sdim}
885218893Sdim
886218893Sdimstatic Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
887218893Sdim                               const DominatorTree *, unsigned) {
888218893Sdim  // undef / X -> undef    (the undef could be a snan).
889218893Sdim  if (match(Op0, m_Undef()))
890218893Sdim    return Op0;
891218893Sdim
892218893Sdim  // X / undef -> undef
893218893Sdim  if (match(Op1, m_Undef()))
894218893Sdim    return Op1;
895218893Sdim
896218893Sdim  return 0;
897218893Sdim}
898218893Sdim
899218893SdimValue *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
900218893Sdim                              const DominatorTree *DT) {
901218893Sdim  return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
902218893Sdim}
903218893Sdim
904221345Sdim/// SimplifyRem - Given operands for an SRem or URem, see if we can
905221345Sdim/// fold the result.  If not, this returns null.
906221345Sdimstatic Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
907221345Sdim                          const TargetData *TD, const DominatorTree *DT,
908221345Sdim                          unsigned MaxRecurse) {
909221345Sdim  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
910221345Sdim    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
911221345Sdim      Constant *Ops[] = { C0, C1 };
912221345Sdim      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
913221345Sdim    }
914221345Sdim  }
915221345Sdim
916221345Sdim  // X % undef -> undef
917221345Sdim  if (match(Op1, m_Undef()))
918221345Sdim    return Op1;
919221345Sdim
920221345Sdim  // undef % X -> 0
921221345Sdim  if (match(Op0, m_Undef()))
922221345Sdim    return Constant::getNullValue(Op0->getType());
923221345Sdim
924221345Sdim  // 0 % X -> 0, we don't need to preserve faults!
925221345Sdim  if (match(Op0, m_Zero()))
926221345Sdim    return Op0;
927221345Sdim
928221345Sdim  // X % 0 -> undef, we don't need to preserve faults!
929221345Sdim  if (match(Op1, m_Zero()))
930221345Sdim    return UndefValue::get(Op0->getType());
931221345Sdim
932221345Sdim  // X % 1 -> 0
933221345Sdim  if (match(Op1, m_One()))
934221345Sdim    return Constant::getNullValue(Op0->getType());
935221345Sdim
936221345Sdim  if (Op0->getType()->isIntegerTy(1))
937221345Sdim    // It can't be remainder by zero, hence it must be remainder by one.
938221345Sdim    return Constant::getNullValue(Op0->getType());
939221345Sdim
940221345Sdim  // X % X -> 0
941221345Sdim  if (Op0 == Op1)
942221345Sdim    return Constant::getNullValue(Op0->getType());
943221345Sdim
944221345Sdim  // If the operation is with the result of a select instruction, check whether
945221345Sdim  // operating on either branch of the select always yields the same value.
946221345Sdim  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
947221345Sdim    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
948221345Sdim      return V;
949221345Sdim
950221345Sdim  // If the operation is with the result of a phi instruction, check whether
951221345Sdim  // operating on all incoming values of the phi always yields the same value.
952221345Sdim  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
953221345Sdim    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
954221345Sdim      return V;
955221345Sdim
956221345Sdim  return 0;
957221345Sdim}
958221345Sdim
959221345Sdim/// SimplifySRemInst - Given operands for an SRem, see if we can
960221345Sdim/// fold the result.  If not, this returns null.
961221345Sdimstatic Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
962221345Sdim                               const DominatorTree *DT, unsigned MaxRecurse) {
963221345Sdim  if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
964221345Sdim    return V;
965221345Sdim
966221345Sdim  return 0;
967221345Sdim}
968221345Sdim
969221345SdimValue *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
970221345Sdim                              const DominatorTree *DT) {
971221345Sdim  return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
972221345Sdim}
973221345Sdim
974221345Sdim/// SimplifyURemInst - Given operands for a URem, see if we can
975221345Sdim/// fold the result.  If not, this returns null.
976221345Sdimstatic Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
977221345Sdim                               const DominatorTree *DT, unsigned MaxRecurse) {
978221345Sdim  if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
979221345Sdim    return V;
980221345Sdim
981221345Sdim  return 0;
982221345Sdim}
983221345Sdim
984221345SdimValue *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
985221345Sdim                              const DominatorTree *DT) {
986221345Sdim  return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
987221345Sdim}
988221345Sdim
989221345Sdimstatic Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
990221345Sdim                               const DominatorTree *, unsigned) {
991221345Sdim  // undef % X -> undef    (the undef could be a snan).
992221345Sdim  if (match(Op0, m_Undef()))
993221345Sdim    return Op0;
994221345Sdim
995221345Sdim  // X % undef -> undef
996221345Sdim  if (match(Op1, m_Undef()))
997221345Sdim    return Op1;
998221345Sdim
999221345Sdim  return 0;
1000221345Sdim}
1001221345Sdim
1002221345SdimValue *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1003221345Sdim                              const DominatorTree *DT) {
1004221345Sdim  return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1005221345Sdim}
1006221345Sdim
1007218893Sdim/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1008218893Sdim/// fold the result.  If not, this returns null.
1009218893Sdimstatic Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1010218893Sdim                            const TargetData *TD, const DominatorTree *DT,
1011218893Sdim                            unsigned MaxRecurse) {
1012218893Sdim  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1013218893Sdim    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1014218893Sdim      Constant *Ops[] = { C0, C1 };
1015218893Sdim      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
1016218893Sdim    }
1017218893Sdim  }
1018218893Sdim
1019218893Sdim  // 0 shift by X -> 0
1020218893Sdim  if (match(Op0, m_Zero()))
1021218893Sdim    return Op0;
1022218893Sdim
1023218893Sdim  // X shift by 0 -> X
1024218893Sdim  if (match(Op1, m_Zero()))
1025218893Sdim    return Op0;
1026218893Sdim
1027218893Sdim  // X shift by undef -> undef because it may shift by the bitwidth.
1028218893Sdim  if (match(Op1, m_Undef()))
1029218893Sdim    return Op1;
1030218893Sdim
1031218893Sdim  // Shifting by the bitwidth or more is undefined.
1032218893Sdim  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1033218893Sdim    if (CI->getValue().getLimitedValue() >=
1034218893Sdim        Op0->getType()->getScalarSizeInBits())
1035218893Sdim      return UndefValue::get(Op0->getType());
1036218893Sdim
1037218893Sdim  // If the operation is with the result of a select instruction, check whether
1038218893Sdim  // operating on either branch of the select always yields the same value.
1039218893Sdim  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1040218893Sdim    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1041218893Sdim      return V;
1042218893Sdim
1043218893Sdim  // If the operation is with the result of a phi instruction, check whether
1044218893Sdim  // operating on all incoming values of the phi always yields the same value.
1045218893Sdim  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1046218893Sdim    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1047218893Sdim      return V;
1048218893Sdim
1049218893Sdim  return 0;
1050218893Sdim}
1051218893Sdim
1052218893Sdim/// SimplifyShlInst - Given operands for an Shl, see if we can
1053218893Sdim/// fold the result.  If not, this returns null.
1054218893Sdimstatic Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1055218893Sdim                              const TargetData *TD, const DominatorTree *DT,
1056218893Sdim                              unsigned MaxRecurse) {
1057218893Sdim  if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1058218893Sdim    return V;
1059218893Sdim
1060218893Sdim  // undef << X -> 0
1061218893Sdim  if (match(Op0, m_Undef()))
1062218893Sdim    return Constant::getNullValue(Op0->getType());
1063218893Sdim
1064218893Sdim  // (X >> A) << A -> X
1065218893Sdim  Value *X;
1066218893Sdim  if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1067218893Sdim      cast<PossiblyExactOperator>(Op0)->isExact())
1068218893Sdim    return X;
1069218893Sdim  return 0;
1070218893Sdim}
1071218893Sdim
1072218893SdimValue *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1073218893Sdim                             const TargetData *TD, const DominatorTree *DT) {
1074218893Sdim  return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
1075218893Sdim}
1076218893Sdim
1077218893Sdim/// SimplifyLShrInst - Given operands for an LShr, see if we can
1078218893Sdim/// fold the result.  If not, this returns null.
1079218893Sdimstatic Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1080218893Sdim                               const TargetData *TD, const DominatorTree *DT,
1081218893Sdim                               unsigned MaxRecurse) {
1082218893Sdim  if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1083218893Sdim    return V;
1084218893Sdim
1085218893Sdim  // undef >>l X -> 0
1086218893Sdim  if (match(Op0, m_Undef()))
1087218893Sdim    return Constant::getNullValue(Op0->getType());
1088218893Sdim
1089218893Sdim  // (X << A) >> A -> X
1090218893Sdim  Value *X;
1091218893Sdim  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1092218893Sdim      cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1093218893Sdim    return X;
1094218893Sdim
1095218893Sdim  return 0;
1096218893Sdim}
1097218893Sdim
1098218893SdimValue *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1099218893Sdim                              const TargetData *TD, const DominatorTree *DT) {
1100218893Sdim  return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1101218893Sdim}
1102218893Sdim
1103218893Sdim/// SimplifyAShrInst - Given operands for an AShr, see if we can
1104218893Sdim/// fold the result.  If not, this returns null.
1105218893Sdimstatic Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1106218893Sdim                               const TargetData *TD, const DominatorTree *DT,
1107218893Sdim                               unsigned MaxRecurse) {
1108218893Sdim  if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1109218893Sdim    return V;
1110218893Sdim
1111218893Sdim  // all ones >>a X -> all ones
1112218893Sdim  if (match(Op0, m_AllOnes()))
1113218893Sdim    return Op0;
1114218893Sdim
1115218893Sdim  // undef >>a X -> all ones
1116218893Sdim  if (match(Op0, m_Undef()))
1117218893Sdim    return Constant::getAllOnesValue(Op0->getType());
1118218893Sdim
1119218893Sdim  // (X << A) >> A -> X
1120218893Sdim  Value *X;
1121218893Sdim  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1122218893Sdim      cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1123218893Sdim    return X;
1124218893Sdim
1125218893Sdim  return 0;
1126218893Sdim}
1127218893Sdim
1128218893SdimValue *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1129218893Sdim                              const TargetData *TD, const DominatorTree *DT) {
1130218893Sdim  return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1131218893Sdim}
1132218893Sdim
1133199989Srdivacky/// SimplifyAndInst - Given operands for an And, see if we can
1134199989Srdivacky/// fold the result.  If not, this returns null.
1135218893Sdimstatic Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1136218893Sdim                              const DominatorTree *DT, unsigned MaxRecurse) {
1137199989Srdivacky  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1138199989Srdivacky    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1139199989Srdivacky      Constant *Ops[] = { CLHS, CRHS };
1140199481Srdivacky      return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1141199481Srdivacky                                      Ops, 2, TD);
1142199481Srdivacky    }
1143218893Sdim
1144199481Srdivacky    // Canonicalize the constant to the RHS.
1145199481Srdivacky    std::swap(Op0, Op1);
1146199481Srdivacky  }
1147218893Sdim
1148199481Srdivacky  // X & undef -> 0
1149218893Sdim  if (match(Op1, m_Undef()))
1150199481Srdivacky    return Constant::getNullValue(Op0->getType());
1151218893Sdim
1152199481Srdivacky  // X & X = X
1153199481Srdivacky  if (Op0 == Op1)
1154199481Srdivacky    return Op0;
1155218893Sdim
1156218893Sdim  // X & 0 = 0
1157218893Sdim  if (match(Op1, m_Zero()))
1158199481Srdivacky    return Op1;
1159218893Sdim
1160218893Sdim  // X & -1 = X
1161218893Sdim  if (match(Op1, m_AllOnes()))
1162218893Sdim    return Op0;
1163218893Sdim
1164199481Srdivacky  // A & ~A  =  ~A & A  =  0
1165218893Sdim  if (match(Op0, m_Not(m_Specific(Op1))) ||
1166218893Sdim      match(Op1, m_Not(m_Specific(Op0))))
1167199481Srdivacky    return Constant::getNullValue(Op0->getType());
1168218893Sdim
1169199481Srdivacky  // (A | ?) & A = A
1170218893Sdim  Value *A = 0, *B = 0;
1171199481Srdivacky  if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1172199481Srdivacky      (A == Op1 || B == Op1))
1173199481Srdivacky    return Op1;
1174218893Sdim
1175199481Srdivacky  // A & (A | ?) = A
1176199481Srdivacky  if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1177199481Srdivacky      (A == Op0 || B == Op0))
1178199481Srdivacky    return Op0;
1179218893Sdim
1180218893Sdim  // Try some generic simplifications for associative operations.
1181218893Sdim  if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1182218893Sdim                                          MaxRecurse))
1183218893Sdim    return V;
1184218893Sdim
1185218893Sdim  // And distributes over Or.  Try some generic simplifications based on this.
1186218893Sdim  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1187218893Sdim                             TD, DT, MaxRecurse))
1188218893Sdim    return V;
1189218893Sdim
1190218893Sdim  // And distributes over Xor.  Try some generic simplifications based on this.
1191218893Sdim  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1192218893Sdim                             TD, DT, MaxRecurse))
1193218893Sdim    return V;
1194218893Sdim
1195218893Sdim  // Or distributes over And.  Try some generic simplifications based on this.
1196218893Sdim  if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1197218893Sdim                                TD, DT, MaxRecurse))
1198218893Sdim    return V;
1199218893Sdim
1200218893Sdim  // If the operation is with the result of a select instruction, check whether
1201218893Sdim  // operating on either branch of the select always yields the same value.
1202218893Sdim  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1203218893Sdim    if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
1204218893Sdim                                         MaxRecurse))
1205218893Sdim      return V;
1206218893Sdim
1207218893Sdim  // If the operation is with the result of a phi instruction, check whether
1208218893Sdim  // operating on all incoming values of the phi always yields the same value.
1209218893Sdim  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1210218893Sdim    if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
1211218893Sdim                                      MaxRecurse))
1212218893Sdim      return V;
1213218893Sdim
1214199481Srdivacky  return 0;
1215199481Srdivacky}
1216199481Srdivacky
1217218893SdimValue *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1218218893Sdim                             const DominatorTree *DT) {
1219218893Sdim  return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
1220218893Sdim}
1221218893Sdim
1222199481Srdivacky/// SimplifyOrInst - Given operands for an Or, see if we can
1223199481Srdivacky/// fold the result.  If not, this returns null.
1224218893Sdimstatic Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1225218893Sdim                             const DominatorTree *DT, unsigned MaxRecurse) {
1226199481Srdivacky  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1227199481Srdivacky    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1228199481Srdivacky      Constant *Ops[] = { CLHS, CRHS };
1229199481Srdivacky      return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1230199481Srdivacky                                      Ops, 2, TD);
1231199481Srdivacky    }
1232218893Sdim
1233199481Srdivacky    // Canonicalize the constant to the RHS.
1234199481Srdivacky    std::swap(Op0, Op1);
1235199481Srdivacky  }
1236218893Sdim
1237199481Srdivacky  // X | undef -> -1
1238218893Sdim  if (match(Op1, m_Undef()))
1239199481Srdivacky    return Constant::getAllOnesValue(Op0->getType());
1240218893Sdim
1241199481Srdivacky  // X | X = X
1242199481Srdivacky  if (Op0 == Op1)
1243199481Srdivacky    return Op0;
1244199481Srdivacky
1245218893Sdim  // X | 0 = X
1246218893Sdim  if (match(Op1, m_Zero()))
1247199481Srdivacky    return Op0;
1248218893Sdim
1249218893Sdim  // X | -1 = -1
1250218893Sdim  if (match(Op1, m_AllOnes()))
1251218893Sdim    return Op1;
1252218893Sdim
1253199481Srdivacky  // A | ~A  =  ~A | A  =  -1
1254218893Sdim  if (match(Op0, m_Not(m_Specific(Op1))) ||
1255218893Sdim      match(Op1, m_Not(m_Specific(Op0))))
1256199481Srdivacky    return Constant::getAllOnesValue(Op0->getType());
1257218893Sdim
1258199481Srdivacky  // (A & ?) | A = A
1259218893Sdim  Value *A = 0, *B = 0;
1260199481Srdivacky  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1261199481Srdivacky      (A == Op1 || B == Op1))
1262199481Srdivacky    return Op1;
1263218893Sdim
1264199481Srdivacky  // A | (A & ?) = A
1265199481Srdivacky  if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1266199481Srdivacky      (A == Op0 || B == Op0))
1267199481Srdivacky    return Op0;
1268218893Sdim
1269219077Sdim  // ~(A & ?) | A = -1
1270219077Sdim  if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1271219077Sdim      (A == Op1 || B == Op1))
1272219077Sdim    return Constant::getAllOnesValue(Op1->getType());
1273219077Sdim
1274219077Sdim  // A | ~(A & ?) = -1
1275219077Sdim  if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1276219077Sdim      (A == Op0 || B == Op0))
1277219077Sdim    return Constant::getAllOnesValue(Op0->getType());
1278219077Sdim
1279218893Sdim  // Try some generic simplifications for associative operations.
1280218893Sdim  if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1281218893Sdim                                          MaxRecurse))
1282218893Sdim    return V;
1283218893Sdim
1284218893Sdim  // Or distributes over And.  Try some generic simplifications based on this.
1285218893Sdim  if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1286218893Sdim                             TD, DT, MaxRecurse))
1287218893Sdim    return V;
1288218893Sdim
1289218893Sdim  // And distributes over Or.  Try some generic simplifications based on this.
1290218893Sdim  if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1291218893Sdim                                TD, DT, MaxRecurse))
1292218893Sdim    return V;
1293218893Sdim
1294218893Sdim  // If the operation is with the result of a select instruction, check whether
1295218893Sdim  // operating on either branch of the select always yields the same value.
1296218893Sdim  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1297218893Sdim    if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
1298218893Sdim                                         MaxRecurse))
1299218893Sdim      return V;
1300218893Sdim
1301218893Sdim  // If the operation is with the result of a phi instruction, check whether
1302218893Sdim  // operating on all incoming values of the phi always yields the same value.
1303218893Sdim  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1304218893Sdim    if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
1305218893Sdim                                      MaxRecurse))
1306218893Sdim      return V;
1307218893Sdim
1308199481Srdivacky  return 0;
1309199481Srdivacky}
1310199481Srdivacky
1311218893SdimValue *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1312218893Sdim                            const DominatorTree *DT) {
1313218893Sdim  return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
1314218893Sdim}
1315199481Srdivacky
1316218893Sdim/// SimplifyXorInst - Given operands for a Xor, see if we can
1317218893Sdim/// fold the result.  If not, this returns null.
1318218893Sdimstatic Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1319218893Sdim                              const DominatorTree *DT, unsigned MaxRecurse) {
1320218893Sdim  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1321218893Sdim    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1322218893Sdim      Constant *Ops[] = { CLHS, CRHS };
1323218893Sdim      return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1324218893Sdim                                      Ops, 2, TD);
1325218893Sdim    }
1326218893Sdim
1327218893Sdim    // Canonicalize the constant to the RHS.
1328218893Sdim    std::swap(Op0, Op1);
1329218893Sdim  }
1330218893Sdim
1331218893Sdim  // A ^ undef -> undef
1332218893Sdim  if (match(Op1, m_Undef()))
1333218893Sdim    return Op1;
1334218893Sdim
1335218893Sdim  // A ^ 0 = A
1336218893Sdim  if (match(Op1, m_Zero()))
1337218893Sdim    return Op0;
1338218893Sdim
1339218893Sdim  // A ^ A = 0
1340218893Sdim  if (Op0 == Op1)
1341218893Sdim    return Constant::getNullValue(Op0->getType());
1342218893Sdim
1343218893Sdim  // A ^ ~A  =  ~A ^ A  =  -1
1344218893Sdim  if (match(Op0, m_Not(m_Specific(Op1))) ||
1345218893Sdim      match(Op1, m_Not(m_Specific(Op0))))
1346218893Sdim    return Constant::getAllOnesValue(Op0->getType());
1347218893Sdim
1348218893Sdim  // Try some generic simplifications for associative operations.
1349218893Sdim  if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1350218893Sdim                                          MaxRecurse))
1351218893Sdim    return V;
1352218893Sdim
1353218893Sdim  // And distributes over Xor.  Try some generic simplifications based on this.
1354218893Sdim  if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1355218893Sdim                                TD, DT, MaxRecurse))
1356218893Sdim    return V;
1357218893Sdim
1358218893Sdim  // Threading Xor over selects and phi nodes is pointless, so don't bother.
1359218893Sdim  // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1360218893Sdim  // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1361218893Sdim  // only if B and C are equal.  If B and C are equal then (since we assume
1362218893Sdim  // that operands have already been simplified) "select(cond, B, C)" should
1363218893Sdim  // have been simplified to the common value of B and C already.  Analysing
1364218893Sdim  // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1365218893Sdim  // for threading over phi nodes.
1366218893Sdim
1367218893Sdim  return 0;
1368218893Sdim}
1369218893Sdim
1370218893SdimValue *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1371218893Sdim                             const DominatorTree *DT) {
1372218893Sdim  return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1373218893Sdim}
1374218893Sdim
1375199481Srdivackystatic const Type *GetCompareTy(Value *Op) {
1376199481Srdivacky  return CmpInst::makeCmpResultType(Op->getType());
1377199481Srdivacky}
1378199481Srdivacky
1379223017Sdim/// ExtractEquivalentCondition - Rummage around inside V looking for something
1380223017Sdim/// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1381223017Sdim/// otherwise return null.  Helper function for analyzing max/min idioms.
1382223017Sdimstatic Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1383223017Sdim                                         Value *LHS, Value *RHS) {
1384223017Sdim  SelectInst *SI = dyn_cast<SelectInst>(V);
1385223017Sdim  if (!SI)
1386223017Sdim    return 0;
1387223017Sdim  CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1388223017Sdim  if (!Cmp)
1389223017Sdim    return 0;
1390223017Sdim  Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1391223017Sdim  if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1392223017Sdim    return Cmp;
1393223017Sdim  if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1394223017Sdim      LHS == CmpRHS && RHS == CmpLHS)
1395223017Sdim    return Cmp;
1396223017Sdim  return 0;
1397223017Sdim}
1398223017Sdim
1399199481Srdivacky/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1400199481Srdivacky/// fold the result.  If not, this returns null.
1401218893Sdimstatic Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1402218893Sdim                               const TargetData *TD, const DominatorTree *DT,
1403218893Sdim                               unsigned MaxRecurse) {
1404199481Srdivacky  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1405199481Srdivacky  assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1406218893Sdim
1407199481Srdivacky  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1408199481Srdivacky    if (Constant *CRHS = dyn_cast<Constant>(RHS))
1409199481Srdivacky      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1410199481Srdivacky
1411199481Srdivacky    // If we have a constant, make sure it is on the RHS.
1412199481Srdivacky    std::swap(LHS, RHS);
1413199481Srdivacky    Pred = CmpInst::getSwappedPredicate(Pred);
1414199481Srdivacky  }
1415218893Sdim
1416218893Sdim  const Type *ITy = GetCompareTy(LHS); // The return type.
1417218893Sdim  const Type *OpTy = LHS->getType();   // The operand type.
1418218893Sdim
1419199481Srdivacky  // icmp X, X -> true/false
1420204792Srdivacky  // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1421204792Srdivacky  // because X could be 0.
1422204792Srdivacky  if (LHS == RHS || isa<UndefValue>(RHS))
1423199481Srdivacky    return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1424218893Sdim
1425218893Sdim  // Special case logic when the operands have i1 type.
1426218893Sdim  if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1427218893Sdim       cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1428218893Sdim    switch (Pred) {
1429218893Sdim    default: break;
1430218893Sdim    case ICmpInst::ICMP_EQ:
1431218893Sdim      // X == 1 -> X
1432218893Sdim      if (match(RHS, m_One()))
1433218893Sdim        return LHS;
1434218893Sdim      break;
1435218893Sdim    case ICmpInst::ICMP_NE:
1436218893Sdim      // X != 0 -> X
1437218893Sdim      if (match(RHS, m_Zero()))
1438218893Sdim        return LHS;
1439218893Sdim      break;
1440218893Sdim    case ICmpInst::ICMP_UGT:
1441218893Sdim      // X >u 0 -> X
1442218893Sdim      if (match(RHS, m_Zero()))
1443218893Sdim        return LHS;
1444218893Sdim      break;
1445218893Sdim    case ICmpInst::ICMP_UGE:
1446218893Sdim      // X >=u 1 -> X
1447218893Sdim      if (match(RHS, m_One()))
1448218893Sdim        return LHS;
1449218893Sdim      break;
1450218893Sdim    case ICmpInst::ICMP_SLT:
1451218893Sdim      // X <s 0 -> X
1452218893Sdim      if (match(RHS, m_Zero()))
1453218893Sdim        return LHS;
1454218893Sdim      break;
1455218893Sdim    case ICmpInst::ICMP_SLE:
1456218893Sdim      // X <=s -1 -> X
1457218893Sdim      if (match(RHS, m_One()))
1458218893Sdim        return LHS;
1459218893Sdim      break;
1460218893Sdim    }
1461218893Sdim  }
1462218893Sdim
1463218893Sdim  // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1464218893Sdim  // different addresses, and what's more the address of a stack variable is
1465218893Sdim  // never null or equal to the address of a global.  Note that generalizing
1466218893Sdim  // to the case where LHS is a global variable address or null is pointless,
1467218893Sdim  // since if both LHS and RHS are constants then we already constant folded
1468218893Sdim  // the compare, and if only one of them is then we moved it to RHS already.
1469218893Sdim  if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1470218893Sdim                               isa<ConstantPointerNull>(RHS)))
1471221345Sdim    // We already know that LHS != RHS.
1472199481Srdivacky    return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1473218893Sdim
1474218893Sdim  // If we are comparing with zero then try hard since this is a common case.
1475218893Sdim  if (match(RHS, m_Zero())) {
1476218893Sdim    bool LHSKnownNonNegative, LHSKnownNegative;
1477199481Srdivacky    switch (Pred) {
1478218893Sdim    default:
1479218893Sdim      assert(false && "Unknown ICmp predicate!");
1480218893Sdim    case ICmpInst::ICMP_ULT:
1481223017Sdim      // getNullValue also works for vectors, unlike getFalse.
1482223017Sdim      return Constant::getNullValue(ITy);
1483218893Sdim    case ICmpInst::ICMP_UGE:
1484223017Sdim      // getAllOnesValue also works for vectors, unlike getTrue.
1485223017Sdim      return ConstantInt::getAllOnesValue(ITy);
1486218893Sdim    case ICmpInst::ICMP_EQ:
1487199481Srdivacky    case ICmpInst::ICMP_ULE:
1488218893Sdim      if (isKnownNonZero(LHS, TD))
1489223017Sdim        return Constant::getNullValue(ITy);
1490199481Srdivacky      break;
1491218893Sdim    case ICmpInst::ICMP_NE:
1492218893Sdim    case ICmpInst::ICMP_UGT:
1493218893Sdim      if (isKnownNonZero(LHS, TD))
1494223017Sdim        return ConstantInt::getAllOnesValue(ITy);
1495218893Sdim      break;
1496218893Sdim    case ICmpInst::ICMP_SLT:
1497218893Sdim      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1498218893Sdim      if (LHSKnownNegative)
1499223017Sdim        return ConstantInt::getAllOnesValue(ITy);
1500218893Sdim      if (LHSKnownNonNegative)
1501223017Sdim        return Constant::getNullValue(ITy);
1502218893Sdim      break;
1503199481Srdivacky    case ICmpInst::ICMP_SLE:
1504218893Sdim      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1505218893Sdim      if (LHSKnownNegative)
1506223017Sdim        return ConstantInt::getAllOnesValue(ITy);
1507218893Sdim      if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1508223017Sdim        return Constant::getNullValue(ITy);
1509199481Srdivacky      break;
1510218893Sdim    case ICmpInst::ICMP_SGE:
1511218893Sdim      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1512218893Sdim      if (LHSKnownNegative)
1513223017Sdim        return Constant::getNullValue(ITy);
1514218893Sdim      if (LHSKnownNonNegative)
1515223017Sdim        return ConstantInt::getAllOnesValue(ITy);
1516218893Sdim      break;
1517218893Sdim    case ICmpInst::ICMP_SGT:
1518218893Sdim      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1519218893Sdim      if (LHSKnownNegative)
1520223017Sdim        return Constant::getNullValue(ITy);
1521218893Sdim      if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1522223017Sdim        return ConstantInt::getAllOnesValue(ITy);
1523218893Sdim      break;
1524218893Sdim    }
1525218893Sdim  }
1526218893Sdim
1527218893Sdim  // See if we are doing a comparison with a constant integer.
1528218893Sdim  if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1529221345Sdim    // Rule out tautological comparisons (eg., ult 0 or uge 0).
1530221345Sdim    ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1531221345Sdim    if (RHS_CR.isEmptySet())
1532221345Sdim      return ConstantInt::getFalse(CI->getContext());
1533221345Sdim    if (RHS_CR.isFullSet())
1534221345Sdim      return ConstantInt::getTrue(CI->getContext());
1535221345Sdim
1536221345Sdim    // Many binary operators with constant RHS have easy to compute constant
1537221345Sdim    // range.  Use them to check whether the comparison is a tautology.
1538221345Sdim    uint32_t Width = CI->getBitWidth();
1539221345Sdim    APInt Lower = APInt(Width, 0);
1540221345Sdim    APInt Upper = APInt(Width, 0);
1541221345Sdim    ConstantInt *CI2;
1542221345Sdim    if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1543221345Sdim      // 'urem x, CI2' produces [0, CI2).
1544221345Sdim      Upper = CI2->getValue();
1545221345Sdim    } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1546221345Sdim      // 'srem x, CI2' produces (-|CI2|, |CI2|).
1547221345Sdim      Upper = CI2->getValue().abs();
1548221345Sdim      Lower = (-Upper) + 1;
1549221345Sdim    } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1550221345Sdim      // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1551221345Sdim      APInt NegOne = APInt::getAllOnesValue(Width);
1552221345Sdim      if (!CI2->isZero())
1553221345Sdim        Upper = NegOne.udiv(CI2->getValue()) + 1;
1554221345Sdim    } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1555221345Sdim      // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1556221345Sdim      APInt IntMin = APInt::getSignedMinValue(Width);
1557221345Sdim      APInt IntMax = APInt::getSignedMaxValue(Width);
1558221345Sdim      APInt Val = CI2->getValue().abs();
1559221345Sdim      if (!Val.isMinValue()) {
1560221345Sdim        Lower = IntMin.sdiv(Val);
1561221345Sdim        Upper = IntMax.sdiv(Val) + 1;
1562221345Sdim      }
1563221345Sdim    } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1564221345Sdim      // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1565221345Sdim      APInt NegOne = APInt::getAllOnesValue(Width);
1566221345Sdim      if (CI2->getValue().ult(Width))
1567221345Sdim        Upper = NegOne.lshr(CI2->getValue()) + 1;
1568221345Sdim    } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1569221345Sdim      // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1570221345Sdim      APInt IntMin = APInt::getSignedMinValue(Width);
1571221345Sdim      APInt IntMax = APInt::getSignedMaxValue(Width);
1572221345Sdim      if (CI2->getValue().ult(Width)) {
1573221345Sdim        Lower = IntMin.ashr(CI2->getValue());
1574221345Sdim        Upper = IntMax.ashr(CI2->getValue()) + 1;
1575221345Sdim      }
1576221345Sdim    } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1577221345Sdim      // 'or x, CI2' produces [CI2, UINT_MAX].
1578221345Sdim      Lower = CI2->getValue();
1579221345Sdim    } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1580221345Sdim      // 'and x, CI2' produces [0, CI2].
1581221345Sdim      Upper = CI2->getValue() + 1;
1582199481Srdivacky    }
1583221345Sdim    if (Lower != Upper) {
1584221345Sdim      ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1585221345Sdim      if (RHS_CR.contains(LHS_CR))
1586221345Sdim        return ConstantInt::getTrue(RHS->getContext());
1587221345Sdim      if (RHS_CR.inverse().contains(LHS_CR))
1588221345Sdim        return ConstantInt::getFalse(RHS->getContext());
1589221345Sdim    }
1590199481Srdivacky  }
1591218893Sdim
1592218893Sdim  // Compare of cast, for example (zext X) != 0 -> X != 0
1593218893Sdim  if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1594218893Sdim    Instruction *LI = cast<CastInst>(LHS);
1595218893Sdim    Value *SrcOp = LI->getOperand(0);
1596218893Sdim    const Type *SrcTy = SrcOp->getType();
1597218893Sdim    const Type *DstTy = LI->getType();
1598218893Sdim
1599218893Sdim    // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1600218893Sdim    // if the integer type is the same size as the pointer type.
1601218893Sdim    if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1602218893Sdim        TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1603218893Sdim      if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1604218893Sdim        // Transfer the cast to the constant.
1605218893Sdim        if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1606218893Sdim                                        ConstantExpr::getIntToPtr(RHSC, SrcTy),
1607218893Sdim                                        TD, DT, MaxRecurse-1))
1608218893Sdim          return V;
1609218893Sdim      } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1610218893Sdim        if (RI->getOperand(0)->getType() == SrcTy)
1611218893Sdim          // Compare without the cast.
1612218893Sdim          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1613218893Sdim                                          TD, DT, MaxRecurse-1))
1614218893Sdim            return V;
1615218893Sdim      }
1616218893Sdim    }
1617218893Sdim
1618218893Sdim    if (isa<ZExtInst>(LHS)) {
1619218893Sdim      // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1620218893Sdim      // same type.
1621218893Sdim      if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1622218893Sdim        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1623218893Sdim          // Compare X and Y.  Note that signed predicates become unsigned.
1624218893Sdim          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1625218893Sdim                                          SrcOp, RI->getOperand(0), TD, DT,
1626218893Sdim                                          MaxRecurse-1))
1627218893Sdim            return V;
1628218893Sdim      }
1629218893Sdim      // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1630218893Sdim      // too.  If not, then try to deduce the result of the comparison.
1631218893Sdim      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1632218893Sdim        // Compute the constant that would happen if we truncated to SrcTy then
1633218893Sdim        // reextended to DstTy.
1634218893Sdim        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1635218893Sdim        Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1636218893Sdim
1637218893Sdim        // If the re-extended constant didn't change then this is effectively
1638218893Sdim        // also a case of comparing two zero-extended values.
1639218893Sdim        if (RExt == CI && MaxRecurse)
1640218893Sdim          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1641218893Sdim                                          SrcOp, Trunc, TD, DT, MaxRecurse-1))
1642218893Sdim            return V;
1643218893Sdim
1644218893Sdim        // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1645218893Sdim        // there.  Use this to work out the result of the comparison.
1646218893Sdim        if (RExt != CI) {
1647218893Sdim          switch (Pred) {
1648218893Sdim          default:
1649218893Sdim            assert(false && "Unknown ICmp predicate!");
1650218893Sdim          // LHS <u RHS.
1651218893Sdim          case ICmpInst::ICMP_EQ:
1652218893Sdim          case ICmpInst::ICMP_UGT:
1653218893Sdim          case ICmpInst::ICMP_UGE:
1654218893Sdim            return ConstantInt::getFalse(CI->getContext());
1655218893Sdim
1656218893Sdim          case ICmpInst::ICMP_NE:
1657218893Sdim          case ICmpInst::ICMP_ULT:
1658218893Sdim          case ICmpInst::ICMP_ULE:
1659218893Sdim            return ConstantInt::getTrue(CI->getContext());
1660218893Sdim
1661218893Sdim          // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
1662218893Sdim          // is non-negative then LHS <s RHS.
1663218893Sdim          case ICmpInst::ICMP_SGT:
1664218893Sdim          case ICmpInst::ICMP_SGE:
1665218893Sdim            return CI->getValue().isNegative() ?
1666218893Sdim              ConstantInt::getTrue(CI->getContext()) :
1667218893Sdim              ConstantInt::getFalse(CI->getContext());
1668218893Sdim
1669218893Sdim          case ICmpInst::ICMP_SLT:
1670218893Sdim          case ICmpInst::ICMP_SLE:
1671218893Sdim            return CI->getValue().isNegative() ?
1672218893Sdim              ConstantInt::getFalse(CI->getContext()) :
1673218893Sdim              ConstantInt::getTrue(CI->getContext());
1674218893Sdim          }
1675218893Sdim        }
1676218893Sdim      }
1677218893Sdim    }
1678218893Sdim
1679218893Sdim    if (isa<SExtInst>(LHS)) {
1680218893Sdim      // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1681218893Sdim      // same type.
1682218893Sdim      if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1683218893Sdim        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1684218893Sdim          // Compare X and Y.  Note that the predicate does not change.
1685218893Sdim          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1686218893Sdim                                          TD, DT, MaxRecurse-1))
1687218893Sdim            return V;
1688218893Sdim      }
1689218893Sdim      // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1690218893Sdim      // too.  If not, then try to deduce the result of the comparison.
1691218893Sdim      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1692218893Sdim        // Compute the constant that would happen if we truncated to SrcTy then
1693218893Sdim        // reextended to DstTy.
1694218893Sdim        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1695218893Sdim        Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1696218893Sdim
1697218893Sdim        // If the re-extended constant didn't change then this is effectively
1698218893Sdim        // also a case of comparing two sign-extended values.
1699218893Sdim        if (RExt == CI && MaxRecurse)
1700218893Sdim          if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1701218893Sdim                                          MaxRecurse-1))
1702218893Sdim            return V;
1703218893Sdim
1704218893Sdim        // Otherwise the upper bits of LHS are all equal, while RHS has varying
1705218893Sdim        // bits there.  Use this to work out the result of the comparison.
1706218893Sdim        if (RExt != CI) {
1707218893Sdim          switch (Pred) {
1708218893Sdim          default:
1709218893Sdim            assert(false && "Unknown ICmp predicate!");
1710218893Sdim          case ICmpInst::ICMP_EQ:
1711218893Sdim            return ConstantInt::getFalse(CI->getContext());
1712218893Sdim          case ICmpInst::ICMP_NE:
1713218893Sdim            return ConstantInt::getTrue(CI->getContext());
1714218893Sdim
1715218893Sdim          // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
1716218893Sdim          // LHS >s RHS.
1717218893Sdim          case ICmpInst::ICMP_SGT:
1718218893Sdim          case ICmpInst::ICMP_SGE:
1719218893Sdim            return CI->getValue().isNegative() ?
1720218893Sdim              ConstantInt::getTrue(CI->getContext()) :
1721218893Sdim              ConstantInt::getFalse(CI->getContext());
1722218893Sdim          case ICmpInst::ICMP_SLT:
1723218893Sdim          case ICmpInst::ICMP_SLE:
1724218893Sdim            return CI->getValue().isNegative() ?
1725218893Sdim              ConstantInt::getFalse(CI->getContext()) :
1726218893Sdim              ConstantInt::getTrue(CI->getContext());
1727218893Sdim
1728218893Sdim          // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
1729218893Sdim          // LHS >u RHS.
1730218893Sdim          case ICmpInst::ICMP_UGT:
1731218893Sdim          case ICmpInst::ICMP_UGE:
1732218893Sdim            // Comparison is true iff the LHS <s 0.
1733218893Sdim            if (MaxRecurse)
1734218893Sdim              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1735218893Sdim                                              Constant::getNullValue(SrcTy),
1736218893Sdim                                              TD, DT, MaxRecurse-1))
1737218893Sdim                return V;
1738218893Sdim            break;
1739218893Sdim          case ICmpInst::ICMP_ULT:
1740218893Sdim          case ICmpInst::ICMP_ULE:
1741218893Sdim            // Comparison is true iff the LHS >=s 0.
1742218893Sdim            if (MaxRecurse)
1743218893Sdim              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1744218893Sdim                                              Constant::getNullValue(SrcTy),
1745218893Sdim                                              TD, DT, MaxRecurse-1))
1746218893Sdim                return V;
1747218893Sdim            break;
1748218893Sdim          }
1749218893Sdim        }
1750218893Sdim      }
1751218893Sdim    }
1752218893Sdim  }
1753218893Sdim
1754218893Sdim  // Special logic for binary operators.
1755218893Sdim  BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1756218893Sdim  BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1757218893Sdim  if (MaxRecurse && (LBO || RBO)) {
1758218893Sdim    // Analyze the case when either LHS or RHS is an add instruction.
1759218893Sdim    Value *A = 0, *B = 0, *C = 0, *D = 0;
1760218893Sdim    // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1761218893Sdim    bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1762218893Sdim    if (LBO && LBO->getOpcode() == Instruction::Add) {
1763218893Sdim      A = LBO->getOperand(0); B = LBO->getOperand(1);
1764218893Sdim      NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1765218893Sdim        (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1766218893Sdim        (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1767218893Sdim    }
1768218893Sdim    if (RBO && RBO->getOpcode() == Instruction::Add) {
1769218893Sdim      C = RBO->getOperand(0); D = RBO->getOperand(1);
1770218893Sdim      NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1771218893Sdim        (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1772218893Sdim        (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1773218893Sdim    }
1774218893Sdim
1775218893Sdim    // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1776218893Sdim    if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1777218893Sdim      if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1778218893Sdim                                      Constant::getNullValue(RHS->getType()),
1779218893Sdim                                      TD, DT, MaxRecurse-1))
1780218893Sdim        return V;
1781218893Sdim
1782218893Sdim    // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1783218893Sdim    if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1784218893Sdim      if (Value *V = SimplifyICmpInst(Pred,
1785218893Sdim                                      Constant::getNullValue(LHS->getType()),
1786218893Sdim                                      C == LHS ? D : C, TD, DT, MaxRecurse-1))
1787218893Sdim        return V;
1788218893Sdim
1789218893Sdim    // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1790218893Sdim    if (A && C && (A == C || A == D || B == C || B == D) &&
1791218893Sdim        NoLHSWrapProblem && NoRHSWrapProblem) {
1792218893Sdim      // Determine Y and Z in the form icmp (X+Y), (X+Z).
1793218893Sdim      Value *Y = (A == C || A == D) ? B : A;
1794218893Sdim      Value *Z = (C == A || C == B) ? D : C;
1795218893Sdim      if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1796218893Sdim        return V;
1797218893Sdim    }
1798218893Sdim  }
1799218893Sdim
1800221345Sdim  if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1801221345Sdim    bool KnownNonNegative, KnownNegative;
1802221345Sdim    switch (Pred) {
1803221345Sdim    default:
1804221345Sdim      break;
1805221345Sdim    case ICmpInst::ICMP_SGT:
1806221345Sdim    case ICmpInst::ICMP_SGE:
1807221345Sdim      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1808221345Sdim      if (!KnownNonNegative)
1809221345Sdim        break;
1810221345Sdim      // fall-through
1811221345Sdim    case ICmpInst::ICMP_EQ:
1812221345Sdim    case ICmpInst::ICMP_UGT:
1813221345Sdim    case ICmpInst::ICMP_UGE:
1814223017Sdim      // getNullValue also works for vectors, unlike getFalse.
1815223017Sdim      return Constant::getNullValue(ITy);
1816221345Sdim    case ICmpInst::ICMP_SLT:
1817221345Sdim    case ICmpInst::ICMP_SLE:
1818221345Sdim      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1819221345Sdim      if (!KnownNonNegative)
1820221345Sdim        break;
1821221345Sdim      // fall-through
1822221345Sdim    case ICmpInst::ICMP_NE:
1823221345Sdim    case ICmpInst::ICMP_ULT:
1824221345Sdim    case ICmpInst::ICMP_ULE:
1825223017Sdim      // getAllOnesValue also works for vectors, unlike getTrue.
1826223017Sdim      return Constant::getAllOnesValue(ITy);
1827221345Sdim    }
1828221345Sdim  }
1829221345Sdim  if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1830221345Sdim    bool KnownNonNegative, KnownNegative;
1831221345Sdim    switch (Pred) {
1832221345Sdim    default:
1833221345Sdim      break;
1834221345Sdim    case ICmpInst::ICMP_SGT:
1835221345Sdim    case ICmpInst::ICMP_SGE:
1836221345Sdim      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1837221345Sdim      if (!KnownNonNegative)
1838221345Sdim        break;
1839221345Sdim      // fall-through
1840221345Sdim    case ICmpInst::ICMP_NE:
1841221345Sdim    case ICmpInst::ICMP_UGT:
1842221345Sdim    case ICmpInst::ICMP_UGE:
1843223017Sdim      // getAllOnesValue also works for vectors, unlike getTrue.
1844223017Sdim      return Constant::getAllOnesValue(ITy);
1845221345Sdim    case ICmpInst::ICMP_SLT:
1846221345Sdim    case ICmpInst::ICMP_SLE:
1847221345Sdim      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1848221345Sdim      if (!KnownNonNegative)
1849221345Sdim        break;
1850221345Sdim      // fall-through
1851221345Sdim    case ICmpInst::ICMP_EQ:
1852221345Sdim    case ICmpInst::ICMP_ULT:
1853221345Sdim    case ICmpInst::ICMP_ULE:
1854223017Sdim      // getNullValue also works for vectors, unlike getFalse.
1855223017Sdim      return Constant::getNullValue(ITy);
1856221345Sdim    }
1857221345Sdim  }
1858221345Sdim
1859221345Sdim  if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1860221345Sdim      LBO->getOperand(1) == RBO->getOperand(1)) {
1861221345Sdim    switch (LBO->getOpcode()) {
1862221345Sdim    default: break;
1863221345Sdim    case Instruction::UDiv:
1864221345Sdim    case Instruction::LShr:
1865221345Sdim      if (ICmpInst::isSigned(Pred))
1866221345Sdim        break;
1867221345Sdim      // fall-through
1868221345Sdim    case Instruction::SDiv:
1869221345Sdim    case Instruction::AShr:
1870223017Sdim      if (!LBO->isExact() || !RBO->isExact())
1871221345Sdim        break;
1872221345Sdim      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1873221345Sdim                                      RBO->getOperand(0), TD, DT, MaxRecurse-1))
1874221345Sdim        return V;
1875221345Sdim      break;
1876221345Sdim    case Instruction::Shl: {
1877221345Sdim      bool NUW = LBO->hasNoUnsignedWrap() && LBO->hasNoUnsignedWrap();
1878221345Sdim      bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1879221345Sdim      if (!NUW && !NSW)
1880221345Sdim        break;
1881221345Sdim      if (!NSW && ICmpInst::isSigned(Pred))
1882221345Sdim        break;
1883221345Sdim      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1884221345Sdim                                      RBO->getOperand(0), TD, DT, MaxRecurse-1))
1885221345Sdim        return V;
1886221345Sdim      break;
1887221345Sdim    }
1888221345Sdim    }
1889221345Sdim  }
1890221345Sdim
1891223017Sdim  // Simplify comparisons involving max/min.
1892223017Sdim  Value *A, *B;
1893223017Sdim  CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1894223017Sdim  CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1895223017Sdim
1896223017Sdim  // Signed variants on "max(a,b)>=a -> true".
1897223017Sdim  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1898223017Sdim    if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1899223017Sdim    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1900223017Sdim    // We analyze this as smax(A, B) pred A.
1901223017Sdim    P = Pred;
1902223017Sdim  } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1903223017Sdim             (A == LHS || B == LHS)) {
1904223017Sdim    if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1905223017Sdim    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1906223017Sdim    // We analyze this as smax(A, B) swapped-pred A.
1907223017Sdim    P = CmpInst::getSwappedPredicate(Pred);
1908223017Sdim  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1909223017Sdim             (A == RHS || B == RHS)) {
1910223017Sdim    if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1911223017Sdim    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1912223017Sdim    // We analyze this as smax(-A, -B) swapped-pred -A.
1913223017Sdim    // Note that we do not need to actually form -A or -B thanks to EqP.
1914223017Sdim    P = CmpInst::getSwappedPredicate(Pred);
1915223017Sdim  } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1916223017Sdim             (A == LHS || B == LHS)) {
1917223017Sdim    if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1918223017Sdim    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1919223017Sdim    // We analyze this as smax(-A, -B) pred -A.
1920223017Sdim    // Note that we do not need to actually form -A or -B thanks to EqP.
1921223017Sdim    P = Pred;
1922223017Sdim  }
1923223017Sdim  if (P != CmpInst::BAD_ICMP_PREDICATE) {
1924223017Sdim    // Cases correspond to "max(A, B) p A".
1925223017Sdim    switch (P) {
1926223017Sdim    default:
1927223017Sdim      break;
1928223017Sdim    case CmpInst::ICMP_EQ:
1929223017Sdim    case CmpInst::ICMP_SLE:
1930223017Sdim      // Equivalent to "A EqP B".  This may be the same as the condition tested
1931223017Sdim      // in the max/min; if so, we can just return that.
1932223017Sdim      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
1933223017Sdim        return V;
1934223017Sdim      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
1935223017Sdim        return V;
1936223017Sdim      // Otherwise, see if "A EqP B" simplifies.
1937223017Sdim      if (MaxRecurse)
1938223017Sdim        if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
1939223017Sdim          return V;
1940223017Sdim      break;
1941223017Sdim    case CmpInst::ICMP_NE:
1942223017Sdim    case CmpInst::ICMP_SGT: {
1943223017Sdim      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
1944223017Sdim      // Equivalent to "A InvEqP B".  This may be the same as the condition
1945223017Sdim      // tested in the max/min; if so, we can just return that.
1946223017Sdim      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
1947223017Sdim        return V;
1948223017Sdim      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
1949223017Sdim        return V;
1950223017Sdim      // Otherwise, see if "A InvEqP B" simplifies.
1951223017Sdim      if (MaxRecurse)
1952223017Sdim        if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
1953223017Sdim          return V;
1954223017Sdim      break;
1955223017Sdim    }
1956223017Sdim    case CmpInst::ICMP_SGE:
1957223017Sdim      // Always true.
1958223017Sdim      return Constant::getAllOnesValue(ITy);
1959223017Sdim    case CmpInst::ICMP_SLT:
1960223017Sdim      // Always false.
1961223017Sdim      return Constant::getNullValue(ITy);
1962223017Sdim    }
1963223017Sdim  }
1964223017Sdim
1965223017Sdim  // Unsigned variants on "max(a,b)>=a -> true".
1966223017Sdim  P = CmpInst::BAD_ICMP_PREDICATE;
1967223017Sdim  if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1968223017Sdim    if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
1969223017Sdim    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1970223017Sdim    // We analyze this as umax(A, B) pred A.
1971223017Sdim    P = Pred;
1972223017Sdim  } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
1973223017Sdim             (A == LHS || B == LHS)) {
1974223017Sdim    if (A != LHS) std::swap(A, B); // A pred umax(A, B).
1975223017Sdim    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1976223017Sdim    // We analyze this as umax(A, B) swapped-pred A.
1977223017Sdim    P = CmpInst::getSwappedPredicate(Pred);
1978223017Sdim  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
1979223017Sdim             (A == RHS || B == RHS)) {
1980223017Sdim    if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
1981223017Sdim    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
1982223017Sdim    // We analyze this as umax(-A, -B) swapped-pred -A.
1983223017Sdim    // Note that we do not need to actually form -A or -B thanks to EqP.
1984223017Sdim    P = CmpInst::getSwappedPredicate(Pred);
1985223017Sdim  } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
1986223017Sdim             (A == LHS || B == LHS)) {
1987223017Sdim    if (A != LHS) std::swap(A, B); // A pred umin(A, B).
1988223017Sdim    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
1989223017Sdim    // We analyze this as umax(-A, -B) pred -A.
1990223017Sdim    // Note that we do not need to actually form -A or -B thanks to EqP.
1991223017Sdim    P = Pred;
1992223017Sdim  }
1993223017Sdim  if (P != CmpInst::BAD_ICMP_PREDICATE) {
1994223017Sdim    // Cases correspond to "max(A, B) p A".
1995223017Sdim    switch (P) {
1996223017Sdim    default:
1997223017Sdim      break;
1998223017Sdim    case CmpInst::ICMP_EQ:
1999223017Sdim    case CmpInst::ICMP_ULE:
2000223017Sdim      // Equivalent to "A EqP B".  This may be the same as the condition tested
2001223017Sdim      // in the max/min; if so, we can just return that.
2002223017Sdim      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2003223017Sdim        return V;
2004223017Sdim      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2005223017Sdim        return V;
2006223017Sdim      // Otherwise, see if "A EqP B" simplifies.
2007223017Sdim      if (MaxRecurse)
2008223017Sdim        if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2009223017Sdim          return V;
2010223017Sdim      break;
2011223017Sdim    case CmpInst::ICMP_NE:
2012223017Sdim    case CmpInst::ICMP_UGT: {
2013223017Sdim      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2014223017Sdim      // Equivalent to "A InvEqP B".  This may be the same as the condition
2015223017Sdim      // tested in the max/min; if so, we can just return that.
2016223017Sdim      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2017223017Sdim        return V;
2018223017Sdim      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2019223017Sdim        return V;
2020223017Sdim      // Otherwise, see if "A InvEqP B" simplifies.
2021223017Sdim      if (MaxRecurse)
2022223017Sdim        if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2023223017Sdim          return V;
2024223017Sdim      break;
2025223017Sdim    }
2026223017Sdim    case CmpInst::ICMP_UGE:
2027223017Sdim      // Always true.
2028223017Sdim      return Constant::getAllOnesValue(ITy);
2029223017Sdim    case CmpInst::ICMP_ULT:
2030223017Sdim      // Always false.
2031223017Sdim      return Constant::getNullValue(ITy);
2032223017Sdim    }
2033223017Sdim  }
2034223017Sdim
2035223017Sdim  // Variants on "max(x,y) >= min(x,z)".
2036223017Sdim  Value *C, *D;
2037223017Sdim  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2038223017Sdim      match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2039223017Sdim      (A == C || A == D || B == C || B == D)) {
2040223017Sdim    // max(x, ?) pred min(x, ?).
2041223017Sdim    if (Pred == CmpInst::ICMP_SGE)
2042223017Sdim      // Always true.
2043223017Sdim      return Constant::getAllOnesValue(ITy);
2044223017Sdim    if (Pred == CmpInst::ICMP_SLT)
2045223017Sdim      // Always false.
2046223017Sdim      return Constant::getNullValue(ITy);
2047223017Sdim  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2048223017Sdim             match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2049223017Sdim             (A == C || A == D || B == C || B == D)) {
2050223017Sdim    // min(x, ?) pred max(x, ?).
2051223017Sdim    if (Pred == CmpInst::ICMP_SLE)
2052223017Sdim      // Always true.
2053223017Sdim      return Constant::getAllOnesValue(ITy);
2054223017Sdim    if (Pred == CmpInst::ICMP_SGT)
2055223017Sdim      // Always false.
2056223017Sdim      return Constant::getNullValue(ITy);
2057223017Sdim  } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2058223017Sdim             match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2059223017Sdim             (A == C || A == D || B == C || B == D)) {
2060223017Sdim    // max(x, ?) pred min(x, ?).
2061223017Sdim    if (Pred == CmpInst::ICMP_UGE)
2062223017Sdim      // Always true.
2063223017Sdim      return Constant::getAllOnesValue(ITy);
2064223017Sdim    if (Pred == CmpInst::ICMP_ULT)
2065223017Sdim      // Always false.
2066223017Sdim      return Constant::getNullValue(ITy);
2067223017Sdim  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2068223017Sdim             match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2069223017Sdim             (A == C || A == D || B == C || B == D)) {
2070223017Sdim    // min(x, ?) pred max(x, ?).
2071223017Sdim    if (Pred == CmpInst::ICMP_ULE)
2072223017Sdim      // Always true.
2073223017Sdim      return Constant::getAllOnesValue(ITy);
2074223017Sdim    if (Pred == CmpInst::ICMP_UGT)
2075223017Sdim      // Always false.
2076223017Sdim      return Constant::getNullValue(ITy);
2077223017Sdim  }
2078223017Sdim
2079218893Sdim  // If the comparison is with the result of a select instruction, check whether
2080218893Sdim  // comparing with either branch of the select always yields the same value.
2081218893Sdim  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2082218893Sdim    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2083218893Sdim      return V;
2084218893Sdim
2085218893Sdim  // If the comparison is with the result of a phi instruction, check whether
2086218893Sdim  // doing the compare with each incoming phi value yields a common result.
2087218893Sdim  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2088218893Sdim    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2089218893Sdim      return V;
2090218893Sdim
2091199481Srdivacky  return 0;
2092199481Srdivacky}
2093199481Srdivacky
2094218893SdimValue *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2095218893Sdim                              const TargetData *TD, const DominatorTree *DT) {
2096218893Sdim  return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2097218893Sdim}
2098218893Sdim
2099199481Srdivacky/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2100199481Srdivacky/// fold the result.  If not, this returns null.
2101218893Sdimstatic Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2102218893Sdim                               const TargetData *TD, const DominatorTree *DT,
2103218893Sdim                               unsigned MaxRecurse) {
2104199481Srdivacky  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2105199481Srdivacky  assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2106199481Srdivacky
2107199481Srdivacky  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2108199481Srdivacky    if (Constant *CRHS = dyn_cast<Constant>(RHS))
2109199481Srdivacky      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
2110218893Sdim
2111199481Srdivacky    // If we have a constant, make sure it is on the RHS.
2112199481Srdivacky    std::swap(LHS, RHS);
2113199481Srdivacky    Pred = CmpInst::getSwappedPredicate(Pred);
2114199481Srdivacky  }
2115218893Sdim
2116199481Srdivacky  // Fold trivial predicates.
2117199481Srdivacky  if (Pred == FCmpInst::FCMP_FALSE)
2118199481Srdivacky    return ConstantInt::get(GetCompareTy(LHS), 0);
2119199481Srdivacky  if (Pred == FCmpInst::FCMP_TRUE)
2120199481Srdivacky    return ConstantInt::get(GetCompareTy(LHS), 1);
2121199481Srdivacky
2122199481Srdivacky  if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2123199481Srdivacky    return UndefValue::get(GetCompareTy(LHS));
2124199481Srdivacky
2125199481Srdivacky  // fcmp x,x -> true/false.  Not all compares are foldable.
2126199481Srdivacky  if (LHS == RHS) {
2127199481Srdivacky    if (CmpInst::isTrueWhenEqual(Pred))
2128199481Srdivacky      return ConstantInt::get(GetCompareTy(LHS), 1);
2129199481Srdivacky    if (CmpInst::isFalseWhenEqual(Pred))
2130199481Srdivacky      return ConstantInt::get(GetCompareTy(LHS), 0);
2131199481Srdivacky  }
2132218893Sdim
2133199481Srdivacky  // Handle fcmp with constant RHS
2134199481Srdivacky  if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2135199481Srdivacky    // If the constant is a nan, see if we can fold the comparison based on it.
2136199481Srdivacky    if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2137199481Srdivacky      if (CFP->getValueAPF().isNaN()) {
2138199481Srdivacky        if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2139199481Srdivacky          return ConstantInt::getFalse(CFP->getContext());
2140199481Srdivacky        assert(FCmpInst::isUnordered(Pred) &&
2141199481Srdivacky               "Comparison must be either ordered or unordered!");
2142199481Srdivacky        // True if unordered.
2143199481Srdivacky        return ConstantInt::getTrue(CFP->getContext());
2144199481Srdivacky      }
2145204642Srdivacky      // Check whether the constant is an infinity.
2146204642Srdivacky      if (CFP->getValueAPF().isInfinity()) {
2147204642Srdivacky        if (CFP->getValueAPF().isNegative()) {
2148204642Srdivacky          switch (Pred) {
2149204642Srdivacky          case FCmpInst::FCMP_OLT:
2150204642Srdivacky            // No value is ordered and less than negative infinity.
2151204642Srdivacky            return ConstantInt::getFalse(CFP->getContext());
2152204642Srdivacky          case FCmpInst::FCMP_UGE:
2153204642Srdivacky            // All values are unordered with or at least negative infinity.
2154204642Srdivacky            return ConstantInt::getTrue(CFP->getContext());
2155204642Srdivacky          default:
2156204642Srdivacky            break;
2157204642Srdivacky          }
2158204642Srdivacky        } else {
2159204642Srdivacky          switch (Pred) {
2160204642Srdivacky          case FCmpInst::FCMP_OGT:
2161204642Srdivacky            // No value is ordered and greater than infinity.
2162204642Srdivacky            return ConstantInt::getFalse(CFP->getContext());
2163204642Srdivacky          case FCmpInst::FCMP_ULE:
2164204642Srdivacky            // All values are unordered with and at most infinity.
2165204642Srdivacky            return ConstantInt::getTrue(CFP->getContext());
2166204642Srdivacky          default:
2167204642Srdivacky            break;
2168204642Srdivacky          }
2169204642Srdivacky        }
2170204642Srdivacky      }
2171199481Srdivacky    }
2172199481Srdivacky  }
2173218893Sdim
2174218893Sdim  // If the comparison is with the result of a select instruction, check whether
2175218893Sdim  // comparing with either branch of the select always yields the same value.
2176218893Sdim  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2177218893Sdim    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2178218893Sdim      return V;
2179218893Sdim
2180218893Sdim  // If the comparison is with the result of a phi instruction, check whether
2181218893Sdim  // doing the compare with each incoming phi value yields a common result.
2182218893Sdim  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2183218893Sdim    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2184218893Sdim      return V;
2185218893Sdim
2186199481Srdivacky  return 0;
2187199481Srdivacky}
2188199481Srdivacky
2189218893SdimValue *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2190218893Sdim                              const TargetData *TD, const DominatorTree *DT) {
2191218893Sdim  return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2192218893Sdim}
2193218893Sdim
2194207618Srdivacky/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2195207618Srdivacky/// the result.  If not, this returns null.
2196207618SrdivackyValue *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2197218893Sdim                                const TargetData *TD, const DominatorTree *) {
2198207618Srdivacky  // select true, X, Y  -> X
2199207618Srdivacky  // select false, X, Y -> Y
2200207618Srdivacky  if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2201207618Srdivacky    return CB->getZExtValue() ? TrueVal : FalseVal;
2202218893Sdim
2203207618Srdivacky  // select C, X, X -> X
2204207618Srdivacky  if (TrueVal == FalseVal)
2205207618Srdivacky    return TrueVal;
2206218893Sdim
2207207618Srdivacky  if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2208207618Srdivacky    return FalseVal;
2209207618Srdivacky  if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2210207618Srdivacky    return TrueVal;
2211207618Srdivacky  if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2212207618Srdivacky    if (isa<Constant>(TrueVal))
2213207618Srdivacky      return TrueVal;
2214207618Srdivacky    return FalseVal;
2215207618Srdivacky  }
2216218893Sdim
2217207618Srdivacky  return 0;
2218207618Srdivacky}
2219207618Srdivacky
2220199989Srdivacky/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2221199989Srdivacky/// fold the result.  If not, this returns null.
2222199989SrdivackyValue *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
2223218893Sdim                             const TargetData *TD, const DominatorTree *) {
2224218893Sdim  // The type of the GEP pointer operand.
2225218893Sdim  const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
2226218893Sdim
2227199989Srdivacky  // getelementptr P -> P.
2228199989Srdivacky  if (NumOps == 1)
2229199989Srdivacky    return Ops[0];
2230199989Srdivacky
2231218893Sdim  if (isa<UndefValue>(Ops[0])) {
2232218893Sdim    // Compute the (pointer) type returned by the GEP instruction.
2233218893Sdim    const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
2234218893Sdim                                                             NumOps-1);
2235218893Sdim    const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2236218893Sdim    return UndefValue::get(GEPTy);
2237218893Sdim  }
2238199989Srdivacky
2239218893Sdim  if (NumOps == 2) {
2240218893Sdim    // getelementptr P, 0 -> P.
2241199989Srdivacky    if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2242199989Srdivacky      if (C->isZero())
2243199989Srdivacky        return Ops[0];
2244218893Sdim    // getelementptr P, N -> P if P points to a type of zero size.
2245218893Sdim    if (TD) {
2246218893Sdim      const Type *Ty = PtrTy->getElementType();
2247218893Sdim      if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2248218893Sdim        return Ops[0];
2249218893Sdim    }
2250218893Sdim  }
2251218893Sdim
2252199989Srdivacky  // Check to see if this is constant foldable.
2253199989Srdivacky  for (unsigned i = 0; i != NumOps; ++i)
2254199989Srdivacky    if (!isa<Constant>(Ops[i]))
2255199989Srdivacky      return 0;
2256218893Sdim
2257199989Srdivacky  return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
2258199989Srdivacky                                        (Constant *const*)Ops+1, NumOps-1);
2259199989Srdivacky}
2260199989Srdivacky
2261218893Sdim/// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2262218893Sdimstatic Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2263218893Sdim  // If all of the PHI's incoming values are the same then replace the PHI node
2264218893Sdim  // with the common value.
2265218893Sdim  Value *CommonValue = 0;
2266218893Sdim  bool HasUndefInput = false;
2267218893Sdim  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2268218893Sdim    Value *Incoming = PN->getIncomingValue(i);
2269218893Sdim    // If the incoming value is the phi node itself, it can safely be skipped.
2270218893Sdim    if (Incoming == PN) continue;
2271218893Sdim    if (isa<UndefValue>(Incoming)) {
2272218893Sdim      // Remember that we saw an undef value, but otherwise ignore them.
2273218893Sdim      HasUndefInput = true;
2274218893Sdim      continue;
2275218893Sdim    }
2276218893Sdim    if (CommonValue && Incoming != CommonValue)
2277218893Sdim      return 0;  // Not the same, bail out.
2278218893Sdim    CommonValue = Incoming;
2279218893Sdim  }
2280199989Srdivacky
2281218893Sdim  // If CommonValue is null then all of the incoming values were either undef or
2282218893Sdim  // equal to the phi node itself.
2283218893Sdim  if (!CommonValue)
2284218893Sdim    return UndefValue::get(PN->getType());
2285218893Sdim
2286218893Sdim  // If we have a PHI node like phi(X, undef, X), where X is defined by some
2287218893Sdim  // instruction, we cannot return X as the result of the PHI node unless it
2288218893Sdim  // dominates the PHI block.
2289218893Sdim  if (HasUndefInput)
2290218893Sdim    return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2291218893Sdim
2292218893Sdim  return CommonValue;
2293218893Sdim}
2294218893Sdim
2295218893Sdim
2296199481Srdivacky//=== Helper functions for higher up the class hierarchy.
2297199481Srdivacky
2298199481Srdivacky/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2299199481Srdivacky/// fold the result.  If not, this returns null.
2300218893Sdimstatic Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2301218893Sdim                            const TargetData *TD, const DominatorTree *DT,
2302218893Sdim                            unsigned MaxRecurse) {
2303199481Srdivacky  switch (Opcode) {
2304218893Sdim  case Instruction::Add:
2305218893Sdim    return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2306218893Sdim                           TD, DT, MaxRecurse);
2307218893Sdim  case Instruction::Sub:
2308218893Sdim    return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2309218893Sdim                           TD, DT, MaxRecurse);
2310218893Sdim  case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
2311218893Sdim  case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2312218893Sdim  case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
2313218893Sdim  case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
2314221345Sdim  case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2315221345Sdim  case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2316221345Sdim  case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
2317218893Sdim  case Instruction::Shl:
2318218893Sdim    return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2319218893Sdim                           TD, DT, MaxRecurse);
2320218893Sdim  case Instruction::LShr:
2321218893Sdim    return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2322218893Sdim  case Instruction::AShr:
2323218893Sdim    return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2324218893Sdim  case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
2325218893Sdim  case Instruction::Or:  return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
2326218893Sdim  case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
2327199481Srdivacky  default:
2328199481Srdivacky    if (Constant *CLHS = dyn_cast<Constant>(LHS))
2329199481Srdivacky      if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2330199481Srdivacky        Constant *COps[] = {CLHS, CRHS};
2331199481Srdivacky        return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
2332199481Srdivacky      }
2333218893Sdim
2334218893Sdim    // If the operation is associative, try some generic simplifications.
2335218893Sdim    if (Instruction::isAssociative(Opcode))
2336218893Sdim      if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2337218893Sdim                                              MaxRecurse))
2338218893Sdim        return V;
2339218893Sdim
2340218893Sdim    // If the operation is with the result of a select instruction, check whether
2341218893Sdim    // operating on either branch of the select always yields the same value.
2342218893Sdim    if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2343218893Sdim      if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
2344218893Sdim                                           MaxRecurse))
2345218893Sdim        return V;
2346218893Sdim
2347218893Sdim    // If the operation is with the result of a phi instruction, check whether
2348218893Sdim    // operating on all incoming values of the phi always yields the same value.
2349218893Sdim    if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2350218893Sdim      if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
2351218893Sdim        return V;
2352218893Sdim
2353199481Srdivacky    return 0;
2354199481Srdivacky  }
2355199481Srdivacky}
2356199481Srdivacky
2357218893SdimValue *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2358218893Sdim                           const TargetData *TD, const DominatorTree *DT) {
2359218893Sdim  return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
2360218893Sdim}
2361218893Sdim
2362199481Srdivacky/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2363199481Srdivacky/// fold the result.
2364218893Sdimstatic Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2365218893Sdim                              const TargetData *TD, const DominatorTree *DT,
2366218893Sdim                              unsigned MaxRecurse) {
2367199481Srdivacky  if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2368218893Sdim    return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2369218893Sdim  return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2370199481Srdivacky}
2371199481Srdivacky
2372218893SdimValue *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2373218893Sdim                             const TargetData *TD, const DominatorTree *DT) {
2374218893Sdim  return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2375218893Sdim}
2376199481Srdivacky
2377199481Srdivacky/// SimplifyInstruction - See if we can compute a simplified version of this
2378199481Srdivacky/// instruction.  If not, this returns null.
2379218893SdimValue *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2380218893Sdim                                 const DominatorTree *DT) {
2381218893Sdim  Value *Result;
2382218893Sdim
2383199481Srdivacky  switch (I->getOpcode()) {
2384199481Srdivacky  default:
2385218893Sdim    Result = ConstantFoldInstruction(I, TD);
2386218893Sdim    break;
2387199989Srdivacky  case Instruction::Add:
2388218893Sdim    Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2389218893Sdim                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2390218893Sdim                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2391218893Sdim                             TD, DT);
2392218893Sdim    break;
2393218893Sdim  case Instruction::Sub:
2394218893Sdim    Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2395218893Sdim                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2396218893Sdim                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2397218893Sdim                             TD, DT);
2398218893Sdim    break;
2399218893Sdim  case Instruction::Mul:
2400218893Sdim    Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2401218893Sdim    break;
2402218893Sdim  case Instruction::SDiv:
2403218893Sdim    Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2404218893Sdim    break;
2405218893Sdim  case Instruction::UDiv:
2406218893Sdim    Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2407218893Sdim    break;
2408218893Sdim  case Instruction::FDiv:
2409218893Sdim    Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2410218893Sdim    break;
2411221345Sdim  case Instruction::SRem:
2412221345Sdim    Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2413221345Sdim    break;
2414221345Sdim  case Instruction::URem:
2415221345Sdim    Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2416221345Sdim    break;
2417221345Sdim  case Instruction::FRem:
2418221345Sdim    Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2419221345Sdim    break;
2420218893Sdim  case Instruction::Shl:
2421218893Sdim    Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2422218893Sdim                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2423218893Sdim                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2424218893Sdim                             TD, DT);
2425218893Sdim    break;
2426218893Sdim  case Instruction::LShr:
2427218893Sdim    Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2428218893Sdim                              cast<BinaryOperator>(I)->isExact(),
2429218893Sdim                              TD, DT);
2430218893Sdim    break;
2431218893Sdim  case Instruction::AShr:
2432218893Sdim    Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2433218893Sdim                              cast<BinaryOperator>(I)->isExact(),
2434218893Sdim                              TD, DT);
2435218893Sdim    break;
2436199481Srdivacky  case Instruction::And:
2437218893Sdim    Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2438218893Sdim    break;
2439199481Srdivacky  case Instruction::Or:
2440218893Sdim    Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2441218893Sdim    break;
2442218893Sdim  case Instruction::Xor:
2443218893Sdim    Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2444218893Sdim    break;
2445199481Srdivacky  case Instruction::ICmp:
2446218893Sdim    Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2447218893Sdim                              I->getOperand(0), I->getOperand(1), TD, DT);
2448218893Sdim    break;
2449199481Srdivacky  case Instruction::FCmp:
2450218893Sdim    Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2451218893Sdim                              I->getOperand(0), I->getOperand(1), TD, DT);
2452218893Sdim    break;
2453207618Srdivacky  case Instruction::Select:
2454218893Sdim    Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2455218893Sdim                                I->getOperand(2), TD, DT);
2456218893Sdim    break;
2457199989Srdivacky  case Instruction::GetElementPtr: {
2458199989Srdivacky    SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2459218893Sdim    Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
2460218893Sdim    break;
2461199481Srdivacky  }
2462218893Sdim  case Instruction::PHI:
2463218893Sdim    Result = SimplifyPHINode(cast<PHINode>(I), DT);
2464218893Sdim    break;
2465199989Srdivacky  }
2466218893Sdim
2467218893Sdim  /// If called on unreachable code, the above logic may report that the
2468218893Sdim  /// instruction simplified to itself.  Make life easier for users by
2469218893Sdim  /// detecting that case here, returning a safe value instead.
2470218893Sdim  return Result == I ? UndefValue::get(I->getType()) : Result;
2471199481Srdivacky}
2472199481Srdivacky
2473199481Srdivacky/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2474199481Srdivacky/// delete the From instruction.  In addition to a basic RAUW, this does a
2475199481Srdivacky/// recursive simplification of the newly formed instructions.  This catches
2476199481Srdivacky/// things where one simplification exposes other opportunities.  This only
2477199481Srdivacky/// simplifies and deletes scalar operations, it does not change the CFG.
2478199481Srdivacky///
2479199481Srdivackyvoid llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2480218893Sdim                                     const TargetData *TD,
2481218893Sdim                                     const DominatorTree *DT) {
2482199481Srdivacky  assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2483218893Sdim
2484210299Sed  // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2485210299Sed  // we can know if it gets deleted out from under us or replaced in a
2486210299Sed  // recursive simplification.
2487199481Srdivacky  WeakVH FromHandle(From);
2488210299Sed  WeakVH ToHandle(To);
2489218893Sdim
2490199481Srdivacky  while (!From->use_empty()) {
2491199481Srdivacky    // Update the instruction to use the new value.
2492210299Sed    Use &TheUse = From->use_begin().getUse();
2493210299Sed    Instruction *User = cast<Instruction>(TheUse.getUser());
2494210299Sed    TheUse = To;
2495210299Sed
2496210299Sed    // Check to see if the instruction can be folded due to the operand
2497210299Sed    // replacement.  For example changing (or X, Y) into (or X, -1) can replace
2498210299Sed    // the 'or' with -1.
2499210299Sed    Value *SimplifiedVal;
2500210299Sed    {
2501210299Sed      // Sanity check to make sure 'User' doesn't dangle across
2502210299Sed      // SimplifyInstruction.
2503210299Sed      AssertingVH<> UserHandle(User);
2504218893Sdim
2505218893Sdim      SimplifiedVal = SimplifyInstruction(User, TD, DT);
2506210299Sed      if (SimplifiedVal == 0) continue;
2507210299Sed    }
2508218893Sdim
2509210299Sed    // Recursively simplify this user to the new value.
2510218893Sdim    ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
2511210299Sed    From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2512210299Sed    To = ToHandle;
2513218893Sdim
2514210299Sed    assert(ToHandle && "To value deleted by recursive simplification?");
2515218893Sdim
2516210299Sed    // If the recursive simplification ended up revisiting and deleting
2517210299Sed    // 'From' then we're done.
2518210299Sed    if (From == 0)
2519210299Sed      return;
2520199481Srdivacky  }
2521218893Sdim
2522210299Sed  // If 'From' has value handles referring to it, do a real RAUW to update them.
2523210299Sed  From->replaceAllUsesWith(To);
2524218893Sdim
2525199481Srdivacky  From->eraseFromParent();
2526199481Srdivacky}
2527