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