LLVM  10.0.0svn
InstructionSimplify.cpp
Go to the documentation of this file.
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements routines for folding instructions into simpler forms
10 // that do not require creating new instructions. This does constant folding
11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
13 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
14 // simplified: This is usually true and assuming it simplifies the logic (if
15 // they have not been simplified then results are correct but maybe suboptimal).
16 //
17 //===----------------------------------------------------------------------===//
18 
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/Statistic.h"
31 #include "llvm/IR/ConstantRange.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/Dominators.h"
35 #include "llvm/IR/GlobalAlias.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/IR/PatternMatch.h"
40 #include "llvm/IR/ValueHandle.h"
41 #include "llvm/Support/KnownBits.h"
42 #include <algorithm>
43 using namespace llvm;
44 using namespace llvm::PatternMatch;
45 
46 #define DEBUG_TYPE "instsimplify"
47 
48 enum { RecursionLimit = 3 };
49 
50 STATISTIC(NumExpand, "Number of expansions");
51 STATISTIC(NumReassoc, "Number of reassociations");
52 
53 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
54 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
55 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
56  const SimplifyQuery &, unsigned);
57 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
58  unsigned);
59 static Value *SimplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
60  const SimplifyQuery &, unsigned);
61 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
62  unsigned);
63 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
64  const SimplifyQuery &Q, unsigned MaxRecurse);
65 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
66 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
67 static Value *SimplifyCastInst(unsigned, Value *, Type *,
68  const SimplifyQuery &, unsigned);
70  unsigned);
71 
72 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
73  Value *FalseVal) {
74  BinaryOperator::BinaryOps BinOpCode;
75  if (auto *BO = dyn_cast<BinaryOperator>(Cond))
76  BinOpCode = BO->getOpcode();
77  else
78  return nullptr;
79 
80  CmpInst::Predicate ExpectedPred, Pred1, Pred2;
81  if (BinOpCode == BinaryOperator::Or) {
82  ExpectedPred = ICmpInst::ICMP_NE;
83  } else if (BinOpCode == BinaryOperator::And) {
84  ExpectedPred = ICmpInst::ICMP_EQ;
85  } else
86  return nullptr;
87 
88  // %A = icmp eq %TV, %FV
89  // %B = icmp eq %X, %Y (and one of these is a select operand)
90  // %C = and %A, %B
91  // %D = select %C, %TV, %FV
92  // -->
93  // %FV
94 
95  // %A = icmp ne %TV, %FV
96  // %B = icmp ne %X, %Y (and one of these is a select operand)
97  // %C = or %A, %B
98  // %D = select %C, %TV, %FV
99  // -->
100  // %TV
101  Value *X, *Y;
102  if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
103  m_Specific(FalseVal)),
104  m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
105  Pred1 != Pred2 || Pred1 != ExpectedPred)
106  return nullptr;
107 
108  if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
109  return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
110 
111  return nullptr;
112 }
113 
114 /// For a boolean type or a vector of boolean type, return false or a vector
115 /// with every element false.
116 static Constant *getFalse(Type *Ty) {
117  return ConstantInt::getFalse(Ty);
118 }
119 
120 /// For a boolean type or a vector of boolean type, return true or a vector
121 /// with every element true.
122 static Constant *getTrue(Type *Ty) {
123  return ConstantInt::getTrue(Ty);
124 }
125 
126 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
127 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
128  Value *RHS) {
129  CmpInst *Cmp = dyn_cast<CmpInst>(V);
130  if (!Cmp)
131  return false;
132  CmpInst::Predicate CPred = Cmp->getPredicate();
133  Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
134  if (CPred == Pred && CLHS == LHS && CRHS == RHS)
135  return true;
136  return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
137  CRHS == LHS;
138 }
139 
140 /// Does the given value dominate the specified phi node?
141 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
143  if (!I)
144  // Arguments and constants dominate all instructions.
145  return true;
146 
147  // If we are processing instructions (and/or basic blocks) that have not been
148  // fully added to a function, the parent nodes may still be null. Simply
149  // return the conservative answer in these cases.
150  if (!I->getParent() || !P->getParent() || !I->getFunction())
151  return false;
152 
153  // If we have a DominatorTree then do a precise test.
154  if (DT)
155  return DT->dominates(I, P);
156 
157  // Otherwise, if the instruction is in the entry block and is not an invoke,
158  // then it obviously dominates all phi nodes.
159  if (I->getParent() == &I->getFunction()->getEntryBlock() &&
160  !isa<InvokeInst>(I))
161  return true;
162 
163  return false;
164 }
165 
166 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
167 /// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
168 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
169 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
170 /// Returns the simplified value, or null if no simplification was performed.
172  Instruction::BinaryOps OpcodeToExpand,
173  const SimplifyQuery &Q, unsigned MaxRecurse) {
174  // Recursion is always used, so bail out at once if we already hit the limit.
175  if (!MaxRecurse--)
176  return nullptr;
177 
178  // Check whether the expression has the form "(A op' B) op C".
179  if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
180  if (Op0->getOpcode() == OpcodeToExpand) {
181  // It does! Try turning it into "(A op C) op' (B op C)".
182  Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
183  // Do "A op C" and "B op C" both simplify?
184  if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
185  if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
186  // They do! Return "L op' R" if it simplifies or is already available.
187  // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
188  if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
189  && L == B && R == A)) {
190  ++NumExpand;
191  return LHS;
192  }
193  // Otherwise return "L op' R" if it simplifies.
194  if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
195  ++NumExpand;
196  return V;
197  }
198  }
199  }
200 
201  // Check whether the expression has the form "A op (B op' C)".
202  if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
203  if (Op1->getOpcode() == OpcodeToExpand) {
204  // It does! Try turning it into "(A op B) op' (A op C)".
205  Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
206  // Do "A op B" and "A op C" both simplify?
207  if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
208  if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
209  // They do! Return "L op' R" if it simplifies or is already available.
210  // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
211  if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
212  && L == C && R == B)) {
213  ++NumExpand;
214  return RHS;
215  }
216  // Otherwise return "L op' R" if it simplifies.
217  if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
218  ++NumExpand;
219  return V;
220  }
221  }
222  }
223 
224  return nullptr;
225 }
226 
227 /// Generic simplifications for associative binary operations.
228 /// Returns the simpler value, or null if none was found.
230  Value *LHS, Value *RHS,
231  const SimplifyQuery &Q,
232  unsigned MaxRecurse) {
233  assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
234 
235  // Recursion is always used, so bail out at once if we already hit the limit.
236  if (!MaxRecurse--)
237  return nullptr;
238 
241 
242  // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
243  if (Op0 && Op0->getOpcode() == Opcode) {
244  Value *A = Op0->getOperand(0);
245  Value *B = Op0->getOperand(1);
246  Value *C = RHS;
247 
248  // Does "B op C" simplify?
249  if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
250  // It does! Return "A op V" if it simplifies or is already available.
251  // If V equals B then "A op V" is just the LHS.
252  if (V == B) return LHS;
253  // Otherwise return "A op V" if it simplifies.
254  if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
255  ++NumReassoc;
256  return W;
257  }
258  }
259  }
260 
261  // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
262  if (Op1 && Op1->getOpcode() == Opcode) {
263  Value *A = LHS;
264  Value *B = Op1->getOperand(0);
265  Value *C = Op1->getOperand(1);
266 
267  // Does "A op B" simplify?
268  if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
269  // It does! Return "V op C" if it simplifies or is already available.
270  // If V equals B then "V op C" is just the RHS.
271  if (V == B) return RHS;
272  // Otherwise return "V op C" if it simplifies.
273  if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
274  ++NumReassoc;
275  return W;
276  }
277  }
278  }
279 
280  // The remaining transforms require commutativity as well as associativity.
281  if (!Instruction::isCommutative(Opcode))
282  return nullptr;
283 
284  // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
285  if (Op0 && Op0->getOpcode() == Opcode) {
286  Value *A = Op0->getOperand(0);
287  Value *B = Op0->getOperand(1);
288  Value *C = RHS;
289 
290  // Does "C op A" simplify?
291  if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
292  // It does! Return "V op B" if it simplifies or is already available.
293  // If V equals A then "V op B" is just the LHS.
294  if (V == A) return LHS;
295  // Otherwise return "V op B" if it simplifies.
296  if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
297  ++NumReassoc;
298  return W;
299  }
300  }
301  }
302 
303  // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
304  if (Op1 && Op1->getOpcode() == Opcode) {
305  Value *A = LHS;
306  Value *B = Op1->getOperand(0);
307  Value *C = Op1->getOperand(1);
308 
309  // Does "C op A" simplify?
310  if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
311  // It does! Return "B op V" if it simplifies or is already available.
312  // If V equals C then "B op V" is just the RHS.
313  if (V == C) return RHS;
314  // Otherwise return "B op V" if it simplifies.
315  if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
316  ++NumReassoc;
317  return W;
318  }
319  }
320  }
321 
322  return nullptr;
323 }
324 
325 /// In the case of a binary operation with a select instruction as an operand,
326 /// try to simplify the binop by seeing whether evaluating it on both branches
327 /// of the select results in the same value. Returns the common value if so,
328 /// otherwise returns null.
330  Value *RHS, const SimplifyQuery &Q,
331  unsigned MaxRecurse) {
332  // Recursion is always used, so bail out at once if we already hit the limit.
333  if (!MaxRecurse--)
334  return nullptr;
335 
336  SelectInst *SI;
337  if (isa<SelectInst>(LHS)) {
338  SI = cast<SelectInst>(LHS);
339  } else {
340  assert(isa<SelectInst>(RHS) && "No select instruction operand!");
341  SI = cast<SelectInst>(RHS);
342  }
343 
344  // Evaluate the BinOp on the true and false branches of the select.
345  Value *TV;
346  Value *FV;
347  if (SI == LHS) {
348  TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
349  FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
350  } else {
351  TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
352  FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
353  }
354 
355  // If they simplified to the same value, then return the common value.
356  // If they both failed to simplify then return null.
357  if (TV == FV)
358  return TV;
359 
360  // If one branch simplified to undef, return the other one.
361  if (TV && isa<UndefValue>(TV))
362  return FV;
363  if (FV && isa<UndefValue>(FV))
364  return TV;
365 
366  // If applying the operation did not change the true and false select values,
367  // then the result of the binop is the select itself.
368  if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
369  return SI;
370 
371  // If one branch simplified and the other did not, and the simplified
372  // value is equal to the unsimplified one, return the simplified value.
373  // For example, select (cond, X, X & Z) & Z -> X & Z.
374  if ((FV && !TV) || (TV && !FV)) {
375  // Check that the simplified value has the form "X op Y" where "op" is the
376  // same as the original operation.
377  Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
378  if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
379  // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
380  // We already know that "op" is the same as for the simplified value. See
381  // if the operands match too. If so, return the simplified value.
382  Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
383  Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
384  Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
385  if (Simplified->getOperand(0) == UnsimplifiedLHS &&
386  Simplified->getOperand(1) == UnsimplifiedRHS)
387  return Simplified;
388  if (Simplified->isCommutative() &&
389  Simplified->getOperand(1) == UnsimplifiedLHS &&
390  Simplified->getOperand(0) == UnsimplifiedRHS)
391  return Simplified;
392  }
393  }
394 
395  return nullptr;
396 }
397 
398 /// In the case of a comparison with a select instruction, try to simplify the
399 /// comparison by seeing whether both branches of the select result in the same
400 /// value. Returns the common value if so, otherwise returns null.
402  Value *RHS, const SimplifyQuery &Q,
403  unsigned MaxRecurse) {
404  // Recursion is always used, so bail out at once if we already hit the limit.
405  if (!MaxRecurse--)
406  return nullptr;
407 
408  // Make sure the select is on the LHS.
409  if (!isa<SelectInst>(LHS)) {
410  std::swap(LHS, RHS);
411  Pred = CmpInst::getSwappedPredicate(Pred);
412  }
413  assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
414  SelectInst *SI = cast<SelectInst>(LHS);
415  Value *Cond = SI->getCondition();
416  Value *TV = SI->getTrueValue();
417  Value *FV = SI->getFalseValue();
418 
419  // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
420  // Does "cmp TV, RHS" simplify?
421  Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
422  if (TCmp == Cond) {
423  // It not only simplified, it simplified to the select condition. Replace
424  // it with 'true'.
425  TCmp = getTrue(Cond->getType());
426  } else if (!TCmp) {
427  // It didn't simplify. However if "cmp TV, RHS" is equal to the select
428  // condition then we can replace it with 'true'. Otherwise give up.
429  if (!isSameCompare(Cond, Pred, TV, RHS))
430  return nullptr;
431  TCmp = getTrue(Cond->getType());
432  }
433 
434  // Does "cmp FV, RHS" simplify?
435  Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
436  if (FCmp == Cond) {
437  // It not only simplified, it simplified to the select condition. Replace
438  // it with 'false'.
439  FCmp = getFalse(Cond->getType());
440  } else if (!FCmp) {
441  // It didn't simplify. However if "cmp FV, RHS" is equal to the select
442  // condition then we can replace it with 'false'. Otherwise give up.
443  if (!isSameCompare(Cond, Pred, FV, RHS))
444  return nullptr;
445  FCmp = getFalse(Cond->getType());
446  }
447 
448  // If both sides simplified to the same value, then use it as the result of
449  // the original comparison.
450  if (TCmp == FCmp)
451  return TCmp;
452 
453  // The remaining cases only make sense if the select condition has the same
454  // type as the result of the comparison, so bail out if this is not so.
455  if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
456  return nullptr;
457  // If the false value simplified to false, then the result of the compare
458  // is equal to "Cond && TCmp". This also catches the case when the false
459  // value simplified to false and the true value to true, returning "Cond".
460  if (match(FCmp, m_Zero()))
461  if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
462  return V;
463  // If the true value simplified to true, then the result of the compare
464  // is equal to "Cond || FCmp".
465  if (match(TCmp, m_One()))
466  if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
467  return V;
468  // Finally, if the false value simplified to true and the true value to
469  // false, then the result of the compare is equal to "!Cond".
470  if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
471  if (Value *V =
472  SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
473  Q, MaxRecurse))
474  return V;
475 
476  return nullptr;
477 }
478 
479 /// In the case of a binary operation with an operand that is a PHI instruction,
480 /// try to simplify the binop by seeing whether evaluating it on the incoming
481 /// phi values yields the same result for every value. If so returns the common
482 /// value, otherwise returns null.
484  Value *RHS, const SimplifyQuery &Q,
485  unsigned MaxRecurse) {
486  // Recursion is always used, so bail out at once if we already hit the limit.
487  if (!MaxRecurse--)
488  return nullptr;
489 
490  PHINode *PI;
491  if (isa<PHINode>(LHS)) {
492  PI = cast<PHINode>(LHS);
493  // Bail out if RHS and the phi may be mutually interdependent due to a loop.
494  if (!valueDominatesPHI(RHS, PI, Q.DT))
495  return nullptr;
496  } else {
497  assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
498  PI = cast<PHINode>(RHS);
499  // Bail out if LHS and the phi may be mutually interdependent due to a loop.
500  if (!valueDominatesPHI(LHS, PI, Q.DT))
501  return nullptr;
502  }
503 
504  // Evaluate the BinOp on the incoming phi values.
505  Value *CommonValue = nullptr;
506  for (Value *Incoming : PI->incoming_values()) {
507  // If the incoming value is the phi node itself, it can safely be skipped.
508  if (Incoming == PI) continue;
509  Value *V = PI == LHS ?
510  SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
511  SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
512  // If the operation failed to simplify, or simplified to a different value
513  // to previously, then give up.
514  if (!V || (CommonValue && V != CommonValue))
515  return nullptr;
516  CommonValue = V;
517  }
518 
519  return CommonValue;
520 }
521 
522 /// In the case of a comparison with a PHI instruction, try to simplify the
523 /// comparison by seeing whether comparing with all of the incoming phi values
524 /// yields the same result every time. If so returns the common result,
525 /// otherwise returns null.
527  const SimplifyQuery &Q, unsigned MaxRecurse) {
528  // Recursion is always used, so bail out at once if we already hit the limit.
529  if (!MaxRecurse--)
530  return nullptr;
531 
532  // Make sure the phi is on the LHS.
533  if (!isa<PHINode>(LHS)) {
534  std::swap(LHS, RHS);
535  Pred = CmpInst::getSwappedPredicate(Pred);
536  }
537  assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
538  PHINode *PI = cast<PHINode>(LHS);
539 
540  // Bail out if RHS and the phi may be mutually interdependent due to a loop.
541  if (!valueDominatesPHI(RHS, PI, Q.DT))
542  return nullptr;
543 
544  // Evaluate the BinOp on the incoming phi values.
545  Value *CommonValue = nullptr;
546  for (Value *Incoming : PI->incoming_values()) {
547  // If the incoming value is the phi node itself, it can safely be skipped.
548  if (Incoming == PI) continue;
549  Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
550  // If the operation failed to simplify, or simplified to a different value
551  // to previously, then give up.
552  if (!V || (CommonValue && V != CommonValue))
553  return nullptr;
554  CommonValue = V;
555  }
556 
557  return CommonValue;
558 }
559 
561  Value *&Op0, Value *&Op1,
562  const SimplifyQuery &Q) {
563  if (auto *CLHS = dyn_cast<Constant>(Op0)) {
564  if (auto *CRHS = dyn_cast<Constant>(Op1))
565  return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
566 
567  // Canonicalize the constant to the RHS if this is a commutative operation.
568  if (Instruction::isCommutative(Opcode))
569  std::swap(Op0, Op1);
570  }
571  return nullptr;
572 }
573 
574 /// Given operands for an Add, see if we can fold the result.
575 /// If not, this returns null.
576 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
577  const SimplifyQuery &Q, unsigned MaxRecurse) {
578  if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
579  return C;
580 
581  // X + undef -> undef
582  if (match(Op1, m_Undef()))
583  return Op1;
584 
585  // X + 0 -> X
586  if (match(Op1, m_Zero()))
587  return Op0;
588 
589  // If two operands are negative, return 0.
590  if (isKnownNegation(Op0, Op1))
591  return Constant::getNullValue(Op0->getType());
592 
593  // X + (Y - X) -> Y
594  // (Y - X) + X -> Y
595  // Eg: X + -X -> 0
596  Value *Y = nullptr;
597  if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
598  match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
599  return Y;
600 
601  // X + ~X -> -1 since ~X = -X-1
602  Type *Ty = Op0->getType();
603  if (match(Op0, m_Not(m_Specific(Op1))) ||
604  match(Op1, m_Not(m_Specific(Op0))))
605  return Constant::getAllOnesValue(Ty);
606 
607  // add nsw/nuw (xor Y, signmask), signmask --> Y
608  // The no-wrapping add guarantees that the top bit will be set by the add.
609  // Therefore, the xor must be clearing the already set sign bit of Y.
610  if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
611  match(Op0, m_Xor(m_Value(Y), m_SignMask())))
612  return Y;
613 
614  // add nuw %x, -1 -> -1, because %x can only be 0.
615  if (IsNUW && match(Op1, m_AllOnes()))
616  return Op1; // Which is -1.
617 
618  /// i1 add -> xor.
619  if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
620  if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
621  return V;
622 
623  // Try some generic simplifications for associative operations.
624  if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
625  MaxRecurse))
626  return V;
627 
628  // Threading Add over selects and phi nodes is pointless, so don't bother.
629  // Threading over the select in "A + select(cond, B, C)" means evaluating
630  // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
631  // only if B and C are equal. If B and C are equal then (since we assume
632  // that operands have already been simplified) "select(cond, B, C)" should
633  // have been simplified to the common value of B and C already. Analysing
634  // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
635  // for threading over phi nodes.
636 
637  return nullptr;
638 }
639 
640 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
641  const SimplifyQuery &Query) {
642  return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
643 }
644 
645 /// Compute the base pointer and cumulative constant offsets for V.
646 ///
647 /// This strips all constant offsets off of V, leaving it the base pointer, and
648 /// accumulates the total constant offset applied in the returned constant. It
649 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
650 /// no constant offsets applied.
651 ///
652 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
653 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
654 /// folding.
656  bool AllowNonInbounds = false) {
658 
659  Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
660  APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
661 
662  V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
663  // As that strip may trace through `addrspacecast`, need to sext or trunc
664  // the offset calculated.
665  IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
666  Offset = Offset.sextOrTrunc(IntPtrTy->getIntegerBitWidth());
667 
668  Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
669  if (V->getType()->isVectorTy())
670  return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
671  OffsetIntPtr);
672  return OffsetIntPtr;
673 }
674 
675 /// Compute the constant difference between two pointer values.
676 /// If the difference is not a constant, returns zero.
678  Value *RHS) {
679  Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
680  Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
681 
682  // If LHS and RHS are not related via constant offsets to the same base
683  // value, there is nothing we can do here.
684  if (LHS != RHS)
685  return nullptr;
686 
687  // Otherwise, the difference of LHS - RHS can be computed as:
688  // LHS - RHS
689  // = (LHSOffset + Base) - (RHSOffset + Base)
690  // = LHSOffset - RHSOffset
691  return ConstantExpr::getSub(LHSOffset, RHSOffset);
692 }
693 
694 /// Given operands for a Sub, see if we can fold the result.
695 /// If not, this returns null.
696 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
697  const SimplifyQuery &Q, unsigned MaxRecurse) {
698  if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
699  return C;
700 
701  // X - undef -> undef
702  // undef - X -> undef
703  if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
704  return UndefValue::get(Op0->getType());
705 
706  // X - 0 -> X
707  if (match(Op1, m_Zero()))
708  return Op0;
709 
710  // X - X -> 0
711  if (Op0 == Op1)
712  return Constant::getNullValue(Op0->getType());
713 
714  // Is this a negation?
715  if (match(Op0, m_Zero())) {
716  // 0 - X -> 0 if the sub is NUW.
717  if (isNUW)
718  return Constant::getNullValue(Op0->getType());
719 
720  KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
721  if (Known.Zero.isMaxSignedValue()) {
722  // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
723  // Op1 must be 0 because negating the minimum signed value is undefined.
724  if (isNSW)
725  return Constant::getNullValue(Op0->getType());
726 
727  // 0 - X -> X if X is 0 or the minimum signed value.
728  return Op1;
729  }
730  }
731 
732  // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
733  // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
734  Value *X = nullptr, *Y = nullptr, *Z = Op1;
735  if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
736  // See if "V === Y - Z" simplifies.
737  if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
738  // It does! Now see if "X + V" simplifies.
739  if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
740  // It does, we successfully reassociated!
741  ++NumReassoc;
742  return W;
743  }
744  // See if "V === X - Z" simplifies.
745  if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
746  // It does! Now see if "Y + V" simplifies.
747  if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
748  // It does, we successfully reassociated!
749  ++NumReassoc;
750  return W;
751  }
752  }
753 
754  // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
755  // For example, X - (X + 1) -> -1
756  X = Op0;
757  if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
758  // See if "V === X - Y" simplifies.
759  if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
760  // It does! Now see if "V - Z" simplifies.
761  if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
762  // It does, we successfully reassociated!
763  ++NumReassoc;
764  return W;
765  }
766  // See if "V === X - Z" simplifies.
767  if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
768  // It does! Now see if "V - Y" simplifies.
769  if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
770  // It does, we successfully reassociated!
771  ++NumReassoc;
772  return W;
773  }
774  }
775 
776  // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
777  // For example, X - (X - Y) -> Y.
778  Z = Op0;
779  if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
780  // See if "V === Z - X" simplifies.
781  if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
782  // It does! Now see if "V + Y" simplifies.
783  if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
784  // It does, we successfully reassociated!
785  ++NumReassoc;
786  return W;
787  }
788 
789  // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
790  if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
791  match(Op1, m_Trunc(m_Value(Y))))
792  if (X->getType() == Y->getType())
793  // See if "V === X - Y" simplifies.
794  if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
795  // It does! Now see if "trunc V" simplifies.
796  if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
797  Q, MaxRecurse - 1))
798  // It does, return the simplified "trunc V".
799  return W;
800 
801  // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
802  if (match(Op0, m_PtrToInt(m_Value(X))) &&
803  match(Op1, m_PtrToInt(m_Value(Y))))
804  if (Constant *Result = computePointerDifference(Q.DL, X, Y))
805  return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
806 
807  // i1 sub -> xor.
808  if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
809  if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
810  return V;
811 
812  // Threading Sub over selects and phi nodes is pointless, so don't bother.
813  // Threading over the select in "A - select(cond, B, C)" means evaluating
814  // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
815  // only if B and C are equal. If B and C are equal then (since we assume
816  // that operands have already been simplified) "select(cond, B, C)" should
817  // have been simplified to the common value of B and C already. Analysing
818  // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
819  // for threading over phi nodes.
820 
821  return nullptr;
822 }
823 
824 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
825  const SimplifyQuery &Q) {
826  return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
827 }
828 
829 /// Given operands for a Mul, see if we can fold the result.
830 /// If not, this returns null.
831 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
832  unsigned MaxRecurse) {
833  if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
834  return C;
835 
836  // X * undef -> 0
837  // X * 0 -> 0
838  if (match(Op1, m_CombineOr(m_Undef(), m_Zero())))
839  return Constant::getNullValue(Op0->getType());
840 
841  // X * 1 -> X
842  if (match(Op1, m_One()))
843  return Op0;
844 
845  // (X / Y) * Y -> X if the division is exact.
846  Value *X = nullptr;
847  if (Q.IIQ.UseInstrInfo &&
848  (match(Op0,
849  m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
850  match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
851  return X;
852 
853  // i1 mul -> and.
854  if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
855  if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
856  return V;
857 
858  // Try some generic simplifications for associative operations.
859  if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
860  MaxRecurse))
861  return V;
862 
863  // Mul distributes over Add. Try some generic simplifications based on this.
864  if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
865  Q, MaxRecurse))
866  return V;
867 
868  // If the operation is with the result of a select instruction, check whether
869  // operating on either branch of the select always yields the same value.
870  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
871  if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
872  MaxRecurse))
873  return V;
874 
875  // If the operation is with the result of a phi instruction, check whether
876  // operating on all incoming values of the phi always yields the same value.
877  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
878  if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
879  MaxRecurse))
880  return V;
881 
882  return nullptr;
883 }
884 
887 }
888 
889 /// Check for common or similar folds of integer division or integer remainder.
890 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
891 static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
892  Type *Ty = Op0->getType();
893 
894  // X / undef -> undef
895  // X % undef -> undef
896  if (match(Op1, m_Undef()))
897  return Op1;
898 
899  // X / 0 -> undef
900  // X % 0 -> undef
901  // We don't need to preserve faults!
902  if (match(Op1, m_Zero()))
903  return UndefValue::get(Ty);
904 
905  // If any element of a constant divisor vector is zero or undef, the whole op
906  // is undef.
907  auto *Op1C = dyn_cast<Constant>(Op1);
908  if (Op1C && Ty->isVectorTy()) {
909  unsigned NumElts = Ty->getVectorNumElements();
910  for (unsigned i = 0; i != NumElts; ++i) {
911  Constant *Elt = Op1C->getAggregateElement(i);
912  if (Elt && (Elt->isNullValue() || isa<UndefValue>(Elt)))
913  return UndefValue::get(Ty);
914  }
915  }
916 
917  // undef / X -> 0
918  // undef % X -> 0
919  if (match(Op0, m_Undef()))
920  return Constant::getNullValue(Ty);
921 
922  // 0 / X -> 0
923  // 0 % X -> 0
924  if (match(Op0, m_Zero()))
925  return Constant::getNullValue(Op0->getType());
926 
927  // X / X -> 1
928  // X % X -> 0
929  if (Op0 == Op1)
930  return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
931 
932  // X / 1 -> X
933  // X % 1 -> 0
934  // If this is a boolean op (single-bit element type), we can't have
935  // division-by-zero or remainder-by-zero, so assume the divisor is 1.
936  // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
937  Value *X;
938  if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
939  (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
940  return IsDiv ? Op0 : Constant::getNullValue(Ty);
941 
942  return nullptr;
943 }
944 
945 /// Given a predicate and two operands, return true if the comparison is true.
946 /// This is a helper for div/rem simplification where we return some other value
947 /// when we can prove a relationship between the operands.
948 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
949  const SimplifyQuery &Q, unsigned MaxRecurse) {
950  Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
951  Constant *C = dyn_cast_or_null<Constant>(V);
952  return (C && C->isAllOnesValue());
953 }
954 
955 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
956 /// to simplify X % Y to X.
957 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
958  unsigned MaxRecurse, bool IsSigned) {
959  // Recursion is always used, so bail out at once if we already hit the limit.
960  if (!MaxRecurse--)
961  return false;
962 
963  if (IsSigned) {
964  // |X| / |Y| --> 0
965  //
966  // We require that 1 operand is a simple constant. That could be extended to
967  // 2 variables if we computed the sign bit for each.
968  //
969  // Make sure that a constant is not the minimum signed value because taking
970  // the abs() of that is undefined.
971  Type *Ty = X->getType();
972  const APInt *C;
973  if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
974  // Is the variable divisor magnitude always greater than the constant
975  // dividend magnitude?
976  // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
977  Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
978  Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
979  if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
980  isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
981  return true;
982  }
983  if (match(Y, m_APInt(C))) {
984  // Special-case: we can't take the abs() of a minimum signed value. If
985  // that's the divisor, then all we have to do is prove that the dividend
986  // is also not the minimum signed value.
987  if (C->isMinSignedValue())
988  return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
989 
990  // Is the variable dividend magnitude always less than the constant
991  // divisor magnitude?
992  // |X| < |C| --> X > -abs(C) and X < abs(C)
993  Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
994  Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
995  if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
996  isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
997  return true;
998  }
999  return false;
1000  }
1001 
1002  // IsSigned == false.
1003  // Is the dividend unsigned less than the divisor?
1004  return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1005 }
1006 
1007 /// These are simplifications common to SDiv and UDiv.
1009  const SimplifyQuery &Q, unsigned MaxRecurse) {
1010  if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1011  return C;
1012 
1013  if (Value *V = simplifyDivRem(Op0, Op1, true))
1014  return V;
1015 
1016  bool IsSigned = Opcode == Instruction::SDiv;
1017 
1018  // (X * Y) / Y -> X if the multiplication does not overflow.
1019  Value *X;
1020  if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1021  auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1022  // If the Mul does not overflow, then we are good to go.
1023  if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1024  (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)))
1025  return X;
1026  // If X has the form X = A / Y, then X * Y cannot overflow.
1027  if ((IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1028  (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1)))))
1029  return X;
1030  }
1031 
1032  // (X rem Y) / Y -> 0
1033  if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1034  (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1035  return Constant::getNullValue(Op0->getType());
1036 
1037  // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1038  ConstantInt *C1, *C2;
1039  if (!IsSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1040  match(Op1, m_ConstantInt(C2))) {
1041  bool Overflow;
1042  (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
1043  if (Overflow)
1044  return Constant::getNullValue(Op0->getType());
1045  }
1046 
1047  // If the operation is with the result of a select instruction, check whether
1048  // operating on either branch of the select always yields the same value.
1049  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1050  if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1051  return V;
1052 
1053  // If the operation is with the result of a phi instruction, check whether
1054  // operating on all incoming values of the phi always yields the same value.
1055  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1056  if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1057  return V;
1058 
1059  if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1060  return Constant::getNullValue(Op0->getType());
1061 
1062  return nullptr;
1063 }
1064 
1065 /// These are simplifications common to SRem and URem.
1067  const SimplifyQuery &Q, unsigned MaxRecurse) {
1068  if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1069  return C;
1070 
1071  if (Value *V = simplifyDivRem(Op0, Op1, false))
1072  return V;
1073 
1074  // (X % Y) % Y -> X % Y
1075  if ((Opcode == Instruction::SRem &&
1076  match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1077  (Opcode == Instruction::URem &&
1078  match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1079  return Op0;
1080 
1081  // (X << Y) % X -> 0
1082  if (Q.IIQ.UseInstrInfo &&
1083  ((Opcode == Instruction::SRem &&
1084  match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1085  (Opcode == Instruction::URem &&
1086  match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1087  return Constant::getNullValue(Op0->getType());
1088 
1089  // If the operation is with the result of a select instruction, check whether
1090  // operating on either branch of the select always yields the same value.
1091  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1092  if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1093  return V;
1094 
1095  // If the operation is with the result of a phi instruction, check whether
1096  // operating on all incoming values of the phi always yields the same value.
1097  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1098  if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1099  return V;
1100 
1101  // If X / Y == 0, then X % Y == X.
1102  if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
1103  return Op0;
1104 
1105  return nullptr;
1106 }
1107 
1108 /// Given operands for an SDiv, see if we can fold the result.
1109 /// If not, this returns null.
1110 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1111  unsigned MaxRecurse) {
1112  // If two operands are negated and no signed overflow, return -1.
1113  if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1114  return Constant::getAllOnesValue(Op0->getType());
1115 
1116  return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse);
1117 }
1118 
1121 }
1122 
1123 /// Given operands for a UDiv, see if we can fold the result.
1124 /// If not, this returns null.
1125 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1126  unsigned MaxRecurse) {
1127  return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse);
1128 }
1129 
1132 }
1133 
1134 /// Given operands for an SRem, see if we can fold the result.
1135 /// If not, this returns null.
1136 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1137  unsigned MaxRecurse) {
1138  // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1139  // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1140  Value *X;
1141  if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1142  return ConstantInt::getNullValue(Op0->getType());
1143 
1144  // If the two operands are negated, return 0.
1145  if (isKnownNegation(Op0, Op1))
1146  return ConstantInt::getNullValue(Op0->getType());
1147 
1148  return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1149 }
1150 
1153 }
1154 
1155 /// Given operands for a URem, see if we can fold the result.
1156 /// If not, this returns null.
1157 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1158  unsigned MaxRecurse) {
1159  return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1160 }
1161 
1164 }
1165 
1166 /// Returns true if a shift by \c Amount always yields undef.
1167 static bool isUndefShift(Value *Amount) {
1168  Constant *C = dyn_cast<Constant>(Amount);
1169  if (!C)
1170  return false;
1171 
1172  // X shift by undef -> undef because it may shift by the bitwidth.
1173  if (isa<UndefValue>(C))
1174  return true;
1175 
1176  // Shifting by the bitwidth or more is undefined.
1177  if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1178  if (CI->getValue().getLimitedValue() >=
1179  CI->getType()->getScalarSizeInBits())
1180  return true;
1181 
1182  // If all lanes of a vector shift are undefined the whole shift is.
1183  if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1184  for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1186  return false;
1187  return true;
1188  }
1189 
1190  return false;
1191 }
1192 
1193 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1194 /// If not, this returns null.
1196  Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
1197  if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1198  return C;
1199 
1200  // 0 shift by X -> 0
1201  if (match(Op0, m_Zero()))
1202  return Constant::getNullValue(Op0->getType());
1203 
1204  // X shift by 0 -> X
1205  // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1206  // would be poison.
1207  Value *X;
1208  if (match(Op1, m_Zero()) ||
1209  (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1210  return Op0;
1211 
1212  // Fold undefined shifts.
1213  if (isUndefShift(Op1))
1214  return UndefValue::get(Op0->getType());
1215 
1216  // If the operation is with the result of a select instruction, check whether
1217  // operating on either branch of the select always yields the same value.
1218  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1219  if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1220  return V;
1221 
1222  // If the operation is with the result of a phi instruction, check whether
1223  // operating on all incoming values of the phi always yields the same value.
1224  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1225  if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1226  return V;
1227 
1228  // If any bits in the shift amount make that value greater than or equal to
1229  // the number of bits in the type, the shift is undefined.
1230  KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1231  if (Known.One.getLimitedValue() >= Known.getBitWidth())
1232  return UndefValue::get(Op0->getType());
1233 
1234  // If all valid bits in the shift amount are known zero, the first operand is
1235  // unchanged.
1236  unsigned NumValidShiftBits = Log2_32_Ceil(Known.getBitWidth());
1237  if (Known.countMinTrailingZeros() >= NumValidShiftBits)
1238  return Op0;
1239 
1240  return nullptr;
1241 }
1242 
1243 /// Given operands for an Shl, LShr or AShr, see if we can
1244 /// fold the result. If not, this returns null.
1246  Value *Op1, bool isExact, const SimplifyQuery &Q,
1247  unsigned MaxRecurse) {
1248  if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1249  return V;
1250 
1251  // X >> X -> 0
1252  if (Op0 == Op1)
1253  return Constant::getNullValue(Op0->getType());
1254 
1255  // undef >> X -> 0
1256  // undef >> X -> undef (if it's exact)
1257  if (match(Op0, m_Undef()))
1258  return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1259 
1260  // The low bit cannot be shifted out of an exact shift if it is set.
1261  if (isExact) {
1262  KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1263  if (Op0Known.One[0])
1264  return Op0;
1265  }
1266 
1267  return nullptr;
1268 }
1269 
1270 /// Given operands for an Shl, see if we can fold the result.
1271 /// If not, this returns null.
1272 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1273  const SimplifyQuery &Q, unsigned MaxRecurse) {
1274  if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1275  return V;
1276 
1277  // undef << X -> 0
1278  // undef << X -> undef if (if it's NSW/NUW)
1279  if (match(Op0, m_Undef()))
1280  return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1281 
1282  // (X >> A) << A -> X
1283  Value *X;
1284  if (Q.IIQ.UseInstrInfo &&
1285  match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1286  return X;
1287 
1288  // shl nuw i8 C, %x -> C iff C has sign bit set.
1289  if (isNUW && match(Op0, m_Negative()))
1290  return Op0;
1291  // NOTE: could use computeKnownBits() / LazyValueInfo,
1292  // but the cost-benefit analysis suggests it isn't worth it.
1293 
1294  return nullptr;
1295 }
1296 
1297 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1298  const SimplifyQuery &Q) {
1299  return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1300 }
1301 
1302 /// Given operands for an LShr, see if we can fold the result.
1303 /// If not, this returns null.
1304 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1305  const SimplifyQuery &Q, unsigned MaxRecurse) {
1306  if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1307  MaxRecurse))
1308  return V;
1309 
1310  // (X << A) >> A -> X
1311  Value *X;
1312  if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1313  return X;
1314 
1315  // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1316  // We can return X as we do in the above case since OR alters no bits in X.
1317  // SimplifyDemandedBits in InstCombine can do more general optimization for
1318  // bit manipulation. This pattern aims to provide opportunities for other
1319  // optimizers by supporting a simple but common case in InstSimplify.
1320  Value *Y;
1321  const APInt *ShRAmt, *ShLAmt;
1322  if (match(Op1, m_APInt(ShRAmt)) &&
1323  match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1324  *ShRAmt == *ShLAmt) {
1325  const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1326  const unsigned Width = Op0->getType()->getScalarSizeInBits();
1327  const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
1328  if (ShRAmt->uge(EffWidthY))
1329  return X;
1330  }
1331 
1332  return nullptr;
1333 }
1334 
1335 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1336  const SimplifyQuery &Q) {
1337  return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1338 }
1339 
1340 /// Given operands for an AShr, see if we can fold the result.
1341 /// If not, this returns null.
1342 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1343  const SimplifyQuery &Q, unsigned MaxRecurse) {
1344  if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1345  MaxRecurse))
1346  return V;
1347 
1348  // all ones >>a X -> -1
1349  // Do not return Op0 because it may contain undef elements if it's a vector.
1350  if (match(Op0, m_AllOnes()))
1351  return Constant::getAllOnesValue(Op0->getType());
1352 
1353  // (X << A) >> A -> X
1354  Value *X;
1355  if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1356  return X;
1357 
1358  // Arithmetic shifting an all-sign-bit value is a no-op.
1359  unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1360  if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1361  return Op0;
1362 
1363  return nullptr;
1364 }
1365 
1366 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1367  const SimplifyQuery &Q) {
1368  return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1369 }
1370 
1371 /// Commuted variants are assumed to be handled by calling this function again
1372 /// with the parameters swapped.
1374  ICmpInst *UnsignedICmp, bool IsAnd,
1375  const SimplifyQuery &Q) {
1376  Value *X, *Y;
1377 
1378  ICmpInst::Predicate EqPred;
1379  if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1380  !ICmpInst::isEquality(EqPred))
1381  return nullptr;
1382 
1383  ICmpInst::Predicate UnsignedPred;
1384 
1385  Value *A, *B;
1386  // Y = (A - B);
1387  if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1388  if (match(UnsignedICmp,
1389  m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1390  ICmpInst::isUnsigned(UnsignedPred)) {
1391  if (UnsignedICmp->getOperand(0) != A)
1392  UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1393 
1394  // A >=/<= B || (A - B) != 0 <--> true
1395  if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1396  UnsignedPred == ICmpInst::ICMP_ULE) &&
1397  EqPred == ICmpInst::ICMP_NE && !IsAnd)
1398  return ConstantInt::getTrue(UnsignedICmp->getType());
1399  // A </> B && (A - B) == 0 <--> false
1400  if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1401  UnsignedPred == ICmpInst::ICMP_UGT) &&
1402  EqPred == ICmpInst::ICMP_EQ && IsAnd)
1403  return ConstantInt::getFalse(UnsignedICmp->getType());
1404  }
1405 
1406  // Given Y = (A - B)
1407  // Y >= A && Y != 0 --> Y >= A iff B != 0
1408  // Y < A || Y == 0 --> Y < A iff B != 0
1409  if (match(UnsignedICmp,
1410  m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1411  if (UnsignedICmp->getOperand(0) != Y)
1412  UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1413 
1414  if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1415  EqPred == ICmpInst::ICMP_NE &&
1416  isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1417  return UnsignedICmp;
1418  if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1419  EqPred == ICmpInst::ICMP_EQ &&
1420  isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1421  return UnsignedICmp;
1422  }
1423  }
1424 
1425  if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1426  ICmpInst::isUnsigned(UnsignedPred))
1427  ;
1428  else if (match(UnsignedICmp,
1429  m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1430  ICmpInst::isUnsigned(UnsignedPred))
1431  UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1432  else
1433  return nullptr;
1434 
1435  // X < Y && Y != 0 --> X < Y
1436  // X < Y || Y != 0 --> Y != 0
1437  if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1438  return IsAnd ? UnsignedICmp : ZeroICmp;
1439 
1440  // X <= Y && Y != 0 --> X <= Y iff X != 0
1441  // X <= Y || Y != 0 --> Y != 0 iff X != 0
1442  if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1443  isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1444  return IsAnd ? UnsignedICmp : ZeroICmp;
1445 
1446  // X > Y && Y == 0 --> Y == 0 iff X != 0
1447  // X > Y || Y == 0 --> X > Y iff X != 0
1448  if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1449  isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1450  return IsAnd ? ZeroICmp : UnsignedICmp;
1451 
1452  // X >= Y || Y != 0 --> true
1453  // X >= Y || Y == 0 --> X >= Y
1454  if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1455  if (EqPred == ICmpInst::ICMP_NE)
1456  return getTrue(UnsignedICmp->getType());
1457  return UnsignedICmp;
1458  }
1459 
1460  // X < Y && Y == 0 --> false
1461  if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1462  IsAnd)
1463  return getFalse(UnsignedICmp->getType());
1464 
1465  return nullptr;
1466 }
1467 
1468 /// Commuted variants are assumed to be handled by calling this function again
1469 /// with the parameters swapped.
1471  ICmpInst::Predicate Pred0, Pred1;
1472  Value *A ,*B;
1473  if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1474  !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1475  return nullptr;
1476 
1477  // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1478  // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1479  // can eliminate Op1 from this 'and'.
1480  if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1481  return Op0;
1482 
1483  // Check for any combination of predicates that are guaranteed to be disjoint.
1484  if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1485  (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1486  (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1487  (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1488  return getFalse(Op0->getType());
1489 
1490  return nullptr;
1491 }
1492 
1493 /// Commuted variants are assumed to be handled by calling this function again
1494 /// with the parameters swapped.
1496  ICmpInst::Predicate Pred0, Pred1;
1497  Value *A ,*B;
1498  if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1499  !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
1500  return nullptr;
1501 
1502  // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1503  // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1504  // can eliminate Op0 from this 'or'.
1505  if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1506  return Op1;
1507 
1508  // Check for any combination of predicates that cover the entire range of
1509  // possibilities.
1510  if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1511  (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1512  (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1513  (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1514  return getTrue(Op0->getType());
1515 
1516  return nullptr;
1517 }
1518 
1519 /// Test if a pair of compares with a shared operand and 2 constants has an
1520 /// empty set intersection, full set union, or if one compare is a superset of
1521 /// the other.
1523  bool IsAnd) {
1524  // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1525  if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1526  return nullptr;
1527 
1528  const APInt *C0, *C1;
1529  if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1530  !match(Cmp1->getOperand(1), m_APInt(C1)))
1531  return nullptr;
1532 
1533  auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1534  auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1535 
1536  // For and-of-compares, check if the intersection is empty:
1537  // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1538  if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1539  return getFalse(Cmp0->getType());
1540 
1541  // For or-of-compares, check if the union is full:
1542  // (icmp X, C0) || (icmp X, C1) --> full set --> true
1543  if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1544  return getTrue(Cmp0->getType());
1545 
1546  // Is one range a superset of the other?
1547  // If this is and-of-compares, take the smaller set:
1548  // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1549  // If this is or-of-compares, take the larger set:
1550  // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1551  if (Range0.contains(Range1))
1552  return IsAnd ? Cmp1 : Cmp0;
1553  if (Range1.contains(Range0))
1554  return IsAnd ? Cmp0 : Cmp1;
1555 
1556  return nullptr;
1557 }
1558 
1560  bool IsAnd) {
1561  ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1562  if (!match(Cmp0->getOperand(1), m_Zero()) ||
1563  !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1564  return nullptr;
1565 
1566  if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1567  return nullptr;
1568 
1569  // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1570  Value *X = Cmp0->getOperand(0);
1571  Value *Y = Cmp1->getOperand(0);
1572 
1573  // If one of the compares is a masked version of a (not) null check, then
1574  // that compare implies the other, so we eliminate the other. Optionally, look
1575  // through a pointer-to-int cast to match a null check of a pointer type.
1576 
1577  // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1578  // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1579  // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1580  // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1581  if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1583  return Cmp1;
1584 
1585  // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1586  // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1587  // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1588  // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1589  if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1591  return Cmp0;
1592 
1593  return nullptr;
1594 }
1595 
1597  const InstrInfoQuery &IIQ) {
1598  // (icmp (add V, C0), C1) & (icmp V, C0)
1599  ICmpInst::Predicate Pred0, Pred1;
1600  const APInt *C0, *C1;
1601  Value *V;
1602  if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1603  return nullptr;
1604 
1605  if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1606  return nullptr;
1607 
1608  auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1609  if (AddInst->getOperand(1) != Op1->getOperand(1))
1610  return nullptr;
1611 
1612  Type *ITy = Op0->getType();
1613  bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1614  bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1615 
1616  const APInt Delta = *C1 - *C0;
1617  if (C0->isStrictlyPositive()) {
1618  if (Delta == 2) {
1619  if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1620  return getFalse(ITy);
1621  if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1622  return getFalse(ITy);
1623  }
1624  if (Delta == 1) {
1625  if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1626  return getFalse(ITy);
1627  if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1628  return getFalse(ITy);
1629  }
1630  }
1631  if (C0->getBoolValue() && isNUW) {
1632  if (Delta == 2)
1633  if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1634  return getFalse(ITy);
1635  if (Delta == 1)
1636  if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1637  return getFalse(ITy);
1638  }
1639 
1640  return nullptr;
1641 }
1642 
1644  const SimplifyQuery &Q) {
1645  if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1646  return X;
1647  if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1648  return X;
1649 
1650  if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1651  return X;
1652  if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0))
1653  return X;
1654 
1655  if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1656  return X;
1657 
1658  if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1659  return X;
1660 
1661  if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1662  return X;
1663  if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1664  return X;
1665 
1666  return nullptr;
1667 }
1668 
1670  const InstrInfoQuery &IIQ) {
1671  // (icmp (add V, C0), C1) | (icmp V, C0)
1672  ICmpInst::Predicate Pred0, Pred1;
1673  const APInt *C0, *C1;
1674  Value *V;
1675  if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1676  return nullptr;
1677 
1678  if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1679  return nullptr;
1680 
1681  auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1682  if (AddInst->getOperand(1) != Op1->getOperand(1))
1683  return nullptr;
1684 
1685  Type *ITy = Op0->getType();
1686  bool isNSW = IIQ.hasNoSignedWrap(AddInst);
1687  bool isNUW = IIQ.hasNoUnsignedWrap(AddInst);
1688 
1689  const APInt Delta = *C1 - *C0;
1690  if (C0->isStrictlyPositive()) {
1691  if (Delta == 2) {
1692  if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1693  return getTrue(ITy);
1694  if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1695  return getTrue(ITy);
1696  }
1697  if (Delta == 1) {
1698  if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1699  return getTrue(ITy);
1700  if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1701  return getTrue(ITy);
1702  }
1703  }
1704  if (C0->getBoolValue() && isNUW) {
1705  if (Delta == 2)
1706  if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1707  return getTrue(ITy);
1708  if (Delta == 1)
1709  if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1710  return getTrue(ITy);
1711  }
1712 
1713  return nullptr;
1714 }
1715 
1717  const SimplifyQuery &Q) {
1718  if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1719  return X;
1720  if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1721  return X;
1722 
1723  if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1724  return X;
1725  if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0))
1726  return X;
1727 
1728  if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1729  return X;
1730 
1731  if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1732  return X;
1733 
1734  if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1735  return X;
1736  if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1737  return X;
1738 
1739  return nullptr;
1740 }
1741 
1743  FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) {
1744  Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1745  Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1746  if (LHS0->getType() != RHS0->getType())
1747  return nullptr;
1748 
1749  FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1750  if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1751  (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1752  // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1753  // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1754  // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1755  // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1756  // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1757  // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1758  // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1759  // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1760  if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
1761  (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
1762  return RHS;
1763 
1764  // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1765  // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1766  // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1767  // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1768  // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1769  // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1770  // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1771  // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1772  if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
1773  (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
1774  return LHS;
1775  }
1776 
1777  return nullptr;
1778 }
1779 
1781  Value *Op0, Value *Op1, bool IsAnd) {
1782  // Look through casts of the 'and' operands to find compares.
1783  auto *Cast0 = dyn_cast<CastInst>(Op0);
1784  auto *Cast1 = dyn_cast<CastInst>(Op1);
1785  if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1786  Cast0->getSrcTy() == Cast1->getSrcTy()) {
1787  Op0 = Cast0->getOperand(0);
1788  Op1 = Cast1->getOperand(0);
1789  }
1790 
1791  Value *V = nullptr;
1792  auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
1793  auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
1794  if (ICmp0 && ICmp1)
1795  V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
1796  : simplifyOrOfICmps(ICmp0, ICmp1, Q);
1797 
1798  auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
1799  auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
1800  if (FCmp0 && FCmp1)
1801  V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
1802 
1803  if (!V)
1804  return nullptr;
1805  if (!Cast0)
1806  return V;
1807 
1808  // If we looked through casts, we can only handle a constant simplification
1809  // because we are not allowed to create a cast instruction here.
1810  if (auto *C = dyn_cast<Constant>(V))
1811  return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
1812 
1813  return nullptr;
1814 }
1815 
1816 /// Check that the Op1 is in expected form, i.e.:
1817 /// %Agg = tail call { i4, i1 } @llvm.[us]mul.with.overflow.i4(i4 %X, i4 %???)
1818 /// %Op1 = extractvalue { i4, i1 } %Agg, 1
1820  Value *X) {
1821  auto *Extract = dyn_cast<ExtractValueInst>(Op1);
1822  // We should only be extracting the overflow bit.
1823  if (!Extract || !Extract->getIndices().equals(1))
1824  return false;
1825  Value *Agg = Extract->getAggregateOperand();
1826  // This should be a multiplication-with-overflow intrinsic.
1827  if (!match(Agg, m_CombineOr(m_Intrinsic<Intrinsic::umul_with_overflow>(),
1828  m_Intrinsic<Intrinsic::smul_with_overflow>())))
1829  return false;
1830  // One of its multipliers should be the value we checked for zero before.
1831  if (!match(Agg, m_CombineOr(m_Argument<0>(m_Specific(X)),
1832  m_Argument<1>(m_Specific(X)))))
1833  return false;
1834  return true;
1835 }
1836 
1837 /// The @llvm.[us]mul.with.overflow intrinsic could have been folded from some
1838 /// other form of check, e.g. one that was using division; it may have been
1839 /// guarded against division-by-zero. We can drop that check now.
1840 /// Look for:
1841 /// %Op0 = icmp ne i4 %X, 0
1842 /// %Agg = tail call { i4, i1 } @llvm.[us]mul.with.overflow.i4(i4 %X, i4 %???)
1843 /// %Op1 = extractvalue { i4, i1 } %Agg, 1
1844 /// %??? = and i1 %Op0, %Op1
1845 /// We can just return %Op1
1847  ICmpInst::Predicate Pred;
1848  Value *X;
1849  if (!match(Op0, m_ICmp(Pred, m_Value(X), m_Zero())) ||
1850  Pred != ICmpInst::Predicate::ICMP_NE)
1851  return nullptr;
1852  // Is Op1 in expected form?
1854  return nullptr;
1855  // Can omit 'and', and just return the overflow bit.
1856  return Op1;
1857 }
1858 
1859 /// The @llvm.[us]mul.with.overflow intrinsic could have been folded from some
1860 /// other form of check, e.g. one that was using division; it may have been
1861 /// guarded against division-by-zero. We can drop that check now.
1862 /// Look for:
1863 /// %Op0 = icmp eq i4 %X, 0
1864 /// %Agg = tail call { i4, i1 } @llvm.[us]mul.with.overflow.i4(i4 %X, i4 %???)
1865 /// %Op1 = extractvalue { i4, i1 } %Agg, 1
1866 /// %NotOp1 = xor i1 %Op1, true
1867 /// %or = or i1 %Op0, %NotOp1
1868 /// We can just return %NotOp1
1870  Value *NotOp1) {
1871  ICmpInst::Predicate Pred;
1872  Value *X;
1873  if (!match(Op0, m_ICmp(Pred, m_Value(X), m_Zero())) ||
1874  Pred != ICmpInst::Predicate::ICMP_EQ)
1875  return nullptr;
1876  // We expect the other hand of an 'or' to be a 'not'.
1877  Value *Op1;
1878  if (!match(NotOp1, m_Not(m_Value(Op1))))
1879  return nullptr;
1880  // Is Op1 in expected form?
1882  return nullptr;
1883  // Can omit 'and', and just return the inverted overflow bit.
1884  return NotOp1;
1885 }
1886 
1887 /// Given operands for an And, see if we can fold the result.
1888 /// If not, this returns null.
1889 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1890  unsigned MaxRecurse) {
1891  if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1892  return C;
1893 
1894  // X & undef -> 0
1895  if (match(Op1, m_Undef()))
1896  return Constant::getNullValue(Op0->getType());
1897 
1898  // X & X = X
1899  if (Op0 == Op1)
1900  return Op0;
1901 
1902  // X & 0 = 0
1903  if (match(Op1, m_Zero()))
1904  return Constant::getNullValue(Op0->getType());
1905 
1906  // X & -1 = X
1907  if (match(Op1, m_AllOnes()))
1908  return Op0;
1909 
1910  // A & ~A = ~A & A = 0
1911  if (match(Op0, m_Not(m_Specific(Op1))) ||
1912  match(Op1, m_Not(m_Specific(Op0))))
1913  return Constant::getNullValue(Op0->getType());
1914 
1915  // (A | ?) & A = A
1916  if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
1917  return Op1;
1918 
1919  // A & (A | ?) = A
1920  if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
1921  return Op0;
1922 
1923  // A mask that only clears known zeros of a shifted value is a no-op.
1924  Value *X;
1925  const APInt *Mask;
1926  const APInt *ShAmt;
1927  if (match(Op1, m_APInt(Mask))) {
1928  // If all bits in the inverted and shifted mask are clear:
1929  // and (shl X, ShAmt), Mask --> shl X, ShAmt
1930  if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
1931  (~(*Mask)).lshr(*ShAmt).isNullValue())
1932  return Op0;
1933 
1934  // If all bits in the inverted and shifted mask are clear:
1935  // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
1936  if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
1937  (~(*Mask)).shl(*ShAmt).isNullValue())
1938  return Op0;
1939  }
1940 
1941  // If we have a multiplication overflow check that is being 'and'ed with a
1942  // check that one of the multipliers is not zero, we can omit the 'and', and
1943  // only keep the overflow check.
1944  if (Value *V = omitCheckForZeroBeforeMulWithOverflow(Op0, Op1))
1945  return V;
1946  if (Value *V = omitCheckForZeroBeforeMulWithOverflow(Op1, Op0))
1947  return V;
1948 
1949  // A & (-A) = A if A is a power of two or zero.
1950  if (match(Op0, m_Neg(m_Specific(Op1))) ||
1951  match(Op1, m_Neg(m_Specific(Op0)))) {
1952  if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1953  Q.DT))
1954  return Op0;
1955  if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1956  Q.DT))
1957  return Op1;
1958  }
1959 
1960  // This is a similar pattern used for checking if a value is a power-of-2:
1961  // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
1962  // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
1963  if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
1964  isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
1965  return Constant::getNullValue(Op1->getType());
1966  if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
1967  isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
1968  return Constant::getNullValue(Op0->getType());
1969 
1970  if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
1971  return V;
1972 
1973  // Try some generic simplifications for associative operations.
1974  if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1975  MaxRecurse))
1976  return V;
1977 
1978  // And distributes over Or. Try some generic simplifications based on this.
1979  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1980  Q, MaxRecurse))
1981  return V;
1982 
1983  // And distributes over Xor. Try some generic simplifications based on this.
1984  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1985  Q, MaxRecurse))
1986  return V;
1987 
1988  // If the operation is with the result of a select instruction, check whether
1989  // operating on either branch of the select always yields the same value.
1990  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1991  if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1992  MaxRecurse))
1993  return V;
1994 
1995  // If the operation is with the result of a phi instruction, check whether
1996  // operating on all incoming values of the phi always yields the same value.
1997  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1998  if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1999  MaxRecurse))
2000  return V;
2001 
2002  // Assuming the effective width of Y is not larger than A, i.e. all bits
2003  // from X and Y are disjoint in (X << A) | Y,
2004  // if the mask of this AND op covers all bits of X or Y, while it covers
2005  // no bits from the other, we can bypass this AND op. E.g.,
2006  // ((X << A) | Y) & Mask -> Y,
2007  // if Mask = ((1 << effective_width_of(Y)) - 1)
2008  // ((X << A) | Y) & Mask -> X << A,
2009  // if Mask = ((1 << effective_width_of(X)) - 1) << A
2010  // SimplifyDemandedBits in InstCombine can optimize the general case.
2011  // This pattern aims to help other passes for a common case.
2012  Value *Y, *XShifted;
2013  if (match(Op1, m_APInt(Mask)) &&
2014  match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
2015  m_Value(XShifted)),
2016  m_Value(Y)))) {
2017  const unsigned Width = Op0->getType()->getScalarSizeInBits();
2018  const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2019  const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2020  const unsigned EffWidthY = Width - YKnown.countMinLeadingZeros();
2021  if (EffWidthY <= ShftCnt) {
2022  const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI,
2023  Q.DT);
2024  const unsigned EffWidthX = Width - XKnown.countMinLeadingZeros();
2025  const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2026  const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2027  // If the mask is extracting all bits from X or Y as is, we can skip
2028  // this AND op.
2029  if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2030  return Y;
2031  if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2032  return XShifted;
2033  }
2034  }
2035 
2036  return nullptr;
2037 }
2038 
2041 }
2042 
2043 /// Given operands for an Or, see if we can fold the result.
2044 /// If not, this returns null.
2045 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2046  unsigned MaxRecurse) {
2047  if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2048  return C;
2049 
2050  // X | undef -> -1
2051  // X | -1 = -1
2052  // Do not return Op1 because it may contain undef elements if it's a vector.
2053  if (match(Op1, m_Undef()) || match(Op1, m_AllOnes()))
2054  return Constant::getAllOnesValue(Op0->getType());
2055 
2056  // X | X = X
2057  // X | 0 = X
2058  if (Op0 == Op1 || match(Op1, m_Zero()))
2059  return Op0;
2060 
2061  // A | ~A = ~A | A = -1
2062  if (match(Op0, m_Not(m_Specific(Op1))) ||
2063  match(Op1, m_Not(m_Specific(Op0))))
2064  return Constant::getAllOnesValue(Op0->getType());
2065 
2066  // (A & ?) | A = A
2067  if (match(Op0, m_c_And(m_Specific(Op1), m_Value())))
2068  return Op1;
2069 
2070  // A | (A & ?) = A
2071  if (match(Op1, m_c_And(m_Specific(Op0), m_Value())))
2072  return Op0;
2073 
2074  // ~(A & ?) | A = -1
2075  if (match(Op0, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
2076  return Constant::getAllOnesValue(Op1->getType());
2077 
2078  // A | ~(A & ?) = -1
2079  if (match(Op1, m_Not(m_c_And(m_Specific(Op1), m_Value()))))
2080  return Constant::getAllOnesValue(Op0->getType());
2081 
2082  Value *A, *B;
2083  // (A & ~B) | (A ^ B) -> (A ^ B)
2084  // (~B & A) | (A ^ B) -> (A ^ B)
2085  // (A & ~B) | (B ^ A) -> (B ^ A)
2086  // (~B & A) | (B ^ A) -> (B ^ A)
2087  if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
2088  (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
2089  match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
2090  return Op1;
2091 
2092  // Commute the 'or' operands.
2093  // (A ^ B) | (A & ~B) -> (A ^ B)
2094  // (A ^ B) | (~B & A) -> (A ^ B)
2095  // (B ^ A) | (A & ~B) -> (B ^ A)
2096  // (B ^ A) | (~B & A) -> (B ^ A)
2097  if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
2098  (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
2099  match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
2100  return Op0;
2101 
2102  // (A & B) | (~A ^ B) -> (~A ^ B)
2103  // (B & A) | (~A ^ B) -> (~A ^ B)
2104  // (A & B) | (B ^ ~A) -> (B ^ ~A)
2105  // (B & A) | (B ^ ~A) -> (B ^ ~A)
2106  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
2107  (match(Op1, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
2108  match(Op1, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
2109  return Op1;
2110 
2111  // (~A ^ B) | (A & B) -> (~A ^ B)
2112  // (~A ^ B) | (B & A) -> (~A ^ B)
2113  // (B ^ ~A) | (A & B) -> (B ^ ~A)
2114  // (B ^ ~A) | (B & A) -> (B ^ ~A)
2115  if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
2116  (match(Op0, m_c_Xor(m_Specific(A), m_Not(m_Specific(B)))) ||
2117  match(Op0, m_c_Xor(m_Not(m_Specific(A)), m_Specific(B)))))
2118  return Op0;
2119 
2120  if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2121  return V;
2122 
2123  // If we have a multiplication overflow check that is being 'and'ed with a
2124  // check that one of the multipliers is not zero, we can omit the 'and', and
2125  // only keep the overflow check.
2127  return V;
2129  return V;
2130 
2131  // Try some generic simplifications for associative operations.
2132  if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
2133  MaxRecurse))
2134  return V;
2135 
2136  // Or distributes over And. Try some generic simplifications based on this.
2137  if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
2138  MaxRecurse))
2139  return V;
2140 
2141  // If the operation is with the result of a select instruction, check whether
2142  // operating on either branch of the select always yields the same value.
2143  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
2144  if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
2145  MaxRecurse))
2146  return V;
2147 
2148  // (A & C1)|(B & C2)
2149  const APInt *C1, *C2;
2150  if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2151  match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2152  if (*C1 == ~*C2) {
2153  // (A & C1)|(B & C2)
2154  // If we have: ((V + N) & C1) | (V & C2)
2155  // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2156  // replace with V+N.
2157  Value *N;
2158  if (C2->isMask() && // C2 == 0+1+
2159  match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2160  // Add commutes, try both ways.
2161  if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2162  return A;
2163  }
2164  // Or commutes, try both ways.
2165  if (C1->isMask() &&
2166  match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2167  // Add commutes, try both ways.
2168  if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2169  return B;
2170  }
2171  }
2172  }
2173 
2174  // If the operation is with the result of a phi instruction, check whether
2175  // operating on all incoming values of the phi always yields the same value.
2176  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2177  if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2178  return V;
2179 
2180  return nullptr;
2181 }
2182 
2185 }
2186 
2187 /// Given operands for a Xor, see if we can fold the result.
2188 /// If not, this returns null.
2189 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2190  unsigned MaxRecurse) {
2191  if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2192  return C;
2193 
2194  // A ^ undef -> undef
2195  if (match(Op1, m_Undef()))
2196  return Op1;
2197 
2198  // A ^ 0 = A
2199  if (match(Op1, m_Zero()))
2200  return Op0;
2201 
2202  // A ^ A = 0
2203  if (Op0 == Op1)
2204  return Constant::getNullValue(Op0->getType());
2205 
2206  // A ^ ~A = ~A ^ A = -1
2207  if (match(Op0, m_Not(m_Specific(Op1))) ||
2208  match(Op1, m_Not(m_Specific(Op0))))
2209  return Constant::getAllOnesValue(Op0->getType());
2210 
2211  // Try some generic simplifications for associative operations.
2212  if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2213  MaxRecurse))
2214  return V;
2215 
2216  // Threading Xor over selects and phi nodes is pointless, so don't bother.
2217  // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2218  // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2219  // only if B and C are equal. If B and C are equal then (since we assume
2220  // that operands have already been simplified) "select(cond, B, C)" should
2221  // have been simplified to the common value of B and C already. Analysing
2222  // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2223  // for threading over phi nodes.
2224 
2225  return nullptr;
2226 }
2227 
2230 }
2231 
2232 
2234  return CmpInst::makeCmpResultType(Op->getType());
2235 }
2236 
2237 /// Rummage around inside V looking for something equivalent to the comparison
2238 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2239 /// Helper function for analyzing max/min idioms.
2241  Value *LHS, Value *RHS) {
2243  if (!SI)
2244  return nullptr;
2245  CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2246  if (!Cmp)
2247  return nullptr;
2248  Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2249  if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2250  return Cmp;
2251  if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2252  LHS == CmpRHS && RHS == CmpLHS)
2253  return Cmp;
2254  return nullptr;
2255 }
2256 
2257 // A significant optimization not implemented here is assuming that alloca
2258 // addresses are not equal to incoming argument values. They don't *alias*,
2259 // as we say, but that doesn't mean they aren't equal, so we take a
2260 // conservative approach.
2261 //
2262 // This is inspired in part by C++11 5.10p1:
2263 // "Two pointers of the same type compare equal if and only if they are both
2264 // null, both point to the same function, or both represent the same
2265 // address."
2266 //
2267 // This is pretty permissive.
2268 //
2269 // It's also partly due to C11 6.5.9p6:
2270 // "Two pointers compare equal if and only if both are null pointers, both are
2271 // pointers to the same object (including a pointer to an object and a
2272 // subobject at its beginning) or function, both are pointers to one past the
2273 // last element of the same array object, or one is a pointer to one past the
2274 // end of one array object and the other is a pointer to the start of a
2275 // different array object that happens to immediately follow the first array
2276 // object in the address space.)
2277 //
2278 // C11's version is more restrictive, however there's no reason why an argument
2279 // couldn't be a one-past-the-end value for a stack object in the caller and be
2280 // equal to the beginning of a stack object in the callee.
2281 //
2282 // If the C and C++ standards are ever made sufficiently restrictive in this
2283 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2284 // this optimization.
2285 static Constant *
2287  const DominatorTree *DT, CmpInst::Predicate Pred,
2288  AssumptionCache *AC, const Instruction *CxtI,
2289  const InstrInfoQuery &IIQ, Value *LHS, Value *RHS) {
2290  // First, skip past any trivial no-ops.
2291  LHS = LHS->stripPointerCasts();
2292  RHS = RHS->stripPointerCasts();
2293 
2294  // A non-null pointer is not equal to a null pointer.
2295  if (llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
2296  IIQ.UseInstrInfo) &&
2297  isa<ConstantPointerNull>(RHS) &&
2298  (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2299  return ConstantInt::get(GetCompareTy(LHS),
2300  !CmpInst::isTrueWhenEqual(Pred));
2301 
2302  // We can only fold certain predicates on pointer comparisons.
2303  switch (Pred) {
2304  default:
2305  return nullptr;
2306 
2307  // Equality comaprisons are easy to fold.
2308  case CmpInst::ICMP_EQ:
2309  case CmpInst::ICMP_NE:
2310  break;
2311 
2312  // We can only handle unsigned relational comparisons because 'inbounds' on
2313  // a GEP only protects against unsigned wrapping.
2314  case CmpInst::ICMP_UGT:
2315  case CmpInst::ICMP_UGE:
2316  case CmpInst::ICMP_ULT:
2317  case CmpInst::ICMP_ULE:
2318  // However, we have to switch them to their signed variants to handle
2319  // negative indices from the base pointer.
2320  Pred = ICmpInst::getSignedPredicate(Pred);
2321  break;
2322  }
2323 
2324  // Strip off any constant offsets so that we can reason about them.
2325  // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2326  // here and compare base addresses like AliasAnalysis does, however there are
2327  // numerous hazards. AliasAnalysis and its utilities rely on special rules
2328  // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2329  // doesn't need to guarantee pointer inequality when it says NoAlias.
2330  Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2331  Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2332 
2333  // If LHS and RHS are related via constant offsets to the same base
2334  // value, we can replace it with an icmp which just compares the offsets.
2335  if (LHS == RHS)
2336  return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2337 
2338  // Various optimizations for (in)equality comparisons.
2339  if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2340  // Different non-empty allocations that exist at the same time have
2341  // different addresses (if the program can tell). Global variables always
2342  // exist, so they always exist during the lifetime of each other and all
2343  // allocas. Two different allocas usually have different addresses...
2344  //
2345  // However, if there's an @llvm.stackrestore dynamically in between two
2346  // allocas, they may have the same address. It's tempting to reduce the
2347  // scope of the problem by only looking at *static* allocas here. That would
2348  // cover the majority of allocas while significantly reducing the likelihood
2349  // of having an @llvm.stackrestore pop up in the middle. However, it's not
2350  // actually impossible for an @llvm.stackrestore to pop up in the middle of
2351  // an entry block. Also, if we have a block that's not attached to a
2352  // function, we can't tell if it's "static" under the current definition.
2353  // Theoretically, this problem could be fixed by creating a new kind of
2354  // instruction kind specifically for static allocas. Such a new instruction
2355  // could be required to be at the top of the entry block, thus preventing it
2356  // from being subject to a @llvm.stackrestore. Instcombine could even
2357  // convert regular allocas into these special allocas. It'd be nifty.
2358  // However, until then, this problem remains open.
2359  //
2360  // So, we'll assume that two non-empty allocas have different addresses
2361  // for now.
2362  //
2363  // With all that, if the offsets are within the bounds of their allocations
2364  // (and not one-past-the-end! so we can't use inbounds!), and their
2365  // allocations aren't the same, the pointers are not equal.
2366  //
2367  // Note that it's not necessary to check for LHS being a global variable
2368  // address, due to canonicalization and constant folding.
2369  if (isa<AllocaInst>(LHS) &&
2370  (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2371  ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2372  ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2373  uint64_t LHSSize, RHSSize;
2374  ObjectSizeOpts Opts;
2375  Opts.NullIsUnknownSize =
2376  NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction());
2377  if (LHSOffsetCI && RHSOffsetCI &&
2378  getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2379  getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
2380  const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2381  const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2382  if (!LHSOffsetValue.isNegative() &&
2383  !RHSOffsetValue.isNegative() &&
2384  LHSOffsetValue.ult(LHSSize) &&
2385  RHSOffsetValue.ult(RHSSize)) {
2386  return ConstantInt::get(GetCompareTy(LHS),
2387  !CmpInst::isTrueWhenEqual(Pred));
2388  }
2389  }
2390 
2391  // Repeat the above check but this time without depending on DataLayout
2392  // or being able to compute a precise size.
2393  if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2394  !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2395  LHSOffset->isNullValue() &&
2396  RHSOffset->isNullValue())
2397  return ConstantInt::get(GetCompareTy(LHS),
2398  !CmpInst::isTrueWhenEqual(Pred));
2399  }
2400 
2401  // Even if an non-inbounds GEP occurs along the path we can still optimize
2402  // equality comparisons concerning the result. We avoid walking the whole
2403  // chain again by starting where the last calls to
2404  // stripAndComputeConstantOffsets left off and accumulate the offsets.
2405  Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2406  Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2407  if (LHS == RHS)
2408  return ConstantExpr::getICmp(Pred,
2409  ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2410  ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2411 
2412  // If one side of the equality comparison must come from a noalias call
2413  // (meaning a system memory allocation function), and the other side must
2414  // come from a pointer that cannot overlap with dynamically-allocated
2415  // memory within the lifetime of the current function (allocas, byval
2416  // arguments, globals), then determine the comparison result here.
2417  SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2418  GetUnderlyingObjects(LHS, LHSUObjs, DL);
2419  GetUnderlyingObjects(RHS, RHSUObjs, DL);
2420 
2421  // Is the set of underlying objects all noalias calls?
2422  auto IsNAC = [](ArrayRef<const Value *> Objects) {
2423  return all_of(Objects, isNoAliasCall);
2424  };
2425 
2426  // Is the set of underlying objects all things which must be disjoint from
2427  // noalias calls. For allocas, we consider only static ones (dynamic
2428  // allocas might be transformed into calls to malloc not simultaneously
2429  // live with the compared-to allocation). For globals, we exclude symbols
2430  // that might be resolve lazily to symbols in another dynamically-loaded
2431  // library (and, thus, could be malloc'ed by the implementation).
2432  auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2433  return all_of(Objects, [](const Value *V) {
2434  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2435  return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2436  if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2437  return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2438  GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2439  !GV->isThreadLocal();
2440  if (const Argument *A = dyn_cast<Argument>(V))
2441  return A->hasByValAttr();
2442  return false;
2443  });
2444  };
2445 
2446  if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2447  (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2448  return ConstantInt::get(GetCompareTy(LHS),
2449  !CmpInst::isTrueWhenEqual(Pred));
2450 
2451  // Fold comparisons for non-escaping pointer even if the allocation call
2452  // cannot be elided. We cannot fold malloc comparison to null. Also, the
2453  // dynamic allocation call could be either of the operands.
2454  Value *MI = nullptr;
2455  if (isAllocLikeFn(LHS, TLI) &&
2456  llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2457  MI = LHS;
2458  else if (isAllocLikeFn(RHS, TLI) &&
2459  llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2460  MI = RHS;
2461  // FIXME: We should also fold the compare when the pointer escapes, but the
2462  // compare dominates the pointer escape
2463  if (MI && !PointerMayBeCaptured(MI, true, true))
2464  return ConstantInt::get(GetCompareTy(LHS),
2466  }
2467 
2468  // Otherwise, fail.
2469  return nullptr;
2470 }
2471 
2472 /// Fold an icmp when its operands have i1 scalar type.
2474  Value *RHS, const SimplifyQuery &Q) {
2475  Type *ITy = GetCompareTy(LHS); // The return type.
2476  Type *OpTy = LHS->getType(); // The operand type.
2477  if (!OpTy->isIntOrIntVectorTy(1))
2478  return nullptr;
2479 
2480  // A boolean compared to true/false can be simplified in 14 out of the 20
2481  // (10 predicates * 2 constants) possible combinations. Cases not handled here
2482  // require a 'not' of the LHS, so those must be transformed in InstCombine.
2483  if (match(RHS, m_Zero())) {
2484  switch (Pred) {
2485  case CmpInst::ICMP_NE: // X != 0 -> X
2486  case CmpInst::ICMP_UGT: // X >u 0 -> X
2487  case CmpInst::ICMP_SLT: // X <s 0 -> X
2488  return LHS;
2489 
2490  case CmpInst::ICMP_ULT: // X <u 0 -> false
2491  case CmpInst::ICMP_SGT: // X >s 0 -> false
2492  return getFalse(ITy);
2493 
2494  case CmpInst::ICMP_UGE: // X >=u 0 -> true
2495  case CmpInst::ICMP_SLE: // X <=s 0 -> true
2496  return getTrue(ITy);
2497 
2498  default: break;
2499  }
2500  } else if (match(RHS, m_One())) {
2501  switch (Pred) {
2502  case CmpInst::ICMP_EQ: // X == 1 -> X
2503  case CmpInst::ICMP_UGE: // X >=u 1 -> X
2504  case CmpInst::ICMP_SLE: // X <=s -1 -> X
2505  return LHS;
2506 
2507  case CmpInst::ICMP_UGT: // X >u 1 -> false
2508  case CmpInst::ICMP_SLT: // X <s -1 -> false
2509  return getFalse(ITy);
2510 
2511  case CmpInst::ICMP_ULE: // X <=u 1 -> true
2512  case CmpInst::ICMP_SGE: // X >=s -1 -> true
2513  return getTrue(ITy);
2514 
2515  default: break;
2516  }
2517  }
2518 
2519  switch (Pred) {
2520  default:
2521  break;
2522  case ICmpInst::ICMP_UGE:
2523  if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2524  return getTrue(ITy);
2525  break;
2526  case ICmpInst::ICMP_SGE:
2527  /// For signed comparison, the values for an i1 are 0 and -1
2528  /// respectively. This maps into a truth table of:
2529  /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2530  /// 0 | 0 | 1 (0 >= 0) | 1
2531  /// 0 | 1 | 1 (0 >= -1) | 1
2532  /// 1 | 0 | 0 (-1 >= 0) | 0
2533  /// 1 | 1 | 1 (-1 >= -1) | 1
2534  if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2535  return getTrue(ITy);
2536  break;
2537  case ICmpInst::ICMP_ULE:
2538  if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2539  return getTrue(ITy);
2540  break;
2541  }
2542 
2543  return nullptr;
2544 }
2545 
2546 /// Try hard to fold icmp with zero RHS because this is a common case.
2548  Value *RHS, const SimplifyQuery &Q) {
2549  if (!match(RHS, m_Zero()))
2550  return nullptr;
2551 
2552  Type *ITy = GetCompareTy(LHS); // The return type.
2553  switch (Pred) {
2554  default:
2555  llvm_unreachable("Unknown ICmp predicate!");
2556  case ICmpInst::ICMP_ULT:
2557  return getFalse(ITy);
2558  case ICmpInst::ICMP_UGE:
2559  return getTrue(ITy);
2560  case ICmpInst::ICMP_EQ:
2561  case ICmpInst::ICMP_ULE:
2562  if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2563  return getFalse(ITy);
2564  break;
2565  case ICmpInst::ICMP_NE:
2566  case ICmpInst::ICMP_UGT:
2567  if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
2568  return getTrue(ITy);
2569  break;
2570  case ICmpInst::ICMP_SLT: {
2571  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2572  if (LHSKnown.isNegative())
2573  return getTrue(ITy);
2574  if (LHSKnown.isNonNegative())
2575  return getFalse(ITy);
2576  break;
2577  }
2578  case ICmpInst::ICMP_SLE: {
2579  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2580  if (LHSKnown.isNegative())
2581  return getTrue(ITy);
2582  if (LHSKnown.isNonNegative() &&
2583  isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2584  return getFalse(ITy);
2585  break;
2586  }
2587  case ICmpInst::ICMP_SGE: {
2588  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2589  if (LHSKnown.isNegative())
2590  return getFalse(ITy);
2591  if (LHSKnown.isNonNegative())
2592  return getTrue(ITy);
2593  break;
2594  }
2595  case ICmpInst::ICMP_SGT: {
2596  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2597  if (LHSKnown.isNegative())
2598  return getFalse(ITy);
2599  if (LHSKnown.isNonNegative() &&
2600  isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2601  return getTrue(ITy);
2602  break;
2603  }
2604  }
2605 
2606  return nullptr;
2607 }
2608 
2610  Value *RHS, const InstrInfoQuery &IIQ) {
2611  Type *ITy = GetCompareTy(RHS); // The return type.
2612 
2613  Value *X;
2614  // Sign-bit checks can be optimized to true/false after unsigned
2615  // floating-point casts:
2616  // icmp slt (bitcast (uitofp X)), 0 --> false
2617  // icmp sgt (bitcast (uitofp X)), -1 --> true
2618  if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
2619  if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
2620  return ConstantInt::getFalse(ITy);
2621  if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
2622  return ConstantInt::getTrue(ITy);
2623  }
2624 
2625  const APInt *C;
2626  if (!match(RHS, m_APInt(C)))
2627  return nullptr;
2628 
2629  // Rule out tautological comparisons (eg., ult 0 or uge 0).
2631  if (RHS_CR.isEmptySet())
2632  return ConstantInt::getFalse(ITy);
2633  if (RHS_CR.isFullSet())
2634  return ConstantInt::getTrue(ITy);
2635 
2636  ConstantRange LHS_CR = computeConstantRange(LHS, IIQ.UseInstrInfo);
2637  if (!LHS_CR.isFullSet()) {
2638  if (RHS_CR.contains(LHS_CR))
2639  return ConstantInt::getTrue(ITy);
2640  if (RHS_CR.inverse().contains(LHS_CR))
2641  return ConstantInt::getFalse(ITy);
2642  }
2643 
2644  return nullptr;
2645 }
2646 
2647 /// TODO: A large part of this logic is duplicated in InstCombine's
2648 /// foldICmpBinOp(). We should be able to share that and avoid the code
2649 /// duplication.
2651  Value *RHS, const SimplifyQuery &Q,
2652  unsigned MaxRecurse) {
2653  Type *ITy = GetCompareTy(LHS); // The return type.
2654 
2655  BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2656  BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2657  if (MaxRecurse && (LBO || RBO)) {
2658  // Analyze the case when either LHS or RHS is an add instruction.
2659  Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2660  // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2661  bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2662  if (LBO && LBO->getOpcode() == Instruction::Add) {
2663  A = LBO->getOperand(0);
2664  B = LBO->getOperand(1);
2665  NoLHSWrapProblem =
2666  ICmpInst::isEquality(Pred) ||
2667  (CmpInst::isUnsigned(Pred) &&
2668  Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
2669  (CmpInst::isSigned(Pred) &&
2670  Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
2671  }
2672  if (RBO && RBO->getOpcode() == Instruction::Add) {
2673  C = RBO->getOperand(0);
2674  D = RBO->getOperand(1);
2675  NoRHSWrapProblem =
2676  ICmpInst::isEquality(Pred) ||
2677  (CmpInst::isUnsigned(Pred) &&
2678  Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
2679  (CmpInst::isSigned(Pred) &&
2680  Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
2681  }
2682 
2683  // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2684  if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2685  if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2686  Constant::getNullValue(RHS->getType()), Q,
2687  MaxRecurse - 1))
2688  return V;
2689 
2690  // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2691  if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2692  if (Value *V =
2694  C == LHS ? D : C, Q, MaxRecurse - 1))
2695  return V;
2696 
2697  // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2698  if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2699  NoRHSWrapProblem) {
2700  // Determine Y and Z in the form icmp (X+Y), (X+Z).
2701  Value *Y, *Z;
2702  if (A == C) {
2703  // C + B == C + D -> B == D
2704  Y = B;
2705  Z = D;
2706  } else if (A == D) {
2707  // D + B == C + D -> B == C
2708  Y = B;
2709  Z = C;
2710  } else if (B == C) {
2711  // A + C == C + D -> A == D
2712  Y = A;
2713  Z = D;
2714  } else {
2715  assert(B == D);
2716  // A + D == C + D -> A == C
2717  Y = A;
2718  Z = C;
2719  }
2720  if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2721  return V;
2722  }
2723  }
2724 
2725  {
2726  Value *Y = nullptr;
2727  // icmp pred (or X, Y), X
2728  if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2729  if (Pred == ICmpInst::ICMP_ULT)
2730  return getFalse(ITy);
2731  if (Pred == ICmpInst::ICMP_UGE)
2732  return getTrue(ITy);
2733 
2734  if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2735  KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2736  KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2737  if (RHSKnown.isNonNegative() && YKnown.isNegative())
2738  return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2739  if (RHSKnown.isNegative() || YKnown.isNonNegative())
2740  return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2741  }
2742  }
2743  // icmp pred X, (or X, Y)
2744  if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2745  if (Pred == ICmpInst::ICMP_ULE)
2746  return getTrue(ITy);
2747  if (Pred == ICmpInst::ICMP_UGT)
2748  return getFalse(ITy);
2749 
2750  if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2751  KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2752  KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2753  if (LHSKnown.isNonNegative() && YKnown.isNegative())
2754  return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2755  if (LHSKnown.isNegative() || YKnown.isNonNegative())
2756  return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2757  }
2758  }
2759  }
2760 
2761  // icmp pred (and X, Y), X
2762  if (LBO && match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
2763  if (Pred == ICmpInst::ICMP_UGT)
2764  return getFalse(ITy);
2765  if (Pred == ICmpInst::ICMP_ULE)
2766  return getTrue(ITy);
2767  }
2768  // icmp pred X, (and X, Y)
2769  if (RBO && match(RBO, m_c_And(m_Value(), m_Specific(LHS)))) {
2770  if (Pred == ICmpInst::ICMP_UGE)
2771  return getTrue(ITy);
2772  if (Pred == ICmpInst::ICMP_ULT)
2773  return getFalse(ITy);
2774  }
2775 
2776  // 0 - (zext X) pred C
2777  if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2778  if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2779  if (RHSC->getValue().isStrictlyPositive()) {
2780  if (Pred == ICmpInst::ICMP_SLT)
2781  return ConstantInt::getTrue(RHSC->getContext());
2782  if (Pred == ICmpInst::ICMP_SGE)
2783  return ConstantInt::getFalse(RHSC->getContext());
2784  if (Pred == ICmpInst::ICMP_EQ)
2785  return ConstantInt::getFalse(RHSC->getContext());
2786  if (Pred == ICmpInst::ICMP_NE)
2787  return ConstantInt::getTrue(RHSC->getContext());
2788  }
2789  if (RHSC->getValue().isNonNegative()) {
2790  if (Pred == ICmpInst::ICMP_SLE)
2791  return ConstantInt::getTrue(RHSC->getContext());
2792  if (Pred == ICmpInst::ICMP_SGT)
2793  return ConstantInt::getFalse(RHSC->getContext());
2794  }
2795  }
2796  }
2797 
2798  // icmp pred (urem X, Y), Y
2799  if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2800  switch (Pred) {
2801  default:
2802  break;
2803  case ICmpInst::ICMP_SGT:
2804  case ICmpInst::ICMP_SGE: {
2805  KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2806  if (!Known.isNonNegative())
2807  break;
2809  }
2810  case ICmpInst::ICMP_EQ:
2811  case ICmpInst::ICMP_UGT:
2812  case ICmpInst::ICMP_UGE:
2813  return getFalse(ITy);
2814  case ICmpInst::ICMP_SLT:
2815  case ICmpInst::ICMP_SLE: {
2816  KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2817  if (!Known.isNonNegative())
2818  break;
2820  }
2821  case ICmpInst::ICMP_NE:
2822  case ICmpInst::ICMP_ULT:
2823  case ICmpInst::ICMP_ULE:
2824  return getTrue(ITy);
2825  }
2826  }
2827 
2828  // icmp pred X, (urem Y, X)
2829  if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2830  switch (Pred) {
2831  default:
2832  break;
2833  case ICmpInst::ICMP_SGT:
2834  case ICmpInst::ICMP_SGE: {
2835  KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2836  if (!Known.isNonNegative())
2837  break;
2839  }
2840  case ICmpInst::ICMP_NE:
2841  case ICmpInst::ICMP_UGT:
2842  case ICmpInst::ICMP_UGE:
2843  return getTrue(ITy);
2844  case ICmpInst::ICMP_SLT:
2845  case ICmpInst::ICMP_SLE: {
2846  KnownBits Known = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2847  if (!Known.isNonNegative())
2848  break;
2850  }
2851  case ICmpInst::ICMP_EQ:
2852  case ICmpInst::ICMP_ULT:
2853  case ICmpInst::ICMP_ULE:
2854  return getFalse(ITy);
2855  }
2856  }
2857 
2858  // x >> y <=u x
2859  // x udiv y <=u x.
2860  if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2861  match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2862  // icmp pred (X op Y), X
2863  if (Pred == ICmpInst::ICMP_UGT)
2864  return getFalse(ITy);
2865  if (Pred == ICmpInst::ICMP_ULE)
2866  return getTrue(ITy);
2867  }
2868 
2869  // x >=u x >> y
2870  // x >=u x udiv y.
2871  if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2872  match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2873  // icmp pred X, (X op Y)
2874  if (Pred == ICmpInst::ICMP_ULT)
2875  return getFalse(ITy);
2876  if (Pred == ICmpInst::ICMP_UGE)
2877  return getTrue(ITy);
2878  }
2879 
2880  // handle:
2881  // CI2 << X == CI
2882  // CI2 << X != CI
2883  //
2884  // where CI2 is a power of 2 and CI isn't
2885  if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2886  const APInt *CI2Val, *CIVal = &CI->getValue();
2887  if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2888  CI2Val->isPowerOf2()) {
2889  if (!CIVal->isPowerOf2()) {
2890  // CI2 << X can equal zero in some circumstances,
2891  // this simplification is unsafe if CI is zero.
2892  //
2893  // We know it is safe if:
2894  // - The shift is nsw, we can't shift out the one bit.
2895  // - The shift is nuw, we can't shift out the one bit.
2896  // - CI2 is one
2897  // - CI isn't zero
2898  if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2899  Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
2900  CI2Val->isOneValue() || !CI->isZero()) {
2901  if (Pred == ICmpInst::ICMP_EQ)
2902  return ConstantInt::getFalse(RHS->getContext());
2903  if (Pred == ICmpInst::ICMP_NE)
2904  return ConstantInt::getTrue(RHS->getContext());
2905  }
2906  }
2907  if (CIVal->isSignMask() && CI2Val->isOneValue()) {
2908  if (Pred == ICmpInst::ICMP_UGT)
2909  return ConstantInt::getFalse(RHS->getContext());
2910  if (Pred == ICmpInst::ICMP_ULE)
2911  return ConstantInt::getTrue(RHS->getContext());
2912  }
2913  }
2914  }
2915 
2916  if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2917  LBO->getOperand(1) == RBO->getOperand(1)) {
2918  switch (LBO->getOpcode()) {
2919  default:
2920  break;
2921  case Instruction::UDiv:
2922  case Instruction::LShr:
2923  if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
2924  !Q.IIQ.isExact(RBO))
2925  break;
2926  if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2927  RBO->getOperand(0), Q, MaxRecurse - 1))
2928  return V;
2929  break;
2930  case Instruction::SDiv:
2931  if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
2932  !Q.IIQ.isExact(RBO))
2933  break;
2934  if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2935  RBO->getOperand(0), Q, MaxRecurse - 1))
2936  return V;
2937  break;
2938  case Instruction::AShr:
2939  if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
2940  break;
2941  if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2942  RBO->getOperand(0), Q, MaxRecurse - 1))
2943  return V;
2944  break;
2945  case Instruction::Shl: {
2946  bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
2947  bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
2948  if (!NUW && !NSW)
2949  break;
2950  if (!NSW && ICmpInst::isSigned(Pred))
2951  break;
2952  if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2953  RBO->getOperand(0), Q, MaxRecurse - 1))
2954  return V;
2955  break;
2956  }
2957  }
2958  }
2959  return nullptr;
2960 }
2961 
2962 /// Simplify integer comparisons where at least one operand of the compare
2963 /// matches an integer min/max idiom.
2965  Value *RHS, const SimplifyQuery &Q,
2966  unsigned MaxRecurse) {
2967  Type *ITy = GetCompareTy(LHS); // The return type.
2968  Value *A, *B;
2970  CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2971 
2972  // Signed variants on "max(a,b)>=a -> true".
2973  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2974  if (A != RHS)
2975  std::swap(A, B); // smax(A, B) pred A.
2976  EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2977  // We analyze this as smax(A, B) pred A.
2978  P = Pred;
2979  } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2980  (A == LHS || B == LHS)) {
2981  if (A != LHS)
2982  std::swap(A, B); // A pred smax(A, B).
2983  EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2984  // We analyze this as smax(A, B) swapped-pred A.
2985  P = CmpInst::getSwappedPredicate(Pred);
2986  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2987  (A == RHS || B == RHS)) {
2988  if (A != RHS)
2989  std::swap(A, B); // smin(A, B) pred A.
2990  EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2991  // We analyze this as smax(-A, -B) swapped-pred -A.
2992  // Note that we do not need to actually form -A or -B thanks to EqP.
2993  P = CmpInst::getSwappedPredicate(Pred);
2994  } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2995  (A == LHS || B == LHS)) {
2996  if (A != LHS)
2997  std::swap(A, B); // A pred smin(A, B).
2998  EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2999  // We analyze this as smax(-A, -B) pred -A.
3000  // Note that we do not need to actually form -A or -B thanks to EqP.
3001  P = Pred;
3002  }
3003  if (P != CmpInst::BAD_ICMP_PREDICATE) {
3004  // Cases correspond to "max(A, B) p A".
3005  switch (P) {
3006  default:
3007  break;
3008  case CmpInst::ICMP_EQ:
3009  case CmpInst::ICMP_SLE:
3010  // Equivalent to "A EqP B". This may be the same as the condition tested
3011  // in the max/min; if so, we can just return that.
3012  if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3013  return V;
3014  if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3015  return V;
3016  // Otherwise, see if "A EqP B" simplifies.
3017  if (MaxRecurse)
3018  if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3019  return V;
3020  break;
3021  case CmpInst::ICMP_NE:
3022  case CmpInst::ICMP_SGT: {
3024  // Equivalent to "A InvEqP B". This may be the same as the condition
3025  // tested in the max/min; if so, we can just return that.
3026  if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3027  return V;
3028  if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3029  return V;
3030  // Otherwise, see if "A InvEqP B" simplifies.
3031  if (MaxRecurse)
3032  if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3033  return V;
3034  break;
3035  }
3036  case CmpInst::ICMP_SGE:
3037  // Always true.
3038  return getTrue(ITy);
3039  case CmpInst::ICMP_SLT:
3040  // Always false.
3041  return getFalse(ITy);
3042  }
3043  }
3044 
3045  // Unsigned variants on "max(a,b)>=a -> true".
3047  if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3048  if (A != RHS)
3049  std::swap(A, B); // umax(A, B) pred A.
3050  EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3051  // We analyze this as umax(A, B) pred A.
3052  P = Pred;
3053  } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3054  (A == LHS || B == LHS)) {
3055  if (A != LHS)
3056  std::swap(A, B); // A pred umax(A, B).
3057  EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3058  // We analyze this as umax(A, B) swapped-pred A.
3059  P = CmpInst::getSwappedPredicate(Pred);
3060  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3061  (A == RHS || B == RHS)) {
3062  if (A != RHS)
3063  std::swap(A, B); // umin(A, B) pred A.
3064  EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3065  // We analyze this as umax(-A, -B) swapped-pred -A.
3066  // Note that we do not need to actually form -A or -B thanks to EqP.
3067  P = CmpInst::getSwappedPredicate(Pred);
3068  } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3069  (A == LHS || B == LHS)) {
3070  if (A != LHS)
3071  std::swap(A, B); // A pred umin(A, B).
3072  EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3073  // We analyze this as umax(-A, -B) pred -A.
3074  // Note that we do not need to actually form -A or -B thanks to EqP.
3075  P = Pred;
3076  }
3077  if (P != CmpInst::BAD_ICMP_PREDICATE) {
3078  // Cases correspond to "max(A, B) p A".
3079  switch (P) {
3080  default:
3081  break;
3082  case CmpInst::ICMP_EQ:
3083  case CmpInst::ICMP_ULE:
3084  // Equivalent to "A EqP B". This may be the same as the condition tested
3085  // in the max/min; if so, we can just return that.
3086  if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3087  return V;
3088  if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3089  return V;
3090  // Otherwise, see if "A EqP B" simplifies.
3091  if (MaxRecurse)
3092  if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3093  return V;
3094  break;
3095  case CmpInst::ICMP_NE:
3096  case CmpInst::ICMP_UGT: {
3098  // Equivalent to "A InvEqP B". This may be the same as the condition
3099  // tested in the max/min; if so, we can just return that.
3100  if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3101  return V;
3102  if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3103  return V;
3104  // Otherwise, see if "A InvEqP B" simplifies.
3105  if (MaxRecurse)
3106  if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3107  return V;
3108  break;
3109  }
3110  case CmpInst::ICMP_UGE:
3111  // Always true.
3112  return getTrue(ITy);
3113  case CmpInst::ICMP_ULT:
3114  // Always false.
3115  return getFalse(ITy);
3116  }
3117  }
3118 
3119  // Variants on "max(x,y) >= min(x,z)".
3120  Value *C, *D;
3121  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3122  match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3123  (A == C || A == D || B == C || B == D)) {
3124  // max(x, ?) pred min(x, ?).
3125  if (Pred == CmpInst::ICMP_SGE)
3126  // Always true.
3127  return getTrue(ITy);
3128  if (Pred == CmpInst::ICMP_SLT)
3129  // Always false.
3130  return getFalse(ITy);
3131  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3132  match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3133  (A == C || A == D || B == C || B == D)) {
3134  // min(x, ?) pred max(x, ?).
3135  if (Pred == CmpInst::ICMP_SLE)
3136  // Always true.
3137  return getTrue(ITy);
3138  if (Pred == CmpInst::ICMP_SGT)
3139  // Always false.
3140  return getFalse(ITy);
3141  } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3142  match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3143  (A == C || A == D || B == C || B == D)) {
3144  // max(x, ?) pred min(x, ?).
3145  if (Pred == CmpInst::ICMP_UGE)
3146  // Always true.
3147  return getTrue(ITy);
3148  if (Pred == CmpInst::ICMP_ULT)
3149  // Always false.
3150  return getFalse(ITy);
3151  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3152  match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3153  (A == C || A == D || B == C || B == D)) {
3154  // min(x, ?) pred max(x, ?).
3155  if (Pred == CmpInst::ICMP_ULE)
3156  // Always true.
3157  return getTrue(ITy);
3158  if (Pred == CmpInst::ICMP_UGT)
3159  // Always false.
3160  return getFalse(ITy);
3161  }
3162 
3163  return nullptr;
3164 }
3165 
3166 /// Given operands for an ICmpInst, see if we can fold the result.
3167 /// If not, this returns null.
3168 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3169  const SimplifyQuery &Q, unsigned MaxRecurse) {
3170  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3171  assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3172 
3173  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3174  if (Constant *CRHS = dyn_cast<Constant>(RHS))
3175  return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3176 
3177  // If we have a constant, make sure it is on the RHS.
3178  std::swap(LHS, RHS);
3179  Pred = CmpInst::getSwappedPredicate(Pred);
3180  }
3181  assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3182 
3183  Type *ITy = GetCompareTy(LHS); // The return type.
3184 
3185  // For EQ and NE, we can always pick a value for the undef to make the
3186  // predicate pass or fail, so we can return undef.
3187  // Matches behavior in llvm::ConstantFoldCompareInstruction.
3188  if (isa<UndefValue>(RHS) && ICmpInst::isEquality(Pred))
3189  return UndefValue::get(ITy);
3190 
3191  // icmp X, X -> true/false
3192  // icmp X, undef -> true/false because undef could be X.
3193  if (LHS == RHS || isa<UndefValue>(RHS))
3194  return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3195 
3196  if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3197  return V;
3198 
3199  if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3200  return V;
3201 
3202  if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3203  return V;
3204 
3205  // If both operands have range metadata, use the metadata
3206  // to simplify the comparison.
3207  if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3208  auto RHS_Instr = cast<Instruction>(RHS);
3209  auto LHS_Instr = cast<Instruction>(LHS);
3210 
3211  if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3212  Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3213  auto RHS_CR = getConstantRangeFromMetadata(
3214  *RHS_Instr->getMetadata(LLVMContext::MD_range));
3215  auto LHS_CR = getConstantRangeFromMetadata(
3216  *LHS_Instr->getMetadata(LLVMContext::MD_range));
3217 
3218  auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3219  if (Satisfied_CR.contains(LHS_CR))
3220  return ConstantInt::getTrue(RHS->getContext());
3221 
3222  auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3223  CmpInst::getInversePredicate(Pred), RHS_CR);
3224  if (InversedSatisfied_CR.contains(LHS_CR))
3225  return ConstantInt::getFalse(RHS->getContext());
3226  }
3227  }
3228 
3229  // Compare of cast, for example (zext X) != 0 -> X != 0
3230  if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3231  Instruction *LI = cast<CastInst>(LHS);
3232  Value *SrcOp = LI->getOperand(0);
3233  Type *SrcTy = SrcOp->getType();
3234  Type *DstTy = LI->getType();
3235 
3236  // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3237  // if the integer type is the same size as the pointer type.
3238  if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3239  Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3240  if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3241  // Transfer the cast to the constant.
3242  if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3243  ConstantExpr::getIntToPtr(RHSC, SrcTy),
3244  Q, MaxRecurse-1))
3245  return V;
3246  } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3247  if (RI->getOperand(0)->getType() == SrcTy)
3248  // Compare without the cast.
3249  if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3250  Q, MaxRecurse-1))
3251  return V;
3252  }
3253  }
3254 
3255  if (isa<ZExtInst>(LHS)) {
3256  // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3257  // same type.
3258  if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3259  if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3260  // Compare X and Y. Note that signed predicates become unsigned.
3262  SrcOp, RI->getOperand(0), Q,
3263  MaxRecurse-1))
3264  return V;
3265  }
3266  // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3267  // too. If not, then try to deduce the result of the comparison.
3268  else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3269  // Compute the constant that would happen if we truncated to SrcTy then
3270  // reextended to DstTy.
3271  Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3272  Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3273 
3274  // If the re-extended constant didn't change then this is effectively
3275  // also a case of comparing two zero-extended values.
3276  if (RExt == CI && MaxRecurse)
3278  SrcOp, Trunc, Q, MaxRecurse-1))
3279  return V;
3280 
3281  // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3282  // there. Use this to work out the result of the comparison.
3283  if (RExt != CI) {
3284  switch (Pred) {
3285  default: llvm_unreachable("Unknown ICmp predicate!");
3286  // LHS <u RHS.
3287  case ICmpInst::ICMP_EQ:
3288  case ICmpInst::ICMP_UGT:
3289  case ICmpInst::ICMP_UGE:
3290  return ConstantInt::getFalse(CI->getContext());
3291 
3292  case ICmpInst::ICMP_NE:
3293  case ICmpInst::ICMP_ULT:
3294  case ICmpInst::ICMP_ULE:
3295  return ConstantInt::getTrue(CI->getContext());
3296 
3297  // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3298  // is non-negative then LHS <s RHS.
3299  case ICmpInst::ICMP_SGT:
3300  case ICmpInst::ICMP_SGE:
3301  return CI->getValue().isNegative() ?
3302  ConstantInt::getTrue(CI->getContext()) :
3303  ConstantInt::getFalse(CI->getContext());
3304 
3305  case ICmpInst::ICMP_SLT:
3306  case ICmpInst::ICMP_SLE:
3307  return CI->getValue().isNegative() ?
3308  ConstantInt::getFalse(CI->getContext()) :
3309  ConstantInt::getTrue(CI->getContext());
3310  }
3311  }
3312  }
3313  }
3314 
3315  if (isa<SExtInst>(LHS)) {
3316  // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3317  // same type.
3318  if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3319  if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3320  // Compare X and Y. Note that the predicate does not change.
3321  if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
3322  Q, MaxRecurse-1))
3323  return V;
3324  }
3325  // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3326  // too. If not, then try to deduce the result of the comparison.
3327  else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3328  // Compute the constant that would happen if we truncated to SrcTy then
3329  // reextended to DstTy.
3330  Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3331  Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3332 
3333  // If the re-extended constant didn't change then this is effectively
3334  // also a case of comparing two sign-extended values.
3335  if (RExt == CI && MaxRecurse)
3336  if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
3337  return V;
3338 
3339  // Otherwise the upper bits of LHS are all equal, while RHS has varying
3340  // bits there. Use this to work out the result of the comparison.
3341  if (RExt != CI) {
3342  switch (Pred) {
3343  default: llvm_unreachable("Unknown ICmp predicate!");
3344  case ICmpInst::ICMP_EQ:
3345  return ConstantInt::getFalse(CI->getContext());
3346  case ICmpInst::ICMP_NE:
3347  return ConstantInt::getTrue(CI->getContext());
3348 
3349  // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3350  // LHS >s RHS.
3351  case ICmpInst::ICMP_SGT:
3352  case ICmpInst::ICMP_SGE:
3353  return CI->getValue().isNegative() ?
3354  ConstantInt::getTrue(CI->getContext()) :
3355  ConstantInt::getFalse(CI->getContext());
3356  case ICmpInst::ICMP_SLT:
3357  case ICmpInst::ICMP_SLE:
3358  return CI->getValue().isNegative() ?
3359  ConstantInt::getFalse(CI->getContext()) :
3360  ConstantInt::getTrue(CI->getContext());
3361 
3362  // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3363  // LHS >u RHS.
3364  case ICmpInst::ICMP_UGT:
3365  case ICmpInst::ICMP_UGE:
3366  // Comparison is true iff the LHS <s 0.
3367  if (MaxRecurse)
3368  if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3369  Constant::getNullValue(SrcTy),
3370  Q, MaxRecurse-1))
3371  return V;
3372  break;
3373  case ICmpInst::ICMP_ULT:
3374  case ICmpInst::ICMP_ULE:
3375  // Comparison is true iff the LHS >=s 0.
3376  if (MaxRecurse)
3377  if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3378  Constant::getNullValue(SrcTy),
3379  Q, MaxRecurse-1))
3380  return V;
3381  break;
3382  }
3383  }
3384  }
3385  }
3386  }
3387 
3388  // icmp eq|ne X, Y -> false|true if X != Y
3389  if (ICmpInst::isEquality(Pred) &&
3390  isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
3391  return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
3392  }
3393 
3394  if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3395  return V;
3396 
3397  if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
3398  return V;
3399 
3400  // Simplify comparisons of related pointers using a powerful, recursive
3401  // GEP-walk when we have target data available..
3402  if (LHS->getType()->isPointerTy())
3403  if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3404  Q.IIQ, LHS, RHS))
3405  return C;
3406  if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3407  if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3408  if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3409  Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3410  Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3411  Q.DL.getTypeSizeInBits(CRHS->getType()))
3412  if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.AC, Q.CxtI,
3413  Q.IIQ, CLHS->getPointerOperand(),
3414  CRHS->getPointerOperand()))
3415  return C;
3416 
3417  if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3418  if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3419  if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3420  GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3421  (ICmpInst::isEquality(Pred) ||
3422  (GLHS->isInBounds() && GRHS->isInBounds() &&
3423  Pred == ICmpInst::getSignedPredicate(Pred)))) {
3424  // The bases are equal and the indices are constant. Build a constant
3425  // expression GEP with the same indices and a null base pointer to see
3426  // what constant folding can make out of it.
3427  Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3428  SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3430  GLHS->getSourceElementType(), Null, IndicesLHS);
3431 
3432  SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3434  GLHS->getSourceElementType(), Null, IndicesRHS);
3435  return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3436  }
3437  }
3438  }
3439 
3440  // If the comparison is with the result of a select instruction, check whether
3441  // comparing with either branch of the select always yields the same value.
3442  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3443  if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3444  return V;
3445 
3446  // If the comparison is with the result of a phi instruction, check whether
3447  // doing the compare with each incoming phi value yields a common result.
3448  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3449  if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3450  return V;
3451 
3452  return nullptr;
3453 }
3454 
3455 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3456  const SimplifyQuery &Q) {
3457  return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3458 }
3459 
3460 /// Given operands for an FCmpInst, see if we can fold the result.
3461 /// If not, this returns null.
3462 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3463  FastMathFlags FMF, const SimplifyQuery &Q,
3464  unsigned MaxRecurse) {
3465  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3466  assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3467 
3468  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3469  if (Constant *CRHS = dyn_cast<Constant>(RHS))
3470  return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3471 
3472  // If we have a constant, make sure it is on the RHS.
3473  std::swap(LHS, RHS);
3474  Pred = CmpInst::getSwappedPredicate(Pred);
3475  }
3476 
3477  // Fold trivial predicates.
3478  Type *RetTy = GetCompareTy(LHS);
3479  if (Pred == FCmpInst::FCMP_FALSE)
3480  return getFalse(RetTy);
3481  if (Pred == FCmpInst::FCMP_TRUE)
3482  return getTrue(RetTy);
3483 
3484  // Fold (un)ordered comparison if we can determine there are no NaNs.
3485  if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
3486  if (FMF.noNaNs() ||
3487  (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
3488  return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
3489 
3490  // NaN is unordered; NaN is not ordered.
3492  "Comparison must be either ordered or unordered");
3493  if (match(RHS, m_NaN()))
3494  return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3495 
3496  // fcmp pred x, undef and fcmp pred undef, x
3497  // fold to true if unordered, false if ordered
3498  if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3499  // Choosing NaN for the undef will always make unordered comparison succeed
3500  // and ordered comparison fail.
3501  return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
3502  }
3503 
3504  // fcmp x,x -> true/false. Not all compares are foldable.
3505  if (LHS == RHS) {
3506  if (CmpInst::isTrueWhenEqual(Pred))
3507  return getTrue(RetTy);
3508  if (CmpInst::isFalseWhenEqual(Pred))
3509  return getFalse(RetTy);
3510  }
3511 
3512  // Handle fcmp with constant RHS.
3513  // TODO: Use match with a specific FP value, so these work with vectors with
3514  // undef lanes.
3515  const APFloat *C;
3516  if (match(RHS, m_APFloat(C))) {
3517  // Check whether the constant is an infinity.
3518  if (C->isInfinity()) {
3519  if (C->isNegative()) {
3520  switch (Pred) {
3521  case FCmpInst::FCMP_OLT:
3522  // No value is ordered and less than negative infinity.
3523  return getFalse(RetTy);
3524  case FCmpInst::FCMP_UGE:
3525  // All values are unordered with or at least negative infinity.
3526  return getTrue(RetTy);
3527  default:
3528  break;
3529  }
3530  } else {
3531  switch (Pred) {
3532  case FCmpInst::FCMP_OGT:
3533  // No value is ordered and greater than infinity.
3534  return getFalse(RetTy);
3535  case FCmpInst::FCMP_ULE:
3536  // All values are unordered with and at most infinity.
3537  return getTrue(RetTy);
3538  default:
3539  break;
3540  }
3541  }
3542  }
3543  if (C->isNegative() && !C->isNegZero()) {
3544  assert(!C->isNaN() && "Unexpected NaN constant!");
3545  // TODO: We can catch more cases by using a range check rather than
3546  // relying on CannotBeOrderedLessThanZero.
3547  switch (Pred) {
3548  case FCmpInst::FCMP_UGE:
3549  case FCmpInst::FCMP_UGT:
3550  case FCmpInst::FCMP_UNE:
3551  // (X >= 0) implies (X > C) when (C < 0)
3552  if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3553  return getTrue(RetTy);
3554  break;
3555  case FCmpInst::FCMP_OEQ:
3556  case FCmpInst::FCMP_OLE:
3557  case FCmpInst::FCMP_OLT:
3558  // (X >= 0) implies !(X < C) when (C < 0)
3559  if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3560  return getFalse(RetTy);
3561  break;
3562  default:
3563  break;
3564  }
3565  }
3566 
3567  // Check comparison of [minnum/maxnum with constant] with other constant.
3568  const APFloat *C2;
3569  if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
3570  C2->compare(*C) == APFloat::cmpLessThan) ||
3571  (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
3572  C2->compare(*C) == APFloat::cmpGreaterThan)) {
3573  bool IsMaxNum =
3574  cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
3575  // The ordered relationship and minnum/maxnum guarantee that we do not
3576  // have NaN constants, so ordered/unordered preds are handled the same.
3577  switch (Pred) {
3579  // minnum(X, LesserC) == C --> false
3580  // maxnum(X, GreaterC) == C --> false
3581  return getFalse(RetTy);
3583  // minnum(X, LesserC) != C --> true
3584  // maxnum(X, GreaterC) != C --> true
3585  return getTrue(RetTy);
3588  // minnum(X, LesserC) >= C --> false
3589  // minnum(X, LesserC) > C --> false
3590  // maxnum(X, GreaterC) >= C --> true
3591  // maxnum(X, GreaterC) > C --> true
3592  return ConstantInt::get(RetTy, IsMaxNum);
3595  // minnum(X, LesserC) <= C --> true
3596  // minnum(X, LesserC) < C --> true
3597  // maxnum(X, GreaterC) <= C --> false
3598  // maxnum(X, GreaterC) < C --> false
3599  return ConstantInt::get(RetTy, !IsMaxNum);
3600  default:
3601  // TRUE/FALSE/ORD/UNO should be handled before this.
3602  llvm_unreachable("Unexpected fcmp predicate");
3603  }
3604  }
3605  }
3606 
3607  if (match(RHS, m_AnyZeroFP())) {
3608  switch (Pred) {
3609  case FCmpInst::FCMP_OGE:
3610  case FCmpInst::FCMP_ULT:
3611  // Positive or zero X >= 0.0 --> true
3612  // Positive or zero X < 0.0 --> false
3613  if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
3615  return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
3616  break;
3617  case FCmpInst::FCMP_UGE:
3618  case FCmpInst::FCMP_OLT:
3619  // Positive or zero or nan X >= 0.0 --> true
3620  // Positive or zero or nan X < 0.0 --> false
3621  if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3622  return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
3623  break;
3624  default:
3625  break;
3626  }
3627  }
3628 
3629  // If the comparison is with the result of a select instruction, check whether
3630  // comparing with either branch of the select always yields the same value.
3631  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3632  if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3633  return V;
3634 
3635  // If the comparison is with the result of a phi instruction, check whether
3636  // doing the compare with each incoming phi value yields a common result.
3637  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3638  if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3639  return V;
3640 
3641  return nullptr;
3642 }
3643 
3644 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3645  FastMathFlags FMF, const SimplifyQuery &Q) {
3646  return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
3647 }
3648 
3649 /// See if V simplifies when its operand Op is replaced with RepOp.
3650 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3651  const SimplifyQuery &Q,
3652  unsigned MaxRecurse) {
3653  // Trivial replacement.
3654  if (V == Op)
3655  return RepOp;
3656 
3657  // We cannot replace a constant, and shouldn't even try.
3658  if (isa<Constant>(Op))
3659  return nullptr;
3660 
3661  auto *I = dyn_cast<Instruction>(V);
3662  if (!I)
3663  return nullptr;
3664 
3665  // If this is a binary operator, try to simplify it with the replaced op.
3666  if (auto *B = dyn_cast<BinaryOperator>(I)) {
3667  // Consider:
3668  // %cmp = icmp eq i32 %x, 2147483647
3669  // %add = add nsw i32 %x, 1
3670  // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3671  //
3672  // We can't replace %sel with %add unless we strip away the flags.
3673  // TODO: This is an unusual limitation because better analysis results in
3674  // worse simplification. InstCombine can do this fold more generally
3675  // by dropping the flags. Remove this fold to save compile-time?
3676  if (isa<OverflowingBinaryOperator>(B))
3677  if (Q.IIQ.hasNoSignedWrap(B) || Q.IIQ.hasNoUnsignedWrap(B))
3678  return nullptr;
3679  if (isa<PossiblyExactOperator>(B) && Q.IIQ.isExact(B))
3680  return nullptr;
3681 
3682  if (MaxRecurse) {
3683  if (B->getOperand(0) == Op)
3684  return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3685  MaxRecurse - 1);
3686  if (B->getOperand(1) == Op)
3687  return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3688  MaxRecurse - 1);
3689  }
3690  }
3691 
3692  // Same for CmpInsts.
3693  if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3694  if (MaxRecurse) {
3695  if (C->getOperand(0) == Op)
3696  return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3697  MaxRecurse - 1);
3698  if (C->getOperand(1) == Op)
3699  return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3700  MaxRecurse - 1);
3701  }
3702  }
3703 
3704  // Same for GEPs.
3705  if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
3706  if (MaxRecurse) {
3707  SmallVector<Value *, 8> NewOps(GEP->getNumOperands());
3708  transform(GEP->operands(), NewOps.begin(),
3709  [&](Value *V) { return V == Op ? RepOp : V; });
3710  return SimplifyGEPInst(GEP->getSourceElementType(), NewOps, Q,
3711  MaxRecurse - 1);
3712  }
3713  }
3714 
3715  // TODO: We could hand off more cases to instsimplify here.
3716 
3717  // If all operands are constant after substituting Op for RepOp then we can
3718  // constant fold the instruction.
3719  if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3720  // Build a list of all constant operands.
3721  SmallVector<Constant *, 8> ConstOps;
3722  for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3723  if (I->getOperand(i) == Op)
3724  ConstOps.push_back(CRepOp);
3725  else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3726  ConstOps.push_back(COp);
3727  else
3728  break;
3729  }
3730 
3731  // All operands were constants, fold it.
3732  if (ConstOps.size() == I->getNumOperands()) {
3733  if (CmpInst *C = dyn_cast<CmpInst>(I))
3734  return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3735  ConstOps[1], Q.DL, Q.TLI);
3736 
3737  if (LoadInst *LI = dyn_cast<LoadInst>(I))
3738  if (!LI->isVolatile())
3739  return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3740 
3741  return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3742  }
3743  }
3744 
3745  return nullptr;
3746 }
3747 
3748 /// Try to simplify a select instruction when its condition operand is an
3749 /// integer comparison where one operand of the compare is a constant.
3750 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3751  const APInt *Y, bool TrueWhenUnset) {
3752  const APInt *C;
3753 
3754  // (X & Y) == 0 ? X & ~Y : X --> X
3755  // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3756  if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3757  *Y == ~*C)
3758  return TrueWhenUnset ? FalseVal : TrueVal;
3759 
3760  // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3761  // (X & Y) != 0 ? X : X & ~Y --> X
3762  if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3763  *Y == ~*C)
3764  return TrueWhenUnset ? FalseVal : TrueVal;
3765 
3766  if (Y->isPowerOf2()) {
3767  // (X & Y) == 0 ? X | Y : X --> X | Y
3768  // (X & Y) != 0 ? X | Y : X --> X
3769  if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3770  *Y == *C)
3771  return TrueWhenUnset ? TrueVal : FalseVal;
3772 
3773  // (X & Y) == 0 ? X : X | Y --> X
3774  // (X & Y) != 0 ? X : X | Y --> X | Y
3775  if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3776  *Y == *C)
3777  return TrueWhenUnset ? TrueVal : FalseVal;
3778  }
3779 
3780  return nullptr;
3781 }
3782 
3783 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
3784 /// eq/ne.
3786  ICmpInst::Predicate Pred,
3787  Value *TrueVal, Value *FalseVal) {
3788  Value *X;
3789  APInt Mask;
3790  if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
3791  return nullptr;
3792 
3793  return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
3794  Pred == ICmpInst::ICMP_EQ);
3795 }
3796 
3797 /// Try to simplify a select instruction when its condition operand is an
3798 /// integer comparison.
3799 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3800  Value *FalseVal, const SimplifyQuery &Q,
3801  unsigned MaxRecurse) {
3802  ICmpInst::Predicate Pred;
3803  Value *CmpLHS, *CmpRHS;
3804  if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3805  return nullptr;
3806 
3807  if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3808  Value *X;
3809  const APInt *Y;
3810  if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3811  if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3812  Pred == ICmpInst::ICMP_EQ))
3813  return V;
3814 
3815  // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
3816  Value *ShAmt;
3817  auto isFsh = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(),
3818  m_Value(ShAmt)),
3819  m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X),
3820  m_Value(ShAmt)));
3821  // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
3822  // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
3823  if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt &&
3824  Pred == ICmpInst::ICMP_EQ)
3825  return X;
3826  // (ShAmt != 0) ? X : fshl(X, *, ShAmt) --> X
3827  // (ShAmt != 0) ? X : fshr(*, X, ShAmt) --> X
3828  if (match(FalseVal, isFsh) && TrueVal == X && CmpLHS == ShAmt &&
3829  Pred == ICmpInst::ICMP_NE)
3830  return X;
3831 
3832  // Test for a zero-shift-guard-op around rotates. These are used to
3833  // avoid UB from oversized shifts in raw IR rotate patterns, but the
3834  // intrinsics do not have that problem.
3835  // We do not allow this transform for the general funnel shift case because
3836  // that would not preserve the poison safety of the original code.
3837  auto isRotate = m_CombineOr(m_Intrinsic<Intrinsic::fshl>(m_Value(X),
3838  m_Deferred(X),
3839  m_Value(ShAmt)),
3840  m_Intrinsic<Intrinsic::fshr>(m_Value(X),
3841  m_Deferred(X),
3842  m_Value(ShAmt)));
3843  // (ShAmt != 0) ? fshl(X, X, ShAmt) : X --> fshl(X, X, ShAmt)
3844  // (ShAmt != 0) ? fshr(X, X, ShAmt) : X --> fshr(X, X, ShAmt)
3845  if (match(TrueVal, isRotate) && FalseVal == X && CmpLHS == ShAmt &&
3846  Pred == ICmpInst::ICMP_NE)
3847  return TrueVal;
3848  // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
3849  // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
3850  if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
3851  Pred == ICmpInst::ICMP_EQ)
3852  return FalseVal;
3853  }
3854 
3855  // Check for other compares that behave like bit test.
3856  if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred,
3857  TrueVal, FalseVal))
3858  return V;
3859 
3860  // If we have an equality comparison, then we know the value in one of the
3861  // arms of the select. See if substituting this value into the arm and
3862  // simplifying the result yields the same value as the other arm.
3863  if (Pred == ICmpInst::ICMP_EQ) {
3864  if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3865  TrueVal ||
3866  SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3867  TrueVal)
3868  return FalseVal;
3869  if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3870  FalseVal ||
3871  SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3872  FalseVal)
3873  return FalseVal;
3874  } else if (Pred == ICmpInst::ICMP_NE) {
3875  if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3876  FalseVal ||
3877  SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3878  FalseVal)
3879  return TrueVal;
3880  if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3881  TrueVal ||
3882  SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3883  TrueVal)
3884  return TrueVal;
3885  }
3886 
3887  return nullptr;
3888 }
3889 
3890 /// Try to simplify a select instruction when its condition operand is a
3891 /// floating-point comparison.
3893  FCmpInst::Predicate Pred;
3894  if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
3895  !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
3896  return nullptr;
3897 
3898  // TODO: The transform may not be valid with -0.0. An incomplete way of
3899  // testing for that possibility is to check if at least one operand is a
3900  // non-zero constant.
3901  const APFloat *C;
3902  if ((match(T, m_APFloat(C)) && C->isNonZero()) ||
3903  (match(F, m_APFloat(C)) && C->isNonZero())) {
3904  // (T == F) ? T : F --> F
3905  // (F == T) ? T : F --> F
3906  if (Pred == FCmpInst::FCMP_OEQ)
3907  return F;
3908 
3909  // (T != F) ? T : F --> T
3910  // (F != T) ? T : F --> T
3911  if (Pred == FCmpInst::FCMP_UNE)
3912  return T;
3913  }
3914 
3915  return nullptr;
3916 }
3917 
3918 /// Given operands for a SelectInst, see if we can fold the result.
3919 /// If not, this returns null.
3920 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3921  const SimplifyQuery &Q, unsigned MaxRecurse) {
3922  if (auto *CondC = dyn_cast<Constant>(Cond)) {
3923  if (auto *TrueC = dyn_cast<Constant>(TrueVal))
3924  if (auto *FalseC = dyn_cast<Constant>(FalseVal))
3925  return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
3926 
3927  // select undef, X, Y -> X or Y
3928  if (isa<UndefValue>(CondC))
3929  return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
3930 
3931  // TODO: Vector constants with undef elements don't simplify.
3932 
3933  // select true, X, Y -> X
3934  if (CondC->isAllOnesValue())
3935  return TrueVal;
3936  // select false, X, Y -> Y
3937  if (CondC->isNullValue())
3938  return FalseVal;
3939  }
3940 
3941  // select ?, X, X -> X
3942  if (TrueVal == FalseVal)
3943  return TrueVal;
3944 
3945  if (isa<UndefValue>(TrueVal)) // select ?, undef, X -> X
3946  return FalseVal;
3947  if (isa<UndefValue>(FalseVal)) // select ?, X, undef -> X
3948  return TrueVal;
3949 
3950  if (Value *V =
3951  simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
3952  return V;
3953 
3954  if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal))
3955  return V;
3956 
3957  if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
3958  return V;
3959 
3960  Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
3961  if (Imp)
3962  return *Imp ? TrueVal : FalseVal;
3963 
3964  return nullptr;
3965 }
3966 
3967 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3968  const SimplifyQuery &Q) {
3969  return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
3970 }
3971 
3972 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3973 /// If not, this returns null.
3975  const SimplifyQuery &Q, unsigned) {
3976  // The type of the GEP pointer operand.
3977  unsigned AS =
3978  cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3979 
3980  // getelementptr P -> P.
3981  if (Ops.size() == 1)
3982  return Ops[0];
3983 
3984  // Compute the (pointer) type returned by the GEP instruction.
3985  Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3986  Type *GEPTy = PointerType::get(LastType, AS);
3987  if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3988  GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3989  else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3990  GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3991 
3992  if (isa<UndefValue>(Ops[0]))
3993  return UndefValue::get(GEPTy);
3994 
3995  if (Ops.size() == 2) {
3996  // getelementptr P, 0 -> P.
3997  if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy)
3998  return Ops[0];
3999 
4000  Type *Ty = SrcTy;
4001  if (Ty->isSized()) {
4002  Value *P;
4003  uint64_t C;
4004  uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
4005  // getelementptr P, N -> P if P points to a type of zero size.
4006  if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy)
4007  return Ops[0];
4008 
4009  // The following transforms are only safe if the ptrtoint cast
4010  // doesn't truncate the pointers.
4011  if (Ops[1]->getType()->getScalarSizeInBits() ==
4012  Q.DL.getIndexSizeInBits(AS)) {
4013  auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
4014  if (match(P, m_Zero()))
4015  return Constant::getNullValue(GEPTy);
4016  Value *Temp;
4017  if (match(P, m_PtrToInt(m_Value(Temp))))
4018  if (Temp->getType() == GEPTy)
4019  return Temp;
4020  return nullptr;
4021  };
4022 
4023  // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
4024  if (TyAllocSize == 1 &&
4025  match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
4026  if (Value *R = PtrToIntOrZero(P))
4027  return R;
4028 
4029  // getelementptr V, (ashr (sub P, V), C) -> Q
4030  // if P points to a type of size 1 << C.
4031  if (match(Ops[1],
4032  m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4033  m_ConstantInt(C))) &&
4034  TyAllocSize == 1ULL << C)
4035  if (Value *R = PtrToIntOrZero(P))
4036  return R;
4037 
4038  // getelementptr V, (sdiv (sub P, V), C) -> Q
4039  // if P points to a type of size C.
4040  if (match(Ops[1],
4041  m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
4042  m_SpecificInt(TyAllocSize))))
4043  if (Value *R = PtrToIntOrZero(P))
4044  return R;
4045  }
4046  }
4047  }
4048 
4049  if (Q.DL.getTypeAllocSize(LastType) == 1 &&
4050  all_of(Ops.slice(1).drop_back(1),
4051  [](Value *Idx) { return match(Idx, m_Zero()); })) {
4052  unsigned IdxWidth =
4053  Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
4054  if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) {
4055  APInt BasePtrOffset(IdxWidth, 0);
4056  Value *StrippedBasePtr =
4057  Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
4058  BasePtrOffset);
4059 
4060  // gep (gep V, C), (sub 0, V) -> C
4061  if (match(Ops.back(),
4062  m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
4063  auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
4064  return ConstantExpr::getIntToPtr(CI, GEPTy);
4065  }
4066  // gep (gep V, C), (xor V, -1) -> C-1
4067  if (match(Ops.back(),
4068  m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
4069  auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
4070  return ConstantExpr::getIntToPtr(CI, GEPTy);
4071  }
4072  }
4073  }
4074 
4075  // Check to see if this is constant foldable.
4076  if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); }))
4077  return nullptr;
4078 
4079  auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
4080  Ops.slice(1));
4081  if (auto *CEFolded = ConstantFoldConstant(CE, Q.DL))
4082  return CEFolded;
4083  return CE;
4084 }
4085 
4087  const SimplifyQuery &Q) {
4088  return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
4089 }
4090 
4091 /// Given operands for an InsertValueInst, see if we can fold the result.
4092 /// If not, this returns null.
4094  ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
4095  unsigned) {
4096  if (Constant *CAgg = dyn_cast<Constant>(Agg))
4097  if (Constant *CVal = dyn_cast<Constant>(Val))
4098  return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
4099 
4100  // insertvalue x, undef, n -> x
4101  if (match(Val, m_Undef()))
4102  return Agg;
4103 
4104  // insertvalue x, (extractvalue y, n), n
4105  if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
4106  if (EV->getAggregateOperand()->getType() == Agg->getType() &&
4107  EV->getIndices() == Idxs) {
4108  // insertvalue undef, (extractvalue y, n), n -> y
4109  if (match(Agg, m_Undef()))
4110  return EV->getAggregateOperand();
4111 
4112  // insertvalue y, (extractvalue y, n), n -> y
4113  if (Agg == EV->getAggregateOperand())
4114  return Agg;
4115  }
4116 
4117  return nullptr;
4118 }
4119 
4121  ArrayRef<unsigned> Idxs,
4122  const SimplifyQuery &Q) {
4124 }
4125 
4127  const SimplifyQuery &Q) {
4128  // Try to constant fold.
4129  auto *VecC = dyn_cast<Constant>(Vec);
4130  auto *ValC = dyn_cast<Constant>(Val);
4131  auto *IdxC = dyn_cast<Constant>(Idx);
4132  if (VecC && ValC && IdxC)
4133  return ConstantFoldInsertElementInstruction(VecC, ValC, IdxC);
4134 
4135  // Fold into undef if index is out of bounds.
4136  if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
4137  uint64_t NumElements = cast<VectorType>(Vec->getType())->getNumElements();
4138  if (CI->uge(NumElements))
4139  return UndefValue::get(Vec->getType());
4140  }
4141 
4142  // If index is undef, it might be out of bounds (see above case)
4143  if (isa<UndefValue>(Idx))
4144  return UndefValue::get(Vec->getType());
4145 
4146  // Inserting an undef scalar? Assume it is the same value as the existing
4147  // vector element.
4148  if (isa<UndefValue>(Val))
4149  return Vec;
4150 
4151  // If we are extracting a value from a vector, then inserting it into the same
4152  // place, that's the input vector:
4153  // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
4154  if (match(Val, m_ExtractElement(m_Specific(Vec), m_Specific(Idx))))
4155  return Vec;
4156 
4157  return nullptr;
4158 }
4159 
4160 /// Given operands for an ExtractValueInst, see if we can fold the result.
4161 /// If not, this returns null.
4163  const SimplifyQuery &, unsigned) {
4164  if (auto *CAgg = dyn_cast<Constant>(Agg))
4165  return ConstantFoldExtractValueInstruction(CAgg, Idxs);
4166 
4167  // extractvalue x, (insertvalue y, elt, n), n -> elt
4168  unsigned NumIdxs = Idxs.size();
4169  for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
4170  IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
4171  ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
4172  unsigned NumInsertValueIdxs = InsertValueIdxs.size();
4173  unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
4174  if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
4175  Idxs.slice(0, NumCommonIdxs)) {
4176  if (NumIdxs == NumInsertValueIdxs)
4177  return IVI->getInsertedValueOperand();
4178  break;
4179  }
4180  }
4181 
4182  return nullptr;
4183 }
4184 
4186  const SimplifyQuery &Q) {
4188 }
4189 
4190 /// Given operands for an ExtractElementInst, see if we can fold the result.
4191 /// If not, this returns null.
4193  unsigned) {
4194  if (auto *CVec = dyn_cast<Constant>(Vec)) {
4195  if (auto *CIdx = dyn_cast<Constant>(Idx))
4196  return ConstantFoldExtractElementInstruction(CVec, CIdx);
4197 
4198  // The index is not relevant if our vector is a splat.
4199  if (auto *Splat = CVec->getSplatValue())
4200  return Splat;
4201 
4202  if (isa<UndefValue>(Vec))
4203  return UndefValue::get(Vec->getType()->getVectorElementType());
4204  }
4205 
4206  // If extracting a specified index from the vector, see if we can recursively
4207  // find a previously computed scalar that was inserted into the vector.
4208  if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
4209  if (IdxC->getValue().uge(Vec->getType()->getVectorNumElements()))
4210  // definitely out of bounds, thus undefined result
4211  return UndefValue::get(Vec->getType()->getVectorElementType());
4212  if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
4213  return Elt;
4214  }
4215 
4216  // An undef extract index can be arbitrarily chosen to be an out-of-range
4217  // index value, which would result in the instruction being undef.
4218  if (isa<UndefValue>(Idx))
4219  return UndefValue::get(Vec->getType()->getVectorElementType());
4220 
4221  return nullptr;
4222 }
4223 
4225  const SimplifyQuery &Q) {
4227 }
4228 
4229 /// See if we can fold the given phi. If not, returns null.
4230 static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
4231  // If all of the PHI's incoming values are the same then replace the PHI node
4232  // with the common value.
4233  Value *CommonValue = nullptr;
4234  bool HasUndefInput = false;
4235  for (Value *Incoming : PN->incoming_values()) {
4236  // If the incoming value is the phi node itself, it can safely be skipped.
4237  if (Incoming == PN) continue;
4238  if (isa<UndefValue>(Incoming)) {
4239  // Remember that we saw an undef value, but otherwise ignore them.
4240  HasUndefInput = true;
4241  continue;
4242  }
4243  if (CommonValue && Incoming != CommonValue)
4244  return nullptr; // Not the same, bail out.
4245  CommonValue = Incoming;
4246  }
4247 
4248  // If CommonValue is null then all of the incoming values were either undef or
4249  // equal to the phi node itself.
4250  if (!CommonValue)
4251  return UndefValue::get(PN->getType());
4252 
4253  // If we have a PHI node like phi(X, undef, X), where X is defined by some
4254  // instruction, we cannot return X as the result of the PHI node unless it
4255  // dominates the PHI block.
4256  if (HasUndefInput)
4257  return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
4258 
4259  return CommonValue;
4260 }
4261 
4262 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4263  Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
4264  if (auto *C = dyn_cast<Constant>(Op))
4265  return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
4266 
4267  if (auto *CI = dyn_cast<CastInst>(Op)) {
4268  auto *Src = CI->getOperand(0);
4269  Type *SrcTy = Src->getType();
4270  Type *MidTy = CI->getType();
4271  Type *DstTy = Ty;
4272  if (Src->getType() == Ty) {
4273  auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4274  auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4275  Type *SrcIntPtrTy =
4276  SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4277  Type *MidIntPtrTy =
4278  MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4279  Type *DstIntPtrTy =
4280  DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4281  if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4282  SrcIntPtrTy, MidIntPtrTy,
4283  DstIntPtrTy) == Instruction::BitCast)
4284  return Src;
4285  }
4286  }
4287 
4288  // bitcast x -> x
4289  if (CastOpc == Instruction::BitCast)
4290  if (Op->getType() == Ty)
4291  return Op;
4292 
4293  return nullptr;
4294 }
4295 
4296 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4297  const SimplifyQuery &Q) {
4298  return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
4299 }
4300 
4301 /// For the given destination element of a shuffle, peek through shuffles to
4302 /// match a root vector source operand that contains that element in the same
4303 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
4304 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
4305  int MaskVal, Value *RootVec,
4306  unsigned MaxRecurse) {
4307  if (!MaxRecurse--)
4308  return nullptr;
4309 
4310  // Bail out if any mask value is undefined. That kind of shuffle may be
4311  // simplified further based on demanded bits or other folds.
4312  if (MaskVal == -1)
4313  return nullptr;
4314 
4315  // The mask value chooses which source operand we need to look at next.
4316  int InVecNumElts = Op0->getType()->getVectorNumElements();
4317  int RootElt = MaskVal;
4318  Value *SourceOp = Op0;
4319  if (MaskVal >= InVecNumElts) {
4320  RootElt = MaskVal - InVecNumElts;
4321  SourceOp = Op1;
4322  }
4323 
4324  // If the source operand is a shuffle itself, look through it to find the
4325  // matching root vector.
4326  if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4327  return foldIdentityShuffles(
4328  DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4329  SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
4330  }
4331 
4332  // TODO: Look through bitcasts? What if the bitcast changes the vector element
4333  // size?
4334 
4335  // The source operand is not a shuffle. Initialize the root vector value for
4336  // this shuffle if that has not been done yet.
4337  if (!RootVec)
4338  RootVec = SourceOp;
4339 
4340  // Give up as soon as a source operand does not match the existing root value.
4341  if (RootVec != SourceOp)
4342  return nullptr;
4343 
4344  // The element must be coming from the same lane in the source vector
4345  // (although it may have crossed lanes in intermediate shuffles).
4346  if (RootElt != DestElt)
4347  return nullptr;
4348 
4349  return RootVec;
4350 }
4351 
4353  Type *RetTy, const SimplifyQuery &Q,
4354  unsigned MaxRecurse) {
4355  if (isa<UndefValue>(Mask))
4356  return UndefValue::get(RetTy);
4357 
4358  Type *InVecTy = Op0->getType();
4359  unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
4360  unsigned InVecNumElts = InVecTy->getVectorNumElements();
4361 
4362  SmallVector<int, 32> Indices;
4363  ShuffleVectorInst::getShuffleMask(Mask, Indices);
4364  assert(MaskNumElts == Indices.size() &&
4365  "Size of Indices not same as number of mask elements?");
4366 
4367  // Canonicalization: If mask does not select elements from an input vector,
4368  // replace that input vector with undef.
4369  bool MaskSelects0 = false, MaskSelects1 = false;
4370  for (unsigned i = 0; i != MaskNumElts; ++i) {
4371  if (Indices[i] == -1)
4372  continue;
4373  if ((unsigned)Indices[i] < InVecNumElts)
4374  MaskSelects0 = true;
4375  else
4376  MaskSelects1 = true;
4377  }
4378  if (!MaskSelects0)
4379  Op0 = UndefValue::get(InVecTy);
4380  if (!MaskSelects1)
4381  Op1 = UndefValue::get(InVecTy);
4382 
4383  auto *Op0Const = dyn_cast<Constant>(Op0);
4384  auto *Op1Const = dyn_cast<Constant>(Op1);
4385 
4386  // If all operands are constant, constant fold the shuffle.
4387  if (Op0Const && Op1Const)
4388  return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4389 
4390  // Canonicalization: if only one input vector is constant, it shall be the
4391  // second one.
4392  if (Op0Const && !Op1Const) {
4393  std::swap(Op0, Op1);
4394  ShuffleVectorInst::commuteShuffleMask(Indices, InVecNumElts);
4395  }
4396 
4397  // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4398  // value type is same as the input vectors' type.
4399  if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4400  if (isa<UndefValue>(Op1) && RetTy == InVecTy &&
4401  OpShuf->getMask()->getSplatValue())
4402  return Op0;
4403 
4404  // Don't fold a shuffle with undef mask elements. This may get folded in a
4405  // better way using demanded bits or other analysis.
4406  // TODO: Should we allow this?
4407  if (find(Indices, -1) != Indices.end())
4408  return nullptr;
4409 
4410  // Check if every element of this shuffle can be mapped back to the
4411  // corresponding element of a single root vector. If so, we don't need this
4412  // shuffle. This handles simple identity shuffles as well as chains of
4413  // shuffles that may widen/narrow and/or move elements across lanes and back.
4414  Value *RootVec = nullptr;
4415  for (unsigned i = 0; i != MaskNumElts; ++i) {
4416  // Note that recursion is limited for each vector element, so if any element
4417  // exceeds the limit, this will fail to simplify.
4418  RootVec =
4419  foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
4420 
4421  // We can't replace a widening/narrowing shuffle with one of its operands.
4422  if (!RootVec || RootVec->getType() != RetTy)
4423  return nullptr;
4424  }
4425  return RootVec;
4426 }
4427 
4428 /// Given operands for a ShuffleVectorInst, fold the result or return null.
4430  Type *RetTy, const SimplifyQuery &Q) {
4431  return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
4432 }
4433 
4435  Value *&Op, const SimplifyQuery &Q) {
4436  if (auto *C = dyn_cast<Constant>(Op))
4437  return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
4438  return nullptr;
4439 }
4440 
4441 /// Given the operand for an FNeg, see if we can fold the result. If not, this
4442 /// returns null.
4444  const SimplifyQuery &Q, unsigned MaxRecurse) {
4445  if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
4446  return C;
4447 
4448  Value *X;
4449  // fneg (fneg X) ==> X
4450  if (match(Op, m_FNeg(m_Value(X))))
4451  return X;
4452 
4453  return nullptr;
4454 }
4455 
4457  const SimplifyQuery &Q) {
4459 }
4460 
4462  // If the input is a vector with undef elements, just return a default NaN.
4463  if (!In->isNaN())
4464  return ConstantFP::getNaN(In->getType());
4465 
4466  // Propagate the existing NaN constant when possible.
4467  // TODO: Should we quiet a signaling NaN?
4468  return In;
4469 }
4470 
4471 static Constant *simplifyFPBinop(Value *Op0, Value *Op1) {
4472  if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
4473  return ConstantFP::getNaN(Op0->getType());
4474 
4475  if (match(Op0, m_NaN()))
4476  return propagateNaN(cast<Constant>(Op0));
4477  if (match(Op1, m_NaN()))
4478  return propagateNaN(cast<Constant>(Op1));
4479 
4480  return nullptr;
4481 }
4482 
4483 /// Given operands for an FAdd, see if we can fold the result. If not, this
4484 /// returns null.
4486  const SimplifyQuery &Q, unsigned MaxRecurse) {
4487  if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
4488  return C;
4489 
4490  if (Constant *C = simplifyFPBinop(Op0, Op1))
4491  return C;
4492 
4493  // fadd X, -0 ==> X
4494  if (match(Op1, m_NegZeroFP()))
4495  return Op0;
4496 
4497  // fadd X, 0 ==> X, when we know X is not -0
4498  if (match(Op1, m_PosZeroFP()) &&
4499  (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4500  return Op0;
4501 
4502  // With nnan: -X + X --> 0.0 (and commuted variant)
4503  // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
4504  // Negative zeros are allowed because we always end up with positive zero:
4505  // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4506  // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
4507  // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
4508  // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
4509  if (FMF.noNaNs()) {
4510  if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
4511  match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
4512  return ConstantFP::getNullValue(Op0->getType());
4513 
4514  if (match(Op0, m_FNeg(m_Specific(Op1))) ||
4515  match(Op1, m_FNeg(m_Specific(Op0))))
4516  return ConstantFP::getNullValue(Op0->getType());
4517  }
4518 
4519  // (X - Y) + Y --> X
4520  // Y + (X - Y) --> X
4521  Value *X;
4522  if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4523  (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
4524  match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
4525  return X;
4526 
4527  return nullptr;
4528 }
4529 
4530 /// Given operands for an FSub, see if we can fold the result. If not, this
4531 /// returns null.
4533  const SimplifyQuery &Q, unsigned MaxRecurse) {
4534  if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
4535  return C;
4536 
4537  if (Constant *C = simplifyFPBinop(Op0, Op1))
4538  return C;
4539 
4540  // fsub X, +0 ==> X
4541  if (match(Op1, m_PosZeroFP()))
4542  return Op0;
4543 
4544  // fsub X, -0 ==> X, when we know X is not -0
4545  if (match(Op1, m_NegZeroFP()) &&
4546  (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
4547  return Op0;
4548 
4549  // fsub -0.0, (fsub -0.0, X) ==> X
4550  // fsub -0.0, (fneg X) ==> X
4551  Value *X;
4552  if (match(Op0, m_NegZeroFP()) &&
4553  match(Op1, m_FNeg(m_Value(X))))
4554  return X;
4555 
4556  // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
4557  // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
4558  if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
4559  (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
4560  match(Op1, m_FNeg(m_Value(X)))))
4561  return X;
4562 
4563  // fsub nnan x, x ==> 0.0
4564  if (FMF.noNaNs() && Op0 == Op1)
4565  return Constant::getNullValue(Op0->getType());
4566 
4567  // Y - (Y - X) --> X
4568  // (X + Y) - Y --> X
4569  if (FMF.noSignedZeros() && FMF.allowReassoc() &&
4570  (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
4571  match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
4572  return X;
4573 
4574  return nullptr;
4575 }
4576 
4577 /// Given the operands for an FMul, see if we can fold the result
4579  const SimplifyQuery &Q, unsigned MaxRecurse) {
4580  if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
4581  return C;
4582 
4583  if (Constant *C = simplifyFPBinop(Op0, Op1))
4584  return C;
4585 
4586  // fmul X, 1.0 ==> X
4587  if (match(Op1, m_FPOne()))
4588  return Op0;
4589 
4590  // fmul nnan nsz X, 0 ==> 0
4591  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP()))
4592  return ConstantFP::getNullValue(Op0->getType());
4593 
4594  // sqrt(X) * sqrt(X) --> X, if we can:
4595  // 1. Remove the intermediate rounding (reassociate).
4596  // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
4597  // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
4598  Value *X;
4599  if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) &&
4600  FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros())
4601  return X;
4602 
4603  return nullptr;
4604 }
4605 
4607  const SimplifyQuery &Q) {
4608  return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
4609 }
4610 
4611 
4613  const SimplifyQuery &Q) {
4614  return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
4615 }
4616 
4618  const SimplifyQuery &Q) {
4619  return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
4620 }
4621 
4623  const SimplifyQuery &Q, unsigned) {
4624  if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
4625  return C;
4626 
4627  if (Constant *C = simplifyFPBinop(Op0, Op1))
4628  return C;
4629 
4630  // X / 1.0 -> X
4631  if (match(Op1, m_FPOne()))
4632  return Op0;
4633 
4634  // 0 / X -> 0
4635  // Requires that NaNs are off (X could be zero) and signed zeroes are
4636  // ignored (X could be positive or negative, so the output sign is unknown).
4637  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
4638  return ConstantFP::getNullValue(Op0->getType());
4639 
4640  if (FMF.noNaNs()) {
4641  // X / X -> 1.0 is legal when NaNs are ignored.
4642  // We can ignore infinities because INF/INF is NaN.
4643  if (Op0 == Op1)
4644  return ConstantFP::get(Op0->getType(), 1.0);
4645 
4646  // (X * Y) / Y --> X if we can reassociate to the above form.
4647  Value *X;
4648  if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
4649  return X;
4650 
4651  // -X / X -> -1.0 and
4652  // X / -X -> -1.0 are legal when NaNs are ignored.
4653  // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
4654  if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
4655  match(Op1, m_FNegNSZ(m_Specific(Op0))))
4656  return ConstantFP::get(Op0->getType(), -1.0);
4657  }
4658 
4659  return nullptr;
4660 }
4661 
4663  const SimplifyQuery &Q) {
4664  return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
4665 }
4666 
4668  const SimplifyQuery &Q, unsigned) {
4669  if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
4670  return C;
4671 
4672  if (Constant *C = simplifyFPBinop(Op0, Op1))
4673  return C;
4674 
4675  // Unlike fdiv, the result of frem always matches the sign of the dividend.
4676  // The constant match may include undef elements in a vector, so return a full
4677  // zero constant as the result.
4678  if (FMF.noNaNs()) {
4679  // +0 % X -> 0
4680  if (match(Op0, m_PosZeroFP()))
4681  return ConstantFP::getNullValue(Op0->getType());
4682  // -0 % X -> -0
4683  if (match(Op0, m_NegZeroFP()))
4684  return ConstantFP::getNegativeZero(Op0->getType());
4685  }
4686 
4687  return nullptr;
4688 }
4689 
4691  const SimplifyQuery &Q) {
4692  return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
4693 }
4694 
4695 //=== Helper functions for higher up the class hierarchy.
4696 
4697 /// Given the operand for a UnaryOperator, see if we can fold the result.
4698 /// If not, this returns null.
4699 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
4700  unsigned MaxRecurse) {
4701  switch (Opcode) {
4702  case Instruction::FNeg:
4703  return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
4704  default:
4705  llvm_unreachable("Unexpected opcode");
4706  }
4707 }
4708 
4709 /// Given the operand for a UnaryOperator, see if we can fold the result.
4710 /// If not, this returns null.
4711 /// Try to use FastMathFlags when folding the result.
4712 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
4713  const FastMathFlags &FMF,
4714  const SimplifyQuery &Q, unsigned MaxRecurse) {
4715  switch (Opcode) {
4716  case Instruction::FNeg:
4717  return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
4718  default:
4719  return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
4720  }
4721 }
4722 
4723 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
4724  return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
4725 }
4726 
4728  const SimplifyQuery &Q) {
4729  return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
4730 }
4731 
4732 /// Given operands for a BinaryOperator, see if we can fold the result.
4733 /// If not, this returns null.
4734 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4735  const SimplifyQuery &Q, unsigned MaxRecurse) {
4736  switch (Opcode) {
4737  case Instruction::Add:
4738  return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
4739  case Instruction::Sub:
4740  return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
4741  case Instruction::Mul:
4742  return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
4743  case Instruction::SDiv:
4744  return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4745  case Instruction::UDiv:
4746  return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
4747  case Instruction::SRem:
4748  return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4749  case Instruction::URem:
4750  return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
4751  case Instruction::Shl:
4752  return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
4753  case Instruction::LShr:
4754  return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
4755  case Instruction::AShr:
4756  return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4757  case Instruction::And:
4758  return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4759  case Instruction::Or:
4760  return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4761  case Instruction::Xor:
4762  return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
4763  case Instruction::FAdd:
4764  return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4765  case Instruction::FSub:
4766  return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4767  case Instruction::FMul:
4768  return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4769  case Instruction::FDiv:
4770  return SimplifyFDivInst(LH