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
19#include "llvm/Analysis/InstructionSimplify.h"
20
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/Analysis/AliasAnalysis.h"
25#include "llvm/Analysis/AssumptionCache.h"
26#include "llvm/Analysis/CaptureTracking.h"
27#include "llvm/Analysis/CmpInstAnalysis.h"
28#include "llvm/Analysis/ConstantFolding.h"
29#include "llvm/Analysis/FloatingPointPredicateUtils.h"
30#include "llvm/Analysis/InstSimplifyFolder.h"
31#include "llvm/Analysis/Loads.h"
32#include "llvm/Analysis/LoopAnalysisManager.h"
33#include "llvm/Analysis/MemoryBuiltins.h"
34#include "llvm/Analysis/OverflowInstAnalysis.h"
35#include "llvm/Analysis/TargetLibraryInfo.h"
36#include "llvm/Analysis/ValueTracking.h"
37#include "llvm/Analysis/VectorUtils.h"
38#include "llvm/IR/ConstantFPRange.h"
39#include "llvm/IR/ConstantRange.h"
40#include "llvm/IR/DataLayout.h"
41#include "llvm/IR/Dominators.h"
42#include "llvm/IR/InstrTypes.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicsAArch64.h"
45#include "llvm/IR/Operator.h"
46#include "llvm/IR/PatternMatch.h"
47#include "llvm/IR/Statepoint.h"
48#include "llvm/Support/KnownBits.h"
49#include "llvm/Support/KnownFPClass.h"
50#include <algorithm>
51#include <optional>
52using namespace llvm;
53using namespace llvm::PatternMatch;
54
55#define DEBUG_TYPE "instsimplify"
56
57enum { RecursionLimit = 3 };
58
59STATISTIC(NumExpand, "Number of expansions");
60STATISTIC(NumReassoc, "Number of reassociations");
61
62static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
63 unsigned);
64static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
65static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
66 const SimplifyQuery &, unsigned);
67static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
68 unsigned);
69static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
70 const SimplifyQuery &, unsigned);
71static Value *simplifyCmpInst(CmpPredicate, Value *, Value *,
72 const SimplifyQuery &, unsigned);
73static Value *simplifyICmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS,
74 const SimplifyQuery &Q, unsigned MaxRecurse);
75static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
76static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
77 unsigned);
78static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
79 unsigned);
80static Value *simplifyGEPInst(Type *, Value *, ArrayRef<Value *>,
81 GEPNoWrapFlags, const SimplifyQuery &, unsigned);
82static Value *simplifySelectInst(Value *, Value *, Value *,
83 const SimplifyQuery &, unsigned);
84static Value *simplifyInstructionWithOperands(Instruction *I,
85 ArrayRef<Value *> NewOps,
86 const SimplifyQuery &SQ,
87 unsigned MaxRecurse);
88
89/// For a boolean type or a vector of boolean type, return false or a vector
90/// with every element false.
91static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
92
93/// For a boolean type or a vector of boolean type, return true or a vector
94/// with every element true.
95static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
96
97/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
98static bool isSameCompare(Value *V, CmpPredicate Pred, Value *LHS, Value *RHS) {
99 CmpInst *Cmp = dyn_cast<CmpInst>(Val: V);
100 if (!Cmp)
101 return false;
102 CmpInst::Predicate CPred = Cmp->getPredicate();
103 Value *CLHS = Cmp->getOperand(i_nocapture: 0), *CRHS = Cmp->getOperand(i_nocapture: 1);
104 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
105 return true;
106 return CPred == CmpInst::getSwappedPredicate(pred: Pred) && CLHS == RHS &&
107 CRHS == LHS;
108}
109
110/// Simplify comparison with true or false branch of select:
111/// %sel = select i1 %cond, i32 %tv, i32 %fv
112/// %cmp = icmp sle i32 %sel, %rhs
113/// Compose new comparison by substituting %sel with either %tv or %fv
114/// and see if it simplifies.
115static Value *simplifyCmpSelCase(CmpPredicate Pred, Value *LHS, Value *RHS,
116 Value *Cond, const SimplifyQuery &Q,
117 unsigned MaxRecurse, Constant *TrueOrFalse) {
118 Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
119 if (SimplifiedCmp == Cond) {
120 // %cmp simplified to the select condition (%cond).
121 return TrueOrFalse;
122 } else if (!SimplifiedCmp && isSameCompare(V: Cond, Pred, LHS, RHS)) {
123 // It didn't simplify. However, if composed comparison is equivalent
124 // to the select condition (%cond) then we can replace it.
125 return TrueOrFalse;
126 }
127 return SimplifiedCmp;
128}
129
130/// Simplify comparison with true branch of select
131static Value *simplifyCmpSelTrueCase(CmpPredicate Pred, Value *LHS, Value *RHS,
132 Value *Cond, const SimplifyQuery &Q,
133 unsigned MaxRecurse) {
134 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
135 TrueOrFalse: getTrue(Ty: Cond->getType()));
136}
137
138/// Simplify comparison with false branch of select
139static Value *simplifyCmpSelFalseCase(CmpPredicate Pred, Value *LHS, Value *RHS,
140 Value *Cond, const SimplifyQuery &Q,
141 unsigned MaxRecurse) {
142 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
143 TrueOrFalse: getFalse(Ty: Cond->getType()));
144}
145
146/// We know comparison with both branches of select can be simplified, but they
147/// are not equal. This routine handles some logical simplifications.
148static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
149 Value *Cond,
150 const SimplifyQuery &Q,
151 unsigned MaxRecurse) {
152 // If the false value simplified to false, then the result of the compare
153 // is equal to "Cond && TCmp". This also catches the case when the false
154 // value simplified to false and the true value to true, returning "Cond".
155 // Folding select to and/or isn't poison-safe in general; impliesPoison
156 // checks whether folding it does not convert a well-defined value into
157 // poison.
158 if (match(V: FCmp, P: m_Zero()) && impliesPoison(ValAssumedPoison: TCmp, V: Cond))
159 if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
160 return V;
161 // If the true value simplified to true, then the result of the compare
162 // is equal to "Cond || FCmp".
163 if (match(V: TCmp, P: m_One()) && impliesPoison(ValAssumedPoison: FCmp, V: Cond))
164 if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
165 return V;
166 // Finally, if the false value simplified to true and the true value to
167 // false, then the result of the compare is equal to "!Cond".
168 if (match(V: FCmp, P: m_One()) && match(V: TCmp, P: m_Zero()))
169 if (Value *V = simplifyXorInst(
170 Cond, Constant::getAllOnesValue(Ty: Cond->getType()), Q, MaxRecurse))
171 return V;
172 return nullptr;
173}
174
175/// Does the given value dominate the specified phi node?
176static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
177 Instruction *I = dyn_cast<Instruction>(Val: V);
178 if (!I)
179 // Arguments and constants dominate all instructions.
180 return true;
181
182 // If we have a DominatorTree then do a precise test.
183 if (DT)
184 return DT->dominates(Def: I, User: P);
185
186 // Otherwise, if the instruction is in the entry block and is not an invoke,
187 // then it obviously dominates all phi nodes.
188 if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(Val: I) &&
189 !isa<CallBrInst>(Val: I))
190 return true;
191
192 return false;
193}
194
195/// Try to simplify a binary operator of form "V op OtherOp" where V is
196/// "(B0 opex B1)" by distributing 'op' across 'opex' as
197/// "(B0 op OtherOp) opex (B1 op OtherOp)".
198static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
199 Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
200 const SimplifyQuery &Q, unsigned MaxRecurse) {
201 auto *B = dyn_cast<BinaryOperator>(Val: V);
202 if (!B || B->getOpcode() != OpcodeToExpand)
203 return nullptr;
204 Value *B0 = B->getOperand(i_nocapture: 0), *B1 = B->getOperand(i_nocapture: 1);
205 Value *L =
206 simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
207 if (!L)
208 return nullptr;
209 Value *R =
210 simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
211 if (!R)
212 return nullptr;
213
214 // Does the expanded pair of binops simplify to the existing binop?
215 if ((L == B0 && R == B1) ||
216 (Instruction::isCommutative(Opcode: OpcodeToExpand) && L == B1 && R == B0)) {
217 ++NumExpand;
218 return B;
219 }
220
221 // Otherwise, return "L op' R" if it simplifies.
222 Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
223 if (!S)
224 return nullptr;
225
226 ++NumExpand;
227 return S;
228}
229
230/// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
231/// distributing op over op'.
232static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L,
233 Value *R,
234 Instruction::BinaryOps OpcodeToExpand,
235 const SimplifyQuery &Q,
236 unsigned MaxRecurse) {
237 // Recursion is always used, so bail out at once if we already hit the limit.
238 if (!MaxRecurse--)
239 return nullptr;
240
241 if (Value *V = expandBinOp(Opcode, V: L, OtherOp: R, OpcodeToExpand, Q, MaxRecurse))
242 return V;
243 if (Value *V = expandBinOp(Opcode, V: R, OtherOp: L, OpcodeToExpand, Q, MaxRecurse))
244 return V;
245 return nullptr;
246}
247
248/// Generic simplifications for associative binary operations.
249/// Returns the simpler value, or null if none was found.
250static Value *simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
251 Value *LHS, Value *RHS,
252 const SimplifyQuery &Q,
253 unsigned MaxRecurse) {
254 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
255
256 // Recursion is always used, so bail out at once if we already hit the limit.
257 if (!MaxRecurse--)
258 return nullptr;
259
260 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(Val: LHS);
261 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(Val: RHS);
262
263 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
264 if (Op0 && Op0->getOpcode() == Opcode) {
265 Value *A = Op0->getOperand(i_nocapture: 0);
266 Value *B = Op0->getOperand(i_nocapture: 1);
267 Value *C = RHS;
268
269 // Does "B op C" simplify?
270 if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
271 // It does! Return "A op V" if it simplifies or is already available.
272 // If V equals B then "A op V" is just the LHS.
273 if (V == B)
274 return LHS;
275 // Otherwise return "A op V" if it simplifies.
276 if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
277 ++NumReassoc;
278 return W;
279 }
280 }
281 }
282
283 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
284 if (Op1 && Op1->getOpcode() == Opcode) {
285 Value *A = LHS;
286 Value *B = Op1->getOperand(i_nocapture: 0);
287 Value *C = Op1->getOperand(i_nocapture: 1);
288
289 // Does "A op B" simplify?
290 if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
291 // It does! Return "V op C" if it simplifies or is already available.
292 // If V equals B then "V op C" is just the RHS.
293 if (V == B)
294 return RHS;
295 // Otherwise return "V op C" if it simplifies.
296 if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
297 ++NumReassoc;
298 return W;
299 }
300 }
301 }
302
303 // The remaining transforms require commutativity as well as associativity.
304 if (!Instruction::isCommutative(Opcode))
305 return nullptr;
306
307 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
308 if (Op0 && Op0->getOpcode() == Opcode) {
309 Value *A = Op0->getOperand(i_nocapture: 0);
310 Value *B = Op0->getOperand(i_nocapture: 1);
311 Value *C = RHS;
312
313 // Does "C op A" simplify?
314 if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
315 // It does! Return "V op B" if it simplifies or is already available.
316 // If V equals A then "V op B" is just the LHS.
317 if (V == A)
318 return LHS;
319 // Otherwise return "V op B" if it simplifies.
320 if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
321 ++NumReassoc;
322 return W;
323 }
324 }
325 }
326
327 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
328 if (Op1 && Op1->getOpcode() == Opcode) {
329 Value *A = LHS;
330 Value *B = Op1->getOperand(i_nocapture: 0);
331 Value *C = Op1->getOperand(i_nocapture: 1);
332
333 // Does "C op A" simplify?
334 if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
335 // It does! Return "B op V" if it simplifies or is already available.
336 // If V equals C then "B op V" is just the RHS.
337 if (V == C)
338 return RHS;
339 // Otherwise return "B op V" if it simplifies.
340 if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
341 ++NumReassoc;
342 return W;
343 }
344 }
345 }
346
347 return nullptr;
348}
349
350/// In the case of a binary operation with a select instruction as an operand,
351/// try to simplify the binop by seeing whether evaluating it on both branches
352/// of the select results in the same value. Returns the common value if so,
353/// otherwise returns null.
354static Value *threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
355 Value *RHS, const SimplifyQuery &Q,
356 unsigned MaxRecurse) {
357 // Recursion is always used, so bail out at once if we already hit the limit.
358 if (!MaxRecurse--)
359 return nullptr;
360
361 SelectInst *SI;
362 if (isa<SelectInst>(Val: LHS)) {
363 SI = cast<SelectInst>(Val: LHS);
364 } else {
365 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
366 SI = cast<SelectInst>(Val: RHS);
367 }
368
369 // Evaluate the BinOp on the true and false branches of the select.
370 Value *TV;
371 Value *FV;
372 if (SI == LHS) {
373 TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
374 FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
375 } else {
376 TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
377 FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
378 }
379
380 // If they simplified to the same value, then return the common value.
381 // If they both failed to simplify then return null.
382 if (TV == FV)
383 return TV;
384
385 // If one branch simplified to undef, return the other one.
386 if (TV && Q.isUndefValue(V: TV))
387 return FV;
388 if (FV && Q.isUndefValue(V: FV))
389 return TV;
390
391 // If applying the operation did not change the true and false select values,
392 // then the result of the binop is the select itself.
393 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
394 return SI;
395
396 // If one branch simplified and the other did not, and the simplified
397 // value is equal to the unsimplified one, return the simplified value.
398 // For example, select (cond, X, X & Z) & Z -> X & Z.
399 if ((FV && !TV) || (TV && !FV)) {
400 // Check that the simplified value has the form "X op Y" where "op" is the
401 // same as the original operation.
402 Instruction *Simplified = dyn_cast<Instruction>(Val: FV ? FV : TV);
403 if (Simplified && Simplified->getOpcode() == unsigned(Opcode) &&
404 !Simplified->hasPoisonGeneratingFlags()) {
405 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
406 // We already know that "op" is the same as for the simplified value. See
407 // if the operands match too. If so, return the simplified value.
408 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
409 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
410 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
411 if (Simplified->getOperand(i: 0) == UnsimplifiedLHS &&
412 Simplified->getOperand(i: 1) == UnsimplifiedRHS)
413 return Simplified;
414 if (Simplified->isCommutative() &&
415 Simplified->getOperand(i: 1) == UnsimplifiedLHS &&
416 Simplified->getOperand(i: 0) == UnsimplifiedRHS)
417 return Simplified;
418 }
419 }
420
421 return nullptr;
422}
423
424/// In the case of a comparison with a select instruction, try to simplify the
425/// comparison by seeing whether both branches of the select result in the same
426/// value. Returns the common value if so, otherwise returns null.
427/// For example, if we have:
428/// %tmp = select i1 %cmp, i32 1, i32 2
429/// %cmp1 = icmp sle i32 %tmp, 3
430/// We can simplify %cmp1 to true, because both branches of select are
431/// less than 3. We compose new comparison by substituting %tmp with both
432/// branches of select and see if it can be simplified.
433static Value *threadCmpOverSelect(CmpPredicate Pred, Value *LHS, Value *RHS,
434 const SimplifyQuery &Q, unsigned MaxRecurse) {
435 // Recursion is always used, so bail out at once if we already hit the limit.
436 if (!MaxRecurse--)
437 return nullptr;
438
439 // Make sure the select is on the LHS.
440 if (!isa<SelectInst>(Val: LHS)) {
441 std::swap(a&: LHS, b&: RHS);
442 Pred = CmpInst::getSwappedPredicate(pred: Pred);
443 }
444 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
445 SelectInst *SI = cast<SelectInst>(Val: LHS);
446 Value *Cond = SI->getCondition();
447 Value *TV = SI->getTrueValue();
448 Value *FV = SI->getFalseValue();
449
450 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
451 // Does "cmp TV, RHS" simplify?
452 Value *TCmp = simplifyCmpSelTrueCase(Pred, LHS: TV, RHS, Cond, Q, MaxRecurse);
453 if (!TCmp)
454 return nullptr;
455
456 // Does "cmp FV, RHS" simplify?
457 Value *FCmp = simplifyCmpSelFalseCase(Pred, LHS: FV, RHS, Cond, Q, MaxRecurse);
458 if (!FCmp)
459 return nullptr;
460
461 // If both sides simplified to the same value, then use it as the result of
462 // the original comparison.
463 if (TCmp == FCmp)
464 return TCmp;
465
466 // The remaining cases only make sense if the select condition has the same
467 // type as the result of the comparison, so bail out if this is not so.
468 if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
469 return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
470
471 return nullptr;
472}
473
474/// In the case of a binary operation with an operand that is a PHI instruction,
475/// try to simplify the binop by seeing whether evaluating it on the incoming
476/// phi values yields the same result for every value. If so returns the common
477/// value, otherwise returns null.
478static Value *threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
479 Value *RHS, const SimplifyQuery &Q,
480 unsigned MaxRecurse) {
481 // Recursion is always used, so bail out at once if we already hit the limit.
482 if (!MaxRecurse--)
483 return nullptr;
484
485 PHINode *PI;
486 if (isa<PHINode>(Val: LHS)) {
487 PI = cast<PHINode>(Val: LHS);
488 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
489 if (!valueDominatesPHI(V: RHS, P: PI, DT: Q.DT))
490 return nullptr;
491 } else {
492 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
493 PI = cast<PHINode>(Val: RHS);
494 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
495 if (!valueDominatesPHI(V: LHS, P: PI, DT: Q.DT))
496 return nullptr;
497 }
498
499 // Evaluate the BinOp on the incoming phi values.
500 Value *CommonValue = nullptr;
501 for (Use &Incoming : PI->incoming_values()) {
502 // If the incoming value is the phi node itself, it can safely be skipped.
503 if (Incoming == PI)
504 continue;
505 Instruction *InTI = PI->getIncomingBlock(U: Incoming)->getTerminator();
506 Value *V = PI == LHS
507 ? simplifyBinOp(Opcode, Incoming, RHS,
508 Q.getWithInstruction(I: InTI), MaxRecurse)
509 : simplifyBinOp(Opcode, LHS, Incoming,
510 Q.getWithInstruction(I: InTI), MaxRecurse);
511 // If the operation failed to simplify, or simplified to a different value
512 // to previously, then give up.
513 if (!V || (CommonValue && V != CommonValue))
514 return nullptr;
515 CommonValue = V;
516 }
517
518 return CommonValue;
519}
520
521/// In the case of a comparison with a PHI instruction, try to simplify the
522/// comparison by seeing whether comparing with all of the incoming phi values
523/// yields the same result every time. If so returns the common result,
524/// otherwise returns null.
525static Value *threadCmpOverPHI(CmpPredicate Pred, Value *LHS, Value *RHS,
526 const SimplifyQuery &Q, unsigned MaxRecurse) {
527 // Recursion is always used, so bail out at once if we already hit the limit.
528 if (!MaxRecurse--)
529 return nullptr;
530
531 // Make sure the phi is on the LHS.
532 if (!isa<PHINode>(Val: LHS)) {
533 std::swap(a&: LHS, b&: RHS);
534 Pred = CmpInst::getSwappedPredicate(pred: Pred);
535 }
536 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
537 PHINode *PI = cast<PHINode>(Val: LHS);
538
539 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
540 if (!valueDominatesPHI(V: RHS, P: PI, DT: Q.DT))
541 return nullptr;
542
543 // Evaluate the BinOp on the incoming phi values.
544 Value *CommonValue = nullptr;
545 for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
546 Value *Incoming = PI->getIncomingValue(i: u);
547 Instruction *InTI = PI->getIncomingBlock(i: u)->getTerminator();
548 // If the incoming value is the phi node itself, it can safely be skipped.
549 if (Incoming == PI)
550 continue;
551 // Change the context instruction to the "edge" that flows into the phi.
552 // This is important because that is where incoming is actually "evaluated"
553 // even though it is used later somewhere else.
554 Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(I: InTI),
555 MaxRecurse);
556 // If the operation failed to simplify, or simplified to a different value
557 // to previously, then give up.
558 if (!V || (CommonValue && V != CommonValue))
559 return nullptr;
560 CommonValue = V;
561 }
562
563 return CommonValue;
564}
565
566static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
567 Value *&Op0, Value *&Op1,
568 const SimplifyQuery &Q) {
569 if (auto *CLHS = dyn_cast<Constant>(Val: Op0)) {
570 if (auto *CRHS = dyn_cast<Constant>(Val: Op1)) {
571 switch (Opcode) {
572 default:
573 break;
574 case Instruction::FAdd:
575 case Instruction::FSub:
576 case Instruction::FMul:
577 case Instruction::FDiv:
578 case Instruction::FRem:
579 if (Q.CxtI != nullptr)
580 return ConstantFoldFPInstOperands(Opcode, LHS: CLHS, RHS: CRHS, DL: Q.DL, I: Q.CxtI);
581 }
582 return ConstantFoldBinaryOpOperands(Opcode, LHS: CLHS, RHS: CRHS, DL: Q.DL);
583 }
584
585 // Canonicalize the constant to the RHS if this is a commutative operation.
586 if (Instruction::isCommutative(Opcode))
587 std::swap(a&: Op0, b&: Op1);
588 }
589 return nullptr;
590}
591
592/// Given operands for an Add, see if we can fold the result.
593/// If not, this returns null.
594static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
595 const SimplifyQuery &Q, unsigned MaxRecurse) {
596 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::Add, Op0, Op1, Q))
597 return C;
598
599 // X + poison -> poison
600 if (isa<PoisonValue>(Val: Op1))
601 return Op1;
602
603 // X + undef -> undef
604 if (Q.isUndefValue(V: Op1))
605 return Op1;
606
607 // X + 0 -> X
608 if (match(V: Op1, P: m_Zero()))
609 return Op0;
610
611 // If two operands are negative, return 0.
612 if (isKnownNegation(X: Op0, Y: Op1))
613 return Constant::getNullValue(Ty: Op0->getType());
614
615 // X + (Y - X) -> Y
616 // (Y - X) + X -> Y
617 // Eg: X + -X -> 0
618 Value *Y = nullptr;
619 if (match(V: Op1, P: m_Sub(L: m_Value(V&: Y), R: m_Specific(V: Op0))) ||
620 match(V: Op0, P: m_Sub(L: m_Value(V&: Y), R: m_Specific(V: Op1))))
621 return Y;
622
623 // X + ~X -> -1 since ~X = -X-1
624 Type *Ty = Op0->getType();
625 if (match(V: Op0, P: m_Not(V: m_Specific(V: Op1))) || match(V: Op1, P: m_Not(V: m_Specific(V: Op0))))
626 return Constant::getAllOnesValue(Ty);
627
628 // add nsw/nuw (xor Y, signmask), signmask --> Y
629 // The no-wrapping add guarantees that the top bit will be set by the add.
630 // Therefore, the xor must be clearing the already set sign bit of Y.
631 if ((IsNSW || IsNUW) && match(V: Op1, P: m_SignMask()) &&
632 match(V: Op0, P: m_Xor(L: m_Value(V&: Y), R: m_SignMask())))
633 return Y;
634
635 // add nuw %x, -1 -> -1, because %x can only be 0.
636 if (IsNUW && match(V: Op1, P: m_AllOnes()))
637 return Op1; // Which is -1.
638
639 /// i1 add -> xor.
640 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(BitWidth: 1))
641 if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
642 return V;
643
644 // Try some generic simplifications for associative operations.
645 if (Value *V =
646 simplifyAssociativeBinOp(Opcode: Instruction::Add, LHS: Op0, RHS: Op1, Q, MaxRecurse))
647 return V;
648
649 // Threading Add over selects and phi nodes is pointless, so don't bother.
650 // Threading over the select in "A + select(cond, B, C)" means evaluating
651 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
652 // only if B and C are equal. If B and C are equal then (since we assume
653 // that operands have already been simplified) "select(cond, B, C)" should
654 // have been simplified to the common value of B and C already. Analysing
655 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
656 // for threading over phi nodes.
657
658 return nullptr;
659}
660
661Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
662 const SimplifyQuery &Query) {
663 return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Q: Query, MaxRecurse: RecursionLimit);
664}
665
666/// Compute the base pointer and cumulative constant offsets for V.
667///
668/// This strips all constant offsets off of V, leaving it the base pointer, and
669/// accumulates the total constant offset applied in the returned constant.
670/// It returns zero if there are no constant offsets applied.
671///
672/// This is very similar to stripAndAccumulateConstantOffsets(), except it
673/// normalizes the offset bitwidth to the stripped pointer type, not the
674/// original pointer type.
675static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V) {
676 assert(V->getType()->isPtrOrPtrVectorTy());
677
678 APInt Offset = APInt::getZero(numBits: DL.getIndexTypeSizeInBits(Ty: V->getType()));
679 V = V->stripAndAccumulateConstantOffsets(DL, Offset,
680 /*AllowNonInbounds=*/true);
681 // As that strip may trace through `addrspacecast`, need to sext or trunc
682 // the offset calculated.
683 return Offset.sextOrTrunc(width: DL.getIndexTypeSizeInBits(Ty: V->getType()));
684}
685
686/// Compute the constant difference between two pointer values.
687/// If the difference is not a constant, returns zero.
688static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
689 Value *RHS) {
690 APInt LHSOffset = stripAndComputeConstantOffsets(DL, V&: LHS);
691 APInt RHSOffset = stripAndComputeConstantOffsets(DL, V&: RHS);
692
693 // If LHS and RHS are not related via constant offsets to the same base
694 // value, there is nothing we can do here.
695 if (LHS != RHS)
696 return nullptr;
697
698 // Otherwise, the difference of LHS - RHS can be computed as:
699 // LHS - RHS
700 // = (LHSOffset + Base) - (RHSOffset + Base)
701 // = LHSOffset - RHSOffset
702 Constant *Res = ConstantInt::get(Context&: LHS->getContext(), V: LHSOffset - RHSOffset);
703 if (auto *VecTy = dyn_cast<VectorType>(Val: LHS->getType()))
704 Res = ConstantVector::getSplat(EC: VecTy->getElementCount(), Elt: Res);
705 return Res;
706}
707
708/// Test if there is a dominating equivalence condition for the
709/// two operands. If there is, try to reduce the binary operation
710/// between the two operands.
711/// Example: Op0 - Op1 --> 0 when Op0 == Op1
712static Value *simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1,
713 const SimplifyQuery &Q, unsigned MaxRecurse) {
714 // Recursive run it can not get any benefit
715 if (MaxRecurse != RecursionLimit)
716 return nullptr;
717
718 std::optional<bool> Imp =
719 isImpliedByDomCondition(Pred: CmpInst::ICMP_EQ, LHS: Op0, RHS: Op1, ContextI: Q.CxtI, DL: Q.DL);
720 if (Imp && *Imp) {
721 Type *Ty = Op0->getType();
722 switch (Opcode) {
723 case Instruction::Sub:
724 case Instruction::Xor:
725 case Instruction::URem:
726 case Instruction::SRem:
727 return Constant::getNullValue(Ty);
728
729 case Instruction::SDiv:
730 case Instruction::UDiv:
731 return ConstantInt::get(Ty, V: 1);
732
733 case Instruction::And:
734 case Instruction::Or:
735 // Could be either one - choose Op1 since that's more likely a constant.
736 return Op1;
737 default:
738 break;
739 }
740 }
741 return nullptr;
742}
743
744/// Given operands for a Sub, see if we can fold the result.
745/// If not, this returns null.
746static Value *simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
747 const SimplifyQuery &Q, unsigned MaxRecurse) {
748 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::Sub, Op0, Op1, Q))
749 return C;
750
751 // X - poison -> poison
752 // poison - X -> poison
753 if (isa<PoisonValue>(Val: Op0) || isa<PoisonValue>(Val: Op1))
754 return PoisonValue::get(T: Op0->getType());
755
756 // X - undef -> undef
757 // undef - X -> undef
758 if (Q.isUndefValue(V: Op0) || Q.isUndefValue(V: Op1))
759 return UndefValue::get(T: Op0->getType());
760
761 // X - 0 -> X
762 if (match(V: Op1, P: m_Zero()))
763 return Op0;
764
765 // X - X -> 0
766 if (Op0 == Op1)
767 return Constant::getNullValue(Ty: Op0->getType());
768
769 // Is this a negation?
770 if (match(V: Op0, P: m_Zero())) {
771 // 0 - X -> 0 if the sub is NUW.
772 if (IsNUW)
773 return Constant::getNullValue(Ty: Op0->getType());
774
775 KnownBits Known = computeKnownBits(V: Op1, Q);
776 if (Known.Zero.isMaxSignedValue()) {
777 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
778 // Op1 must be 0 because negating the minimum signed value is undefined.
779 if (IsNSW)
780 return Constant::getNullValue(Ty: Op0->getType());
781
782 // 0 - X -> X if X is 0 or the minimum signed value.
783 return Op1;
784 }
785 }
786
787 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
788 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
789 Value *X = nullptr, *Y = nullptr, *Z = Op1;
790 if (MaxRecurse && match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_Value(V&: Y)))) { // (X + Y) - Z
791 // See if "V === Y - Z" simplifies.
792 if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
793 // It does! Now see if "X + V" simplifies.
794 if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
795 // It does, we successfully reassociated!
796 ++NumReassoc;
797 return W;
798 }
799 // See if "V === X - Z" simplifies.
800 if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
801 // It does! Now see if "Y + V" simplifies.
802 if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
803 // It does, we successfully reassociated!
804 ++NumReassoc;
805 return W;
806 }
807 }
808
809 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
810 // For example, X - (X + 1) -> -1
811 X = Op0;
812 if (MaxRecurse && match(V: Op1, P: m_Add(L: m_Value(V&: Y), R: m_Value(V&: Z)))) { // X - (Y + Z)
813 // See if "V === X - Y" simplifies.
814 if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
815 // It does! Now see if "V - Z" simplifies.
816 if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
817 // It does, we successfully reassociated!
818 ++NumReassoc;
819 return W;
820 }
821 // See if "V === X - Z" simplifies.
822 if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
823 // It does! Now see if "V - Y" simplifies.
824 if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
825 // It does, we successfully reassociated!
826 ++NumReassoc;
827 return W;
828 }
829 }
830
831 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
832 // For example, X - (X - Y) -> Y.
833 Z = Op0;
834 if (MaxRecurse && match(V: Op1, P: m_Sub(L: m_Value(V&: X), R: m_Value(V&: Y)))) // Z - (X - Y)
835 // See if "V === Z - X" simplifies.
836 if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
837 // It does! Now see if "V + Y" simplifies.
838 if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
839 // It does, we successfully reassociated!
840 ++NumReassoc;
841 return W;
842 }
843
844 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
845 if (MaxRecurse && match(V: Op0, P: m_Trunc(Op: m_Value(V&: X))) &&
846 match(V: Op1, P: m_Trunc(Op: m_Value(V&: Y))))
847 if (X->getType() == Y->getType())
848 // See if "V === X - Y" simplifies.
849 if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
850 // It does! Now see if "trunc V" simplifies.
851 if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
852 Q, MaxRecurse - 1))
853 // It does, return the simplified "trunc V".
854 return W;
855
856 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
857 if (match(V: Op0, P: m_PtrToIntOrAddr(Op: m_Value(V&: X))) &&
858 match(V: Op1, P: m_PtrToIntOrAddr(Op: m_Value(V&: Y)))) {
859 if (Constant *Result = computePointerDifference(DL: Q.DL, LHS: X, RHS: Y))
860 return ConstantFoldIntegerCast(C: Result, DestTy: Op0->getType(), /*IsSigned*/ true,
861 DL: Q.DL);
862 }
863
864 // i1 sub -> xor.
865 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(BitWidth: 1))
866 if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
867 return V;
868
869 // Threading Sub over selects and phi nodes is pointless, so don't bother.
870 // Threading over the select in "A - select(cond, B, C)" means evaluating
871 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
872 // only if B and C are equal. If B and C are equal then (since we assume
873 // that operands have already been simplified) "select(cond, B, C)" should
874 // have been simplified to the common value of B and C already. Analysing
875 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
876 // for threading over phi nodes.
877
878 if (Value *V = simplifyByDomEq(Opcode: Instruction::Sub, Op0, Op1, Q, MaxRecurse))
879 return V;
880
881 // (sub nuw C_Mask, (xor X, C_Mask)) -> X
882 if (IsNUW) {
883 Value *X;
884 if (match(V: Op1, P: m_Xor(L: m_Value(V&: X), R: m_Specific(V: Op0))) &&
885 match(V: Op0, P: m_LowBitMask()))
886 return X;
887 }
888
889 return nullptr;
890}
891
892Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
893 const SimplifyQuery &Q) {
894 return ::simplifySubInst(Op0, Op1, IsNSW, IsNUW, Q, MaxRecurse: RecursionLimit);
895}
896
897/// Given operands for a Mul, see if we can fold the result.
898/// If not, this returns null.
899static Value *simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
900 const SimplifyQuery &Q, unsigned MaxRecurse) {
901 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::Mul, Op0, Op1, Q))
902 return C;
903
904 // X * poison -> poison
905 if (isa<PoisonValue>(Val: Op1))
906 return Op1;
907
908 // X * undef -> 0
909 // X * 0 -> 0
910 if (Q.isUndefValue(V: Op1) || match(V: Op1, P: m_Zero()))
911 return Constant::getNullValue(Ty: Op0->getType());
912
913 // X * 1 -> X
914 if (match(V: Op1, P: m_One()))
915 return Op0;
916
917 // (X / Y) * Y -> X if the division is exact.
918 Value *X = nullptr;
919 if (Q.IIQ.UseInstrInfo &&
920 (match(V: Op0,
921 P: m_Exact(SubPattern: m_IDiv(L: m_Value(V&: X), R: m_Specific(V: Op1)))) || // (X / Y) * Y
922 match(V: Op1, P: m_Exact(SubPattern: m_IDiv(L: m_Value(V&: X), R: m_Specific(V: Op0)))))) // Y * (X / Y)
923 return X;
924
925 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
926 // mul i1 nsw is a special-case because -1 * -1 is poison (+1 is not
927 // representable). All other cases reduce to 0, so just return 0.
928 if (IsNSW)
929 return ConstantInt::getNullValue(Ty: Op0->getType());
930
931 // Treat "mul i1" as "and i1".
932 if (MaxRecurse)
933 if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
934 return V;
935 }
936
937 // Try some generic simplifications for associative operations.
938 if (Value *V =
939 simplifyAssociativeBinOp(Opcode: Instruction::Mul, LHS: Op0, RHS: Op1, Q, MaxRecurse))
940 return V;
941
942 // Mul distributes over Add. Try some generic simplifications based on this.
943 if (Value *V = expandCommutativeBinOp(Opcode: Instruction::Mul, L: Op0, R: Op1,
944 OpcodeToExpand: Instruction::Add, Q, MaxRecurse))
945 return V;
946
947 // If the operation is with the result of a select instruction, check whether
948 // operating on either branch of the select always yields the same value.
949 if (isa<SelectInst>(Val: Op0) || isa<SelectInst>(Val: Op1))
950 if (Value *V =
951 threadBinOpOverSelect(Opcode: Instruction::Mul, LHS: Op0, RHS: Op1, Q, MaxRecurse))
952 return V;
953
954 // If the operation is with the result of a phi instruction, check whether
955 // operating on all incoming values of the phi always yields the same value.
956 if (isa<PHINode>(Val: Op0) || isa<PHINode>(Val: Op1))
957 if (Value *V =
958 threadBinOpOverPHI(Opcode: Instruction::Mul, LHS: Op0, RHS: Op1, Q, MaxRecurse))
959 return V;
960
961 return nullptr;
962}
963
964Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
965 const SimplifyQuery &Q) {
966 return ::simplifyMulInst(Op0, Op1, IsNSW, IsNUW, Q, MaxRecurse: RecursionLimit);
967}
968
969/// Given a predicate and two operands, return true if the comparison is true.
970/// This is a helper for div/rem simplification where we return some other value
971/// when we can prove a relationship between the operands.
972static bool isICmpTrue(CmpPredicate Pred, Value *LHS, Value *RHS,
973 const SimplifyQuery &Q, unsigned MaxRecurse) {
974 Value *V = simplifyICmpInst(Predicate: Pred, LHS, RHS, Q, MaxRecurse);
975 Constant *C = dyn_cast_or_null<Constant>(Val: V);
976 return (C && C->isAllOnesValue());
977}
978
979/// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
980/// to simplify X % Y to X.
981static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
982 unsigned MaxRecurse, bool IsSigned) {
983 // Recursion is always used, so bail out at once if we already hit the limit.
984 if (!MaxRecurse--)
985 return false;
986
987 if (IsSigned) {
988 // (X srem Y) sdiv Y --> 0
989 if (match(V: X, P: m_SRem(L: m_Value(), R: m_Specific(V: Y))))
990 return true;
991
992 // |X| / |Y| --> 0
993 //
994 // We require that 1 operand is a simple constant. That could be extended to
995 // 2 variables if we computed the sign bit for each.
996 //
997 // Make sure that a constant is not the minimum signed value because taking
998 // the abs() of that is undefined.
999 Type *Ty = X->getType();
1000 const APInt *C;
1001 if (match(V: X, P: m_APInt(Res&: C)) && !C->isMinSignedValue()) {
1002 // Is the variable divisor magnitude always greater than the constant
1003 // dividend magnitude?
1004 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
1005 Constant *PosDividendC = ConstantInt::get(Ty, V: C->abs());
1006 Constant *NegDividendC = ConstantInt::get(Ty, V: -C->abs());
1007 if (isICmpTrue(Pred: CmpInst::ICMP_SLT, LHS: Y, RHS: NegDividendC, Q, MaxRecurse) ||
1008 isICmpTrue(Pred: CmpInst::ICMP_SGT, LHS: Y, RHS: PosDividendC, Q, MaxRecurse))
1009 return true;
1010 }
1011 if (match(V: Y, P: m_APInt(Res&: C))) {
1012 // Special-case: we can't take the abs() of a minimum signed value. If
1013 // that's the divisor, then all we have to do is prove that the dividend
1014 // is also not the minimum signed value.
1015 if (C->isMinSignedValue())
1016 return isICmpTrue(Pred: CmpInst::ICMP_NE, LHS: X, RHS: Y, Q, MaxRecurse);
1017
1018 // Is the variable dividend magnitude always less than the constant
1019 // divisor magnitude?
1020 // |X| < |C| --> X > -abs(C) and X < abs(C)
1021 Constant *PosDivisorC = ConstantInt::get(Ty, V: C->abs());
1022 Constant *NegDivisorC = ConstantInt::get(Ty, V: -C->abs());
1023 if (isICmpTrue(Pred: CmpInst::ICMP_SGT, LHS: X, RHS: NegDivisorC, Q, MaxRecurse) &&
1024 isICmpTrue(Pred: CmpInst::ICMP_SLT, LHS: X, RHS: PosDivisorC, Q, MaxRecurse))
1025 return true;
1026 }
1027 return false;
1028 }
1029
1030 // IsSigned == false.
1031
1032 // Is the unsigned dividend known to be less than a constant divisor?
1033 // TODO: Convert this (and above) to range analysis
1034 // ("computeConstantRangeIncludingKnownBits")?
1035 const APInt *C;
1036 if (match(V: Y, P: m_APInt(Res&: C)) && computeKnownBits(V: X, Q).getMaxValue().ult(RHS: *C))
1037 return true;
1038
1039 // Try again for any divisor:
1040 // Is the dividend unsigned less than the divisor?
1041 return isICmpTrue(Pred: ICmpInst::ICMP_ULT, LHS: X, RHS: Y, Q, MaxRecurse);
1042}
1043
1044/// Check for common or similar folds of integer division or integer remainder.
1045/// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
1046static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
1047 Value *Op1, const SimplifyQuery &Q,
1048 unsigned MaxRecurse) {
1049 bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
1050 bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
1051
1052 Type *Ty = Op0->getType();
1053
1054 // X / undef -> poison
1055 // X % undef -> poison
1056 if (Q.isUndefValue(V: Op1) || isa<PoisonValue>(Val: Op1))
1057 return PoisonValue::get(T: Ty);
1058
1059 // X / 0 -> poison
1060 // X % 0 -> poison
1061 // We don't need to preserve faults!
1062 if (match(V: Op1, P: m_Zero()))
1063 return PoisonValue::get(T: Ty);
1064
1065 // poison / X -> poison
1066 // poison % X -> poison
1067 if (isa<PoisonValue>(Val: Op0))
1068 return Op0;
1069
1070 // undef / X -> 0
1071 // undef % X -> 0
1072 if (Q.isUndefValue(V: Op0))
1073 return Constant::getNullValue(Ty);
1074
1075 // 0 / X -> 0
1076 // 0 % X -> 0
1077 if (match(V: Op0, P: m_Zero()))
1078 return Constant::getNullValue(Ty: Op0->getType());
1079
1080 // X / X -> 1
1081 // X % X -> 0
1082 if (Op0 == Op1)
1083 return IsDiv ? ConstantInt::get(Ty, V: 1) : Constant::getNullValue(Ty);
1084
1085 KnownBits Known = computeKnownBits(V: Op1, Q);
1086 // X / 0 -> poison
1087 // X % 0 -> poison
1088 // If the divisor is known to be zero, just return poison. This can happen in
1089 // some cases where its provable indirectly the denominator is zero but it's
1090 // not trivially simplifiable (i.e known zero through a phi node).
1091 if (Known.isZero())
1092 return PoisonValue::get(T: Ty);
1093
1094 // X / 1 -> X
1095 // X % 1 -> 0
1096 // If the divisor can only be zero or one, we can't have division-by-zero
1097 // or remainder-by-zero, so assume the divisor is 1.
1098 // e.g. 1, zext (i8 X), sdiv X (Y and 1)
1099 if (Known.countMinLeadingZeros() == Known.getBitWidth() - 1)
1100 return IsDiv ? Op0 : Constant::getNullValue(Ty);
1101
1102 // If X * Y does not overflow, then:
1103 // X * Y / Y -> X
1104 // X * Y % Y -> 0
1105 Value *X;
1106 if (match(V: Op0, P: m_c_Mul(L: m_Value(V&: X), R: m_Specific(V: Op1)))) {
1107 auto *Mul = cast<OverflowingBinaryOperator>(Val: Op0);
1108 // The multiplication can't overflow if it is defined not to, or if
1109 // X == A / Y for some A.
1110 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Op: Mul)) ||
1111 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Op: Mul)) ||
1112 (IsSigned && match(V: X, P: m_SDiv(L: m_Value(), R: m_Specific(V: Op1)))) ||
1113 (!IsSigned && match(V: X, P: m_UDiv(L: m_Value(), R: m_Specific(V: Op1))))) {
1114 return IsDiv ? X : Constant::getNullValue(Ty: Op0->getType());
1115 }
1116 }
1117
1118 if (isDivZero(X: Op0, Y: Op1, Q, MaxRecurse, IsSigned))
1119 return IsDiv ? Constant::getNullValue(Ty: Op0->getType()) : Op0;
1120
1121 if (Value *V = simplifyByDomEq(Opcode, Op0, Op1, Q, MaxRecurse))
1122 return V;
1123
1124 // If the operation is with the result of a select instruction, check whether
1125 // operating on either branch of the select always yields the same value.
1126 if (isa<SelectInst>(Val: Op0) || isa<SelectInst>(Val: Op1))
1127 if (Value *V = threadBinOpOverSelect(Opcode, LHS: Op0, RHS: Op1, Q, MaxRecurse))
1128 return V;
1129
1130 // If the operation is with the result of a phi instruction, check whether
1131 // operating on all incoming values of the phi always yields the same value.
1132 if (isa<PHINode>(Val: Op0) || isa<PHINode>(Val: Op1))
1133 if (Value *V = threadBinOpOverPHI(Opcode, LHS: Op0, RHS: Op1, Q, MaxRecurse))
1134 return V;
1135
1136 return nullptr;
1137}
1138
1139/// These are simplifications common to SDiv and UDiv.
1140static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1141 bool IsExact, const SimplifyQuery &Q,
1142 unsigned MaxRecurse) {
1143 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1144 return C;
1145
1146 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1147 return V;
1148
1149 const APInt *DivC;
1150 if (IsExact && match(V: Op1, P: m_APInt(Res&: DivC))) {
1151 // If this is an exact divide by a constant, then the dividend (Op0) must
1152 // have at least as many trailing zeros as the divisor to divide evenly. If
1153 // it has less trailing zeros, then the result must be poison.
1154 if (DivC->countr_zero()) {
1155 KnownBits KnownOp0 = computeKnownBits(V: Op0, Q);
1156 if (KnownOp0.countMaxTrailingZeros() < DivC->countr_zero())
1157 return PoisonValue::get(T: Op0->getType());
1158 }
1159
1160 // udiv exact (mul nsw X, C), C --> X
1161 // sdiv exact (mul nuw X, C), C --> X
1162 // where C is not a power of 2.
1163 Value *X;
1164 if (!DivC->isPowerOf2() &&
1165 (Opcode == Instruction::UDiv
1166 ? match(V: Op0, P: m_NSWMul(L: m_Value(V&: X), R: m_Specific(V: Op1)))
1167 : match(V: Op0, P: m_NUWMul(L: m_Value(V&: X), R: m_Specific(V: Op1)))))
1168 return X;
1169 }
1170
1171 return nullptr;
1172}
1173
1174/// These are simplifications common to SRem and URem.
1175static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1176 const SimplifyQuery &Q, unsigned MaxRecurse) {
1177 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1178 return C;
1179
1180 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1181 return V;
1182
1183 // (X << Y) % X -> 0
1184 if (Q.IIQ.UseInstrInfo) {
1185 if ((Opcode == Instruction::SRem &&
1186 match(V: Op0, P: m_NSWShl(L: m_Specific(V: Op1), R: m_Value()))) ||
1187 (Opcode == Instruction::URem &&
1188 match(V: Op0, P: m_NUWShl(L: m_Specific(V: Op1), R: m_Value()))))
1189 return Constant::getNullValue(Ty: Op0->getType());
1190
1191 const APInt *C0;
1192 if (match(V: Op1, P: m_APInt(Res&: C0))) {
1193 // (srem (mul nsw X, C1), C0) -> 0 if C1 s% C0 == 0
1194 // (urem (mul nuw X, C1), C0) -> 0 if C1 u% C0 == 0
1195 if (Opcode == Instruction::SRem
1196 ? match(V: Op0,
1197 P: m_NSWMul(L: m_Value(), R: m_CheckedInt(CheckFn: [C0](const APInt &C) {
1198 return C.srem(RHS: *C0).isZero();
1199 })))
1200 : match(V: Op0,
1201 P: m_NUWMul(L: m_Value(), R: m_CheckedInt(CheckFn: [C0](const APInt &C) {
1202 return C.urem(RHS: *C0).isZero();
1203 }))))
1204 return Constant::getNullValue(Ty: Op0->getType());
1205 }
1206 }
1207 return nullptr;
1208}
1209
1210/// Given operands for an SDiv, see if we can fold the result.
1211/// If not, this returns null.
1212static Value *simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1213 const SimplifyQuery &Q, unsigned MaxRecurse) {
1214 // If two operands are negated and no signed overflow, return -1.
1215 if (isKnownNegation(X: Op0, Y: Op1, /*NeedNSW=*/true))
1216 return Constant::getAllOnesValue(Ty: Op0->getType());
1217
1218 return simplifyDiv(Opcode: Instruction::SDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1219}
1220
1221Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1222 const SimplifyQuery &Q) {
1223 return ::simplifySDivInst(Op0, Op1, IsExact, Q, MaxRecurse: RecursionLimit);
1224}
1225
1226/// Given operands for a UDiv, see if we can fold the result.
1227/// If not, this returns null.
1228static Value *simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1229 const SimplifyQuery &Q, unsigned MaxRecurse) {
1230 return simplifyDiv(Opcode: Instruction::UDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1231}
1232
1233Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1234 const SimplifyQuery &Q) {
1235 return ::simplifyUDivInst(Op0, Op1, IsExact, Q, MaxRecurse: RecursionLimit);
1236}
1237
1238/// Given operands for an SRem, see if we can fold the result.
1239/// If not, this returns null.
1240static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1241 unsigned MaxRecurse) {
1242 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1243 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1244 Value *X;
1245 if (match(V: Op1, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1))
1246 return ConstantInt::getNullValue(Ty: Op0->getType());
1247
1248 // If the two operands are negated, return 0.
1249 if (isKnownNegation(X: Op0, Y: Op1))
1250 return ConstantInt::getNullValue(Ty: Op0->getType());
1251
1252 return simplifyRem(Opcode: Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1253}
1254
1255Value *llvm::simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1256 return ::simplifySRemInst(Op0, Op1, Q, MaxRecurse: RecursionLimit);
1257}
1258
1259/// Given operands for a URem, see if we can fold the result.
1260/// If not, this returns null.
1261static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1262 unsigned MaxRecurse) {
1263 return simplifyRem(Opcode: Instruction::URem, Op0, Op1, Q, MaxRecurse);
1264}
1265
1266Value *llvm::simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1267 return ::simplifyURemInst(Op0, Op1, Q, MaxRecurse: RecursionLimit);
1268}
1269
1270/// Returns true if a shift by \c Amount always yields poison.
1271static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
1272 Constant *C = dyn_cast<Constant>(Val: Amount);
1273 if (!C)
1274 return false;
1275
1276 // X shift by undef -> poison because it may shift by the bitwidth.
1277 if (Q.isUndefValue(V: C))
1278 return true;
1279
1280 // Shifting by the bitwidth or more is poison. This covers scalars and
1281 // fixed/scalable vectors with splat constants.
1282 const APInt *AmountC;
1283 if (match(V: C, P: m_APInt(Res&: AmountC)) && AmountC->uge(RHS: AmountC->getBitWidth()))
1284 return true;
1285
1286 // Try harder for fixed-length vectors:
1287 // If all lanes of a vector shift are poison, the whole shift is poison.
1288 if (isa<ConstantVector>(Val: C) || isa<ConstantDataVector>(Val: C)) {
1289 for (unsigned I = 0,
1290 E = cast<FixedVectorType>(Val: C->getType())->getNumElements();
1291 I != E; ++I)
1292 if (!isPoisonShift(Amount: C->getAggregateElement(Elt: I), Q))
1293 return false;
1294 return true;
1295 }
1296
1297 return false;
1298}
1299
1300/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1301/// If not, this returns null.
1302static Value *simplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1303 Value *Op1, bool IsNSW, const SimplifyQuery &Q,
1304 unsigned MaxRecurse) {
1305 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1306 return C;
1307
1308 // poison shift by X -> poison
1309 if (isa<PoisonValue>(Val: Op0))
1310 return Op0;
1311
1312 // 0 shift by X -> 0
1313 if (match(V: Op0, P: m_Zero()))
1314 return Constant::getNullValue(Ty: Op0->getType());
1315
1316 // X shift by 0 -> X
1317 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1318 // would be poison.
1319 Value *X;
1320 if (match(V: Op1, P: m_Zero()) ||
1321 (match(V: Op1, P: m_SExt(Op: m_Value(V&: X))) && X->getType()->isIntOrIntVectorTy(BitWidth: 1)))
1322 return Op0;
1323
1324 // Fold undefined shifts.
1325 if (isPoisonShift(Amount: Op1, Q))
1326 return PoisonValue::get(T: Op0->getType());
1327
1328 // If the operation is with the result of a select instruction, check whether
1329 // operating on either branch of the select always yields the same value.
1330 if (isa<SelectInst>(Val: Op0) || isa<SelectInst>(Val: Op1))
1331 if (Value *V = threadBinOpOverSelect(Opcode, LHS: Op0, RHS: Op1, Q, MaxRecurse))
1332 return V;
1333
1334 // If the operation is with the result of a phi instruction, check whether
1335 // operating on all incoming values of the phi always yields the same value.
1336 if (isa<PHINode>(Val: Op0) || isa<PHINode>(Val: Op1))
1337 if (Value *V = threadBinOpOverPHI(Opcode, LHS: Op0, RHS: Op1, Q, MaxRecurse))
1338 return V;
1339
1340 // If any bits in the shift amount make that value greater than or equal to
1341 // the number of bits in the type, the shift is undefined.
1342 KnownBits KnownAmt = computeKnownBits(V: Op1, Q);
1343 if (KnownAmt.getMinValue().uge(RHS: KnownAmt.getBitWidth()))
1344 return PoisonValue::get(T: Op0->getType());
1345
1346 // If all valid bits in the shift amount are known zero, the first operand is
1347 // unchanged.
1348 unsigned NumValidShiftBits = Log2_32_Ceil(Value: KnownAmt.getBitWidth());
1349 if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
1350 return Op0;
1351
1352 // Check for nsw shl leading to a poison value.
1353 if (IsNSW) {
1354 assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
1355 KnownBits KnownVal = computeKnownBits(V: Op0, Q);
1356 KnownBits KnownShl = KnownBits::shl(LHS: KnownVal, RHS: KnownAmt);
1357
1358 if (KnownVal.Zero.isSignBitSet())
1359 KnownShl.Zero.setSignBit();
1360 if (KnownVal.One.isSignBitSet())
1361 KnownShl.One.setSignBit();
1362
1363 if (KnownShl.hasConflict())
1364 return PoisonValue::get(T: Op0->getType());
1365 }
1366
1367 return nullptr;
1368}
1369
1370/// Given operands for an LShr or AShr, see if we can fold the result. If not,
1371/// this returns null.
1372static Value *simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1373 Value *Op1, bool IsExact,
1374 const SimplifyQuery &Q, unsigned MaxRecurse) {
1375 if (Value *V =
1376 simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
1377 return V;
1378
1379 // X >> X -> 0
1380 if (Op0 == Op1)
1381 return Constant::getNullValue(Ty: Op0->getType());
1382
1383 // undef >> X -> 0
1384 // undef >> X -> undef (if it's exact)
1385 if (Q.isUndefValue(V: Op0))
1386 return IsExact ? Op0 : Constant::getNullValue(Ty: Op0->getType());
1387
1388 // The low bit cannot be shifted out of an exact shift if it is set.
1389 // TODO: Generalize by counting trailing zeros (see fold for exact division).
1390 if (IsExact) {
1391 KnownBits Op0Known = computeKnownBits(V: Op0, Q);
1392 if (Op0Known.One[0])
1393 return Op0;
1394 }
1395
1396 return nullptr;
1397}
1398
1399/// Given operands for an Shl, see if we can fold the result.
1400/// If not, this returns null.
1401static Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1402 const SimplifyQuery &Q, unsigned MaxRecurse) {
1403 if (Value *V =
1404 simplifyShift(Opcode: Instruction::Shl, Op0, Op1, IsNSW, Q, MaxRecurse))
1405 return V;
1406
1407 Type *Ty = Op0->getType();
1408 // undef << X -> 0
1409 // undef << X -> undef if (if it's NSW/NUW)
1410 if (Q.isUndefValue(V: Op0))
1411 return IsNSW || IsNUW ? Op0 : Constant::getNullValue(Ty);
1412
1413 // (X >> A) << A -> X
1414 Value *X;
1415 if (Q.IIQ.UseInstrInfo &&
1416 match(V: Op0, P: m_Exact(SubPattern: m_Shr(L: m_Value(V&: X), R: m_Specific(V: Op1)))))
1417 return X;
1418
1419 // shl nuw i8 C, %x -> C iff C has sign bit set.
1420 if (IsNUW && match(V: Op0, P: m_Negative()))
1421 return Op0;
1422 // NOTE: could use computeKnownBits() / LazyValueInfo,
1423 // but the cost-benefit analysis suggests it isn't worth it.
1424
1425 // "nuw" guarantees that only zeros are shifted out, and "nsw" guarantees
1426 // that the sign-bit does not change, so the only input that does not
1427 // produce poison is 0, and "0 << (bitwidth-1) --> 0".
1428 if (IsNSW && IsNUW &&
1429 match(V: Op1, P: m_SpecificInt(V: Ty->getScalarSizeInBits() - 1)))
1430 return Constant::getNullValue(Ty);
1431
1432 return nullptr;
1433}
1434
1435Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1436 const SimplifyQuery &Q) {
1437 return ::simplifyShlInst(Op0, Op1, IsNSW, IsNUW, Q, MaxRecurse: RecursionLimit);
1438}
1439
1440/// Given operands for an LShr, see if we can fold the result.
1441/// If not, this returns null.
1442static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1443 const SimplifyQuery &Q, unsigned MaxRecurse) {
1444 if (Value *V = simplifyRightShift(Opcode: Instruction::LShr, Op0, Op1, IsExact, Q,
1445 MaxRecurse))
1446 return V;
1447
1448 // (X << A) >> A -> X
1449 Value *X;
1450 if (Q.IIQ.UseInstrInfo && match(V: Op0, P: m_NUWShl(L: m_Value(V&: X), R: m_Specific(V: Op1))))
1451 return X;
1452
1453 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1454 // We can return X as we do in the above case since OR alters no bits in X.
1455 // SimplifyDemandedBits in InstCombine can do more general optimization for
1456 // bit manipulation. This pattern aims to provide opportunities for other
1457 // optimizers by supporting a simple but common case in InstSimplify.
1458 Value *Y;
1459 const APInt *ShRAmt, *ShLAmt;
1460 if (Q.IIQ.UseInstrInfo && match(V: Op1, P: m_APInt(Res&: ShRAmt)) &&
1461 match(V: Op0, P: m_c_Or(L: m_NUWShl(L: m_Value(V&: X), R: m_APInt(Res&: ShLAmt)), R: m_Value(V&: Y))) &&
1462 *ShRAmt == *ShLAmt) {
1463 const KnownBits YKnown = computeKnownBits(V: Y, Q);
1464 const unsigned EffWidthY = YKnown.countMaxActiveBits();
1465 if (ShRAmt->uge(RHS: EffWidthY))
1466 return X;
1467 }
1468
1469 return nullptr;
1470}
1471
1472Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1473 const SimplifyQuery &Q) {
1474 return ::simplifyLShrInst(Op0, Op1, IsExact, Q, MaxRecurse: RecursionLimit);
1475}
1476
1477/// Given operands for an AShr, see if we can fold the result.
1478/// If not, this returns null.
1479static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1480 const SimplifyQuery &Q, unsigned MaxRecurse) {
1481 if (Value *V = simplifyRightShift(Opcode: Instruction::AShr, Op0, Op1, IsExact, Q,
1482 MaxRecurse))
1483 return V;
1484
1485 // -1 >>a X --> -1
1486 // (-1 << X) a>> X --> -1
1487 // We could return the original -1 constant to preserve poison elements.
1488 if (match(V: Op0, P: m_AllOnes()) ||
1489 match(V: Op0, P: m_Shl(L: m_AllOnes(), R: m_Specific(V: Op1))))
1490 return Constant::getAllOnesValue(Ty: Op0->getType());
1491
1492 // (X << A) >> A -> X
1493 Value *X;
1494 if (Q.IIQ.UseInstrInfo && match(V: Op0, P: m_NSWShl(L: m_Value(V&: X), R: m_Specific(V: Op1))))
1495 return X;
1496
1497 // Arithmetic shifting an all-sign-bit value is a no-op.
1498 unsigned NumSignBits = ComputeNumSignBits(Op: Op0, DL: Q.DL, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT);
1499 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1500 return Op0;
1501
1502 return nullptr;
1503}
1504
1505Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1506 const SimplifyQuery &Q) {
1507 return ::simplifyAShrInst(Op0, Op1, IsExact, Q, MaxRecurse: RecursionLimit);
1508}
1509
1510/// Commuted variants are assumed to be handled by calling this function again
1511/// with the parameters swapped.
1512static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1513 ICmpInst *UnsignedICmp, bool IsAnd,
1514 const SimplifyQuery &Q) {
1515 Value *X, *Y;
1516
1517 CmpPredicate EqPred;
1518 if (!match(V: ZeroICmp, P: m_ICmp(Pred&: EqPred, L: m_Value(V&: Y), R: m_Zero())) ||
1519 !ICmpInst::isEquality(P: EqPred))
1520 return nullptr;
1521
1522 CmpPredicate UnsignedPred;
1523
1524 Value *A, *B;
1525 // Y = (A - B);
1526 if (match(V: Y, P: m_Sub(L: m_Value(V&: A), R: m_Value(V&: B)))) {
1527 if (match(V: UnsignedICmp,
1528 P: m_c_ICmp(Pred&: UnsignedPred, L: m_Specific(V: A), R: m_Specific(V: B))) &&
1529 ICmpInst::isUnsigned(predicate: UnsignedPred)) {
1530 // A >=/<= B || (A - B) != 0 <--> true
1531 if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1532 UnsignedPred == ICmpInst::ICMP_ULE) &&
1533 EqPred == ICmpInst::ICMP_NE && !IsAnd)
1534 return ConstantInt::getTrue(Ty: UnsignedICmp->getType());
1535 // A </> B && (A - B) == 0 <--> false
1536 if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1537 UnsignedPred == ICmpInst::ICMP_UGT) &&
1538 EqPred == ICmpInst::ICMP_EQ && IsAnd)
1539 return ConstantInt::getFalse(Ty: UnsignedICmp->getType());
1540
1541 // A </> B && (A - B) != 0 <--> A </> B
1542 // A </> B || (A - B) != 0 <--> (A - B) != 0
1543 if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1544 UnsignedPred == ICmpInst::ICMP_UGT))
1545 return IsAnd ? UnsignedICmp : ZeroICmp;
1546
1547 // A <=/>= B && (A - B) == 0 <--> (A - B) == 0
1548 // A <=/>= B || (A - B) == 0 <--> A <=/>= B
1549 if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1550 UnsignedPred == ICmpInst::ICMP_UGE))
1551 return IsAnd ? ZeroICmp : UnsignedICmp;
1552 }
1553
1554 // Given Y = (A - B)
1555 // Y >= A && Y != 0 --> Y >= A iff B != 0
1556 // Y < A || Y == 0 --> Y < A iff B != 0
1557 if (match(V: UnsignedICmp,
1558 P: m_c_ICmp(Pred&: UnsignedPred, L: m_Specific(V: Y), R: m_Specific(V: A)))) {
1559 if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1560 EqPred == ICmpInst::ICMP_NE && isKnownNonZero(V: B, Q))
1561 return UnsignedICmp;
1562 if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1563 EqPred == ICmpInst::ICMP_EQ && isKnownNonZero(V: B, Q))
1564 return UnsignedICmp;
1565 }
1566 }
1567
1568 if (match(V: UnsignedICmp, P: m_ICmp(Pred&: UnsignedPred, L: m_Value(V&: X), R: m_Specific(V: Y))) &&
1569 ICmpInst::isUnsigned(predicate: UnsignedPred))
1570 ;
1571 else if (match(V: UnsignedICmp,
1572 P: m_ICmp(Pred&: UnsignedPred, L: m_Specific(V: Y), R: m_Value(V&: X))) &&
1573 ICmpInst::isUnsigned(predicate: UnsignedPred))
1574 UnsignedPred = ICmpInst::getSwappedPredicate(pred: UnsignedPred);
1575 else
1576 return nullptr;
1577
1578 // X > Y && Y == 0 --> Y == 0 iff X != 0
1579 // X > Y || Y == 0 --> X > Y iff X != 0
1580 if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1581 isKnownNonZero(V: X, Q))
1582 return IsAnd ? ZeroICmp : UnsignedICmp;
1583
1584 // X <= Y && Y != 0 --> X <= Y iff X != 0
1585 // X <= Y || Y != 0 --> Y != 0 iff X != 0
1586 if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1587 isKnownNonZero(V: X, Q))
1588 return IsAnd ? UnsignedICmp : ZeroICmp;
1589
1590 // The transforms below here are expected to be handled more generally with
1591 // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1592 // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1593 // these are candidates for removal.
1594
1595 // X < Y && Y != 0 --> X < Y
1596 // X < Y || Y != 0 --> Y != 0
1597 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1598 return IsAnd ? UnsignedICmp : ZeroICmp;
1599
1600 // X >= Y && Y == 0 --> Y == 0
1601 // X >= Y || Y == 0 --> X >= Y
1602 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1603 return IsAnd ? ZeroICmp : UnsignedICmp;
1604
1605 // X < Y && Y == 0 --> false
1606 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1607 IsAnd)
1608 return getFalse(Ty: UnsignedICmp->getType());
1609
1610 // X >= Y || Y != 0 --> true
1611 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1612 !IsAnd)
1613 return getTrue(Ty: UnsignedICmp->getType());
1614
1615 return nullptr;
1616}
1617
1618/// Test if a pair of compares with a shared operand and 2 constants has an
1619/// empty set intersection, full set union, or if one compare is a superset of
1620/// the other.
1621static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1622 bool IsAnd) {
1623 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1624 if (Cmp0->getOperand(i_nocapture: 0) != Cmp1->getOperand(i_nocapture: 0))
1625 return nullptr;
1626
1627 const APInt *C0, *C1;
1628 if (!match(V: Cmp0->getOperand(i_nocapture: 1), P: m_APInt(Res&: C0)) ||
1629 !match(V: Cmp1->getOperand(i_nocapture: 1), P: m_APInt(Res&: C1)))
1630 return nullptr;
1631
1632 auto Range0 = ConstantRange::makeExactICmpRegion(Pred: Cmp0->getPredicate(), Other: *C0);
1633 auto Range1 = ConstantRange::makeExactICmpRegion(Pred: Cmp1->getPredicate(), Other: *C1);
1634
1635 // For and-of-compares, check if the intersection is empty:
1636 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1637 if (IsAnd && Range0.intersectWith(CR: Range1).isEmptySet())
1638 return getFalse(Ty: Cmp0->getType());
1639
1640 // For or-of-compares, check if the union is full:
1641 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1642 if (!IsAnd && Range0.unionWith(CR: Range1).isFullSet())
1643 return getTrue(Ty: Cmp0->getType());
1644
1645 // Is one range a superset of the other?
1646 // If this is and-of-compares, take the smaller set:
1647 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1648 // If this is or-of-compares, take the larger set:
1649 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1650 if (Range0.contains(CR: Range1))
1651 return IsAnd ? Cmp1 : Cmp0;
1652 if (Range1.contains(CR: Range0))
1653 return IsAnd ? Cmp0 : Cmp1;
1654
1655 return nullptr;
1656}
1657
1658static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1659 const InstrInfoQuery &IIQ) {
1660 // (icmp (add V, C0), C1) & (icmp V, C0)
1661 CmpPredicate Pred0, Pred1;
1662 const APInt *C0, *C1;
1663 Value *V;
1664 if (!match(V: Op0, P: m_ICmp(Pred&: Pred0, L: m_Add(L: m_Value(V), R: m_APInt(Res&: C0)), R: m_APInt(Res&: C1))))
1665 return nullptr;
1666
1667 if (!match(V: Op1, P: m_ICmp(Pred&: Pred1, L: m_Specific(V), R: m_Value())))
1668 return nullptr;
1669
1670 auto *AddInst = cast<OverflowingBinaryOperator>(Val: Op0->getOperand(i_nocapture: 0));
1671 if (AddInst->getOperand(i_nocapture: 1) != Op1->getOperand(i_nocapture: 1))
1672 return nullptr;
1673
1674 Type *ITy = Op0->getType();
1675 bool IsNSW = IIQ.hasNoSignedWrap(Op: AddInst);
1676 bool IsNUW = IIQ.hasNoUnsignedWrap(Op: AddInst);
1677
1678 const APInt Delta = *C1 - *C0;
1679 if (C0->isStrictlyPositive()) {
1680 if (Delta == 2) {
1681 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1682 return getFalse(Ty: ITy);
1683 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1684 return getFalse(Ty: ITy);
1685 }
1686 if (Delta == 1) {
1687 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1688 return getFalse(Ty: ITy);
1689 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1690 return getFalse(Ty: ITy);
1691 }
1692 }
1693 if (C0->getBoolValue() && IsNUW) {
1694 if (Delta == 2)
1695 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1696 return getFalse(Ty: ITy);
1697 if (Delta == 1)
1698 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1699 return getFalse(Ty: ITy);
1700 }
1701
1702 return nullptr;
1703}
1704
1705/// Try to simplify and/or of icmp with ctpop intrinsic.
1706static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
1707 bool IsAnd) {
1708 CmpPredicate Pred0, Pred1;
1709 Value *X;
1710 const APInt *C;
1711 if (!match(V: Cmp0, P: m_ICmp(Pred&: Pred0, L: m_Intrinsic<Intrinsic::ctpop>(Op0: m_Value(V&: X)),
1712 R: m_APInt(Res&: C))) ||
1713 !match(V: Cmp1, P: m_ICmp(Pred&: Pred1, L: m_Specific(V: X), R: m_ZeroInt())) || C->isZero())
1714 return nullptr;
1715
1716 // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
1717 if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
1718 return Cmp1;
1719 // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
1720 if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
1721 return Cmp1;
1722
1723 return nullptr;
1724}
1725
1726static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1727 const SimplifyQuery &Q) {
1728 if (Value *X = simplifyUnsignedRangeCheck(ZeroICmp: Op0, UnsignedICmp: Op1, /*IsAnd=*/true, Q))
1729 return X;
1730 if (Value *X = simplifyUnsignedRangeCheck(ZeroICmp: Op1, UnsignedICmp: Op0, /*IsAnd=*/true, Q))
1731 return X;
1732
1733 if (Value *X = simplifyAndOrOfICmpsWithConstants(Cmp0: Op0, Cmp1: Op1, IsAnd: true))
1734 return X;
1735
1736 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Cmp0: Op0, Cmp1: Op1, IsAnd: true))
1737 return X;
1738 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Cmp0: Op1, Cmp1: Op0, IsAnd: true))
1739 return X;
1740
1741 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, IIQ: Q.IIQ))
1742 return X;
1743 if (Value *X = simplifyAndOfICmpsWithAdd(Op0: Op1, Op1: Op0, IIQ: Q.IIQ))
1744 return X;
1745
1746 return nullptr;
1747}
1748
1749static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1750 const InstrInfoQuery &IIQ) {
1751 // (icmp (add V, C0), C1) | (icmp V, C0)
1752 CmpPredicate Pred0, Pred1;
1753 const APInt *C0, *C1;
1754 Value *V;
1755 if (!match(V: Op0, P: m_ICmp(Pred&: Pred0, L: m_Add(L: m_Value(V), R: m_APInt(Res&: C0)), R: m_APInt(Res&: C1))))
1756 return nullptr;
1757
1758 if (!match(V: Op1, P: m_ICmp(Pred&: Pred1, L: m_Specific(V), R: m_Value())))
1759 return nullptr;
1760
1761 auto *AddInst = cast<BinaryOperator>(Val: Op0->getOperand(i_nocapture: 0));
1762 if (AddInst->getOperand(i_nocapture: 1) != Op1->getOperand(i_nocapture: 1))
1763 return nullptr;
1764
1765 Type *ITy = Op0->getType();
1766 bool IsNSW = IIQ.hasNoSignedWrap(Op: AddInst);
1767 bool IsNUW = IIQ.hasNoUnsignedWrap(Op: AddInst);
1768
1769 const APInt Delta = *C1 - *C0;
1770 if (C0->isStrictlyPositive()) {
1771 if (Delta == 2) {
1772 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1773 return getTrue(Ty: ITy);
1774 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1775 return getTrue(Ty: ITy);
1776 }
1777 if (Delta == 1) {
1778 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1779 return getTrue(Ty: ITy);
1780 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1781 return getTrue(Ty: ITy);
1782 }
1783 }
1784 if (C0->getBoolValue() && IsNUW) {
1785 if (Delta == 2)
1786 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1787 return getTrue(Ty: ITy);
1788 if (Delta == 1)
1789 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1790 return getTrue(Ty: ITy);
1791 }
1792
1793 return nullptr;
1794}
1795
1796static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1797 const SimplifyQuery &Q) {
1798 if (Value *X = simplifyUnsignedRangeCheck(ZeroICmp: Op0, UnsignedICmp: Op1, /*IsAnd=*/false, Q))
1799 return X;
1800 if (Value *X = simplifyUnsignedRangeCheck(ZeroICmp: Op1, UnsignedICmp: Op0, /*IsAnd=*/false, Q))
1801 return X;
1802
1803 if (Value *X = simplifyAndOrOfICmpsWithConstants(Cmp0: Op0, Cmp1: Op1, IsAnd: false))
1804 return X;
1805
1806 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Cmp0: Op0, Cmp1: Op1, IsAnd: false))
1807 return X;
1808 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Cmp0: Op1, Cmp1: Op0, IsAnd: false))
1809 return X;
1810
1811 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, IIQ: Q.IIQ))
1812 return X;
1813 if (Value *X = simplifyOrOfICmpsWithAdd(Op0: Op1, Op1: Op0, IIQ: Q.IIQ))
1814 return X;
1815
1816 return nullptr;
1817}
1818
1819/// Test if a pair of compares with a shared operand and 2 constants has an
1820/// empty set intersection, full set union, or if one compare is a superset of
1821/// the other.
1822static Value *simplifyAndOrOfFCmpsWithConstants(FCmpInst *Cmp0, FCmpInst *Cmp1,
1823 bool IsAnd) {
1824 // Look for this pattern: {and/or} (fcmp X, C0), (fcmp X, C1)).
1825 if (Cmp0->getOperand(i_nocapture: 0) != Cmp1->getOperand(i_nocapture: 0))
1826 return nullptr;
1827
1828 const APFloat *C0, *C1;
1829 if (!match(V: Cmp0->getOperand(i_nocapture: 1), P: m_APFloat(Res&: C0)) ||
1830 !match(V: Cmp1->getOperand(i_nocapture: 1), P: m_APFloat(Res&: C1)))
1831 return nullptr;
1832
1833 auto Range0 = ConstantFPRange::makeExactFCmpRegion(
1834 Pred: IsAnd ? Cmp0->getPredicate() : Cmp0->getInversePredicate(), Other: *C0);
1835 auto Range1 = ConstantFPRange::makeExactFCmpRegion(
1836 Pred: IsAnd ? Cmp1->getPredicate() : Cmp1->getInversePredicate(), Other: *C1);
1837
1838 if (!Range0 || !Range1)
1839 return nullptr;
1840
1841 // For and-of-compares, check if the intersection is empty:
1842 // (fcmp X, C0) && (fcmp X, C1) --> empty set --> false
1843 if (Range0->intersectWith(CR: *Range1).isEmptySet())
1844 return ConstantInt::getBool(Ty: Cmp0->getType(), V: !IsAnd);
1845
1846 // Is one range a superset of the other?
1847 // If this is and-of-compares, take the smaller set:
1848 // (fcmp ogt X, 4) && (fcmp ogt X, 42) --> fcmp ogt X, 42
1849 // If this is or-of-compares, take the larger set:
1850 // (fcmp ogt X, 4) || (fcmp ogt X, 42) --> fcmp ogt X, 4
1851 if (Range0->contains(CR: *Range1))
1852 return Cmp1;
1853 if (Range1->contains(CR: *Range0))
1854 return Cmp0;
1855
1856 return nullptr;
1857}
1858
1859static Value *simplifyAndOrOfFCmps(const SimplifyQuery &Q, FCmpInst *LHS,
1860 FCmpInst *RHS, bool IsAnd) {
1861 Value *LHS0 = LHS->getOperand(i_nocapture: 0), *LHS1 = LHS->getOperand(i_nocapture: 1);
1862 Value *RHS0 = RHS->getOperand(i_nocapture: 0), *RHS1 = RHS->getOperand(i_nocapture: 1);
1863 if (LHS0->getType() != RHS0->getType())
1864 return nullptr;
1865
1866 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1867 auto AbsOrSelfLHS0 = m_CombineOr(L: m_Specific(V: LHS0), R: m_FAbs(Op0: m_Specific(V: LHS0)));
1868 if ((PredL == FCmpInst::FCMP_ORD || PredL == FCmpInst::FCMP_UNO) &&
1869 ((FCmpInst::isOrdered(predicate: PredR) && IsAnd) ||
1870 (FCmpInst::isUnordered(predicate: PredR) && !IsAnd))) {
1871 // (fcmp ord X, 0) & (fcmp o** X/abs(X), Y) --> fcmp o** X/abs(X), Y
1872 // (fcmp uno X, 0) & (fcmp o** X/abs(X), Y) --> false
1873 // (fcmp uno X, 0) | (fcmp u** X/abs(X), Y) --> fcmp u** X/abs(X), Y
1874 // (fcmp ord X, 0) | (fcmp u** X/abs(X), Y) --> true
1875 if ((match(V: RHS0, P: AbsOrSelfLHS0) || match(V: RHS1, P: AbsOrSelfLHS0)) &&
1876 match(V: LHS1, P: m_PosZeroFP()))
1877 return FCmpInst::isOrdered(predicate: PredL) == FCmpInst::isOrdered(predicate: PredR)
1878 ? static_cast<Value *>(RHS)
1879 : ConstantInt::getBool(Ty: LHS->getType(), V: !IsAnd);
1880 }
1881
1882 auto AbsOrSelfRHS0 = m_CombineOr(L: m_Specific(V: RHS0), R: m_FAbs(Op0: m_Specific(V: RHS0)));
1883 if ((PredR == FCmpInst::FCMP_ORD || PredR == FCmpInst::FCMP_UNO) &&
1884 ((FCmpInst::isOrdered(predicate: PredL) && IsAnd) ||
1885 (FCmpInst::isUnordered(predicate: PredL) && !IsAnd))) {
1886 // (fcmp o** X/abs(X), Y) & (fcmp ord X, 0) --> fcmp o** X/abs(X), Y
1887 // (fcmp o** X/abs(X), Y) & (fcmp uno X, 0) --> false
1888 // (fcmp u** X/abs(X), Y) | (fcmp uno X, 0) --> fcmp u** X/abs(X), Y
1889 // (fcmp u** X/abs(X), Y) | (fcmp ord X, 0) --> true
1890 if ((match(V: LHS0, P: AbsOrSelfRHS0) || match(V: LHS1, P: AbsOrSelfRHS0)) &&
1891 match(V: RHS1, P: m_PosZeroFP()))
1892 return FCmpInst::isOrdered(predicate: PredL) == FCmpInst::isOrdered(predicate: PredR)
1893 ? static_cast<Value *>(LHS)
1894 : ConstantInt::getBool(Ty: LHS->getType(), V: !IsAnd);
1895 }
1896
1897 if (auto *V = simplifyAndOrOfFCmpsWithConstants(Cmp0: LHS, Cmp1: RHS, IsAnd))
1898 return V;
1899
1900 return nullptr;
1901}
1902
1903static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0,
1904 Value *Op1, bool IsAnd) {
1905 // Look through casts of the 'and' operands to find compares.
1906 auto *Cast0 = dyn_cast<CastInst>(Val: Op0);
1907 auto *Cast1 = dyn_cast<CastInst>(Val: Op1);
1908 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1909 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1910 Op0 = Cast0->getOperand(i_nocapture: 0);
1911 Op1 = Cast1->getOperand(i_nocapture: 0);
1912 }
1913
1914 Value *V = nullptr;
1915 auto *ICmp0 = dyn_cast<ICmpInst>(Val: Op0);
1916 auto *ICmp1 = dyn_cast<ICmpInst>(Val: Op1);
1917 if (ICmp0 && ICmp1)
1918 V = IsAnd ? simplifyAndOfICmps(Op0: ICmp0, Op1: ICmp1, Q)
1919 : simplifyOrOfICmps(Op0: ICmp0, Op1: ICmp1, Q);
1920
1921 auto *FCmp0 = dyn_cast<FCmpInst>(Val: Op0);
1922 auto *FCmp1 = dyn_cast<FCmpInst>(Val: Op1);
1923 if (FCmp0 && FCmp1)
1924 V = simplifyAndOrOfFCmps(Q, LHS: FCmp0, RHS: FCmp1, IsAnd);
1925
1926 if (!V)
1927 return nullptr;
1928 if (!Cast0)
1929 return V;
1930
1931 // If we looked through casts, we can only handle a constant simplification
1932 // because we are not allowed to create a cast instruction here.
1933 if (auto *C = dyn_cast<Constant>(Val: V))
1934 return ConstantFoldCastOperand(Opcode: Cast0->getOpcode(), C, DestTy: Cast0->getType(),
1935 DL: Q.DL);
1936
1937 return nullptr;
1938}
1939
1940static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
1941 const SimplifyQuery &Q,
1942 bool AllowRefinement,
1943 SmallVectorImpl<Instruction *> *DropFlags,
1944 unsigned MaxRecurse);
1945
1946static Value *simplifyAndOrWithICmpEq(unsigned Opcode, Value *Op0, Value *Op1,
1947 const SimplifyQuery &Q,
1948 unsigned MaxRecurse) {
1949 assert((Opcode == Instruction::And || Opcode == Instruction::Or) &&
1950 "Must be and/or");
1951 CmpPredicate Pred;
1952 Value *A, *B;
1953 if (!match(V: Op0, P: m_ICmp(Pred, L: m_Value(V&: A), R: m_Value(V&: B))) ||
1954 !ICmpInst::isEquality(P: Pred))
1955 return nullptr;
1956
1957 auto Simplify = [&](Value *Res) -> Value * {
1958 Constant *Absorber = ConstantExpr::getBinOpAbsorber(Opcode, Ty: Res->getType());
1959
1960 // and (icmp eq a, b), x implies (a==b) inside x.
1961 // or (icmp ne a, b), x implies (a==b) inside x.
1962 // If x simplifies to true/false, we can simplify the and/or.
1963 if (Pred ==
1964 (Opcode == Instruction::And ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
1965 if (Res == Absorber)
1966 return Absorber;
1967 if (Res == ConstantExpr::getBinOpIdentity(Opcode, Ty: Res->getType()))
1968 return Op0;
1969 return nullptr;
1970 }
1971
1972 // If we have and (icmp ne a, b), x and for a==b we can simplify x to false,
1973 // then we can drop the icmp, as x will already be false in the case where
1974 // the icmp is false. Similar for or and true.
1975 if (Res == Absorber)
1976 return Op1;
1977 return nullptr;
1978 };
1979
1980 // In the final case (Res == Absorber with inverted predicate), it is safe to
1981 // refine poison during simplification, but not undef. For simplicity always
1982 // disable undef-based folds here.
1983 if (Value *Res = simplifyWithOpReplaced(V: Op1, Op: A, RepOp: B, Q: Q.getWithoutUndef(),
1984 /* AllowRefinement */ true,
1985 /* DropFlags */ nullptr, MaxRecurse))
1986 return Simplify(Res);
1987 if (Value *Res = simplifyWithOpReplaced(V: Op1, Op: B, RepOp: A, Q: Q.getWithoutUndef(),
1988 /* AllowRefinement */ true,
1989 /* DropFlags */ nullptr, MaxRecurse))
1990 return Simplify(Res);
1991
1992 return nullptr;
1993}
1994
1995/// Given a bitwise logic op, check if the operands are add/sub with a common
1996/// source value and inverted constant (identity: C - X -> ~(X + ~C)).
1997static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
1998 Instruction::BinaryOps Opcode) {
1999 assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
2000 assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
2001 Value *X;
2002 Constant *C1, *C2;
2003 if ((match(V: Op0, P: m_Add(L: m_Value(V&: X), R: m_Constant(C&: C1))) &&
2004 match(V: Op1, P: m_Sub(L: m_Constant(C&: C2), R: m_Specific(V: X)))) ||
2005 (match(V: Op1, P: m_Add(L: m_Value(V&: X), R: m_Constant(C&: C1))) &&
2006 match(V: Op0, P: m_Sub(L: m_Constant(C&: C2), R: m_Specific(V: X))))) {
2007 if (ConstantExpr::getNot(C: C1) == C2) {
2008 // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
2009 // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
2010 // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
2011 Type *Ty = Op0->getType();
2012 return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
2013 : ConstantInt::getAllOnesValue(Ty);
2014 }
2015 }
2016 return nullptr;
2017}
2018
2019// Commutative patterns for and that will be tried with both operand orders.
2020static Value *simplifyAndCommutative(Value *Op0, Value *Op1,
2021 const SimplifyQuery &Q,
2022 unsigned MaxRecurse) {
2023 // ~A & A = 0
2024 if (match(V: Op0, P: m_Not(V: m_Specific(V: Op1))))
2025 return Constant::getNullValue(Ty: Op0->getType());
2026
2027 // (A | ?) & A = A
2028 if (match(V: Op0, P: m_c_Or(L: m_Specific(V: Op1), R: m_Value())))
2029 return Op1;
2030
2031 // (X | ~Y) & (X | Y) --> X
2032 Value *X, *Y;
2033 if (match(V: Op0, P: m_c_Or(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
2034 match(V: Op1, P: m_c_Or(L: m_Specific(V: X), R: m_Specific(V: Y))))
2035 return X;
2036
2037 // If we have a multiplication overflow check that is being 'and'ed with a
2038 // check that one of the multipliers is not zero, we can omit the 'and', and
2039 // only keep the overflow check.
2040 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, IsAnd: true))
2041 return Op1;
2042
2043 // -A & A = A if A is a power of two or zero.
2044 if (match(V: Op0, P: m_Neg(V: m_Specific(V: Op1))) &&
2045 isKnownToBeAPowerOfTwo(V: Op1, DL: Q.DL, /*OrZero*/ true, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT))
2046 return Op1;
2047
2048 // This is a similar pattern used for checking if a value is a power-of-2:
2049 // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2050 if (match(V: Op0, P: m_Add(L: m_Specific(V: Op1), R: m_AllOnes())) &&
2051 isKnownToBeAPowerOfTwo(V: Op1, DL: Q.DL, /*OrZero*/ true, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT))
2052 return Constant::getNullValue(Ty: Op1->getType());
2053
2054 // (x << N) & ((x << M) - 1) --> 0, where x is known to be a power of 2 and
2055 // M <= N.
2056 const APInt *Shift1, *Shift2;
2057 if (match(V: Op0, P: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: Shift1))) &&
2058 match(V: Op1, P: m_Add(L: m_Shl(L: m_Specific(V: X), R: m_APInt(Res&: Shift2)), R: m_AllOnes())) &&
2059 isKnownToBeAPowerOfTwo(V: X, DL: Q.DL, /*OrZero*/ true, AC: Q.AC, CxtI: Q.CxtI) &&
2060 Shift1->uge(RHS: *Shift2))
2061 return Constant::getNullValue(Ty: Op0->getType());
2062
2063 if (Value *V =
2064 simplifyAndOrWithICmpEq(Opcode: Instruction::And, Op0, Op1, Q, MaxRecurse))
2065 return V;
2066
2067 return nullptr;
2068}
2069
2070/// Given operands for an And, see if we can fold the result.
2071/// If not, this returns null.
2072static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2073 unsigned MaxRecurse) {
2074 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::And, Op0, Op1, Q))
2075 return C;
2076
2077 // X & poison -> poison
2078 if (isa<PoisonValue>(Val: Op1))
2079 return Op1;
2080
2081 // X & undef -> 0
2082 if (Q.isUndefValue(V: Op1))
2083 return Constant::getNullValue(Ty: Op0->getType());
2084
2085 // X & X = X
2086 if (Op0 == Op1)
2087 return Op0;
2088
2089 // X & 0 = 0
2090 if (match(V: Op1, P: m_Zero()))
2091 return Constant::getNullValue(Ty: Op0->getType());
2092
2093 // X & -1 = X
2094 if (match(V: Op1, P: m_AllOnes()))
2095 return Op0;
2096
2097 if (Value *Res = simplifyAndCommutative(Op0, Op1, Q, MaxRecurse))
2098 return Res;
2099 if (Value *Res = simplifyAndCommutative(Op0: Op1, Op1: Op0, Q, MaxRecurse))
2100 return Res;
2101
2102 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Opcode: Instruction::And))
2103 return V;
2104
2105 // A mask that only clears known zeros of a shifted value is a no-op.
2106 const APInt *Mask;
2107 const APInt *ShAmt;
2108 Value *X, *Y;
2109 if (match(V: Op1, P: m_APInt(Res&: Mask))) {
2110 // If all bits in the inverted and shifted mask are clear:
2111 // and (shl X, ShAmt), Mask --> shl X, ShAmt
2112 if (match(V: Op0, P: m_Shl(L: m_Value(V&: X), R: m_APInt(Res&: ShAmt))) &&
2113 (~(*Mask)).lshr(ShiftAmt: *ShAmt).isZero())
2114 return Op0;
2115
2116 // If all bits in the inverted and shifted mask are clear:
2117 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2118 if (match(V: Op0, P: m_LShr(L: m_Value(V&: X), R: m_APInt(Res&: ShAmt))) &&
2119 (~(*Mask)).shl(ShiftAmt: *ShAmt).isZero())
2120 return Op0;
2121 }
2122
2123 // and 2^x-1, 2^C --> 0 where x <= C.
2124 const APInt *PowerC;
2125 Value *Shift;
2126 if (match(V: Op1, P: m_Power2(V&: PowerC)) &&
2127 match(V: Op0, P: m_Add(L: m_Value(V&: Shift), R: m_AllOnes())) &&
2128 isKnownToBeAPowerOfTwo(V: Shift, DL: Q.DL, /*OrZero*/ false, AC: Q.AC, CxtI: Q.CxtI,
2129 DT: Q.DT)) {
2130 KnownBits Known = computeKnownBits(V: Shift, Q);
2131 // Use getActiveBits() to make use of the additional power of two knowledge
2132 if (PowerC->getActiveBits() >= Known.getMaxValue().getActiveBits())
2133 return ConstantInt::getNullValue(Ty: Op1->getType());
2134 }
2135
2136 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, IsAnd: true))
2137 return V;
2138
2139 // Try some generic simplifications for associative operations.
2140 if (Value *V =
2141 simplifyAssociativeBinOp(Opcode: Instruction::And, LHS: Op0, RHS: Op1, Q, MaxRecurse))
2142 return V;
2143
2144 // And distributes over Or. Try some generic simplifications based on this.
2145 if (Value *V = expandCommutativeBinOp(Opcode: Instruction::And, L: Op0, R: Op1,
2146 OpcodeToExpand: Instruction::Or, Q, MaxRecurse))
2147 return V;
2148
2149 // And distributes over Xor. Try some generic simplifications based on this.
2150 if (Value *V = expandCommutativeBinOp(Opcode: Instruction::And, L: Op0, R: Op1,
2151 OpcodeToExpand: Instruction::Xor, Q, MaxRecurse))
2152 return V;
2153
2154 if (isa<SelectInst>(Val: Op0) || isa<SelectInst>(Val: Op1)) {
2155 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2156 // A & (A && B) -> A && B
2157 if (match(V: Op1, P: m_Select(C: m_Specific(V: Op0), L: m_Value(), R: m_Zero())))
2158 return Op1;
2159 else if (match(V: Op0, P: m_Select(C: m_Specific(V: Op1), L: m_Value(), R: m_Zero())))
2160 return Op0;
2161 }
2162 // If the operation is with the result of a select instruction, check
2163 // whether operating on either branch of the select always yields the same
2164 // value.
2165 if (Value *V =
2166 threadBinOpOverSelect(Opcode: Instruction::And, LHS: Op0, RHS: Op1, Q, MaxRecurse))
2167 return V;
2168 }
2169
2170 // If the operation is with the result of a phi instruction, check whether
2171 // operating on all incoming values of the phi always yields the same value.
2172 if (isa<PHINode>(Val: Op0) || isa<PHINode>(Val: Op1))
2173 if (Value *V =
2174 threadBinOpOverPHI(Opcode: Instruction::And, LHS: Op0, RHS: Op1, Q, MaxRecurse))
2175 return V;
2176
2177 // Assuming the effective width of Y is not larger than A, i.e. all bits
2178 // from X and Y are disjoint in (X << A) | Y,
2179 // if the mask of this AND op covers all bits of X or Y, while it covers
2180 // no bits from the other, we can bypass this AND op. E.g.,
2181 // ((X << A) | Y) & Mask -> Y,
2182 // if Mask = ((1 << effective_width_of(Y)) - 1)
2183 // ((X << A) | Y) & Mask -> X << A,
2184 // if Mask = ((1 << effective_width_of(X)) - 1) << A
2185 // SimplifyDemandedBits in InstCombine can optimize the general case.
2186 // This pattern aims to help other passes for a common case.
2187 Value *XShifted;
2188 if (Q.IIQ.UseInstrInfo && match(V: Op1, P: m_APInt(Res&: Mask)) &&
2189 match(V: Op0, P: m_c_Or(L: m_CombineAnd(L: m_NUWShl(L: m_Value(V&: X), R: m_APInt(Res&: ShAmt)),
2190 R: m_Value(V&: XShifted)),
2191 R: m_Value(V&: Y)))) {
2192 const unsigned Width = Op0->getType()->getScalarSizeInBits();
2193 const unsigned ShftCnt = ShAmt->getLimitedValue(Limit: Width);
2194 const KnownBits YKnown = computeKnownBits(V: Y, Q);
2195 const unsigned EffWidthY = YKnown.countMaxActiveBits();
2196 if (EffWidthY <= ShftCnt) {
2197 const KnownBits XKnown = computeKnownBits(V: X, Q);
2198 const unsigned EffWidthX = XKnown.countMaxActiveBits();
2199 const APInt EffBitsY = APInt::getLowBitsSet(numBits: Width, loBitsSet: EffWidthY);
2200 const APInt EffBitsX = APInt::getLowBitsSet(numBits: Width, loBitsSet: EffWidthX) << ShftCnt;
2201 // If the mask is extracting all bits from X or Y as is, we can skip
2202 // this AND op.
2203 if (EffBitsY.isSubsetOf(RHS: *Mask) && !EffBitsX.intersects(RHS: *Mask))
2204 return Y;
2205 if (EffBitsX.isSubsetOf(RHS: *Mask) && !EffBitsY.intersects(RHS: *Mask))
2206 return XShifted;
2207 }
2208 }
2209
2210 // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2211 // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2212 BinaryOperator *Or;
2213 if (match(V: Op0, P: m_c_Xor(L: m_Value(V&: X),
2214 R: m_CombineAnd(L: m_BinOp(I&: Or),
2215 R: m_c_Or(L: m_Deferred(V: X), R: m_Value(V&: Y))))) &&
2216 match(V: Op1, P: m_c_Xor(L: m_Specific(V: Or), R: m_Specific(V: Y))))
2217 return Constant::getNullValue(Ty: Op0->getType());
2218
2219 const APInt *C1;
2220 Value *A;
2221 // (A ^ C) & (A ^ ~C) -> 0
2222 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_APInt(Res&: C1))) &&
2223 match(V: Op1, P: m_Xor(L: m_Specific(V: A), R: m_SpecificInt(V: ~*C1))))
2224 return Constant::getNullValue(Ty: Op0->getType());
2225
2226 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2227 if (std::optional<bool> Implied = isImpliedCondition(LHS: Op0, RHS: Op1, DL: Q.DL)) {
2228 // If Op0 is true implies Op1 is true, then Op0 is a subset of Op1.
2229 if (*Implied == true)
2230 return Op0;
2231 // If Op0 is true implies Op1 is false, then they are not true together.
2232 if (*Implied == false)
2233 return ConstantInt::getFalse(Ty: Op0->getType());
2234 }
2235 if (std::optional<bool> Implied = isImpliedCondition(LHS: Op1, RHS: Op0, DL: Q.DL)) {
2236 // If Op1 is true implies Op0 is true, then Op1 is a subset of Op0.
2237 if (*Implied)
2238 return Op1;
2239 // If Op1 is true implies Op0 is false, then they are not true together.
2240 if (!*Implied)
2241 return ConstantInt::getFalse(Ty: Op1->getType());
2242 }
2243 }
2244
2245 if (Value *V = simplifyByDomEq(Opcode: Instruction::And, Op0, Op1, Q, MaxRecurse))
2246 return V;
2247
2248 return nullptr;
2249}
2250
2251Value *llvm::simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2252 return ::simplifyAndInst(Op0, Op1, Q, MaxRecurse: RecursionLimit);
2253}
2254
2255// TODO: Many of these folds could use LogicalAnd/LogicalOr.
2256static Value *simplifyOrLogic(Value *X, Value *Y) {
2257 assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2258 Type *Ty = X->getType();
2259
2260 // X | ~X --> -1
2261 if (match(V: Y, P: m_Not(V: m_Specific(V: X))))
2262 return ConstantInt::getAllOnesValue(Ty);
2263
2264 // X | ~(X & ?) = -1
2265 if (match(V: Y, P: m_Not(V: m_c_And(L: m_Specific(V: X), R: m_Value()))))
2266 return ConstantInt::getAllOnesValue(Ty);
2267
2268 // X | (X & ?) --> X
2269 if (match(V: Y, P: m_c_And(L: m_Specific(V: X), R: m_Value())))
2270 return X;
2271
2272 Value *A, *B;
2273
2274 // (A ^ B) | (A | B) --> A | B
2275 // (A ^ B) | (B | A) --> B | A
2276 if (match(V: X, P: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))) &&
2277 match(V: Y, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2278 return Y;
2279
2280 // ~(A ^ B) | (A | B) --> -1
2281 // ~(A ^ B) | (B | A) --> -1
2282 if (match(V: X, P: m_Not(V: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B)))) &&
2283 match(V: Y, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2284 return ConstantInt::getAllOnesValue(Ty);
2285
2286 // (A & ~B) | (A ^ B) --> A ^ B
2287 // (~B & A) | (A ^ B) --> A ^ B
2288 // (A & ~B) | (B ^ A) --> B ^ A
2289 // (~B & A) | (B ^ A) --> B ^ A
2290 if (match(V: X, P: m_c_And(L: m_Value(V&: A), R: m_Not(V: m_Value(V&: B)))) &&
2291 match(V: Y, P: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: B))))
2292 return Y;
2293
2294 // (~A ^ B) | (A & B) --> ~A ^ B
2295 // (B ^ ~A) | (A & B) --> B ^ ~A
2296 // (~A ^ B) | (B & A) --> ~A ^ B
2297 // (B ^ ~A) | (B & A) --> B ^ ~A
2298 if (match(V: X, P: m_c_Xor(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B))) &&
2299 match(V: Y, P: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))
2300 return X;
2301
2302 // (~A | B) | (A ^ B) --> -1
2303 // (~A | B) | (B ^ A) --> -1
2304 // (B | ~A) | (A ^ B) --> -1
2305 // (B | ~A) | (B ^ A) --> -1
2306 if (match(V: X, P: m_c_Or(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B))) &&
2307 match(V: Y, P: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: B))))
2308 return ConstantInt::getAllOnesValue(Ty);
2309
2310 // (~A & B) | ~(A | B) --> ~A
2311 // (~A & B) | ~(B | A) --> ~A
2312 // (B & ~A) | ~(A | B) --> ~A
2313 // (B & ~A) | ~(B | A) --> ~A
2314 Value *NotA;
2315 if (match(V: X, P: m_c_And(L: m_CombineAnd(L: m_Value(V&: NotA), R: m_Not(V: m_Value(V&: A))),
2316 R: m_Value(V&: B))) &&
2317 match(V: Y, P: m_Not(V: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B)))))
2318 return NotA;
2319 // The same is true of Logical And
2320 // TODO: This could share the logic of the version above if there was a
2321 // version of LogicalAnd that allowed more than just i1 types.
2322 if (match(V: X, P: m_c_LogicalAnd(L: m_CombineAnd(L: m_Value(V&: NotA), R: m_Not(V: m_Value(V&: A))),
2323 R: m_Value(V&: B))) &&
2324 match(V: Y, P: m_Not(V: m_c_LogicalOr(L: m_Specific(V: A), R: m_Specific(V: B)))))
2325 return NotA;
2326
2327 // ~(A ^ B) | (A & B) --> ~(A ^ B)
2328 // ~(A ^ B) | (B & A) --> ~(A ^ B)
2329 Value *NotAB;
2330 if (match(V: X, P: m_CombineAnd(L: m_Not(V: m_Xor(L: m_Value(V&: A), R: m_Value(V&: B))),
2331 R: m_Value(V&: NotAB))) &&
2332 match(V: Y, P: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))
2333 return NotAB;
2334
2335 // ~(A & B) | (A ^ B) --> ~(A & B)
2336 // ~(A & B) | (B ^ A) --> ~(A & B)
2337 if (match(V: X, P: m_CombineAnd(L: m_Not(V: m_And(L: m_Value(V&: A), R: m_Value(V&: B))),
2338 R: m_Value(V&: NotAB))) &&
2339 match(V: Y, P: m_c_Xor(L: m_Specific(V: A), R: m_Specific(V: B))))
2340 return NotAB;
2341
2342 return nullptr;
2343}
2344
2345/// Given operands for an Or, see if we can fold the result.
2346/// If not, this returns null.
2347static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2348 unsigned MaxRecurse) {
2349 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::Or, Op0, Op1, Q))
2350 return C;
2351
2352 // X | poison -> poison
2353 if (isa<PoisonValue>(Val: Op1))
2354 return Op1;
2355
2356 // X | undef -> -1
2357 // X | -1 = -1
2358 // Do not return Op1 because it may contain undef elements if it's a vector.
2359 if (Q.isUndefValue(V: Op1) || match(V: Op1, P: m_AllOnes()))
2360 return Constant::getAllOnesValue(Ty: Op0->getType());
2361
2362 // X | X = X
2363 // X | 0 = X
2364 if (Op0 == Op1 || match(V: Op1, P: m_Zero()))
2365 return Op0;
2366
2367 if (Value *R = simplifyOrLogic(X: Op0, Y: Op1))
2368 return R;
2369 if (Value *R = simplifyOrLogic(X: Op1, Y: Op0))
2370 return R;
2371
2372 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Opcode: Instruction::Or))
2373 return V;
2374
2375 // Rotated -1 is still -1:
2376 // (-1 << X) | (-1 >> (C - X)) --> -1
2377 // (-1 >> X) | (-1 << (C - X)) --> -1
2378 // ...with C <= bitwidth (and commuted variants).
2379 Value *X, *Y;
2380 if ((match(V: Op0, P: m_Shl(L: m_AllOnes(), R: m_Value(V&: X))) &&
2381 match(V: Op1, P: m_LShr(L: m_AllOnes(), R: m_Value(V&: Y)))) ||
2382 (match(V: Op1, P: m_Shl(L: m_AllOnes(), R: m_Value(V&: X))) &&
2383 match(V: Op0, P: m_LShr(L: m_AllOnes(), R: m_Value(V&: Y))))) {
2384 const APInt *C;
2385 if ((match(V: X, P: m_Sub(L: m_APInt(Res&: C), R: m_Specific(V: Y))) ||
2386 match(V: Y, P: m_Sub(L: m_APInt(Res&: C), R: m_Specific(V: X)))) &&
2387 C->ule(RHS: X->getType()->getScalarSizeInBits())) {
2388 return ConstantInt::getAllOnesValue(Ty: X->getType());
2389 }
2390 }
2391
2392 // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2393 // are mixing in another shift that is redundant with the funnel shift.
2394
2395 // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2396 // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2397 if (match(V: Op0,
2398 P: m_Intrinsic<Intrinsic::fshl>(Op0: m_Value(V&: X), Op1: m_Value(), Op2: m_Value(V&: Y))) &&
2399 match(V: Op1, P: m_Shl(L: m_Specific(V: X), R: m_Specific(V: Y))))
2400 return Op0;
2401 if (match(V: Op1,
2402 P: m_Intrinsic<Intrinsic::fshl>(Op0: m_Value(V&: X), Op1: m_Value(), Op2: m_Value(V&: Y))) &&
2403 match(V: Op0, P: m_Shl(L: m_Specific(V: X), R: m_Specific(V: Y))))
2404 return Op1;
2405
2406 // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2407 // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2408 if (match(V: Op0,
2409 P: m_Intrinsic<Intrinsic::fshr>(Op0: m_Value(), Op1: m_Value(V&: X), Op2: m_Value(V&: Y))) &&
2410 match(V: Op1, P: m_LShr(L: m_Specific(V: X), R: m_Specific(V: Y))))
2411 return Op0;
2412 if (match(V: Op1,
2413 P: m_Intrinsic<Intrinsic::fshr>(Op0: m_Value(), Op1: m_Value(V&: X), Op2: m_Value(V&: Y))) &&
2414 match(V: Op0, P: m_LShr(L: m_Specific(V: X), R: m_Specific(V: Y))))
2415 return Op1;
2416
2417 if (Value *V =
2418 simplifyAndOrWithICmpEq(Opcode: Instruction::Or, Op0, Op1, Q, MaxRecurse))
2419 return V;
2420 if (Value *V =
2421 simplifyAndOrWithICmpEq(Opcode: Instruction::Or, Op0: Op1, Op1: Op0, Q, MaxRecurse))
2422 return V;
2423
2424 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, IsAnd: false))
2425 return V;
2426
2427 // If we have a multiplication overflow check that is being 'and'ed with a
2428 // check that one of the multipliers is not zero, we can omit the 'and', and
2429 // only keep the overflow check.
2430 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, IsAnd: false))
2431 return Op1;
2432 if (isCheckForZeroAndMulWithOverflow(Op0: Op1, Op1: Op0, IsAnd: false))
2433 return Op0;
2434
2435 // Try some generic simplifications for associative operations.
2436 if (Value *V =
2437 simplifyAssociativeBinOp(Opcode: Instruction::Or, LHS: Op0, RHS: Op1, Q, MaxRecurse))
2438 return V;
2439
2440 // Or distributes over And. Try some generic simplifications based on this.
2441 if (Value *V = expandCommutativeBinOp(Opcode: Instruction::Or, L: Op0, R: Op1,
2442 OpcodeToExpand: Instruction::And, Q, MaxRecurse))
2443 return V;
2444
2445 if (isa<SelectInst>(Val: Op0) || isa<SelectInst>(Val: Op1)) {
2446 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2447 // A | (A || B) -> A || B
2448 if (match(V: Op1, P: m_Select(C: m_Specific(V: Op0), L: m_One(), R: m_Value())))
2449 return Op1;
2450 else if (match(V: Op0, P: m_Select(C: m_Specific(V: Op1), L: m_One(), R: m_Value())))
2451 return Op0;
2452 }
2453 // If the operation is with the result of a select instruction, check
2454 // whether operating on either branch of the select always yields the same
2455 // value.
2456 if (Value *V =
2457 threadBinOpOverSelect(Opcode: Instruction::Or, LHS: Op0, RHS: Op1, Q, MaxRecurse))
2458 return V;
2459 }
2460
2461 // (A & C1)|(B & C2)
2462 Value *A, *B;
2463 const APInt *C1, *C2;
2464 if (match(V: Op0, P: m_And(L: m_Value(V&: A), R: m_APInt(Res&: C1))) &&
2465 match(V: Op1, P: m_And(L: m_Value(V&: B), R: m_APInt(Res&: C2)))) {
2466 if (*C1 == ~*C2) {
2467 // (A & C1)|(B & C2)
2468 // If we have: ((V + N) & C1) | (V & C2)
2469 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2470 // replace with V+N.
2471 Value *N;
2472 if (C2->isMask() && // C2 == 0+1+
2473 match(V: A, P: m_c_Add(L: m_Specific(V: B), R: m_Value(V&: N)))) {
2474 // Add commutes, try both ways.
2475 if (MaskedValueIsZero(V: N, Mask: *C2, SQ: Q))
2476 return A;
2477 }
2478 // Or commutes, try both ways.
2479 if (C1->isMask() && match(V: B, P: m_c_Add(L: m_Specific(V: A), R: m_Value(V&: N)))) {
2480 // Add commutes, try both ways.
2481 if (MaskedValueIsZero(V: N, Mask: *C1, SQ: Q))
2482 return B;
2483 }
2484 }
2485 }
2486
2487 // If the operation is with the result of a phi instruction, check whether
2488 // operating on all incoming values of the phi always yields the same value.
2489 if (isa<PHINode>(Val: Op0) || isa<PHINode>(Val: Op1))
2490 if (Value *V = threadBinOpOverPHI(Opcode: Instruction::Or, LHS: Op0, RHS: Op1, Q, MaxRecurse))
2491 return V;
2492
2493 // (A ^ C) | (A ^ ~C) -> -1, i.e. all bits set to one.
2494 if (match(V: Op0, P: m_Xor(L: m_Value(V&: A), R: m_APInt(Res&: C1))) &&
2495 match(V: Op1, P: m_Xor(L: m_Specific(V: A), R: m_SpecificInt(V: ~*C1))))
2496 return Constant::getAllOnesValue(Ty: Op0->getType());
2497
2498 if (Op0->getType()->isIntOrIntVectorTy(BitWidth: 1)) {
2499 if (std::optional<bool> Implied =
2500 isImpliedCondition(LHS: Op0, RHS: Op1, DL: Q.DL, LHSIsTrue: false)) {
2501 // If Op0 is false implies Op1 is false, then Op1 is a subset of Op0.
2502 if (*Implied == false)
2503 return Op0;
2504 // If Op0 is false implies Op1 is true, then at least one is always true.
2505 if (*Implied == true)
2506 return ConstantInt::getTrue(Ty: Op0->getType());
2507 }
2508 if (std::optional<bool> Implied =
2509 isImpliedCondition(LHS: Op1, RHS: Op0, DL: Q.DL, LHSIsTrue: false)) {
2510 // If Op1 is false implies Op0 is false, then Op0 is a subset of Op1.
2511 if (*Implied == false)
2512 return Op1;
2513 // If Op1 is false implies Op0 is true, then at least one is always true.
2514 if (*Implied == true)
2515 return ConstantInt::getTrue(Ty: Op1->getType());
2516 }
2517 }
2518
2519 if (Value *V = simplifyByDomEq(Opcode: Instruction::Or, Op0, Op1, Q, MaxRecurse))
2520 return V;
2521
2522 return nullptr;
2523}
2524
2525Value *llvm::simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2526 return ::simplifyOrInst(Op0, Op1, Q, MaxRecurse: RecursionLimit);
2527}
2528
2529/// Given operands for a Xor, see if we can fold the result.
2530/// If not, this returns null.
2531static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2532 unsigned MaxRecurse) {
2533 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::Xor, Op0, Op1, Q))
2534 return C;
2535
2536 // X ^ poison -> poison
2537 if (isa<PoisonValue>(Val: Op1))
2538 return Op1;
2539
2540 // A ^ undef -> undef
2541 if (Q.isUndefValue(V: Op1))
2542 return Op1;
2543
2544 // A ^ 0 = A
2545 if (match(V: Op1, P: m_Zero()))
2546 return Op0;
2547
2548 // A ^ A = 0
2549 if (Op0 == Op1)
2550 return Constant::getNullValue(Ty: Op0->getType());
2551
2552 // A ^ ~A = ~A ^ A = -1
2553 if (match(V: Op0, P: m_Not(V: m_Specific(V: Op1))) || match(V: Op1, P: m_Not(V: m_Specific(V: Op0))))
2554 return Constant::getAllOnesValue(Ty: Op0->getType());
2555
2556 auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2557 Value *A, *B;
2558 // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2559 if (match(V: X, P: m_c_And(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: B))) &&
2560 match(V: Y, P: m_c_Or(L: m_Specific(V: A), R: m_Specific(V: B))))
2561 return A;
2562
2563 // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2564 // The 'not' op must contain a complete -1 operand (no undef elements for
2565 // vector) for the transform to be safe.
2566 Value *NotA;
2567 if (match(V: X, P: m_c_Or(L: m_CombineAnd(L: m_Not(V: m_Value(V&: A)), R: m_Value(V&: NotA)),
2568 R: m_Value(V&: B))) &&
2569 match(V: Y, P: m_c_And(L: m_Specific(V: A), R: m_Specific(V: B))))
2570 return NotA;
2571
2572 return nullptr;
2573 };
2574 if (Value *R = foldAndOrNot(Op0, Op1))
2575 return R;
2576 if (Value *R = foldAndOrNot(Op1, Op0))
2577 return R;
2578
2579 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Opcode: Instruction::Xor))
2580 return V;
2581
2582 // Try some generic simplifications for associative operations.
2583 if (Value *V =
2584 simplifyAssociativeBinOp(Opcode: Instruction::Xor, LHS: Op0, RHS: Op1, Q, MaxRecurse))
2585 return V;
2586
2587 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2588 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2589 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2590 // only if B and C are equal. If B and C are equal then (since we assume
2591 // that operands have already been simplified) "select(cond, B, C)" should
2592 // have been simplified to the common value of B and C already. Analysing
2593 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2594 // for threading over phi nodes.
2595
2596 if (Value *V = simplifyByDomEq(Opcode: Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2597 return V;
2598
2599 // (xor (sub nuw C_Mask, X), C_Mask) -> X
2600 {
2601 Value *X;
2602 if (match(V: Op0, P: m_NUWSub(L: m_Specific(V: Op1), R: m_Value(V&: X))) &&
2603 match(V: Op1, P: m_LowBitMask()))
2604 return X;
2605 }
2606
2607 return nullptr;
2608}
2609
2610Value *llvm::simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2611 return ::simplifyXorInst(Op0, Op1, Q, MaxRecurse: RecursionLimit);
2612}
2613
2614static Type *getCompareTy(Value *Op) {
2615 return CmpInst::makeCmpResultType(opnd_type: Op->getType());
2616}
2617
2618/// Rummage around inside V looking for something equivalent to the comparison
2619/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2620/// Helper function for analyzing max/min idioms.
2621static Value *extractEquivalentCondition(Value *V, CmpPredicate Pred,
2622 Value *LHS, Value *RHS) {
2623 SelectInst *SI = dyn_cast<SelectInst>(Val: V);
2624 if (!SI)
2625 return nullptr;
2626 CmpInst *Cmp = dyn_cast<CmpInst>(Val: SI->getCondition());
2627 if (!Cmp)
2628 return nullptr;
2629 Value *CmpLHS = Cmp->getOperand(i_nocapture: 0), *CmpRHS = Cmp->getOperand(i_nocapture: 1);
2630 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2631 return Cmp;
2632 if (Pred == CmpInst::getSwappedPredicate(pred: Cmp->getPredicate()) &&
2633 LHS == CmpRHS && RHS == CmpLHS)
2634 return Cmp;
2635 return nullptr;
2636}
2637
2638/// Return true if the underlying object (storage) must be disjoint from
2639/// storage returned by any noalias return call.
2640static bool isAllocDisjoint(const Value *V) {
2641 // For allocas, we consider only static ones (dynamic
2642 // allocas might be transformed into calls to malloc not simultaneously
2643 // live with the compared-to allocation). For globals, we exclude symbols
2644 // that might be resolve lazily to symbols in another dynamically-loaded
2645 // library (and, thus, could be malloc'ed by the implementation).
2646 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Val: V))
2647 return AI->isStaticAlloca();
2648 if (const GlobalValue *GV = dyn_cast<GlobalValue>(Val: V))
2649 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2650 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2651 !GV->isThreadLocal();
2652 if (const Argument *A = dyn_cast<Argument>(Val: V))
2653 return A->hasByValAttr();
2654 return false;
2655}
2656
2657/// Return true if V1 and V2 are each the base of some distict storage region
2658/// [V, object_size(V)] which do not overlap. Note that zero sized regions
2659/// *are* possible, and that zero sized regions do not overlap with any other.
2660static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
2661 // Global variables always exist, so they always exist during the lifetime
2662 // of each other and all allocas. Global variables themselves usually have
2663 // non-overlapping storage, but since their addresses are constants, the
2664 // case involving two globals does not reach here and is instead handled in
2665 // constant folding.
2666 //
2667 // Two different allocas usually have different addresses...
2668 //
2669 // However, if there's an @llvm.stackrestore dynamically in between two
2670 // allocas, they may have the same address. It's tempting to reduce the
2671 // scope of the problem by only looking at *static* allocas here. That would
2672 // cover the majority of allocas while significantly reducing the likelihood
2673 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2674 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2675 // an entry block. Also, if we have a block that's not attached to a
2676 // function, we can't tell if it's "static" under the current definition.
2677 // Theoretically, this problem could be fixed by creating a new kind of
2678 // instruction kind specifically for static allocas. Such a new instruction
2679 // could be required to be at the top of the entry block, thus preventing it
2680 // from being subject to a @llvm.stackrestore. Instcombine could even
2681 // convert regular allocas into these special allocas. It'd be nifty.
2682 // However, until then, this problem remains open.
2683 //
2684 // So, we'll assume that two non-empty allocas have different addresses
2685 // for now.
2686 auto isByValArg = [](const Value *V) {
2687 const Argument *A = dyn_cast<Argument>(Val: V);
2688 return A && A->hasByValAttr();
2689 };
2690
2691 // Byval args are backed by store which does not overlap with each other,
2692 // allocas, or globals.
2693 if (isByValArg(V1))
2694 return isa<AllocaInst>(Val: V2) || isa<GlobalVariable>(Val: V2) || isByValArg(V2);
2695 if (isByValArg(V2))
2696 return isa<AllocaInst>(Val: V1) || isa<GlobalVariable>(Val: V1) || isByValArg(V1);
2697
2698 return isa<AllocaInst>(Val: V1) &&
2699 (isa<AllocaInst>(Val: V2) || isa<GlobalVariable>(Val: V2));
2700}
2701
2702// A significant optimization not implemented here is assuming that alloca
2703// addresses are not equal to incoming argument values. They don't *alias*,
2704// as we say, but that doesn't mean they aren't equal, so we take a
2705// conservative approach.
2706//
2707// This is inspired in part by C++11 5.10p1:
2708// "Two pointers of the same type compare equal if and only if they are both
2709// null, both point to the same function, or both represent the same
2710// address."
2711//
2712// This is pretty permissive.
2713//
2714// It's also partly due to C11 6.5.9p6:
2715// "Two pointers compare equal if and only if both are null pointers, both are
2716// pointers to the same object (including a pointer to an object and a
2717// subobject at its beginning) or function, both are pointers to one past the
2718// last element of the same array object, or one is a pointer to one past the
2719// end of one array object and the other is a pointer to the start of a
2720// different array object that happens to immediately follow the first array
2721// object in the address space.)
2722//
2723// C11's version is more restrictive, however there's no reason why an argument
2724// couldn't be a one-past-the-end value for a stack object in the caller and be
2725// equal to the beginning of a stack object in the callee.
2726//
2727// If the C and C++ standards are ever made sufficiently restrictive in this
2728// area, it may be possible to update LLVM's semantics accordingly and reinstate
2729// this optimization.
2730static Constant *computePointerICmp(CmpPredicate Pred, Value *LHS, Value *RHS,
2731 const SimplifyQuery &Q) {
2732 assert(LHS->getType() == RHS->getType() && "Must have same types");
2733 const DataLayout &DL = Q.DL;
2734 const TargetLibraryInfo *TLI = Q.TLI;
2735
2736 // We fold equality and unsigned predicates on pointer comparisons, but forbid
2737 // signed predicates since a GEP with inbounds could cross the sign boundary.
2738 if (CmpInst::isSigned(predicate: Pred))
2739 return nullptr;
2740
2741 // We have to switch to a signed predicate to handle negative indices from
2742 // the base pointer.
2743 Pred = ICmpInst::getSignedPredicate(Pred);
2744
2745 // Strip off any constant offsets so that we can reason about them.
2746 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2747 // here and compare base addresses like AliasAnalysis does, however there are
2748 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2749 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2750 // doesn't need to guarantee pointer inequality when it says NoAlias.
2751
2752 // Even if an non-inbounds GEP occurs along the path we can still optimize
2753 // equality comparisons concerning the result.
2754 bool AllowNonInbounds = ICmpInst::isEquality(P: Pred);
2755 unsigned IndexSize = DL.getIndexTypeSizeInBits(Ty: LHS->getType());
2756 APInt LHSOffset(IndexSize, 0), RHSOffset(IndexSize, 0);
2757 LHS = LHS->stripAndAccumulateConstantOffsets(DL, Offset&: LHSOffset, AllowNonInbounds);
2758 RHS = RHS->stripAndAccumulateConstantOffsets(DL, Offset&: RHSOffset, AllowNonInbounds);
2759
2760 // If LHS and RHS are related via constant offsets to the same base
2761 // value, we can replace it with an icmp which just compares the offsets.
2762 if (LHS == RHS)
2763 return ConstantInt::get(Ty: getCompareTy(Op: LHS),
2764 V: ICmpInst::compare(LHS: LHSOffset, RHS: RHSOffset, Pred));
2765
2766 // Various optimizations for (in)equality comparisons.
2767 if (ICmpInst::isEquality(P: Pred)) {
2768 // Different non-empty allocations that exist at the same time have
2769 // different addresses (if the program can tell). If the offsets are
2770 // within the bounds of their allocations (and not one-past-the-end!
2771 // so we can't use inbounds!), and their allocations aren't the same,
2772 // the pointers are not equal.
2773 if (haveNonOverlappingStorage(V1: LHS, V2: RHS)) {
2774 uint64_t LHSSize, RHSSize;
2775 ObjectSizeOpts Opts;
2776 Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2777 auto *F = [](Value *V) -> Function * {
2778 if (auto *I = dyn_cast<Instruction>(Val: V))
2779 return I->getFunction();
2780 if (auto *A = dyn_cast<Argument>(Val: V))
2781 return A->getParent();
2782 return nullptr;
2783 }(LHS);
2784 Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
2785 if (getObjectSize(Ptr: LHS, Size&: LHSSize, DL, TLI, Opts) && LHSSize != 0 &&
2786 getObjectSize(Ptr: RHS, Size&: RHSSize, DL, TLI, Opts) && RHSSize != 0) {
2787 APInt Dist = LHSOffset - RHSOffset;
2788 if (Dist.isNonNegative() ? Dist.ult(RHS: LHSSize) : (-Dist).ult(RHS: RHSSize))
2789 return ConstantInt::get(Ty: getCompareTy(Op: LHS),
2790 V: !CmpInst::isTrueWhenEqual(predicate: Pred));
2791 }
2792 }
2793
2794 // If one side of the equality comparison must come from a noalias call
2795 // (meaning a system memory allocation function), and the other side must
2796 // come from a pointer that cannot overlap with dynamically-allocated
2797 // memory within the lifetime of the current function (allocas, byval
2798 // arguments, globals), then determine the comparison result here.
2799 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2800 getUnderlyingObjects(V: LHS, Objects&: LHSUObjs);
2801 getUnderlyingObjects(V: RHS, Objects&: RHSUObjs);
2802
2803 // Is the set of underlying objects all noalias calls?
2804 auto IsNAC = [](ArrayRef<const Value *> Objects) {
2805 return all_of(Range&: Objects, P: isNoAliasCall);
2806 };
2807
2808 // Is the set of underlying objects all things which must be disjoint from
2809 // noalias calls. We assume that indexing from such disjoint storage
2810 // into the heap is undefined, and thus offsets can be safely ignored.
2811 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2812 return all_of(Range&: Objects, P: ::isAllocDisjoint);
2813 };
2814
2815 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2816 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2817 return ConstantInt::get(Ty: getCompareTy(Op: LHS),
2818 V: !CmpInst::isTrueWhenEqual(predicate: Pred));
2819
2820 // Fold comparisons for non-escaping pointer even if the allocation call
2821 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2822 // dynamic allocation call could be either of the operands. Note that
2823 // the other operand can not be based on the alloc - if it were, then
2824 // the cmp itself would be a capture.
2825 Value *MI = nullptr;
2826 if (isAllocLikeFn(V: LHS, TLI) && llvm::isKnownNonZero(V: RHS, Q))
2827 MI = LHS;
2828 else if (isAllocLikeFn(V: RHS, TLI) && llvm::isKnownNonZero(V: LHS, Q))
2829 MI = RHS;
2830 if (MI) {
2831 // FIXME: This is incorrect, see PR54002. While we can assume that the
2832 // allocation is at an address that makes the comparison false, this
2833 // requires that *all* comparisons to that address be false, which
2834 // InstSimplify cannot guarantee.
2835 struct CustomCaptureTracker : public CaptureTracker {
2836 bool Captured = false;
2837 void tooManyUses() override { Captured = true; }
2838 Action captured(const Use *U, UseCaptureInfo CI) override {
2839 // TODO(captures): Use UseCaptureInfo.
2840 if (auto *ICmp = dyn_cast<ICmpInst>(Val: U->getUser())) {
2841 // Comparison against value stored in global variable. Given the
2842 // pointer does not escape, its value cannot be guessed and stored
2843 // separately in a global variable.
2844 unsigned OtherIdx = 1 - U->getOperandNo();
2845 auto *LI = dyn_cast<LoadInst>(Val: ICmp->getOperand(i_nocapture: OtherIdx));
2846 if (LI && isa<GlobalVariable>(Val: LI->getPointerOperand()))
2847 return Continue;
2848 }
2849
2850 Captured = true;
2851 return Stop;
2852 }
2853 };
2854 CustomCaptureTracker Tracker;
2855 PointerMayBeCaptured(V: MI, Tracker: &Tracker);
2856 if (!Tracker.Captured)
2857 return ConstantInt::get(Ty: getCompareTy(Op: LHS),
2858 V: CmpInst::isFalseWhenEqual(predicate: Pred));
2859 }
2860 }
2861
2862 // Otherwise, fail.
2863 return nullptr;
2864}
2865
2866/// Fold an icmp when its operands have i1 scalar type.
2867static Value *simplifyICmpOfBools(CmpPredicate Pred, Value *LHS, Value *RHS,
2868 const SimplifyQuery &Q) {
2869 Type *ITy = getCompareTy(Op: LHS); // The return type.
2870 Type *OpTy = LHS->getType(); // The operand type.
2871 if (!OpTy->isIntOrIntVectorTy(BitWidth: 1))
2872 return nullptr;
2873
2874 // A boolean compared to true/false can be reduced in 14 out of the 20
2875 // (10 predicates * 2 constants) possible combinations. The other
2876 // 6 cases require a 'not' of the LHS.
2877
2878 auto ExtractNotLHS = [](Value *V) -> Value * {
2879 Value *X;
2880 if (match(V, P: m_Not(V: m_Value(V&: X))))
2881 return X;
2882 return nullptr;
2883 };
2884
2885 if (match(V: RHS, P: m_Zero())) {
2886 switch (Pred) {
2887 case CmpInst::ICMP_NE: // X != 0 -> X
2888 case CmpInst::ICMP_UGT: // X >u 0 -> X
2889 case CmpInst::ICMP_SLT: // X <s 0 -> X
2890 return LHS;
2891
2892 case CmpInst::ICMP_EQ: // not(X) == 0 -> X != 0 -> X
2893 case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2894 case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2895 if (Value *X = ExtractNotLHS(LHS))
2896 return X;
2897 break;
2898
2899 case CmpInst::ICMP_ULT: // X <u 0 -> false
2900 case CmpInst::ICMP_SGT: // X >s 0 -> false
2901 return getFalse(Ty: ITy);
2902
2903 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2904 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2905 return getTrue(Ty: ITy);
2906
2907 default:
2908 break;
2909 }
2910 } else if (match(V: RHS, P: m_One())) {
2911 switch (Pred) {
2912 case CmpInst::ICMP_EQ: // X == 1 -> X
2913 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2914 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2915 return LHS;
2916
2917 case CmpInst::ICMP_NE: // not(X) != 1 -> X == 1 -> X
2918 case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u 1 -> X
2919 case CmpInst::ICMP_SGT: // not(X) >s 1 -> X <=s -1 -> X
2920 if (Value *X = ExtractNotLHS(LHS))
2921 return X;
2922 break;
2923
2924 case CmpInst::ICMP_UGT: // X >u 1 -> false
2925 case CmpInst::ICMP_SLT: // X <s -1 -> false
2926 return getFalse(Ty: ITy);
2927
2928 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2929 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2930 return getTrue(Ty: ITy);
2931
2932 default:
2933 break;
2934 }
2935 }
2936
2937 switch (Pred) {
2938 default:
2939 break;
2940 case ICmpInst::ICMP_UGE:
2941 if (isImpliedCondition(LHS: RHS, RHS: LHS, DL: Q.DL).value_or(u: false))
2942 return getTrue(Ty: ITy);
2943 break;
2944 case ICmpInst::ICMP_SGE:
2945 /// For signed comparison, the values for an i1 are 0 and -1
2946 /// respectively. This maps into a truth table of:
2947 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2948 /// 0 | 0 | 1 (0 >= 0) | 1
2949 /// 0 | 1 | 1 (0 >= -1) | 1
2950 /// 1 | 0 | 0 (-1 >= 0) | 0
2951 /// 1 | 1 | 1 (-1 >= -1) | 1
2952 if (isImpliedCondition(LHS, RHS, DL: Q.DL).value_or(u: false))
2953 return getTrue(Ty: ITy);
2954 break;
2955 case ICmpInst::ICMP_ULE:
2956 if (isImpliedCondition(LHS, RHS, DL: Q.DL).value_or(u: false))
2957 return getTrue(Ty: ITy);
2958 break;
2959 case ICmpInst::ICMP_SLE:
2960 /// SLE follows the same logic as SGE with the LHS and RHS swapped.
2961 if (isImpliedCondition(LHS: RHS, RHS: LHS, DL: Q.DL).value_or(u: false))
2962 return getTrue(Ty: ITy);
2963 break;
2964 }
2965
2966 return nullptr;
2967}
2968
2969/// Check if RHS is zero or can be transformed to an equivalent zero comparison.
2970/// E.g., icmp sgt X, -1 --> icmp sge X, 0
2971static bool matchEquivZeroRHS(CmpPredicate &Pred, const Value *RHS) {
2972 // icmp [pred] X, 0 --> as-is
2973 if (match(V: RHS, P: m_Zero()))
2974 return true;
2975
2976 // Handle comparisons with -1 (all ones)
2977 if (match(V: RHS, P: m_AllOnes())) {
2978 switch (Pred) {
2979 case ICmpInst::ICMP_SGT:
2980 // icmp sgt X, -1 --> icmp sge X, 0
2981 Pred = ICmpInst::ICMP_SGE;
2982 return true;
2983 case ICmpInst::ICMP_SLE:
2984 // icmp sle X, -1 --> icmp slt X, 0
2985 Pred = ICmpInst::ICMP_SLT;
2986 return true;
2987 // Note: unsigned comparisons with -1 (UINT_MAX) are not handled here:
2988 // - icmp ugt X, -1 is always false (nothing > UINT_MAX)
2989 // - icmp ule X, -1 is always true (everything <= UINT_MAX)
2990 default:
2991 return false;
2992 }
2993 }
2994
2995 // Handle comparisons with 1
2996 if (match(V: RHS, P: m_One())) {
2997 switch (Pred) {
2998 case ICmpInst::ICMP_SGE:
2999 // icmp sge X, 1 --> icmp sgt X, 0
3000 Pred = ICmpInst::ICMP_SGT;
3001 return true;
3002 case ICmpInst::ICMP_UGE:
3003 // icmp uge X, 1 --> icmp ugt X, 0
3004 Pred = ICmpInst::ICMP_UGT;
3005 return true;
3006 case ICmpInst::ICMP_SLT:
3007 // icmp slt X, 1 --> icmp sle X, 0
3008 Pred = ICmpInst::ICMP_SLE;
3009 return true;
3010 case ICmpInst::ICMP_ULT:
3011 // icmp ult X, 1 --> icmp ule X, 0
3012 Pred = ICmpInst::ICMP_ULE;
3013 return true;
3014 default:
3015 return false;
3016 }
3017 }
3018
3019 return false;
3020}
3021
3022/// Try hard to fold icmp with zero RHS because this is a common case.
3023/// Note that, this function also handles the equivalent zero RHS, e.g.,
3024/// icmp sgt X, -1 --> icmp sge X, 0
3025static Value *simplifyICmpWithZero(CmpPredicate Pred, Value *LHS, Value *RHS,
3026 const SimplifyQuery &Q) {
3027 // Check if RHS is zero or can be transformed to an equivalent zero comparison
3028 if (!matchEquivZeroRHS(Pred, RHS))
3029 return nullptr;
3030
3031 Type *ITy = getCompareTy(Op: LHS); // The return type.
3032 switch (Pred) {
3033 default:
3034 llvm_unreachable("Unknown ICmp predicate!");
3035 case ICmpInst::ICMP_ULT:
3036 return getFalse(Ty: ITy);
3037 case ICmpInst::ICMP_UGE:
3038 return getTrue(Ty: ITy);
3039 case ICmpInst::ICMP_EQ:
3040 case ICmpInst::ICMP_ULE:
3041 if (isKnownNonZero(V: LHS, Q))
3042 return getFalse(Ty: ITy);
3043 break;
3044 case ICmpInst::ICMP_NE:
3045 case ICmpInst::ICMP_UGT:
3046 if (isKnownNonZero(V: LHS, Q))
3047 return getTrue(Ty: ITy);
3048 break;
3049 case ICmpInst::ICMP_SLT: {
3050 KnownBits LHSKnown = computeKnownBits(V: LHS, Q);
3051 if (LHSKnown.isNegative())
3052 return getTrue(Ty: ITy);
3053 if (LHSKnown.isNonNegative())
3054 return getFalse(Ty: ITy);
3055 break;
3056 }
3057 case ICmpInst::ICMP_SLE: {
3058 KnownBits LHSKnown = computeKnownBits(V: LHS, Q);
3059 if (LHSKnown.isNegative())
3060 return getTrue(Ty: ITy);
3061 if (LHSKnown.isNonNegative() && isKnownNonZero(V: LHS, Q))
3062 return getFalse(Ty: ITy);
3063 break;
3064 }
3065 case ICmpInst::ICMP_SGE: {
3066 KnownBits LHSKnown = computeKnownBits(V: LHS, Q);
3067 if (LHSKnown.isNegative())
3068 return getFalse(Ty: ITy);
3069 if (LHSKnown.isNonNegative())
3070 return getTrue(Ty: ITy);
3071 break;
3072 }
3073 case ICmpInst::ICMP_SGT: {
3074 KnownBits LHSKnown = computeKnownBits(V: LHS, Q);
3075 if (LHSKnown.isNegative())
3076 return getFalse(Ty: ITy);
3077 if (LHSKnown.isNonNegative() && isKnownNonZero(V: LHS, Q))
3078 return getTrue(Ty: ITy);
3079 break;
3080 }
3081 }
3082
3083 return nullptr;
3084}
3085
3086static Value *simplifyICmpWithConstant(CmpPredicate Pred, Value *LHS,
3087 Value *RHS, const SimplifyQuery &Q) {
3088 Type *ITy = getCompareTy(Op: RHS); // The return type.
3089
3090 Value *X;
3091 const APInt *C;
3092 if (!match(V: RHS, P: m_APIntAllowPoison(Res&: C)))
3093 return nullptr;
3094
3095 // Sign-bit checks can be optimized to true/false after unsigned
3096 // floating-point casts:
3097 // icmp slt (bitcast (uitofp X)), 0 --> false
3098 // icmp sgt (bitcast (uitofp X)), -1 --> true
3099 if (match(V: LHS, P: m_ElementWiseBitCast(Op: m_UIToFP(Op: m_Value(V&: X))))) {
3100 bool TrueIfSigned;
3101 if (isSignBitCheck(Pred, RHS: *C, TrueIfSigned))
3102 return ConstantInt::getBool(Ty: ITy, V: !TrueIfSigned);
3103 }
3104
3105 // Rule out tautological comparisons (eg., ult 0 or uge 0).
3106 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, Other: *C);
3107 if (RHS_CR.isEmptySet())
3108 return ConstantInt::getFalse(Ty: ITy);
3109 if (RHS_CR.isFullSet())
3110 return ConstantInt::getTrue(Ty: ITy);
3111
3112 ConstantRange LHS_CR =
3113 computeConstantRange(V: LHS, ForSigned: CmpInst::isSigned(predicate: Pred), UseInstrInfo: Q.IIQ.UseInstrInfo);
3114 if (!LHS_CR.isFullSet()) {
3115 if (RHS_CR.contains(CR: LHS_CR))
3116 return ConstantInt::getTrue(Ty: ITy);
3117 if (RHS_CR.inverse().contains(CR: LHS_CR))
3118 return ConstantInt::getFalse(Ty: ITy);
3119 }
3120
3121 // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC)
3122 // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
3123 const APInt *MulC;
3124 if (Q.IIQ.UseInstrInfo && ICmpInst::isEquality(P: Pred) &&
3125 ((match(V: LHS, P: m_NUWMul(L: m_Value(), R: m_APIntAllowPoison(Res&: MulC))) &&
3126 *MulC != 0 && C->urem(RHS: *MulC) != 0) ||
3127 (match(V: LHS, P: m_NSWMul(L: m_Value(), R: m_APIntAllowPoison(Res&: MulC))) &&
3128 *MulC != 0 && C->srem(RHS: *MulC) != 0)))
3129 return ConstantInt::get(Ty: ITy, V: Pred == ICmpInst::ICMP_NE);
3130
3131 if (Pred == ICmpInst::ICMP_UGE && C->isOne() && isKnownNonZero(V: LHS, Q))
3132 return ConstantInt::getTrue(Ty: ITy);
3133
3134 return nullptr;
3135}
3136
3137enum class MonotonicType { GreaterEq, LowerEq };
3138
3139/// Get values V_i such that V uge V_i (GreaterEq) or V ule V_i (LowerEq).
3140static void getUnsignedMonotonicValues(SmallPtrSetImpl<Value *> &Res, Value *V,
3141 MonotonicType Type,
3142 const SimplifyQuery &Q,
3143 unsigned Depth = 0) {
3144 if (!Res.insert(Ptr: V).second)
3145 return;
3146
3147 // Can be increased if useful.
3148 if (++Depth > 1)
3149 return;
3150
3151 auto *I = dyn_cast<Instruction>(Val: V);
3152 if (!I)
3153 return;
3154
3155 Value *X, *Y;
3156 if (Type == MonotonicType::GreaterEq) {
3157 if (match(V: I, P: m_Or(L: m_Value(V&: X), R: m_Value(V&: Y))) ||
3158 match(V: I, P: m_Intrinsic<Intrinsic::uadd_sat>(Op0: m_Value(V&: X), Op1: m_Value(V&: Y)))) {
3159 getUnsignedMonotonicValues(Res, V: X, Type, Q, Depth);
3160 getUnsignedMonotonicValues(Res, V: Y, Type, Q, Depth);
3161 }
3162 // X * Y >= X --> true
3163 if (match(V: I, P: m_NUWMul(L: m_Value(V&: X), R: m_Value(V&: Y)))) {
3164 if (isKnownNonZero(V: X, Q))
3165 getUnsignedMonotonicValues(Res, V: Y, Type, Q, Depth);
3166 if (isKnownNonZero(V: Y, Q))
3167 getUnsignedMonotonicValues(Res, V: X, Type, Q, Depth);
3168 }
3169 } else {
3170 assert(Type == MonotonicType::LowerEq);
3171 switch (I->getOpcode()) {
3172 case Instruction::And:
3173 getUnsignedMonotonicValues(Res, V: I->getOperand(i: 0), Type, Q, Depth);
3174 getUnsignedMonotonicValues(Res, V: I->getOperand(i: 1), Type, Q, Depth);
3175 break;
3176 case Instruction::URem:
3177 case Instruction::UDiv:
3178 case Instruction::LShr:
3179 getUnsignedMonotonicValues(Res, V: I->getOperand(i: 0), Type, Q, Depth);
3180 break;
3181 case Instruction::Call:
3182 if (match(V: I, P: m_Intrinsic<Intrinsic::usub_sat>(Op0: m_Value(V&: X))))
3183 getUnsignedMonotonicValues(Res, V: X, Type, Q, Depth);
3184 break;
3185 default:
3186 break;
3187 }
3188 }
3189}
3190
3191static Value *simplifyICmpUsingMonotonicValues(CmpPredicate Pred, Value *LHS,
3192 Value *RHS,
3193 const SimplifyQuery &Q) {
3194 if (Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_ULT)
3195 return nullptr;
3196
3197 // We have LHS uge GreaterValues and LowerValues uge RHS. If any of the
3198 // GreaterValues and LowerValues are the same, it follows that LHS uge RHS.
3199 SmallPtrSet<Value *, 4> GreaterValues;
3200 SmallPtrSet<Value *, 4> LowerValues;
3201 getUnsignedMonotonicValues(Res&: GreaterValues, V: LHS, Type: MonotonicType::GreaterEq, Q);
3202 getUnsignedMonotonicValues(Res&: LowerValues, V: RHS, Type: MonotonicType::LowerEq, Q);
3203 for (Value *GV : GreaterValues)
3204 if (LowerValues.contains(Ptr: GV))
3205 return ConstantInt::getBool(Ty: getCompareTy(Op: LHS),
3206 V: Pred == ICmpInst::ICMP_UGE);
3207 return nullptr;
3208}
3209
3210static Value *simplifyICmpWithBinOpOnLHS(CmpPredicate Pred, BinaryOperator *LBO,
3211 Value *RHS, const SimplifyQuery &Q,
3212 unsigned MaxRecurse) {
3213 Type *ITy = getCompareTy(Op: RHS); // The return type.
3214
3215 Value *Y = nullptr;
3216 // icmp pred (or X, Y), X
3217 if (match(V: LBO, P: m_c_Or(L: m_Value(V&: Y), R: m_Specific(V: RHS)))) {
3218 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
3219 KnownBits RHSKnown = computeKnownBits(V: RHS, Q);
3220 KnownBits YKnown = computeKnownBits(V: Y, Q);
3221 if (RHSKnown.isNonNegative() && YKnown.isNegative())
3222 return Pred == ICmpInst::ICMP_SLT ? getTrue(Ty: ITy) : getFalse(Ty: ITy);
3223 if (RHSKnown.isNegative() || YKnown.isNonNegative())
3224 return Pred == ICmpInst::ICMP_SLT ? getFalse(Ty: ITy) : getTrue(Ty: ITy);
3225 }
3226 }
3227
3228 // icmp pred (urem X, Y), Y
3229 if (match(V: LBO, P: m_URem(L: m_Value(), R: m_Specific(V: RHS)))) {
3230 switch (Pred) {
3231 default:
3232 break;
3233 case ICmpInst::ICMP_SGT:
3234 case ICmpInst::ICMP_SGE: {
3235 KnownBits Known = computeKnownBits(V: RHS, Q);
3236 if (!Known.isNonNegative())
3237 break;
3238 [[fallthrough]];
3239 }
3240 case ICmpInst::ICMP_EQ:
3241 case ICmpInst::ICMP_UGT:
3242 case ICmpInst::ICMP_UGE:
3243 return getFalse(Ty: ITy);
3244 case ICmpInst::ICMP_SLT:
3245 case ICmpInst::ICMP_SLE: {
3246 KnownBits Known = computeKnownBits(V: RHS, Q);
3247 if (!Known.isNonNegative())
3248 break;
3249 [[fallthrough]];
3250 }
3251 case ICmpInst::ICMP_NE:
3252 case ICmpInst::ICMP_ULT:
3253 case ICmpInst::ICMP_ULE:
3254 return getTrue(Ty: ITy);
3255 }
3256 }
3257
3258 // If x is nonzero:
3259 // x >>u C <u x --> true for C != 0.
3260 // x >>u C != x --> true for C != 0.
3261 // x >>u C >=u x --> false for C != 0.
3262 // x >>u C == x --> false for C != 0.
3263 // x udiv C <u x --> true for C != 1.
3264 // x udiv C != x --> true for C != 1.
3265 // x udiv C >=u x --> false for C != 1.
3266 // x udiv C == x --> false for C != 1.
3267 // TODO: allow non-constant shift amount/divisor
3268 const APInt *C;
3269 if ((match(V: LBO, P: m_LShr(L: m_Specific(V: RHS), R: m_APInt(Res&: C))) && *C != 0) ||
3270 (match(V: LBO, P: m_UDiv(L: m_Specific(V: RHS), R: m_APInt(Res&: C))) && *C != 1)) {
3271 if (isKnownNonZero(V: RHS, Q)) {
3272 switch (Pred) {
3273 default:
3274 break;
3275 case ICmpInst::ICMP_EQ:
3276 case ICmpInst::ICMP_UGE:
3277 case ICmpInst::ICMP_UGT:
3278 return getFalse(Ty: ITy);
3279 case ICmpInst::ICMP_NE:
3280 case ICmpInst::ICMP_ULT:
3281 case ICmpInst::ICMP_ULE:
3282 return getTrue(Ty: ITy);
3283 }
3284 }
3285 }
3286
3287 // (x*C1)/C2 <= x for C1 <= C2.
3288 // This holds even if the multiplication overflows: Assume that x != 0 and
3289 // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3290 // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3291 //
3292 // Additionally, either the multiplication and division might be represented
3293 // as shifts:
3294 // (x*C1)>>C2 <= x for C1 < 2**C2.
3295 // (x<<C1)/C2 <= x for 2**C1 < C2.
3296 const APInt *C1, *C2;
3297 if ((match(V: LBO, P: m_UDiv(L: m_Mul(L: m_Specific(V: RHS), R: m_APInt(Res&: C1)), R: m_APInt(Res&: C2))) &&
3298 C1->ule(RHS: *C2)) ||
3299 (match(V: LBO, P: m_LShr(L: m_Mul(L: m_Specific(V: RHS), R: m_APInt(Res&: C1)), R: m_APInt(Res&: C2))) &&
3300 C1->ule(RHS: APInt(C2->getBitWidth(), 1) << *C2)) ||
3301 (match(V: LBO, P: m_UDiv(L: m_Shl(L: m_Specific(V: RHS), R: m_APInt(Res&: C1)), R: m_APInt(Res&: C2))) &&
3302 (APInt(C1->getBitWidth(), 1) << *C1).ule(RHS: *C2))) {
3303 if (Pred == ICmpInst::ICMP_UGT)
3304 return getFalse(Ty: ITy);
3305 if (Pred == ICmpInst::ICMP_ULE)
3306 return getTrue(Ty: ITy);
3307 }
3308
3309 // (sub C, X) == X, C is odd --> false
3310 // (sub C, X) != X, C is odd --> true
3311 if (match(V: LBO, P: m_Sub(L: m_APIntAllowPoison(Res&: C), R: m_Specific(V: RHS))) &&
3312 (*C & 1) == 1 && ICmpInst::isEquality(P: Pred))
3313 return (Pred == ICmpInst::ICMP_EQ) ? getFalse(Ty: ITy) : getTrue(Ty: ITy);
3314
3315 return nullptr;
3316}
3317
3318// If only one of the icmp's operands has NSW flags, try to prove that:
3319//
3320// icmp slt/sgt/sle/sge (x + C1), (x +nsw C2)
3321//
3322// is equivalent to:
3323//
3324// icmp slt/sgt/sle/sge C1, C2
3325//
3326// which is true if x + C2 has the NSW flags set and:
3327// *) C1 <= C2 && C1 >= 0, or
3328// *) C2 <= C1 && C1 <= 0.
3329//
3330static bool trySimplifyICmpWithAdds(CmpPredicate Pred, Value *LHS, Value *RHS,
3331 const InstrInfoQuery &IIQ) {
3332 // TODO: support other predicates.
3333 if (!ICmpInst::isSigned(predicate: Pred) || !IIQ.UseInstrInfo)
3334 return false;
3335
3336 // Canonicalize nsw add as RHS.
3337 if (!match(V: RHS, P: m_NSWAdd(L: m_Value(), R: m_Value())))
3338 std::swap(a&: LHS, b&: RHS);
3339 if (!match(V: RHS, P: m_NSWAdd(L: m_Value(), R: m_Value())))
3340 return false;
3341
3342 Value *X;
3343 const APInt *C1, *C2;
3344 if (!match(V: LHS, P: m_Add(L: m_Value(V&: X), R: m_APInt(Res&: C1))) ||
3345 !match(V: RHS, P: m_Add(L: m_Specific(V: X), R: m_APInt(Res&: C2))))
3346 return false;
3347
3348 return (C1->sle(RHS: *C2) && C1->isNonNegative()) ||
3349 (C2->sle(RHS: *C1) && C1->isNonPositive());
3350}
3351
3352/// TODO: A large part of this logic is duplicated in InstCombine's
3353/// foldICmpBinOp(). We should be able to share that and avoid the code
3354/// duplication.
3355static Value *simplifyICmpWithBinOp(CmpPredicate Pred, Value *LHS, Value *RHS,
3356 const SimplifyQuery &Q,
3357 unsigned MaxRecurse) {
3358 BinaryOperator *LBO = dyn_cast<BinaryOperator>(Val: LHS);
3359 BinaryOperator *RBO = dyn_cast<BinaryOperator>(Val: RHS);
3360 if (MaxRecurse && (LBO || RBO)) {
3361 // Analyze the case when either LHS or RHS is an add instruction.
3362 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3363 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3364 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3365 if (LBO && LBO->getOpcode() == Instruction::Add) {
3366 A = LBO->getOperand(i_nocapture: 0);
3367 B = LBO->getOperand(i_nocapture: 1);
3368 NoLHSWrapProblem =
3369 ICmpInst::isEquality(P: Pred) ||
3370 (CmpInst::isUnsigned(predicate: Pred) &&
3371 Q.IIQ.hasNoUnsignedWrap(Op: cast<OverflowingBinaryOperator>(Val: LBO))) ||
3372 (CmpInst::isSigned(predicate: Pred) &&
3373 Q.IIQ.hasNoSignedWrap(Op: cast<OverflowingBinaryOperator>(Val: LBO)));
3374 }
3375 if (RBO && RBO->getOpcode() == Instruction::Add) {
3376 C = RBO->getOperand(i_nocapture: 0);
3377 D = RBO->getOperand(i_nocapture: 1);
3378 NoRHSWrapProblem =
3379 ICmpInst::isEquality(P: Pred) ||
3380 (CmpInst::isUnsigned(predicate: Pred) &&
3381 Q.IIQ.hasNoUnsignedWrap(Op: cast<OverflowingBinaryOperator>(Val: RBO))) ||
3382 (CmpInst::isSigned(predicate: Pred) &&
3383 Q.IIQ.hasNoSignedWrap(Op: cast<OverflowingBinaryOperator>(Val: RBO)));
3384 }
3385
3386 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3387 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3388 if (Value *V = simplifyICmpInst(Predicate: Pred, LHS: A == RHS ? B : A,
3389 RHS: Constant::getNullValue(Ty: RHS->getType()), Q,
3390 MaxRecurse: MaxRecurse - 1))
3391 return V;
3392
3393 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3394 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3395 if (Value *V =
3396 simplifyICmpInst(Predicate: Pred, LHS: Constant::getNullValue(Ty: LHS->getType()),
3397 RHS: C == LHS ? D : C, Q, MaxRecurse: MaxRecurse - 1))
3398 return V;
3399
3400 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3401 bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3402 trySimplifyICmpWithAdds(Pred, LHS, RHS, IIQ: Q.IIQ);
3403 if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3404 // Determine Y and Z in the form icmp (X+Y), (X+Z).
3405 Value *Y, *Z;
3406 if (A == C) {
3407 // C + B == C + D -> B == D
3408 Y = B;
3409 Z = D;
3410 } else if (A == D) {
3411 // D + B == C + D -> B == C
3412 Y = B;
3413 Z = C;
3414 } else if (B == C) {
3415 // A + C == C + D -> A == D
3416 Y = A;
3417 Z = D;
3418 } else {
3419 assert(B == D);
3420 // A + D == C + D -> A == C
3421 Y = A;
3422 Z = C;
3423 }
3424 if (Value *V = simplifyICmpInst(Predicate: Pred, LHS: Y, RHS: Z, Q, MaxRecurse: MaxRecurse - 1))
3425 return V;
3426 }
3427 }
3428
3429 if (LBO)
3430 if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3431 return V;
3432
3433 if (RBO)
3434 if (Value *V = simplifyICmpWithBinOpOnLHS(
3435 Pred: ICmpInst::getSwappedPredicate(pred: Pred), LBO: RBO, RHS: LHS, Q, MaxRecurse))
3436 return V;
3437
3438 // 0 - (zext X) pred C
3439 if (!CmpInst::isUnsigned(predicate: Pred) && match(V: LHS, P: m_Neg(V: m_ZExt(Op: m_Value())))) {
3440 const APInt *C;
3441 if (match(V: RHS, P: m_APInt(Res&: C))) {
3442 if (C->isStrictlyPositive()) {
3443 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3444 return ConstantInt::getTrue(Ty: getCompareTy(Op: RHS));
3445 if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3446 return ConstantInt::getFalse(Ty: getCompareTy(Op: RHS));
3447 }
3448 if (C->isNonNegative()) {
3449 if (Pred == ICmpInst::ICMP_SLE)
3450 return ConstantInt::getTrue(Ty: getCompareTy(Op: RHS));
3451 if (Pred == ICmpInst::ICMP_SGT)
3452 return ConstantInt::getFalse(Ty: getCompareTy(Op: RHS));
3453 }
3454 }
3455 }
3456
3457 // If C2 is a power-of-2 and C is not:
3458 // (C2 << X) == C --> false
3459 // (C2 << X) != C --> true
3460 const APInt *C;
3461 if (match(V: LHS, P: m_Shl(L: m_Power2(), R: m_Value())) &&
3462 match(V: RHS, P: m_APIntAllowPoison(Res&: C)) && !C->isPowerOf2()) {
3463 // C2 << X can equal zero in some circumstances.
3464 // This simplification might be unsafe if C is zero.
3465 //
3466 // We know it is safe if:
3467 // - The shift is nsw. We can't shift out the one bit.
3468 // - The shift is nuw. We can't shift out the one bit.
3469 // - C2 is one.
3470 // - C isn't zero.
3471 if (Q.IIQ.hasNoSignedWrap(Op: cast<OverflowingBinaryOperator>(Val: LBO)) ||
3472 Q.IIQ.hasNoUnsignedWrap(Op: cast<OverflowingBinaryOperator>(Val: LBO)) ||
3473 match(V: LHS, P: m_Shl(L: m_One(), R: m_Value())) || !C->isZero()) {
3474 if (Pred == ICmpInst::ICMP_EQ)
3475 return ConstantInt::getFalse(Ty: getCompareTy(Op: RHS));
3476 if (Pred == ICmpInst::ICMP_NE)
3477 return ConstantInt::getTrue(Ty: getCompareTy(Op: RHS));
3478 }
3479 }
3480
3481 // If C is a power-of-2:
3482 // (C << X) >u 0x8000 --> false
3483 // (C << X) <=u 0x8000 --> true
3484 if (match(V: LHS, P: m_Shl(L: m_Power2(), R: m_Value())) && match(V: RHS, P: m_SignMask())) {
3485 if (Pred == ICmpInst::ICMP_UGT)
3486 return ConstantInt::getFalse(Ty: getCompareTy(Op: RHS));
3487 if (Pred == ICmpInst::ICMP_ULE)
3488 return ConstantInt::getTrue(Ty: getCompareTy(Op: RHS));
3489 }
3490
3491 if (!MaxRecurse || !LBO || !RBO || LBO->getOpcode() != RBO->getOpcode())
3492 return nullptr;
3493
3494 if (LBO->getOperand(i_nocapture: 0) == RBO->getOperand(i_nocapture: 0)) {
3495 switch (LBO->getOpcode()) {
3496 default:
3497 break;
3498 case Instruction::Shl: {
3499 bool NUW = Q.IIQ.hasNoUnsignedWrap(Op: LBO) && Q.IIQ.hasNoUnsignedWrap(Op: RBO);
3500 bool NSW = Q.IIQ.hasNoSignedWrap(Op: LBO) && Q.IIQ.hasNoSignedWrap(Op: RBO);
3501 if (!NUW || (ICmpInst::isSigned(predicate: Pred) && !NSW) ||
3502 !isKnownNonZero(V: LBO->getOperand(i_nocapture: 0), Q))
3503 break;
3504 if (Value *V = simplifyICmpInst(Predicate: Pred, LHS: LBO->getOperand(i_nocapture: 1),
3505 RHS: RBO->getOperand(i_nocapture: 1), Q, MaxRecurse: MaxRecurse - 1))
3506 return V;
3507 break;
3508 }
3509 // If C1 & C2 == C1, A = X and/or C1, B = X and/or C2:
3510 // icmp ule A, B -> true
3511 // icmp ugt A, B -> false
3512 // icmp sle A, B -> true (C1 and C2 are the same sign)
3513 // icmp sgt A, B -> false (C1 and C2 are the same sign)
3514 case Instruction::And:
3515 case Instruction::Or: {
3516 const APInt *C1, *C2;
3517 if (ICmpInst::isRelational(P: Pred) &&
3518 match(V: LBO->getOperand(i_nocapture: 1), P: m_APInt(Res&: C1)) &&
3519 match(V: RBO->getOperand(i_nocapture: 1), P: m_APInt(Res&: C2))) {
3520 if (!C1->isSubsetOf(RHS: *C2)) {
3521 std::swap(a&: C1, b&: C2);
3522 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
3523 }
3524 if (C1->isSubsetOf(RHS: *C2)) {
3525 if (Pred == ICmpInst::ICMP_ULE)
3526 return ConstantInt::getTrue(Ty: getCompareTy(Op: LHS));
3527 if (Pred == ICmpInst::ICMP_UGT)
3528 return ConstantInt::getFalse(Ty: getCompareTy(Op: LHS));
3529 if (C1->isNonNegative() == C2->isNonNegative()) {
3530 if (Pred == ICmpInst::ICMP_SLE)
3531 return ConstantInt::getTrue(Ty: getCompareTy(Op: LHS));
3532 if (Pred == ICmpInst::ICMP_SGT)
3533 return ConstantInt::getFalse(Ty: getCompareTy(Op: LHS));
3534 }
3535 }
3536 }
3537 break;
3538 }
3539 }
3540 }
3541
3542 if (LBO->getOperand(i_nocapture: 1) == RBO->getOperand(i_nocapture: 1)) {
3543 switch (LBO->getOpcode()) {
3544 default:
3545 break;
3546 case Instruction::UDiv:
3547 case Instruction::LShr:
3548 if (ICmpInst::isSigned(predicate: Pred) || !Q.IIQ.isExact(Op: LBO) ||
3549 !Q.IIQ.isExact(Op: RBO))
3550 break;
3551 if (Value *V = simplifyICmpInst(Predicate: Pred, LHS: LBO->getOperand(i_nocapture: 0),
3552 RHS: RBO->getOperand(i_nocapture: 0), Q, MaxRecurse: MaxRecurse - 1))
3553 return V;
3554 break;
3555 case Instruction::SDiv:
3556 if (!ICmpInst::isEquality(P: Pred) || !Q.IIQ.isExact(Op: LBO) ||
3557 !Q.IIQ.isExact(Op: RBO))
3558 break;
3559 if (Value *V = simplifyICmpInst(Predicate: Pred, LHS: LBO->getOperand(i_nocapture: 0),
3560 RHS: RBO->getOperand(i_nocapture: 0), Q, MaxRecurse: MaxRecurse - 1))
3561 return V;
3562 break;
3563 case Instruction::AShr:
3564 if (!Q.IIQ.isExact(Op: LBO) || !Q.IIQ.isExact(Op: RBO))
3565 break;
3566 if (Value *V = simplifyICmpInst(Predicate: Pred, LHS: LBO->getOperand(i_nocapture: 0),
3567 RHS: RBO->getOperand(i_nocapture: 0), Q, MaxRecurse: MaxRecurse - 1))
3568 return V;
3569 break;
3570 case Instruction::Shl: {
3571 bool NUW = Q.IIQ.hasNoUnsignedWrap(Op: LBO) && Q.IIQ.hasNoUnsignedWrap(Op: RBO);
3572 bool NSW = Q.IIQ.hasNoSignedWrap(Op: LBO) && Q.IIQ.hasNoSignedWrap(Op: RBO);
3573 if (!NUW && !NSW)
3574 break;
3575 if (!NSW && ICmpInst::isSigned(predicate: Pred))
3576 break;
3577 if (Value *V = simplifyICmpInst(Predicate: Pred, LHS: LBO->getOperand(i_nocapture: 0),
3578 RHS: RBO->getOperand(i_nocapture: 0), Q, MaxRecurse: MaxRecurse - 1))
3579 return V;
3580 break;
3581 }
3582 }
3583 }
3584 return nullptr;
3585}
3586
3587/// simplify integer comparisons where at least one operand of the compare
3588/// matches an integer min/max idiom.
3589static Value *simplifyICmpWithMinMax(CmpPredicate Pred, Value *LHS, Value *RHS,
3590 const SimplifyQuery &Q,
3591 unsigned MaxRecurse) {
3592 Type *ITy = getCompareTy(Op: LHS); // The return type.
3593 Value *A, *B;
3594 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3595 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3596
3597 // Signed variants on "max(a,b)>=a -> true".
3598 if (match(V: LHS, P: m_SMax(L: m_Value(V&: A), R: m_Value(V&: B))) && (A == RHS || B == RHS)) {
3599 if (A != RHS)
3600 std::swap(a&: A, b&: B); // smax(A, B) pred A.
3601 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3602 // We analyze this as smax(A, B) pred A.
3603 P = Pred;
3604 } else if (match(V: RHS, P: m_SMax(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3605 (A == LHS || B == LHS)) {
3606 if (A != LHS)
3607 std::swap(a&: A, b&: B); // A pred smax(A, B).
3608 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3609 // We analyze this as smax(A, B) swapped-pred A.
3610 P = CmpInst::getSwappedPredicate(pred: Pred);
3611 } else if (match(V: LHS, P: m_SMin(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3612 (A == RHS || B == RHS)) {
3613 if (A != RHS)
3614 std::swap(a&: A, b&: B); // smin(A, B) pred A.
3615 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3616 // We analyze this as smax(-A, -B) swapped-pred -A.
3617 // Note that we do not need to actually form -A or -B thanks to EqP.
3618 P = CmpInst::getSwappedPredicate(pred: Pred);
3619 } else if (match(V: RHS, P: m_SMin(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3620 (A == LHS || B == LHS)) {
3621 if (A != LHS)
3622 std::swap(a&: A, b&: B); // A pred smin(A, B).
3623 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3624 // We analyze this as smax(-A, -B) pred -A.
3625 // Note that we do not need to actually form -A or -B thanks to EqP.
3626 P = Pred;
3627 }
3628 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3629 // Cases correspond to "max(A, B) p A".
3630 switch (P) {
3631 default:
3632 break;
3633 case CmpInst::ICMP_EQ:
3634 case CmpInst::ICMP_SLE:
3635 // Equivalent to "A EqP B". This may be the same as the condition tested
3636 // in the max/min; if so, we can just return that.
3637 if (Value *V = extractEquivalentCondition(V: LHS, Pred: EqP, LHS: A, RHS: B))
3638 return V;
3639 if (Value *V = extractEquivalentCondition(V: RHS, Pred: EqP, LHS: A, RHS: B))
3640 return V;
3641 // Otherwise, see if "A EqP B" simplifies.
3642 if (MaxRecurse)
3643 if (Value *V = simplifyICmpInst(Predicate: EqP, LHS: A, RHS: B, Q, MaxRecurse: MaxRecurse - 1))
3644 return V;
3645 break;
3646 case CmpInst::ICMP_NE:
3647 case CmpInst::ICMP_SGT: {
3648 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(pred: EqP);
3649 // Equivalent to "A InvEqP B". This may be the same as the condition
3650 // tested in the max/min; if so, we can just return that.
3651 if (Value *V = extractEquivalentCondition(V: LHS, Pred: InvEqP, LHS: A, RHS: B))
3652 return V;
3653 if (Value *V = extractEquivalentCondition(V: RHS, Pred: InvEqP, LHS: A, RHS: B))
3654 return V;
3655 // Otherwise, see if "A InvEqP B" simplifies.
3656 if (MaxRecurse)
3657 if (Value *V = simplifyICmpInst(Predicate: InvEqP, LHS: A, RHS: B, Q, MaxRecurse: MaxRecurse - 1))
3658 return V;
3659 break;
3660 }
3661 case CmpInst::ICMP_SGE:
3662 // Always true.
3663 return getTrue(Ty: ITy);
3664 case CmpInst::ICMP_SLT:
3665 // Always false.
3666 return getFalse(Ty: ITy);
3667 }
3668 }
3669
3670 // Unsigned variants on "max(a,b)>=a -> true".
3671 P = CmpInst::BAD_ICMP_PREDICATE;
3672 if (match(V: LHS, P: m_UMax(L: m_Value(V&: A), R: m_Value(V&: B))) && (A == RHS || B == RHS)) {
3673 if (A != RHS)
3674 std::swap(a&: A, b&: B); // umax(A, B) pred A.
3675 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3676 // We analyze this as umax(A, B) pred A.
3677 P = Pred;
3678 } else if (match(V: RHS, P: m_UMax(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3679 (A == LHS || B == LHS)) {
3680 if (A != LHS)
3681 std::swap(a&: A, b&: B); // A pred umax(A, B).
3682 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3683 // We analyze this as umax(A, B) swapped-pred A.
3684 P = CmpInst::getSwappedPredicate(pred: Pred);
3685 } else if (match(V: LHS, P: m_UMin(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3686 (A == RHS || B == RHS)) {
3687 if (A != RHS)
3688 std::swap(a&: A, b&: B); // umin(A, B) pred A.
3689 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3690 // We analyze this as umax(-A, -B) swapped-pred -A.
3691 // Note that we do not need to actually form -A or -B thanks to EqP.
3692 P = CmpInst::getSwappedPredicate(pred: Pred);
3693 } else if (match(V: RHS, P: m_UMin(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3694 (A == LHS || B == LHS)) {
3695 if (A != LHS)
3696 std::swap(a&: A, b&: B); // A pred umin(A, B).
3697 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3698 // We analyze this as umax(-A, -B) pred -A.
3699 // Note that we do not need to actually form -A or -B thanks to EqP.
3700 P = Pred;
3701 }
3702 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3703 // Cases correspond to "max(A, B) p A".
3704 switch (P) {
3705 default:
3706 break;
3707 case CmpInst::ICMP_EQ:
3708 case CmpInst::ICMP_ULE:
3709 // Equivalent to "A EqP B". This may be the same as the condition tested
3710 // in the max/min; if so, we can just return that.
3711 if (Value *V = extractEquivalentCondition(V: LHS, Pred: EqP, LHS: A, RHS: B))
3712 return V;
3713 if (Value *V = extractEquivalentCondition(V: RHS, Pred: EqP, LHS: A, RHS: B))
3714 return V;
3715 // Otherwise, see if "A EqP B" simplifies.
3716 if (MaxRecurse)
3717 if (Value *V = simplifyICmpInst(Predicate: EqP, LHS: A, RHS: B, Q, MaxRecurse: MaxRecurse - 1))
3718 return V;
3719 break;
3720 case CmpInst::ICMP_NE:
3721 case CmpInst::ICMP_UGT: {
3722 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(pred: EqP);
3723 // Equivalent to "A InvEqP B". This may be the same as the condition
3724 // tested in the max/min; if so, we can just return that.
3725 if (Value *V = extractEquivalentCondition(V: LHS, Pred: InvEqP, LHS: A, RHS: B))
3726 return V;
3727 if (Value *V = extractEquivalentCondition(V: RHS, Pred: InvEqP, LHS: A, RHS: B))
3728 return V;
3729 // Otherwise, see if "A InvEqP B" simplifies.
3730 if (MaxRecurse)
3731 if (Value *V = simplifyICmpInst(Predicate: InvEqP, LHS: A, RHS: B, Q, MaxRecurse: MaxRecurse - 1))
3732 return V;
3733 break;
3734 }
3735 case CmpInst::ICMP_UGE:
3736 return getTrue(Ty: ITy);
3737 case CmpInst::ICMP_ULT:
3738 return getFalse(Ty: ITy);
3739 }
3740 }
3741
3742 // Comparing 1 each of min/max with a common operand?
3743 // Canonicalize min operand to RHS.
3744 if (match(V: LHS, P: m_UMin(L: m_Value(), R: m_Value())) ||
3745 match(V: LHS, P: m_SMin(L: m_Value(), R: m_Value()))) {
3746 std::swap(a&: LHS, b&: RHS);
3747 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
3748 }
3749
3750 Value *C, *D;
3751 if (match(V: LHS, P: m_SMax(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3752 match(V: RHS, P: m_SMin(L: m_Value(V&: C), R: m_Value(V&: D))) &&
3753 (A == C || A == D || B == C || B == D)) {
3754 // smax(A, B) >=s smin(A, D) --> true
3755 if (Pred == CmpInst::ICMP_SGE)
3756 return getTrue(Ty: ITy);
3757 // smax(A, B) <s smin(A, D) --> false
3758 if (Pred == CmpInst::ICMP_SLT)
3759 return getFalse(Ty: ITy);
3760 } else if (match(V: LHS, P: m_UMax(L: m_Value(V&: A), R: m_Value(V&: B))) &&
3761 match(V: RHS, P: m_UMin(L: m_Value(V&: C), R: m_Value(V&: D))) &&
3762 (A == C || A == D || B == C || B == D)) {
3763 // umax(A, B) >=u umin(A, D) --> true
3764 if (Pred == CmpInst::ICMP_UGE)
3765 return getTrue(Ty: ITy);
3766 // umax(A, B) <u umin(A, D) --> false
3767 if (Pred == CmpInst::ICMP_ULT)
3768 return getFalse(Ty: ITy);
3769 }
3770
3771 return nullptr;
3772}
3773
3774static Value *simplifyICmpWithDominatingAssume(CmpPredicate Predicate,
3775 Value *LHS, Value *RHS,
3776 const SimplifyQuery &Q) {
3777 // Gracefully handle instructions that have not been inserted yet.
3778 if (!Q.AC || !Q.CxtI)
3779 return nullptr;
3780
3781 for (Value *AssumeBaseOp : {LHS, RHS}) {
3782 for (auto &AssumeVH : Q.AC->assumptionsFor(V: AssumeBaseOp)) {
3783 if (!AssumeVH)
3784 continue;
3785
3786 CallInst *Assume = cast<CallInst>(Val&: AssumeVH);
3787 if (std::optional<bool> Imp = isImpliedCondition(
3788 LHS: Assume->getArgOperand(i: 0), RHSPred: Predicate, RHSOp0: LHS, RHSOp1: RHS, DL: Q.DL))
3789 if (isValidAssumeForContext(I: Assume, CxtI: Q.CxtI, DT: Q.DT))
3790 return ConstantInt::get(Ty: getCompareTy(Op: LHS), V: *Imp);
3791 }
3792 }
3793
3794 return nullptr;
3795}
3796
3797static Value *simplifyICmpWithIntrinsicOnLHS(CmpPredicate Pred, Value *LHS,
3798 Value *RHS) {
3799 auto *II = dyn_cast<IntrinsicInst>(Val: LHS);
3800 if (!II)
3801 return nullptr;
3802
3803 switch (II->getIntrinsicID()) {
3804 case Intrinsic::uadd_sat:
3805 // uadd.sat(X, Y) uge X + Y
3806 if (match(V: RHS, P: m_c_Add(L: m_Specific(V: II->getArgOperand(i: 0)),
3807 R: m_Specific(V: II->getArgOperand(i: 1))))) {
3808 if (Pred == ICmpInst::ICMP_UGE)
3809 return ConstantInt::getTrue(Ty: getCompareTy(Op: II));
3810 if (Pred == ICmpInst::ICMP_ULT)
3811 return ConstantInt::getFalse(Ty: getCompareTy(Op: II));
3812 }
3813 return nullptr;
3814 case Intrinsic::usub_sat:
3815 // usub.sat(X, Y) ule X - Y
3816 if (match(V: RHS, P: m_Sub(L: m_Specific(V: II->getArgOperand(i: 0)),
3817 R: m_Specific(V: II->getArgOperand(i: 1))))) {
3818 if (Pred == ICmpInst::ICMP_ULE)
3819 return ConstantInt::getTrue(Ty: getCompareTy(Op: II));
3820 if (Pred == ICmpInst::ICMP_UGT)
3821 return ConstantInt::getFalse(Ty: getCompareTy(Op: II));
3822 }
3823 return nullptr;
3824 default:
3825 return nullptr;
3826 }
3827}
3828
3829/// Helper method to get range from metadata or attribute.
3830static std::optional<ConstantRange> getRange(Value *V,
3831 const InstrInfoQuery &IIQ) {
3832 if (Instruction *I = dyn_cast<Instruction>(Val: V))
3833 if (MDNode *MD = IIQ.getMetadata(I, KindID: LLVMContext::MD_range))
3834 return getConstantRangeFromMetadata(RangeMD: *MD);
3835
3836 if (const Argument *A = dyn_cast<Argument>(Val: V))
3837 return A->getRange();
3838 else if (const CallBase *CB = dyn_cast<CallBase>(Val: V))
3839 return CB->getRange();
3840
3841 return std::nullopt;
3842}
3843
3844/// Given operands for an ICmpInst, see if we can fold the result.
3845/// If not, this returns null.
3846static Value *simplifyICmpInst(CmpPredicate Pred, Value *LHS, Value *RHS,
3847 const SimplifyQuery &Q, unsigned MaxRecurse) {
3848 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3849
3850 if (Constant *CLHS = dyn_cast<Constant>(Val: LHS)) {
3851 if (Constant *CRHS = dyn_cast<Constant>(Val: RHS))
3852 return ConstantFoldCompareInstOperands(Predicate: Pred, LHS: CLHS, RHS: CRHS, DL: Q.DL, TLI: Q.TLI);
3853
3854 // If we have a constant, make sure it is on the RHS.
3855 std::swap(a&: LHS, b&: RHS);
3856 Pred = CmpInst::getSwappedPredicate(pred: Pred);
3857 }
3858 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3859
3860 Type *ITy = getCompareTy(Op: LHS); // The return type.
3861
3862 // icmp poison, X -> poison
3863 if (isa<PoisonValue>(Val: RHS))
3864 return PoisonValue::get(T: ITy);
3865
3866 // For EQ and NE, we can always pick a value for the undef to make the
3867 // predicate pass or fail, so we can return undef.
3868 // Matches behavior in llvm::ConstantFoldCompareInstruction.
3869 if (Q.isUndefValue(V: RHS) && ICmpInst::isEquality(P: Pred))
3870 return UndefValue::get(T: ITy);
3871
3872 // icmp X, X -> true/false
3873 // icmp X, undef -> true/false because undef could be X.
3874 if (LHS == RHS || Q.isUndefValue(V: RHS))
3875 return ConstantInt::get(Ty: ITy, V: CmpInst::isTrueWhenEqual(predicate: Pred));
3876
3877 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3878 return V;
3879
3880 // TODO: Sink/common this with other potentially expensive calls that use
3881 // ValueTracking? See comment below for isKnownNonEqual().
3882 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3883 return V;
3884
3885 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q))
3886 return V;
3887
3888 // If both operands have range metadata, use the metadata
3889 // to simplify the comparison.
3890 if (std::optional<ConstantRange> RhsCr = getRange(V: RHS, IIQ: Q.IIQ))
3891 if (std::optional<ConstantRange> LhsCr = getRange(V: LHS, IIQ: Q.IIQ)) {
3892 if (LhsCr->icmp(Pred, Other: *RhsCr))
3893 return ConstantInt::getTrue(Ty: ITy);
3894
3895 if (LhsCr->icmp(Pred: CmpInst::getInversePredicate(pred: Pred), Other: *RhsCr))
3896 return ConstantInt::getFalse(Ty: ITy);
3897 }
3898
3899 // Compare of cast, for example (zext X) != 0 -> X != 0
3900 if (isa<CastInst>(Val: LHS) && (isa<Constant>(Val: RHS) || isa<CastInst>(Val: RHS))) {
3901 Instruction *LI = cast<CastInst>(Val: LHS);
3902 Value *SrcOp = LI->getOperand(i: 0);
3903 Type *SrcTy = SrcOp->getType();
3904 Type *DstTy = LI->getType();
3905
3906 // Turn icmp (ptrtoint/ptrtoaddr x), (ptrtoint/ptrtoaddr/constant) into a
3907 // compare of the input if the integer type is the same size as the
3908 // pointer address type (icmp only compares the address of the pointer).
3909 if (MaxRecurse && (isa<PtrToIntInst, PtrToAddrInst>(Val: LI)) &&
3910 Q.DL.getAddressType(PtrTy: SrcTy) == DstTy) {
3911 if (Constant *RHSC = dyn_cast<Constant>(Val: RHS)) {
3912 // Transfer the cast to the constant.
3913 if (Value *V = simplifyICmpInst(Pred, LHS: SrcOp,
3914 RHS: ConstantExpr::getIntToPtr(C: RHSC, Ty: SrcTy),
3915 Q, MaxRecurse: MaxRecurse - 1))
3916 return V;
3917 } else if (isa<PtrToIntInst, PtrToAddrInst>(Val: RHS)) {
3918 auto *RI = cast<CastInst>(Val: RHS);
3919 if (RI->getOperand(i_nocapture: 0)->getType() == SrcTy)
3920 // Compare without the cast.
3921 if (Value *V = simplifyICmpInst(Pred, LHS: SrcOp, RHS: RI->getOperand(i_nocapture: 0), Q,
3922 MaxRecurse: MaxRecurse - 1))
3923 return V;
3924 }
3925 }
3926
3927 if (isa<ZExtInst>(Val: LHS)) {
3928 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3929 // same type.
3930 if (ZExtInst *RI = dyn_cast<ZExtInst>(Val: RHS)) {
3931 if (MaxRecurse && SrcTy == RI->getOperand(i_nocapture: 0)->getType())
3932 // Compare X and Y. Note that signed predicates become unsigned.
3933 if (Value *V =
3934 simplifyICmpInst(Pred: ICmpInst::getUnsignedPredicate(Pred), LHS: SrcOp,
3935 RHS: RI->getOperand(i_nocapture: 0), Q, MaxRecurse: MaxRecurse - 1))
3936 return V;
3937 }
3938 // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3939 else if (SExtInst *RI = dyn_cast<SExtInst>(Val: RHS)) {
3940 if (SrcOp == RI->getOperand(i_nocapture: 0)) {
3941 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3942 return ConstantInt::getTrue(Ty: ITy);
3943 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3944 return ConstantInt::getFalse(Ty: ITy);
3945 }
3946 }
3947 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3948 // too. If not, then try to deduce the result of the comparison.
3949 else if (match(V: RHS, P: m_ImmConstant())) {
3950 Constant *C = dyn_cast<Constant>(Val: RHS);
3951 assert(C != nullptr);
3952
3953 // Compute the constant that would happen if we truncated to SrcTy then
3954 // reextended to DstTy.
3955 Constant *Trunc =
3956 ConstantFoldCastOperand(Opcode: Instruction::Trunc, C, DestTy: SrcTy, DL: Q.DL);
3957 assert(Trunc && "Constant-fold of ImmConstant should not fail");
3958 Constant *RExt =
3959 ConstantFoldCastOperand(Opcode: CastInst::ZExt, C: Trunc, DestTy: DstTy, DL: Q.DL);
3960 assert(RExt && "Constant-fold of ImmConstant should not fail");
3961 Constant *AnyEq =
3962 ConstantFoldCompareInstOperands(Predicate: ICmpInst::ICMP_EQ, LHS: RExt, RHS: C, DL: Q.DL);
3963 assert(AnyEq && "Constant-fold of ImmConstant should not fail");
3964
3965 // If the re-extended constant didn't change any of the elements then
3966 // this is effectively also a case of comparing two zero-extended
3967 // values.
3968 if (AnyEq->isAllOnesValue() && MaxRecurse)
3969 if (Value *V = simplifyICmpInst(Pred: ICmpInst::getUnsignedPredicate(Pred),
3970 LHS: SrcOp, RHS: Trunc, Q, MaxRecurse: MaxRecurse - 1))
3971 return V;
3972
3973 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3974 // there. Use this to work out the result of the comparison.
3975 if (AnyEq->isNullValue()) {
3976 switch (Pred) {
3977 default:
3978 llvm_unreachable("Unknown ICmp predicate!");
3979 // LHS <u RHS.
3980 case ICmpInst::ICMP_EQ:
3981 case ICmpInst::ICMP_UGT:
3982 case ICmpInst::ICMP_UGE:
3983 return Constant::getNullValue(Ty: ITy);
3984
3985 case ICmpInst::ICMP_NE:
3986 case ICmpInst::ICMP_ULT:
3987 case ICmpInst::ICMP_ULE:
3988 return Constant::getAllOnesValue(Ty: ITy);
3989
3990 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3991 // is non-negative then LHS <s RHS.
3992 case ICmpInst::ICMP_SGT:
3993 case ICmpInst::ICMP_SGE:
3994 return ConstantFoldCompareInstOperands(
3995 Predicate: ICmpInst::ICMP_SLT, LHS: C, RHS: Constant::getNullValue(Ty: C->getType()),
3996 DL: Q.DL);
3997 case ICmpInst::ICMP_SLT:
3998 case ICmpInst::ICMP_SLE:
3999 return ConstantFoldCompareInstOperands(
4000 Predicate: ICmpInst::ICMP_SGE, LHS: C, RHS: Constant::getNullValue(Ty: C->getType()),
4001 DL: Q.DL);
4002 }
4003 }
4004 }
4005 }
4006
4007 if (isa<SExtInst>(Val: LHS)) {
4008 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
4009 // same type.
4010 if (SExtInst *RI = dyn_cast<SExtInst>(Val: RHS)) {
4011 if (MaxRecurse && SrcTy == RI->getOperand(i_nocapture: 0)->getType())
4012 // Compare X and Y. Note that the predicate does not change.
4013 if (Value *V = simplifyICmpInst(Pred, LHS: SrcOp, RHS: RI->getOperand(i_nocapture: 0), Q,
4014 MaxRecurse: MaxRecurse - 1))
4015 return V;
4016 }
4017 // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
4018 else if (ZExtInst *RI = dyn_cast<ZExtInst>(Val: RHS)) {
4019 if (SrcOp == RI->getOperand(i_nocapture: 0)) {
4020 if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
4021 return ConstantInt::getTrue(Ty: ITy);
4022 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
4023 return ConstantInt::getFalse(Ty: ITy);
4024 }
4025 }
4026 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
4027 // too. If not, then try to deduce the result of the comparison.
4028 else if (match(V: RHS, P: m_ImmConstant())) {
4029 Constant *C = cast<Constant>(Val: RHS);
4030
4031 // Compute the constant that would happen if we truncated to SrcTy then
4032 // reextended to DstTy.
4033 Constant *Trunc =
4034 ConstantFoldCastOperand(Opcode: Instruction::Trunc, C, DestTy: SrcTy, DL: Q.DL);
4035 assert(Trunc && "Constant-fold of ImmConstant should not fail");
4036 Constant *RExt =
4037 ConstantFoldCastOperand(Opcode: CastInst::SExt, C: Trunc, DestTy: DstTy, DL: Q.DL);
4038 assert(RExt && "Constant-fold of ImmConstant should not fail");
4039 Constant *AnyEq =
4040 ConstantFoldCompareInstOperands(Predicate: ICmpInst::ICMP_EQ, LHS: RExt, RHS: C, DL: Q.DL);
4041 assert(AnyEq && "Constant-fold of ImmConstant should not fail");
4042
4043 // If the re-extended constant didn't change then this is effectively
4044 // also a case of comparing two sign-extended values.
4045 if (AnyEq->isAllOnesValue() && MaxRecurse)
4046 if (Value *V =
4047 simplifyICmpInst(Pred, LHS: SrcOp, RHS: Trunc, Q, MaxRecurse: MaxRecurse - 1))
4048 return V;
4049
4050 // Otherwise the upper bits of LHS are all equal, while RHS has varying
4051 // bits there. Use this to work out the result of the comparison.
4052 if (AnyEq->isNullValue()) {
4053 switch (Pred) {
4054 default:
4055 llvm_unreachable("Unknown ICmp predicate!");
4056 case ICmpInst::ICMP_EQ:
4057 return Constant::getNullValue(Ty: ITy);
4058 case ICmpInst::ICMP_NE:
4059 return Constant::getAllOnesValue(Ty: ITy);
4060
4061 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
4062 // LHS >s RHS.
4063 case ICmpInst::ICMP_SGT:
4064 case ICmpInst::ICMP_SGE:
4065 return ConstantFoldCompareInstOperands(
4066 Predicate: ICmpInst::ICMP_SLT, LHS: C, RHS: Constant::getNullValue(Ty: C->getType()),
4067 DL: Q.DL);
4068 case ICmpInst::ICMP_SLT:
4069 case ICmpInst::ICMP_SLE:
4070 return ConstantFoldCompareInstOperands(
4071 Predicate: ICmpInst::ICMP_SGE, LHS: C, RHS: Constant::getNullValue(Ty: C->getType()),
4072 DL: Q.DL);
4073
4074 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
4075 // LHS >u RHS.
4076 case ICmpInst::ICMP_UGT:
4077 case ICmpInst::ICMP_UGE:
4078 // Comparison is true iff the LHS <s 0.
4079 if (MaxRecurse)
4080 if (Value *V = simplifyICmpInst(Pred: ICmpInst::ICMP_SLT, LHS: SrcOp,
4081 RHS: Constant::getNullValue(Ty: SrcTy), Q,
4082 MaxRecurse: MaxRecurse - 1))
4083 return V;
4084 break;
4085 case ICmpInst::ICMP_ULT:
4086 case ICmpInst::ICMP_ULE:
4087 // Comparison is true iff the LHS >=s 0.
4088 if (MaxRecurse)
4089 if (Value *V = simplifyICmpInst(Pred: ICmpInst::ICMP_SGE, LHS: SrcOp,
4090 RHS: Constant::getNullValue(Ty: SrcTy), Q,
4091 MaxRecurse: MaxRecurse - 1))
4092 return V;
4093 break;
4094 }
4095 }
4096 }
4097 }
4098 }
4099
4100 // icmp eq|ne X, Y -> false|true if X != Y
4101 // This is potentially expensive, and we have already computedKnownBits for
4102 // compares with 0 above here, so only try this for a non-zero compare.
4103 if (ICmpInst::isEquality(P: Pred) && !match(V: RHS, P: m_Zero()) &&
4104 isKnownNonEqual(V1: LHS, V2: RHS, SQ: Q)) {
4105 return Pred == ICmpInst::ICMP_NE ? getTrue(Ty: ITy) : getFalse(Ty: ITy);
4106 }
4107
4108 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
4109 return V;
4110
4111 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
4112 return V;
4113
4114 if (Value *V = simplifyICmpWithIntrinsicOnLHS(Pred, LHS, RHS))
4115 return V;
4116 if (Value *V = simplifyICmpWithIntrinsicOnLHS(
4117 Pred: ICmpInst::getSwappedPredicate(pred: Pred), LHS: RHS, RHS: LHS))
4118 return V;
4119
4120 if (Value *V = simplifyICmpUsingMonotonicValues(Pred, LHS, RHS, Q))
4121 return V;
4122 if (Value *V = simplifyICmpUsingMonotonicValues(
4123 Pred: ICmpInst::getSwappedPredicate(pred: Pred), LHS: RHS, RHS: LHS, Q))
4124 return V;
4125
4126 if (Value *V = simplifyICmpWithDominatingAssume(Predicate: Pred, LHS, RHS, Q))
4127 return V;
4128
4129 if (std::optional<bool> Res =
4130 isImpliedByDomCondition(Pred, LHS, RHS, ContextI: Q.CxtI, DL: Q.DL))
4131 return ConstantInt::getBool(Ty: ITy, V: *Res);
4132
4133 // Simplify comparisons of related pointers using a powerful, recursive
4134 // GEP-walk when we have target data available..
4135 if (LHS->getType()->isPointerTy())
4136 if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
4137 return C;
4138
4139 // If the comparison is with the result of a select instruction, check whether
4140 // comparing with either branch of the select always yields the same value.
4141 if (isa<SelectInst>(Val: LHS) || isa<SelectInst>(Val: RHS))
4142 if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4143 return V;
4144
4145 // If the comparison is with the result of a phi instruction, check whether
4146 // doing the compare with each incoming phi value yields a common result.
4147 if (isa<PHINode>(Val: LHS) || isa<PHINode>(Val: RHS))
4148 if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4149 return V;
4150
4151 return nullptr;
4152}
4153
4154Value *llvm::simplifyICmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS,
4155 const SimplifyQuery &Q) {
4156 return ::simplifyICmpInst(Pred: Predicate, LHS, RHS, Q, MaxRecurse: RecursionLimit);
4157}
4158
4159/// Given operands for an FCmpInst, see if we can fold the result.
4160/// If not, this returns null.
4161static Value *simplifyFCmpInst(CmpPredicate Pred, Value *LHS, Value *RHS,
4162 FastMathFlags FMF, const SimplifyQuery &Q,
4163 unsigned MaxRecurse) {
4164 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
4165
4166 if (Constant *CLHS = dyn_cast<Constant>(Val: LHS)) {
4167 if (Constant *CRHS = dyn_cast<Constant>(Val: RHS)) {
4168 // if the folding isn't successfull, fall back to the rest of the logic
4169 if (auto *Result = ConstantFoldCompareInstOperands(Predicate: Pred, LHS: CLHS, RHS: CRHS, DL: Q.DL,
4170 TLI: Q.TLI, I: Q.CxtI))
4171 return Result;
4172 } else {
4173 // If we have a constant, make sure it is on the RHS.
4174 std::swap(a&: LHS, b&: RHS);
4175 Pred = CmpInst::getSwappedPredicate(pred: Pred);
4176 }
4177 }
4178
4179 // Fold trivial predicates.
4180 Type *RetTy = getCompareTy(Op: LHS);
4181 if (Pred == FCmpInst::FCMP_FALSE)
4182 return getFalse(Ty: RetTy);
4183 if (Pred == FCmpInst::FCMP_TRUE)
4184 return getTrue(Ty: RetTy);
4185
4186 // fcmp pred x, poison and fcmp pred poison, x
4187 // fold to poison
4188 if (isa<PoisonValue>(Val: LHS) || isa<PoisonValue>(Val: RHS))
4189 return PoisonValue::get(T: RetTy);
4190
4191 // fcmp pred x, undef and fcmp pred undef, x
4192 // fold to true if unordered, false if ordered
4193 if (Q.isUndefValue(V: LHS) || Q.isUndefValue(V: RHS)) {
4194 // Choosing NaN for the undef will always make unordered comparison succeed
4195 // and ordered comparison fail.
4196 return ConstantInt::get(Ty: RetTy, V: CmpInst::isUnordered(predicate: Pred));
4197 }
4198
4199 // fcmp x,x -> true/false. Not all compares are foldable.
4200 if (LHS == RHS) {
4201 if (CmpInst::isTrueWhenEqual(predicate: Pred))
4202 return getTrue(Ty: RetTy);
4203 if (CmpInst::isFalseWhenEqual(predicate: Pred))
4204 return getFalse(Ty: RetTy);
4205 }
4206
4207 // Fold (un)ordered comparison if we can determine there are no NaNs.
4208 //
4209 // This catches the 2 variable input case, constants are handled below as a
4210 // class-like compare.
4211 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
4212 KnownFPClass RHSClass = computeKnownFPClass(V: RHS, InterestedClasses: fcAllFlags, SQ: Q);
4213 KnownFPClass LHSClass = computeKnownFPClass(V: LHS, InterestedClasses: fcAllFlags, SQ: Q);
4214
4215 if (FMF.noNaNs() ||
4216 (RHSClass.isKnownNeverNaN() && LHSClass.isKnownNeverNaN()))
4217 return ConstantInt::get(Ty: RetTy, V: Pred == FCmpInst::FCMP_ORD);
4218
4219 if (RHSClass.isKnownAlwaysNaN() || LHSClass.isKnownAlwaysNaN())
4220 return ConstantInt::get(Ty: RetTy, V: Pred == CmpInst::FCMP_UNO);
4221 }
4222
4223 if (std::optional<bool> Res =
4224 isImpliedByDomCondition(Pred, LHS, RHS, ContextI: Q.CxtI, DL: Q.DL))
4225 return ConstantInt::getBool(Ty: RetTy, V: *Res);
4226
4227 const APFloat *C = nullptr;
4228 match(V: RHS, P: m_APFloatAllowPoison(Res&: C));
4229 std::optional<KnownFPClass> FullKnownClassLHS;
4230
4231 // Lazily compute the possible classes for LHS. Avoid computing it twice if
4232 // RHS is a 0.
4233 auto computeLHSClass = [=, &FullKnownClassLHS](FPClassTest InterestedFlags =
4234 fcAllFlags) {
4235 if (FullKnownClassLHS)
4236 return *FullKnownClassLHS;
4237 return computeKnownFPClass(V: LHS, FMF, InterestedClasses: InterestedFlags, SQ: Q);
4238 };
4239
4240 if (C && Q.CxtI) {
4241 // Fold out compares that express a class test.
4242 //
4243 // FIXME: Should be able to perform folds without context
4244 // instruction. Always pass in the context function?
4245
4246 const Function *ParentF = Q.CxtI->getFunction();
4247 auto [ClassVal, ClassTest] = fcmpToClassTest(Pred, F: *ParentF, LHS, ConstRHS: C);
4248 if (ClassVal) {
4249 FullKnownClassLHS = computeLHSClass();
4250 if ((FullKnownClassLHS->KnownFPClasses & ClassTest) == fcNone)
4251 return getFalse(Ty: RetTy);
4252 if ((FullKnownClassLHS->KnownFPClasses & ~ClassTest) == fcNone)
4253 return getTrue(Ty: RetTy);
4254 }
4255 }
4256
4257 // Handle fcmp with constant RHS.
4258 if (C) {
4259 // TODO: If we always required a context function, we wouldn't need to
4260 // special case nans.
4261 if (C->isNaN())
4262 return ConstantInt::get(Ty: RetTy, V: CmpInst::isUnordered(predicate: Pred));
4263
4264 // TODO: Need version fcmpToClassTest which returns implied class when the
4265 // compare isn't a complete class test. e.g. > 1.0 implies fcPositive, but
4266 // isn't implementable as a class call.
4267 if (C->isNegative() && !C->isNegZero()) {
4268 FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4269
4270 // TODO: We can catch more cases by using a range check rather than
4271 // relying on CannotBeOrderedLessThanZero.
4272 switch (Pred) {
4273 case FCmpInst::FCMP_UGE:
4274 case FCmpInst::FCMP_UGT:
4275 case FCmpInst::FCMP_UNE: {
4276 KnownFPClass KnownClass = computeLHSClass(Interested);
4277
4278 // (X >= 0) implies (X > C) when (C < 0)
4279 if (KnownClass.cannotBeOrderedLessThanZero())
4280 return getTrue(Ty: RetTy);
4281 break;
4282 }
4283 case FCmpInst::FCMP_OEQ:
4284 case FCmpInst::FCMP_OLE:
4285 case FCmpInst::FCMP_OLT: {
4286 KnownFPClass KnownClass = computeLHSClass(Interested);
4287
4288 // (X >= 0) implies !(X < C) when (C < 0)
4289 if (KnownClass.cannotBeOrderedLessThanZero())
4290 return getFalse(Ty: RetTy);
4291 break;
4292 }
4293 default:
4294 break;
4295 }
4296 }
4297 // Check comparison of [minnum/maxnum with constant] with other constant.
4298 const APFloat *C2;
4299 if ((match(V: LHS, P: m_Intrinsic<Intrinsic::minnum>(Op0: m_Value(), Op1: m_APFloat(Res&: C2))) &&
4300 *C2 < *C) ||
4301 (match(V: LHS, P: m_Intrinsic<Intrinsic::maxnum>(Op0: m_Value(), Op1: m_APFloat(Res&: C2))) &&
4302 *C2 > *C)) {
4303 bool IsMaxNum =
4304 cast<IntrinsicInst>(Val: LHS)->getIntrinsicID() == Intrinsic::maxnum;
4305 // The ordered relationship and minnum/maxnum guarantee that we do not
4306 // have NaN constants, so ordered/unordered preds are handled the same.
4307 switch (Pred) {
4308 case FCmpInst::FCMP_OEQ:
4309 case FCmpInst::FCMP_UEQ:
4310 // minnum(X, LesserC) == C --> false
4311 // maxnum(X, GreaterC) == C --> false
4312 return getFalse(Ty: RetTy);
4313 case FCmpInst::FCMP_ONE:
4314 case FCmpInst::FCMP_UNE:
4315 // minnum(X, LesserC) != C --> true
4316 // maxnum(X, GreaterC) != C --> true
4317 return getTrue(Ty: RetTy);
4318 case FCmpInst::FCMP_OGE:
4319 case FCmpInst::FCMP_UGE:
4320 case FCmpInst::FCMP_OGT:
4321 case FCmpInst::FCMP_UGT:
4322 // minnum(X, LesserC) >= C --> false
4323 // minnum(X, LesserC) > C --> false
4324 // maxnum(X, GreaterC) >= C --> true
4325 // maxnum(X, GreaterC) > C --> true
4326 return ConstantInt::get(Ty: RetTy, V: IsMaxNum);
4327 case FCmpInst::FCMP_OLE:
4328 case FCmpInst::FCMP_ULE:
4329 case FCmpInst::FCMP_OLT:
4330 case FCmpInst::FCMP_ULT:
4331 // minnum(X, LesserC) <= C --> true
4332 // minnum(X, LesserC) < C --> true
4333 // maxnum(X, GreaterC) <= C --> false
4334 // maxnum(X, GreaterC) < C --> false
4335 return ConstantInt::get(Ty: RetTy, V: !IsMaxNum);
4336 default:
4337 // TRUE/FALSE/ORD/UNO should be handled before this.
4338 llvm_unreachable("Unexpected fcmp predicate");
4339 }
4340 }
4341 }
4342
4343 // TODO: Could fold this with above if there were a matcher which returned all
4344 // classes in a non-splat vector.
4345 if (match(V: RHS, P: m_AnyZeroFP())) {
4346 switch (Pred) {
4347 case FCmpInst::FCMP_OGE:
4348 case FCmpInst::FCMP_ULT: {
4349 FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4350 if (!FMF.noNaNs())
4351 Interested |= fcNan;
4352
4353 KnownFPClass Known = computeLHSClass(Interested);
4354
4355 // Positive or zero X >= 0.0 --> true
4356 // Positive or zero X < 0.0 --> false
4357 if ((FMF.noNaNs() || Known.isKnownNeverNaN()) &&
4358 Known.cannotBeOrderedLessThanZero())
4359 return Pred == FCmpInst::FCMP_OGE ? getTrue(Ty: RetTy) : getFalse(Ty: RetTy);
4360 break;
4361 }
4362 case FCmpInst::FCMP_UGE:
4363 case FCmpInst::FCMP_OLT: {
4364 FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4365 KnownFPClass Known = computeLHSClass(Interested);
4366
4367 // Positive or zero or nan X >= 0.0 --> true
4368 // Positive or zero or nan X < 0.0 --> false
4369 if (Known.cannotBeOrderedLessThanZero())
4370 return Pred == FCmpInst::FCMP_UGE ? getTrue(Ty: RetTy) : getFalse(Ty: RetTy);
4371 break;
4372 }
4373 default:
4374 break;
4375 }
4376 }
4377
4378 // If the comparison is with the result of a select instruction, check whether
4379 // comparing with either branch of the select always yields the same value.
4380 if (isa<SelectInst>(Val: LHS) || isa<SelectInst>(Val: RHS))
4381 if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4382 return V;
4383
4384 // If the comparison is with the result of a phi instruction, check whether
4385 // doing the compare with each incoming phi value yields a common result.
4386 if (isa<PHINode>(Val: LHS) || isa<PHINode>(Val: RHS))
4387 if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4388 return V;
4389
4390 return nullptr;
4391}
4392
4393Value *llvm::simplifyFCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS,
4394 FastMathFlags FMF, const SimplifyQuery &Q) {
4395 return ::simplifyFCmpInst(Pred: Predicate, LHS, RHS, FMF, Q, MaxRecurse: RecursionLimit);
4396}
4397
4398static Value *simplifyWithOpsReplaced(Value *V,
4399 ArrayRef<std::pair<Value *, Value *>> Ops,
4400 const SimplifyQuery &Q,
4401 bool AllowRefinement,
4402 SmallVectorImpl<Instruction *> *DropFlags,
4403 unsigned MaxRecurse) {
4404 assert((AllowRefinement || !Q.CanUseUndef) &&
4405 "If AllowRefinement=false then CanUseUndef=false");
4406 for (const auto &OpAndRepOp : Ops) {
4407 // We cannot replace a constant, and shouldn't even try.
4408 if (isa<Constant>(Val: OpAndRepOp.first))
4409 return nullptr;
4410
4411 // Trivial replacement.
4412 if (V == OpAndRepOp.first)
4413 return OpAndRepOp.second;
4414 }
4415
4416 if (!MaxRecurse--)
4417 return nullptr;
4418
4419 auto *I = dyn_cast<Instruction>(Val: V);
4420 if (!I)
4421 return nullptr;
4422
4423 // The arguments of a phi node might refer to a value from a previous
4424 // cycle iteration.
4425 if (isa<PHINode>(Val: I))
4426 return nullptr;
4427
4428 // Don't fold away llvm.is.constant checks based on assumptions.
4429 if (match(V: I, P: m_Intrinsic<Intrinsic::is_constant>()))
4430 return nullptr;
4431
4432 // Don't simplify freeze.
4433 if (isa<FreezeInst>(Val: I))
4434 return nullptr;
4435
4436 for (const auto &OpAndRepOp : Ops) {
4437 // For vector types, the simplification must hold per-lane, so forbid
4438 // potentially cross-lane operations like shufflevector.
4439 if (OpAndRepOp.first->getType()->isVectorTy() &&
4440 !isNotCrossLaneOperation(I))
4441 return nullptr;
4442 }
4443
4444 // Replace Op with RepOp in instruction operands.
4445 SmallVector<Value *, 8> NewOps;
4446 bool AnyReplaced = false;
4447 for (Value *InstOp : I->operands()) {
4448 if (Value *NewInstOp = simplifyWithOpsReplaced(
4449 V: InstOp, Ops, Q, AllowRefinement, DropFlags, MaxRecurse)) {
4450 NewOps.push_back(Elt: NewInstOp);
4451 AnyReplaced = InstOp != NewInstOp;
4452 } else {
4453 NewOps.push_back(Elt: InstOp);
4454 }
4455
4456 // Bail out if any operand is undef and SimplifyQuery disables undef
4457 // simplification. Constant folding currently doesn't respect this option.
4458 if (isa<UndefValue>(Val: NewOps.back()) && !Q.CanUseUndef)
4459 return nullptr;
4460 }
4461
4462 if (!AnyReplaced)
4463 return nullptr;
4464
4465 if (!AllowRefinement) {
4466 // General InstSimplify functions may refine the result, e.g. by returning
4467 // a constant for a potentially poison value. To avoid this, implement only
4468 // a few non-refining but profitable transforms here.
4469
4470 if (auto *BO = dyn_cast<BinaryOperator>(Val: I)) {
4471 unsigned Opcode = BO->getOpcode();
4472 // id op x -> x, x op id -> x
4473 // Exclude floats, because x op id may produce a different NaN value.
4474 if (!BO->getType()->isFPOrFPVectorTy()) {
4475 if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, Ty: I->getType()))
4476 return NewOps[1];
4477 if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, Ty: I->getType(),
4478 /* RHS */ AllowRHSConstant: true))
4479 return NewOps[0];
4480 }
4481
4482 // x & x -> x, x | x -> x
4483 if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4484 NewOps[0] == NewOps[1]) {
4485 // or disjoint x, x results in poison.
4486 if (auto *PDI = dyn_cast<PossiblyDisjointInst>(Val: BO)) {
4487 if (PDI->isDisjoint()) {
4488 if (!DropFlags)
4489 return nullptr;
4490 DropFlags->push_back(Elt: BO);
4491 }
4492 }
4493 return NewOps[0];
4494 }
4495
4496 // x - x -> 0, x ^ x -> 0. This is non-refining, because x is non-poison
4497 // by assumption and this case never wraps, so nowrap flags can be
4498 // ignored.
4499 if ((Opcode == Instruction::Sub || Opcode == Instruction::Xor) &&
4500 NewOps[0] == NewOps[1] &&
4501 any_of(Range&: Ops, P: [=](const auto &Rep) { return NewOps[0] == Rep.second; }))
4502 return Constant::getNullValue(Ty: I->getType());
4503
4504 // If we are substituting an absorber constant into a binop and extra
4505 // poison can't leak if we remove the select -- because both operands of
4506 // the binop are based on the same value -- then it may be safe to replace
4507 // the value with the absorber constant. Examples:
4508 // (Op == 0) ? 0 : (Op & -Op) --> Op & -Op
4509 // (Op == 0) ? 0 : (Op * (binop Op, C)) --> Op * (binop Op, C)
4510 // (Op == -1) ? -1 : (Op | (binop C, Op) --> Op | (binop C, Op)
4511 Constant *Absorber = ConstantExpr::getBinOpAbsorber(Opcode, Ty: I->getType());
4512 if ((NewOps[0] == Absorber || NewOps[1] == Absorber) &&
4513 any_of(Range&: Ops,
4514 P: [=](const auto &Rep) { return impliesPoison(BO, Rep.first); }))
4515 return Absorber;
4516 }
4517
4518 if (auto *II = dyn_cast<IntrinsicInst>(Val: I)) {
4519 // `x == y ? 0 : ucmp(x, y)` where under the replacement y -> x,
4520 // `ucmp(x, x)` becomes `0`.
4521 if ((II->getIntrinsicID() == Intrinsic::scmp ||
4522 II->getIntrinsicID() == Intrinsic::ucmp) &&
4523 NewOps[0] == NewOps[1]) {
4524 if (II->hasPoisonGeneratingAnnotations()) {
4525 if (!DropFlags)
4526 return nullptr;
4527
4528 DropFlags->push_back(Elt: II);
4529 }
4530
4531 return ConstantInt::get(Ty: I->getType(), V: 0);
4532 }
4533 }
4534
4535 if (isa<GetElementPtrInst>(Val: I)) {
4536 // getelementptr x, 0 -> x.
4537 // This never returns poison, even if inbounds is set.
4538 if (NewOps.size() == 2 && match(V: NewOps[1], P: m_Zero()))
4539 return NewOps[0];
4540 }
4541 } else {
4542 // The simplification queries below may return the original value. Consider:
4543 // %div = udiv i32 %arg, %arg2
4544 // %mul = mul nsw i32 %div, %arg2
4545 // %cmp = icmp eq i32 %mul, %arg
4546 // %sel = select i1 %cmp, i32 %div, i32 undef
4547 // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4548 // simplifies back to %arg. This can only happen because %mul does not
4549 // dominate %div. To ensure a consistent return value contract, we make sure
4550 // that this case returns nullptr as well.
4551 auto PreventSelfSimplify = [V](Value *Simplified) {
4552 return Simplified != V ? Simplified : nullptr;
4553 };
4554
4555 return PreventSelfSimplify(
4556 ::simplifyInstructionWithOperands(I, NewOps, SQ: Q, MaxRecurse));
4557 }
4558
4559 // If all operands are constant after substituting Op for RepOp then we can
4560 // constant fold the instruction.
4561 SmallVector<Constant *, 8> ConstOps;
4562 for (Value *NewOp : NewOps) {
4563 if (Constant *ConstOp = dyn_cast<Constant>(Val: NewOp))
4564 ConstOps.push_back(Elt: ConstOp);
4565 else
4566 return nullptr;
4567 }
4568
4569 // Consider:
4570 // %cmp = icmp eq i32 %x, 2147483647
4571 // %add = add nsw i32 %x, 1
4572 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
4573 //
4574 // We can't replace %sel with %add unless we strip away the flags (which
4575 // will be done in InstCombine).
4576 // TODO: This may be unsound, because it only catches some forms of
4577 // refinement.
4578 if (!AllowRefinement) {
4579 auto *II = dyn_cast<IntrinsicInst>(Val: I);
4580 if (canCreatePoison(Op: cast<Operator>(Val: I), ConsiderFlagsAndMetadata: !DropFlags)) {
4581 // abs cannot create poison if the value is known to never be int_min.
4582 if (II && II->getIntrinsicID() == Intrinsic::abs) {
4583 if (!ConstOps[0]->isNotMinSignedValue())
4584 return nullptr;
4585 } else
4586 return nullptr;
4587 }
4588
4589 if (DropFlags && II) {
4590 // If we're going to change the poison flag of abs/ctz to false, also
4591 // perform constant folding that way, so we get an integer instead of a
4592 // poison value here.
4593 switch (II->getIntrinsicID()) {
4594 case Intrinsic::abs:
4595 case Intrinsic::ctlz:
4596 case Intrinsic::cttz:
4597 ConstOps[1] = ConstantInt::getFalse(Context&: I->getContext());
4598 break;
4599 default:
4600 break;
4601 }
4602 }
4603
4604 Constant *Res = ConstantFoldInstOperands(I, Ops: ConstOps, DL: Q.DL, TLI: Q.TLI,
4605 /*AllowNonDeterministic=*/false);
4606 if (DropFlags && Res && I->hasPoisonGeneratingAnnotations())
4607 DropFlags->push_back(Elt: I);
4608 return Res;
4609 }
4610
4611 return ConstantFoldInstOperands(I, Ops: ConstOps, DL: Q.DL, TLI: Q.TLI,
4612 /*AllowNonDeterministic=*/false);
4613}
4614
4615static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4616 const SimplifyQuery &Q,
4617 bool AllowRefinement,
4618 SmallVectorImpl<Instruction *> *DropFlags,
4619 unsigned MaxRecurse) {
4620 return simplifyWithOpsReplaced(V, Ops: {{Op, RepOp}}, Q, AllowRefinement,
4621 DropFlags, MaxRecurse);
4622}
4623
4624Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4625 const SimplifyQuery &Q,
4626 bool AllowRefinement,
4627 SmallVectorImpl<Instruction *> *DropFlags) {
4628 // If refinement is disabled, also disable undef simplifications (which are
4629 // always refinements) in SimplifyQuery.
4630 if (!AllowRefinement)
4631 return ::simplifyWithOpReplaced(V, Op, RepOp, Q: Q.getWithoutUndef(),
4632 AllowRefinement, DropFlags, MaxRecurse: RecursionLimit);
4633 return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement, DropFlags,
4634 MaxRecurse: RecursionLimit);
4635}
4636
4637/// Try to simplify a select instruction when its condition operand is an
4638/// integer comparison where one operand of the compare is a constant.
4639static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4640 const APInt *Y, bool TrueWhenUnset) {
4641 const APInt *C;
4642
4643 // (X & Y) == 0 ? X & ~Y : X --> X
4644 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
4645 if (FalseVal == X && match(V: TrueVal, P: m_And(L: m_Specific(V: X), R: m_APInt(Res&: C))) &&
4646 *Y == ~*C)
4647 return TrueWhenUnset ? FalseVal : TrueVal;
4648
4649 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
4650 // (X & Y) != 0 ? X : X & ~Y --> X
4651 if (TrueVal == X && match(V: FalseVal, P: m_And(L: m_Specific(V: X), R: m_APInt(Res&: C))) &&
4652 *Y == ~*C)
4653 return TrueWhenUnset ? FalseVal : TrueVal;
4654
4655 if (Y->isPowerOf2()) {
4656 // (X & Y) == 0 ? X | Y : X --> X | Y
4657 // (X & Y) != 0 ? X | Y : X --> X
4658 if (FalseVal == X && match(V: TrueVal, P: m_Or(L: m_Specific(V: X), R: m_APInt(Res&: C))) &&
4659 *Y == *C) {
4660 // We can't return the or if it has the disjoint flag.
4661 if (TrueWhenUnset && cast<PossiblyDisjointInst>(Val: TrueVal)->isDisjoint())
4662 return nullptr;
4663 return TrueWhenUnset ? TrueVal : FalseVal;
4664 }
4665
4666 // (X & Y) == 0 ? X : X | Y --> X
4667 // (X & Y) != 0 ? X : X | Y --> X | Y
4668 if (TrueVal == X && match(V: FalseVal, P: m_Or(L: m_Specific(V: X), R: m_APInt(Res&: C))) &&
4669 *Y == *C) {
4670 // We can't return the or if it has the disjoint flag.
4671 if (!TrueWhenUnset && cast<PossiblyDisjointInst>(Val: FalseVal)->isDisjoint())
4672 return nullptr;
4673 return TrueWhenUnset ? TrueVal : FalseVal;
4674 }
4675 }
4676
4677 return nullptr;
4678}
4679
4680static Value *simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS,
4681 CmpPredicate Pred, Value *TVal,
4682 Value *FVal) {
4683 // Canonicalize common cmp+sel operand as CmpLHS.
4684 if (CmpRHS == TVal || CmpRHS == FVal) {
4685 std::swap(a&: CmpLHS, b&: CmpRHS);
4686 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
4687 }
4688
4689 // Canonicalize common cmp+sel operand as TVal.
4690 if (CmpLHS == FVal) {
4691 std::swap(a&: TVal, b&: FVal);
4692 Pred = ICmpInst::getInversePredicate(pred: Pred);
4693 }
4694
4695 // A vector select may be shuffling together elements that are equivalent
4696 // based on the max/min/select relationship.
4697 Value *X = CmpLHS, *Y = CmpRHS;
4698 bool PeekedThroughSelectShuffle = false;
4699 auto *Shuf = dyn_cast<ShuffleVectorInst>(Val: FVal);
4700 if (Shuf && Shuf->isSelect()) {
4701 if (Shuf->getOperand(i_nocapture: 0) == Y)
4702 FVal = Shuf->getOperand(i_nocapture: 1);
4703 else if (Shuf->getOperand(i_nocapture: 1) == Y)
4704 FVal = Shuf->getOperand(i_nocapture: 0);
4705 else
4706 return nullptr;
4707 PeekedThroughSelectShuffle = true;
4708 }
4709
4710 // (X pred Y) ? X : max/min(X, Y)
4711 auto *MMI = dyn_cast<MinMaxIntrinsic>(Val: FVal);
4712 if (!MMI || TVal != X ||
4713 !match(V: FVal, P: m_c_MaxOrMin(L: m_Specific(V: X), R: m_Specific(V: Y))))
4714 return nullptr;
4715
4716 // (X > Y) ? X : max(X, Y) --> max(X, Y)
4717 // (X >= Y) ? X : max(X, Y) --> max(X, Y)
4718 // (X < Y) ? X : min(X, Y) --> min(X, Y)
4719 // (X <= Y) ? X : min(X, Y) --> min(X, Y)
4720 //
4721 // The equivalence allows a vector select (shuffle) of max/min and Y. Ex:
4722 // (X > Y) ? X : (Z ? max(X, Y) : Y)
4723 // If Z is true, this reduces as above, and if Z is false:
4724 // (X > Y) ? X : Y --> max(X, Y)
4725 ICmpInst::Predicate MMPred = MMI->getPredicate();
4726 if (MMPred == CmpInst::getStrictPredicate(pred: Pred))
4727 return MMI;
4728
4729 // Other transforms are not valid with a shuffle.
4730 if (PeekedThroughSelectShuffle)
4731 return nullptr;
4732
4733 // (X == Y) ? X : max/min(X, Y) --> max/min(X, Y)
4734 if (Pred == CmpInst::ICMP_EQ)
4735 return MMI;
4736
4737 // (X != Y) ? X : max/min(X, Y) --> X
4738 if (Pred == CmpInst::ICMP_NE)
4739 return X;
4740
4741 // (X < Y) ? X : max(X, Y) --> X
4742 // (X <= Y) ? X : max(X, Y) --> X
4743 // (X > Y) ? X : min(X, Y) --> X
4744 // (X >= Y) ? X : min(X, Y) --> X
4745 ICmpInst::Predicate InvPred = CmpInst::getInversePredicate(pred: Pred);
4746 if (MMPred == CmpInst::getStrictPredicate(pred: InvPred))
4747 return X;
4748
4749 return nullptr;
4750}
4751
4752/// An alternative way to test if a bit is set or not.
4753/// uses e.g. sgt/slt or trunc instead of eq/ne.
4754static Value *simplifySelectWithBitTest(Value *CondVal, Value *TrueVal,
4755 Value *FalseVal) {
4756 if (auto Res = decomposeBitTest(Cond: CondVal))
4757 return simplifySelectBitTest(TrueVal, FalseVal, X: Res->X, Y: &Res->Mask,
4758 TrueWhenUnset: Res->Pred == ICmpInst::ICMP_EQ);
4759
4760 return nullptr;
4761}
4762
4763/// Try to simplify a select instruction when its condition operand is an
4764/// integer equality or floating-point equivalence comparison.
4765static Value *simplifySelectWithEquivalence(
4766 ArrayRef<std::pair<Value *, Value *>> Replacements, Value *TrueVal,
4767 Value *FalseVal, const SimplifyQuery &Q, unsigned MaxRecurse) {
4768 Value *SimplifiedFalseVal =
4769 simplifyWithOpsReplaced(V: FalseVal, Ops: Replacements, Q: Q.getWithoutUndef(),
4770 /* AllowRefinement */ false,
4771 /* DropFlags */ nullptr, MaxRecurse);
4772 if (!SimplifiedFalseVal)
4773 SimplifiedFalseVal = FalseVal;
4774
4775 Value *SimplifiedTrueVal =
4776 simplifyWithOpsReplaced(V: TrueVal, Ops: Replacements, Q,
4777 /* AllowRefinement */ true,
4778 /* DropFlags */ nullptr, MaxRecurse);
4779 if (!SimplifiedTrueVal)
4780 SimplifiedTrueVal = TrueVal;
4781
4782 if (SimplifiedFalseVal == SimplifiedTrueVal)
4783 return FalseVal;
4784
4785 return nullptr;
4786}
4787
4788/// Try to simplify a select instruction when its condition operand is an
4789/// integer comparison.
4790static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4791 Value *FalseVal,
4792 const SimplifyQuery &Q,
4793 unsigned MaxRecurse) {
4794 CmpPredicate Pred;
4795 Value *CmpLHS, *CmpRHS;
4796 if (!match(V: CondVal, P: m_ICmp(Pred, L: m_Value(V&: CmpLHS), R: m_Value(V&: CmpRHS))))
4797 return nullptr;
4798
4799 if (Value *V = simplifyCmpSelOfMaxMin(CmpLHS, CmpRHS, Pred, TVal: TrueVal, FVal: FalseVal))
4800 return V;
4801
4802 // Canonicalize ne to eq predicate.
4803 if (Pred == ICmpInst::ICMP_NE) {
4804 Pred = ICmpInst::ICMP_EQ;
4805 std::swap(a&: TrueVal, b&: FalseVal);
4806 }
4807
4808 // Check for integer min/max with a limit constant:
4809 // X > MIN_INT ? X : MIN_INT --> X
4810 // X < MAX_INT ? X : MAX_INT --> X
4811 if (TrueVal->getType()->isIntOrIntVectorTy()) {
4812 Value *X, *Y;
4813 SelectPatternFlavor SPF =
4814 matchDecomposedSelectPattern(CmpI: cast<ICmpInst>(Val: CondVal), TrueVal, FalseVal,
4815 LHS&: X, RHS&: Y)
4816 .Flavor;
4817 if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
4818 APInt LimitC = getMinMaxLimit(SPF: getInverseMinMaxFlavor(SPF),
4819 BitWidth: X->getType()->getScalarSizeInBits());
4820 if (match(V: Y, P: m_SpecificInt(V: LimitC)))
4821 return X;
4822 }
4823 }
4824
4825 if (Pred == ICmpInst::ICMP_EQ && match(V: CmpRHS, P: m_Zero())) {
4826 Value *X;
4827 const APInt *Y;
4828 if (match(V: CmpLHS, P: m_And(L: m_Value(V&: X), R: m_APInt(Res&: Y))))
4829 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4830 /*TrueWhenUnset=*/true))
4831 return V;
4832
4833 // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4834 Value *ShAmt;
4835 auto isFsh = m_CombineOr(L: m_FShl(Op0: m_Value(V&: X), Op1: m_Value(), Op2: m_Value(V&: ShAmt)),
4836 R: m_FShr(Op0: m_Value(), Op1: m_Value(V&: X), Op2: m_Value(V&: ShAmt)));
4837 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4838 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4839 if (match(V: TrueVal, P: isFsh) && FalseVal == X && CmpLHS == ShAmt)
4840 return X;
4841
4842 // Test for a zero-shift-guard-op around rotates. These are used to
4843 // avoid UB from oversized shifts in raw IR rotate patterns, but the
4844 // intrinsics do not have that problem.
4845 // We do not allow this transform for the general funnel shift case because
4846 // that would not preserve the poison safety of the original code.
4847 auto isRotate =
4848 m_CombineOr(L: m_FShl(Op0: m_Value(V&: X), Op1: m_Deferred(V: X), Op2: m_Value(V&: ShAmt)),
4849 R: m_FShr(Op0: m_Value(V&: X), Op1: m_Deferred(V: X), Op2: m_Value(V&: ShAmt)));
4850 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4851 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4852 if (match(V: FalseVal, P: isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4853 Pred == ICmpInst::ICMP_EQ)
4854 return FalseVal;
4855
4856 // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4857 // X == 0 ? -abs(X) : abs(X) --> abs(X)
4858 if (match(V: TrueVal, P: m_Intrinsic<Intrinsic::abs>(Op0: m_Specific(V: CmpLHS))) &&
4859 match(V: FalseVal, P: m_Neg(V: m_Intrinsic<Intrinsic::abs>(Op0: m_Specific(V: CmpLHS)))))
4860 return FalseVal;
4861 if (match(V: TrueVal,
4862 P: m_Neg(V: m_Intrinsic<Intrinsic::abs>(Op0: m_Specific(V: CmpLHS)))) &&
4863 match(V: FalseVal, P: m_Intrinsic<Intrinsic::abs>(Op0: m_Specific(V: CmpLHS))))
4864 return FalseVal;
4865 }
4866
4867 // If we have a scalar equality comparison, then we know the value in one of
4868 // the arms of the select. See if substituting this value into the arm and
4869 // simplifying the result yields the same value as the other arm.
4870 if (Pred == ICmpInst::ICMP_EQ) {
4871 if (CmpLHS->getType()->isIntOrIntVectorTy() ||
4872 canReplacePointersIfEqual(From: CmpLHS, To: CmpRHS, DL: Q.DL))
4873 if (Value *V = simplifySelectWithEquivalence(Replacements: {{CmpLHS, CmpRHS}}, TrueVal,
4874 FalseVal, Q, MaxRecurse))
4875 return V;
4876 if (CmpLHS->getType()->isIntOrIntVectorTy() ||
4877 canReplacePointersIfEqual(From: CmpRHS, To: CmpLHS, DL: Q.DL))
4878 if (Value *V = simplifySelectWithEquivalence(Replacements: {{CmpRHS, CmpLHS}}, TrueVal,
4879 FalseVal, Q, MaxRecurse))
4880 return V;
4881
4882 Value *X;
4883 Value *Y;
4884 // select((X | Y) == 0 ? X : 0) --> 0 (commuted 2 ways)
4885 if (match(V: CmpLHS, P: m_Or(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
4886 match(V: CmpRHS, P: m_Zero())) {
4887 // (X | Y) == 0 implies X == 0 and Y == 0.
4888 if (Value *V = simplifySelectWithEquivalence(
4889 Replacements: {{X, CmpRHS}, {Y, CmpRHS}}, TrueVal, FalseVal, Q, MaxRecurse))
4890 return V;
4891 }
4892
4893 // select((X & Y) == -1 ? X : -1) --> -1 (commuted 2 ways)
4894 if (match(V: CmpLHS, P: m_And(L: m_Value(V&: X), R: m_Value(V&: Y))) &&
4895 match(V: CmpRHS, P: m_AllOnes())) {
4896 // (X & Y) == -1 implies X == -1 and Y == -1.
4897 if (Value *V = simplifySelectWithEquivalence(
4898 Replacements: {{X, CmpRHS}, {Y, CmpRHS}}, TrueVal, FalseVal, Q, MaxRecurse))
4899 return V;
4900 }
4901 }
4902
4903 return nullptr;
4904}
4905
4906/// Try to simplify a select instruction when its condition operand is a
4907/// floating-point comparison.
4908static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4909 const SimplifyQuery &Q,
4910 unsigned MaxRecurse) {
4911 CmpPredicate Pred;
4912 Value *CmpLHS, *CmpRHS;
4913 if (!match(V: Cond, P: m_FCmp(Pred, L: m_Value(V&: CmpLHS), R: m_Value(V&: CmpRHS))))
4914 return nullptr;
4915 FCmpInst *I = cast<FCmpInst>(Val: Cond);
4916
4917 bool IsEquiv = I->isEquivalence();
4918 if (I->isEquivalence(/*Invert=*/true)) {
4919 std::swap(a&: T, b&: F);
4920 Pred = FCmpInst::getInversePredicate(pred: Pred);
4921 IsEquiv = true;
4922 }
4923
4924 // This transforms is safe if at least one operand is known to not be zero.
4925 // Otherwise, the select can change the sign of a zero operand.
4926 if (IsEquiv) {
4927 if (Value *V = simplifySelectWithEquivalence(Replacements: {{CmpLHS, CmpRHS}}, TrueVal: T, FalseVal: F, Q,
4928 MaxRecurse))
4929 return V;
4930 if (Value *V = simplifySelectWithEquivalence(Replacements: {{CmpRHS, CmpLHS}}, TrueVal: T, FalseVal: F, Q,
4931 MaxRecurse))
4932 return V;
4933 }
4934
4935 // Canonicalize CmpLHS to be T, and CmpRHS to be F, if they're swapped.
4936 if (CmpLHS == F && CmpRHS == T)
4937 std::swap(a&: CmpLHS, b&: CmpRHS);
4938
4939 if (CmpLHS != T || CmpRHS != F)
4940 return nullptr;
4941
4942 // This transform is also safe if we do not have (do not care about) -0.0.
4943 if (Q.CxtI && isa<FPMathOperator>(Val: Q.CxtI) && Q.CxtI->hasNoSignedZeros()) {
4944 // (T == F) ? T : F --> F
4945 if (Pred == FCmpInst::FCMP_OEQ)
4946 return F;
4947
4948 // (T != F) ? T : F --> T
4949 if (Pred == FCmpInst::FCMP_UNE)
4950 return T;
4951 }
4952
4953 return nullptr;
4954}
4955
4956/// Look for the following pattern and simplify %to_fold to %identicalPhi.
4957/// Here %phi, %to_fold and %phi.next perform the same functionality as
4958/// %identicalPhi and hence the select instruction %to_fold can be folded
4959/// into %identicalPhi.
4960///
4961/// BB1:
4962/// %identicalPhi = phi [ X, %BB0 ], [ %identicalPhi.next, %BB1 ]
4963/// %phi = phi [ X, %BB0 ], [ %phi.next, %BB1 ]
4964/// ...
4965/// %identicalPhi.next = select %cmp, %val, %identicalPhi
4966/// (or select %cmp, %identicalPhi, %val)
4967/// %to_fold = select %cmp2, %identicalPhi, %phi
4968/// %phi.next = select %cmp, %val, %to_fold
4969/// (or select %cmp, %to_fold, %val)
4970///
4971/// Prove that %phi and %identicalPhi are the same by induction:
4972///
4973/// Base case: Both %phi and %identicalPhi are equal on entry to the loop.
4974/// Inductive case:
4975/// Suppose %phi and %identicalPhi are equal at iteration i.
4976/// We look at their values at iteration i+1 which are %phi.next and
4977/// %identicalPhi.next. They would have become different only when %cmp is
4978/// false and the corresponding values %to_fold and %identicalPhi differ
4979/// (similar reason for the other "or" case in the bracket).
4980///
4981/// The only condition when %to_fold and %identicalPh could differ is when %cmp2
4982/// is false and %to_fold is %phi, which contradicts our inductive hypothesis
4983/// that %phi and %identicalPhi are equal. Thus %phi and %identicalPhi are
4984/// always equal at iteration i+1.
4985bool isSelectWithIdenticalPHI(PHINode &PN, PHINode &IdenticalPN) {
4986 if (PN.getParent() != IdenticalPN.getParent())
4987 return false;
4988 if (PN.getNumIncomingValues() != 2)
4989 return false;
4990
4991 // Check that only the backedge incoming value is different.
4992 unsigned DiffVals = 0;
4993 BasicBlock *DiffValBB = nullptr;
4994 for (unsigned i = 0; i < 2; i++) {
4995 BasicBlock *PredBB = PN.getIncomingBlock(i);
4996 if (PN.getIncomingValue(i) !=
4997 IdenticalPN.getIncomingValueForBlock(BB: PredBB)) {
4998 DiffVals++;
4999 DiffValBB = PredBB;
5000 }
5001 }
5002 if (DiffVals != 1)
5003 return false;
5004 // Now check that the backedge incoming values are two select
5005 // instructions with the same condition. Either their true
5006 // values are the same, or their false values are the same.
5007 auto *SI = dyn_cast<SelectInst>(Val: PN.getIncomingValueForBlock(BB: DiffValBB));
5008 auto *IdenticalSI =
5009 dyn_cast<SelectInst>(Val: IdenticalPN.getIncomingValueForBlock(BB: DiffValBB));
5010 if (!SI || !IdenticalSI)
5011 return false;
5012 if (SI->getCondition() != IdenticalSI->getCondition())
5013 return false;
5014
5015 SelectInst *SIOtherVal = nullptr;
5016 Value *IdenticalSIOtherVal = nullptr;
5017 if (SI->getTrueValue() == IdenticalSI->getTrueValue()) {
5018 SIOtherVal = dyn_cast<SelectInst>(Val: SI->getFalseValue());
5019 IdenticalSIOtherVal = IdenticalSI->getFalseValue();
5020 } else if (SI->getFalseValue() == IdenticalSI->getFalseValue()) {
5021 SIOtherVal = dyn_cast<SelectInst>(Val: SI->getTrueValue());
5022 IdenticalSIOtherVal = IdenticalSI->getTrueValue();
5023 } else {
5024 return false;
5025 }
5026
5027 // Now check that the other values in select, i.e., %to_fold and
5028 // %identicalPhi, are essentially the same value.
5029 if (!SIOtherVal || IdenticalSIOtherVal != &IdenticalPN)
5030 return false;
5031 if (!(SIOtherVal->getTrueValue() == &IdenticalPN &&
5032 SIOtherVal->getFalseValue() == &PN) &&
5033 !(SIOtherVal->getTrueValue() == &PN &&
5034 SIOtherVal->getFalseValue() == &IdenticalPN))
5035 return false;
5036 return true;
5037}
5038
5039/// Given operands for a SelectInst, see if we can fold the result.
5040/// If not, this returns null.
5041static Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
5042 const SimplifyQuery &Q, unsigned MaxRecurse) {
5043 if (auto *CondC = dyn_cast<Constant>(Val: Cond)) {
5044 if (auto *TrueC = dyn_cast<Constant>(Val: TrueVal))
5045 if (auto *FalseC = dyn_cast<Constant>(Val: FalseVal))
5046 if (Constant *C = ConstantFoldSelectInstruction(Cond: CondC, V1: TrueC, V2: FalseC))
5047 return C;
5048
5049 // select poison, X, Y -> poison
5050 if (isa<PoisonValue>(Val: CondC))
5051 return PoisonValue::get(T: TrueVal->getType());
5052
5053 // select undef, X, Y -> X or Y
5054 if (Q.isUndefValue(V: CondC))
5055 return isa<Constant>(Val: FalseVal) ? FalseVal : TrueVal;
5056
5057 // select true, X, Y --> X
5058 // select false, X, Y --> Y
5059 // For vectors, allow undef/poison elements in the condition to match the
5060 // defined elements, so we can eliminate the select.
5061 if (match(V: CondC, P: m_One()))
5062 return TrueVal;
5063 if (match(V: CondC, P: m_Zero()))
5064 return FalseVal;
5065 }
5066
5067 assert(Cond->getType()->isIntOrIntVectorTy(1) &&
5068 "Select must have bool or bool vector condition");
5069 assert(TrueVal->getType() == FalseVal->getType() &&
5070 "Select must have same types for true/false ops");
5071
5072 if (Cond->getType() == TrueVal->getType()) {
5073 // select i1 Cond, i1 true, i1 false --> i1 Cond
5074 if (match(V: TrueVal, P: m_One()) && match(V: FalseVal, P: m_ZeroInt()))
5075 return Cond;
5076
5077 // (X && Y) ? X : Y --> Y (commuted 2 ways)
5078 if (match(V: Cond, P: m_c_LogicalAnd(L: m_Specific(V: TrueVal), R: m_Specific(V: FalseVal))))
5079 return FalseVal;
5080
5081 // (X || Y) ? X : Y --> X (commuted 2 ways)
5082 if (match(V: Cond, P: m_c_LogicalOr(L: m_Specific(V: TrueVal), R: m_Specific(V: FalseVal))))
5083 return TrueVal;
5084
5085 // (X || Y) ? false : X --> false (commuted 2 ways)
5086 if (match(V: Cond, P: m_c_LogicalOr(L: m_Specific(V: FalseVal), R: m_Value())) &&
5087 match(V: TrueVal, P: m_ZeroInt()))
5088 return ConstantInt::getFalse(Ty: Cond->getType());
5089
5090 // Match patterns that end in logical-and.
5091 if (match(V: FalseVal, P: m_ZeroInt())) {
5092 // !(X || Y) && X --> false (commuted 2 ways)
5093 if (match(V: Cond, P: m_Not(V: m_c_LogicalOr(L: m_Specific(V: TrueVal), R: m_Value()))))
5094 return ConstantInt::getFalse(Ty: Cond->getType());
5095 // X && !(X || Y) --> false (commuted 2 ways)
5096 if (match(V: TrueVal, P: m_Not(V: m_c_LogicalOr(L: m_Specific(V: Cond), R: m_Value()))))
5097 return ConstantInt::getFalse(Ty: Cond->getType());
5098
5099 // (X || Y) && Y --> Y (commuted 2 ways)
5100 if (match(V: Cond, P: m_c_LogicalOr(L: m_Specific(V: TrueVal), R: m_Value())))
5101 return TrueVal;
5102 // Y && (X || Y) --> Y (commuted 2 ways)
5103 if (match(V: TrueVal, P: m_c_LogicalOr(L: m_Specific(V: Cond), R: m_Value())))
5104 return Cond;
5105
5106 // (X || Y) && (X || !Y) --> X (commuted 8 ways)
5107 Value *X, *Y;
5108 if (match(V: Cond, P: m_c_LogicalOr(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
5109 match(V: TrueVal, P: m_c_LogicalOr(L: m_Specific(V: X), R: m_Specific(V: Y))))
5110 return X;
5111 if (match(V: TrueVal, P: m_c_LogicalOr(L: m_Value(V&: X), R: m_Not(V: m_Value(V&: Y)))) &&
5112 match(V: Cond, P: m_c_LogicalOr(L: m_Specific(V: X), R: m_Specific(V: Y))))
5113 return X;
5114 }
5115
5116 // Match patterns that end in logical-or.
5117 if (match(V: TrueVal, P: m_One())) {
5118 // !(X && Y) || X --> true (commuted 2 ways)
5119 if (match(V: Cond, P: m_Not(V: m_c_LogicalAnd(L: m_Specific(V: FalseVal), R: m_Value()))))
5120 return ConstantInt::getTrue(Ty: Cond->getType());
5121 // X || !(X && Y) --> true (commuted 2 ways)
5122 if (match(V: FalseVal, P: m_Not(V: m_c_LogicalAnd(L: m_Specific(V: Cond), R: m_Value()))))
5123 return ConstantInt::getTrue(Ty: Cond->getType());
5124
5125 // (X && Y) || Y --> Y (commuted 2 ways)
5126 if (match(V: Cond, P: m_c_LogicalAnd(L: m_Specific(V: FalseVal), R: m_Value())))
5127 return FalseVal;
5128 // Y || (X && Y) --> Y (commuted 2 ways)
5129 if (match(V: FalseVal, P: m_c_LogicalAnd(L: m_Specific(V: Cond), R: m_Value())))
5130 return Cond;
5131 }
5132 }
5133
5134 // select ?, X, X -> X
5135 if (TrueVal == FalseVal)
5136 return TrueVal;
5137
5138 if (Cond == TrueVal) {
5139 // select i1 X, i1 X, i1 false --> X (logical-and)
5140 if (match(V: FalseVal, P: m_ZeroInt()))
5141 return Cond;
5142 // select i1 X, i1 X, i1 true --> true
5143 if (match(V: FalseVal, P: m_One()))
5144 return ConstantInt::getTrue(Ty: Cond->getType());
5145 }
5146 if (Cond == FalseVal) {
5147 // select i1 X, i1 true, i1 X --> X (logical-or)
5148 if (match(V: TrueVal, P: m_One()))
5149 return Cond;
5150 // select i1 X, i1 false, i1 X --> false
5151 if (match(V: TrueVal, P: m_ZeroInt()))
5152 return ConstantInt::getFalse(Ty: Cond->getType());
5153 }
5154
5155 // If the true or false value is poison, we can fold to the other value.
5156 // If the true or false value is undef, we can fold to the other value as
5157 // long as the other value isn't poison.
5158 // select ?, poison, X -> X
5159 // select ?, undef, X -> X
5160 if (isa<PoisonValue>(Val: TrueVal) ||
5161 (Q.isUndefValue(V: TrueVal) && impliesPoison(ValAssumedPoison: FalseVal, V: Cond)))
5162 return FalseVal;
5163 // select ?, X, poison -> X
5164 // select ?, X, undef -> X
5165 if (isa<PoisonValue>(Val: FalseVal) ||
5166 (Q.isUndefValue(V: FalseVal) && impliesPoison(ValAssumedPoison: TrueVal, V: Cond)))
5167 return TrueVal;
5168
5169 // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
5170 Constant *TrueC, *FalseC;
5171 if (isa<FixedVectorType>(Val: TrueVal->getType()) &&
5172 match(V: TrueVal, P: m_Constant(C&: TrueC)) &&
5173 match(V: FalseVal, P: m_Constant(C&: FalseC))) {
5174 unsigned NumElts =
5175 cast<FixedVectorType>(Val: TrueC->getType())->getNumElements();
5176 SmallVector<Constant *, 16> NewC;
5177 for (unsigned i = 0; i != NumElts; ++i) {
5178 // Bail out on incomplete vector constants.
5179 Constant *TEltC = TrueC->getAggregateElement(Elt: i);
5180 Constant *FEltC = FalseC->getAggregateElement(Elt: i);
5181 if (!TEltC || !FEltC)
5182 break;
5183
5184 // If the elements match (undef or not), that value is the result. If only
5185 // one element is undef, choose the defined element as the safe result.
5186 if (TEltC == FEltC)
5187 NewC.push_back(Elt: TEltC);
5188 else if (isa<PoisonValue>(Val: TEltC) ||
5189 (Q.isUndefValue(V: TEltC) && isGuaranteedNotToBePoison(V: FEltC)))
5190 NewC.push_back(Elt: FEltC);
5191 else if (isa<PoisonValue>(Val: FEltC) ||
5192 (Q.isUndefValue(V: FEltC) && isGuaranteedNotToBePoison(V: TEltC)))
5193 NewC.push_back(Elt: TEltC);
5194 else
5195 break;
5196 }
5197 if (NewC.size() == NumElts)
5198 return ConstantVector::get(V: NewC);
5199 }
5200
5201 if (Value *V =
5202 simplifySelectWithICmpCond(CondVal: Cond, TrueVal, FalseVal, Q, MaxRecurse))
5203 return V;
5204
5205 if (Value *V = simplifySelectWithBitTest(CondVal: Cond, TrueVal, FalseVal))
5206 return V;
5207
5208 if (Value *V = simplifySelectWithFCmp(Cond, T: TrueVal, F: FalseVal, Q, MaxRecurse))
5209 return V;
5210
5211 std::optional<bool> Imp = isImpliedByDomCondition(Cond, ContextI: Q.CxtI, DL: Q.DL);
5212 if (Imp)
5213 return *Imp ? TrueVal : FalseVal;
5214 // Look for same PHIs in the true and false values.
5215 if (auto *TruePHI = dyn_cast<PHINode>(Val: TrueVal))
5216 if (auto *FalsePHI = dyn_cast<PHINode>(Val: FalseVal)) {
5217 if (isSelectWithIdenticalPHI(PN&: *TruePHI, IdenticalPN&: *FalsePHI))
5218 return FalseVal;
5219 if (isSelectWithIdenticalPHI(PN&: *FalsePHI, IdenticalPN&: *TruePHI))
5220 return TrueVal;
5221 }
5222 return nullptr;
5223}
5224
5225Value *llvm::simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
5226 const SimplifyQuery &Q) {
5227 return ::simplifySelectInst(Cond, TrueVal, FalseVal, Q, MaxRecurse: RecursionLimit);
5228}
5229
5230/// Given operands for an GetElementPtrInst, see if we can fold the result.
5231/// If not, this returns null.
5232static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
5233 ArrayRef<Value *> Indices, GEPNoWrapFlags NW,
5234 const SimplifyQuery &Q, unsigned) {
5235 // The type of the GEP pointer operand.
5236 unsigned AS =
5237 cast<PointerType>(Val: Ptr->getType()->getScalarType())->getAddressSpace();
5238
5239 // getelementptr P -> P.
5240 if (Indices.empty())
5241 return Ptr;
5242
5243 // Compute the (pointer) type returned by the GEP instruction.
5244 Type *LastType = GetElementPtrInst::getIndexedType(Ty: SrcTy, IdxList: Indices);
5245 Type *GEPTy = Ptr->getType();
5246 if (!GEPTy->isVectorTy()) {
5247 for (Value *Op : Indices) {
5248 // If one of the operands is a vector, the result type is a vector of
5249 // pointers. All vector operands must have the same number of elements.
5250 if (VectorType *VT = dyn_cast<VectorType>(Val: Op->getType())) {
5251 GEPTy = VectorType::get(ElementType: GEPTy, EC: VT->getElementCount());
5252 break;
5253 }
5254 }
5255 }
5256
5257 // All-zero GEP is a no-op, unless it performs a vector splat.
5258 if (Ptr->getType() == GEPTy && all_of(Range&: Indices, P: match_fn(P: m_Zero())))
5259 return Ptr;
5260
5261 // getelementptr poison, idx -> poison
5262 // getelementptr baseptr, poison -> poison
5263 if (isa<PoisonValue>(Val: Ptr) || any_of(Range&: Indices, P: IsaPred<PoisonValue>))
5264 return PoisonValue::get(T: GEPTy);
5265
5266 // getelementptr undef, idx -> undef
5267 if (Q.isUndefValue(V: Ptr))
5268 return UndefValue::get(T: GEPTy);
5269
5270 bool IsScalableVec =
5271 SrcTy->isScalableTy() || any_of(Range&: Indices, P: [](const Value *V) {
5272 return isa<ScalableVectorType>(Val: V->getType());
5273 });
5274
5275 if (Indices.size() == 1) {
5276 Type *Ty = SrcTy;
5277 if (!IsScalableVec && Ty->isSized()) {
5278 Value *P;
5279 uint64_t C;
5280 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
5281 // getelementptr P, N -> P if P points to a type of zero size.
5282 if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
5283 return Ptr;
5284
5285 // The following transforms are only safe if the ptrtoint cast
5286 // doesn't truncate the address of the pointers. The non-address bits
5287 // must be the same, as the underlying objects are the same.
5288 if (Indices[0]->getType()->getScalarSizeInBits() >=
5289 Q.DL.getAddressSizeInBits(AS)) {
5290 auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
5291 return P->getType() == GEPTy &&
5292 getUnderlyingObject(V: P) == getUnderlyingObject(V: Ptr);
5293 };
5294 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
5295 if (TyAllocSize == 1 &&
5296 match(V: Indices[0], P: m_Sub(L: m_PtrToIntOrAddr(Op: m_Value(V&: P)),
5297 R: m_PtrToIntOrAddr(Op: m_Specific(V: Ptr)))) &&
5298 CanSimplify())
5299 return P;
5300
5301 // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
5302 // size 1 << C.
5303 if (match(V: Indices[0], P: m_AShr(L: m_Sub(L: m_PtrToIntOrAddr(Op: m_Value(V&: P)),
5304 R: m_PtrToIntOrAddr(Op: m_Specific(V: Ptr))),
5305 R: m_ConstantInt(V&: C))) &&
5306 TyAllocSize == 1ULL << C && CanSimplify())
5307 return P;
5308
5309 // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
5310 // size C.
5311 if (match(V: Indices[0], P: m_SDiv(L: m_Sub(L: m_PtrToIntOrAddr(Op: m_Value(V&: P)),
5312 R: m_PtrToIntOrAddr(Op: m_Specific(V: Ptr))),
5313 R: m_SpecificInt(V: TyAllocSize))) &&
5314 CanSimplify())
5315 return P;
5316 }
5317 }
5318 }
5319
5320 if (!IsScalableVec && Q.DL.getTypeAllocSize(Ty: LastType) == 1 &&
5321 all_of(Range: Indices.drop_back(N: 1), P: match_fn(P: m_Zero()))) {
5322 unsigned IdxWidth =
5323 Q.DL.getIndexSizeInBits(AS: Ptr->getType()->getPointerAddressSpace());
5324 if (Q.DL.getTypeSizeInBits(Ty: Indices.back()->getType()) == IdxWidth) {
5325 APInt BasePtrOffset(IdxWidth, 0);
5326 Value *StrippedBasePtr =
5327 Ptr->stripAndAccumulateInBoundsConstantOffsets(DL: Q.DL, Offset&: BasePtrOffset);
5328
5329 // Avoid creating inttoptr of zero here: While LLVMs treatment of
5330 // inttoptr is generally conservative, this particular case is folded to
5331 // a null pointer, which will have incorrect provenance.
5332
5333 // gep (gep V, C), (sub 0, V) -> C
5334 if (match(V: Indices.back(),
5335 P: m_Neg(V: m_PtrToInt(Op: m_Specific(V: StrippedBasePtr)))) &&
5336 !BasePtrOffset.isZero()) {
5337 auto *CI = ConstantInt::get(Context&: GEPTy->getContext(), V: BasePtrOffset);
5338 return ConstantExpr::getIntToPtr(C: CI, Ty: GEPTy);
5339 }
5340 // gep (gep V, C), (xor V, -1) -> C-1
5341 if (match(V: Indices.back(),
5342 P: m_Xor(L: m_PtrToInt(Op: m_Specific(V: StrippedBasePtr)), R: m_AllOnes())) &&
5343 !BasePtrOffset.isOne()) {
5344 auto *CI = ConstantInt::get(Context&: GEPTy->getContext(), V: BasePtrOffset - 1);
5345 return ConstantExpr::getIntToPtr(C: CI, Ty: GEPTy);
5346 }
5347 }
5348 }
5349
5350 // Check to see if this is constant foldable.
5351 if (!isa<Constant>(Val: Ptr) || !all_of(Range&: Indices, P: IsaPred<Constant>))
5352 return nullptr;
5353
5354 if (!ConstantExpr::isSupportedGetElementPtr(SrcElemTy: SrcTy))
5355 return ConstantFoldGetElementPtr(Ty: SrcTy, C: cast<Constant>(Val: Ptr), InRange: std::nullopt,
5356 Idxs: Indices);
5357
5358 auto *CE =
5359 ConstantExpr::getGetElementPtr(Ty: SrcTy, C: cast<Constant>(Val: Ptr), IdxList: Indices, NW);
5360 return ConstantFoldConstant(C: CE, DL: Q.DL);
5361}
5362
5363Value *llvm::simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
5364 GEPNoWrapFlags NW, const SimplifyQuery &Q) {
5365 return ::simplifyGEPInst(SrcTy, Ptr, Indices, NW, Q, RecursionLimit);
5366}
5367
5368/// Given operands for an InsertValueInst, see if we can fold the result.
5369/// If not, this returns null.
5370static Value *simplifyInsertValueInst(Value *Agg, Value *Val,
5371 ArrayRef<unsigned> Idxs,
5372 const SimplifyQuery &Q, unsigned) {
5373 if (Constant *CAgg = dyn_cast<Constant>(Val: Agg))
5374 if (Constant *CVal = dyn_cast<Constant>(Val))
5375 return ConstantFoldInsertValueInstruction(Agg: CAgg, Val: CVal, Idxs);
5376
5377 // insertvalue x, poison, n -> x
5378 // insertvalue x, undef, n -> x if x cannot be poison
5379 if (isa<PoisonValue>(Val) ||
5380 (Q.isUndefValue(V: Val) && isGuaranteedNotToBePoison(V: Agg)))
5381 return Agg;
5382
5383 // insertvalue x, (extractvalue y, n), n
5384 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
5385 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
5386 EV->getIndices() == Idxs) {
5387 // insertvalue poison, (extractvalue y, n), n -> y
5388 // insertvalue undef, (extractvalue y, n), n -> y if y cannot be poison
5389 if (isa<PoisonValue>(Val: Agg) ||
5390 (Q.isUndefValue(V: Agg) &&
5391 isGuaranteedNotToBePoison(V: EV->getAggregateOperand())))
5392 return EV->getAggregateOperand();
5393
5394 // insertvalue y, (extractvalue y, n), n -> y
5395 if (Agg == EV->getAggregateOperand())
5396 return Agg;
5397 }
5398
5399 return nullptr;
5400}
5401
5402Value *llvm::simplifyInsertValueInst(Value *Agg, Value *Val,
5403 ArrayRef<unsigned> Idxs,
5404 const SimplifyQuery &Q) {
5405 return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
5406}
5407
5408Value *llvm::simplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
5409 const SimplifyQuery &Q) {
5410 // Try to constant fold.
5411 auto *VecC = dyn_cast<Constant>(Val: Vec);
5412 auto *ValC = dyn_cast<Constant>(Val);
5413 auto *IdxC = dyn_cast<Constant>(Val: Idx);
5414 if (VecC && ValC && IdxC)
5415 return ConstantExpr::getInsertElement(Vec: VecC, Elt: ValC, Idx: IdxC);
5416
5417 // For fixed-length vector, fold into poison if index is out of bounds.
5418 if (auto *CI = dyn_cast<ConstantInt>(Val: Idx)) {
5419 if (isa<FixedVectorType>(Val: Vec->getType()) &&
5420 CI->uge(Num: cast<FixedVectorType>(Val: Vec->getType())->getNumElements()))
5421 return PoisonValue::get(T: Vec->getType());
5422 }
5423
5424 // If index is undef, it might be out of bounds (see above case)
5425 if (Q.isUndefValue(V: Idx))
5426 return PoisonValue::get(T: Vec->getType());
5427
5428 // If the scalar is poison, or it is undef and there is no risk of
5429 // propagating poison from the vector value, simplify to the vector value.
5430 if (isa<PoisonValue>(Val) ||
5431 (Q.isUndefValue(V: Val) && isGuaranteedNotToBePoison(V: Vec)))
5432 return Vec;
5433
5434 // Inserting the splatted value into a constant splat does nothing.
5435 if (VecC && ValC && VecC->getSplatValue() == ValC)
5436 return Vec;
5437
5438 // If we are extracting a value from a vector, then inserting it into the same
5439 // place, that's the input vector:
5440 // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
5441 if (match(V: Val, P: m_ExtractElt(Val: m_Specific(V: Vec), Idx: m_Specific(V: Idx))))
5442 return Vec;
5443
5444 return nullptr;
5445}
5446
5447/// Given operands for an ExtractValueInst, see if we can fold the result.
5448/// If not, this returns null.
5449static Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
5450 const SimplifyQuery &, unsigned) {
5451 if (auto *CAgg = dyn_cast<Constant>(Val: Agg))
5452 return ConstantFoldExtractValueInstruction(Agg: CAgg, Idxs);
5453
5454 // extractvalue x, (insertvalue y, elt, n), n -> elt
5455 unsigned NumIdxs = Idxs.size();
5456 for (auto *IVI = dyn_cast<InsertValueInst>(Val: Agg); IVI != nullptr;
5457 IVI = dyn_cast<InsertValueInst>(Val: IVI->getAggregateOperand())) {
5458 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
5459 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
5460 unsigned NumCommonIdxs = std::min(a: NumInsertValueIdxs, b: NumIdxs);
5461 if (InsertValueIdxs.slice(N: 0, M: NumCommonIdxs) ==
5462 Idxs.slice(N: 0, M: NumCommonIdxs)) {
5463 if (NumIdxs == NumInsertValueIdxs)
5464 return IVI->getInsertedValueOperand();
5465 break;
5466 }
5467 }
5468
5469 // Simplify umul_with_overflow where one operand is 1.
5470 Value *V;
5471 if (Idxs.size() == 1 &&
5472 (match(V: Agg,
5473 P: m_Intrinsic<Intrinsic::umul_with_overflow>(Op0: m_Value(V), Op1: m_One())) ||
5474 match(V: Agg, P: m_Intrinsic<Intrinsic::umul_with_overflow>(Op0: m_One(),
5475 Op1: m_Value(V))))) {
5476 if (Idxs[0] == 0)
5477 return V;
5478 assert(Idxs[0] == 1 && "invalid index");
5479 return getFalse(Ty: CmpInst::makeCmpResultType(opnd_type: V->getType()));
5480 }
5481
5482 return nullptr;
5483}
5484
5485Value *llvm::simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
5486 const SimplifyQuery &Q) {
5487 return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
5488}
5489
5490/// Given operands for an ExtractElementInst, see if we can fold the result.
5491/// If not, this returns null.
5492static Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
5493 const SimplifyQuery &Q, unsigned) {
5494 auto *VecVTy = cast<VectorType>(Val: Vec->getType());
5495 if (auto *CVec = dyn_cast<Constant>(Val: Vec)) {
5496 if (auto *CIdx = dyn_cast<Constant>(Val: Idx))
5497 return ConstantExpr::getExtractElement(Vec: CVec, Idx: CIdx);
5498
5499 if (Q.isUndefValue(V: Vec))
5500 return UndefValue::get(T: VecVTy->getElementType());
5501 }
5502
5503 // An undef extract index can be arbitrarily chosen to be an out-of-range
5504 // index value, which would result in the instruction being poison.
5505 if (Q.isUndefValue(V: Idx))
5506 return PoisonValue::get(T: VecVTy->getElementType());
5507
5508 // If extracting a specified index from the vector, see if we can recursively
5509 // find a previously computed scalar that was inserted into the vector.
5510 if (auto *IdxC = dyn_cast<ConstantInt>(Val: Idx)) {
5511 // For fixed-length vector, fold into undef if index is out of bounds.
5512 unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
5513 if (isa<FixedVectorType>(Val: VecVTy) && IdxC->getValue().uge(RHS: MinNumElts))
5514 return PoisonValue::get(T: VecVTy->getElementType());
5515 // Handle case where an element is extracted from a splat.
5516 if (IdxC->getValue().ult(RHS: MinNumElts))
5517 if (auto *Splat = getSplatValue(V: Vec))
5518 return Splat;
5519 if (Value *Elt = findScalarElement(V: Vec, EltNo: IdxC->getZExtValue()))
5520 return Elt;
5521 } else {
5522 // extractelt x, (insertelt y, elt, n), n -> elt
5523 // If the possibly-variable indices are trivially known to be equal
5524 // (because they are the same operand) then use the value that was
5525 // inserted directly.
5526 auto *IE = dyn_cast<InsertElementInst>(Val: Vec);
5527 if (IE && IE->getOperand(i_nocapture: 2) == Idx)
5528 return IE->getOperand(i_nocapture: 1);
5529
5530 // The index is not relevant if our vector is a splat.
5531 if (Value *Splat = getSplatValue(V: Vec))
5532 return Splat;
5533 }
5534 return nullptr;
5535}
5536
5537Value *llvm::simplifyExtractElementInst(Value *Vec, Value *Idx,
5538 const SimplifyQuery &Q) {
5539 return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
5540}
5541
5542/// See if we can fold the given phi. If not, returns null.
5543static Value *simplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
5544 const SimplifyQuery &Q) {
5545 // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
5546 // here, because the PHI we may succeed simplifying to was not
5547 // def-reachable from the original PHI!
5548
5549 // If all of the PHI's incoming values are the same then replace the PHI node
5550 // with the common value.
5551 Value *CommonValue = nullptr;
5552 bool HasPoisonInput = false;
5553 bool HasUndefInput = false;
5554 for (Value *Incoming : IncomingValues) {
5555 // If the incoming value is the phi node itself, it can safely be skipped.
5556 if (Incoming == PN)
5557 continue;
5558 if (isa<PoisonValue>(Val: Incoming)) {
5559 HasPoisonInput = true;
5560 continue;
5561 }
5562 if (Q.isUndefValue(V: Incoming)) {
5563 // Remember that we saw an undef value, but otherwise ignore them.
5564 HasUndefInput = true;
5565 continue;
5566 }
5567 if (CommonValue && Incoming != CommonValue)
5568 return nullptr; // Not the same, bail out.
5569 CommonValue = Incoming;
5570 }
5571
5572 // If CommonValue is null then all of the incoming values were either undef,
5573 // poison or equal to the phi node itself.
5574 if (!CommonValue)
5575 return HasUndefInput ? UndefValue::get(T: PN->getType())
5576 : PoisonValue::get(T: PN->getType());
5577
5578 if (HasPoisonInput || HasUndefInput) {
5579 // If we have a PHI node like phi(X, undef, X), where X is defined by some
5580 // instruction, we cannot return X as the result of the PHI node unless it
5581 // dominates the PHI block.
5582 if (!valueDominatesPHI(V: CommonValue, P: PN, DT: Q.DT))
5583 return nullptr;
5584
5585 // Make sure we do not replace an undef value with poison.
5586 if (HasUndefInput &&
5587 !isGuaranteedNotToBePoison(V: CommonValue, AC: Q.AC, CtxI: Q.CxtI, DT: Q.DT))
5588 return nullptr;
5589 return CommonValue;
5590 }
5591
5592 return CommonValue;
5593}
5594
5595static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5596 const SimplifyQuery &Q, unsigned MaxRecurse) {
5597 if (auto *C = dyn_cast<Constant>(Val: Op))
5598 return ConstantFoldCastOperand(Opcode: CastOpc, C, DestTy: Ty, DL: Q.DL);
5599
5600 if (auto *CI = dyn_cast<CastInst>(Val: Op)) {
5601 auto *Src = CI->getOperand(i_nocapture: 0);
5602 Type *SrcTy = Src->getType();
5603 Type *MidTy = CI->getType();
5604 Type *DstTy = Ty;
5605 if (Src->getType() == Ty) {
5606 auto FirstOp = CI->getOpcode();
5607 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
5608 if (CastInst::isEliminableCastPair(firstOpcode: FirstOp, secondOpcode: SecondOp, SrcTy, MidTy, DstTy,
5609 DL: &Q.DL) == Instruction::BitCast)
5610 return Src;
5611 }
5612 }
5613
5614 // bitcast x -> x
5615 if (CastOpc == Instruction::BitCast)
5616 if (Op->getType() == Ty)
5617 return Op;
5618
5619 // ptrtoint (ptradd (Ptr, X - ptrtoint(Ptr))) -> X
5620 Value *Ptr, *X;
5621 if ((CastOpc == Instruction::PtrToInt || CastOpc == Instruction::PtrToAddr) &&
5622 match(V: Op,
5623 P: m_PtrAdd(PointerOp: m_Value(V&: Ptr),
5624 OffsetOp: m_Sub(L: m_Value(V&: X), R: m_PtrToIntOrAddr(Op: m_Deferred(V: Ptr))))) &&
5625 X->getType() == Ty && Ty == Q.DL.getIndexType(PtrTy: Ptr->getType()))
5626 return X;
5627
5628 return nullptr;
5629}
5630
5631Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5632 const SimplifyQuery &Q) {
5633 return ::simplifyCastInst(CastOpc, Op, Ty, Q, MaxRecurse: RecursionLimit);
5634}
5635
5636/// For the given destination element of a shuffle, peek through shuffles to
5637/// match a root vector source operand that contains that element in the same
5638/// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
5639static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
5640 int MaskVal, Value *RootVec,
5641 unsigned MaxRecurse) {
5642 if (!MaxRecurse--)
5643 return nullptr;
5644
5645 // Bail out if any mask value is undefined. That kind of shuffle may be
5646 // simplified further based on demanded bits or other folds.
5647 if (MaskVal == -1)
5648 return nullptr;
5649
5650 // The mask value chooses which source operand we need to look at next.
5651 int InVecNumElts = cast<FixedVectorType>(Val: Op0->getType())->getNumElements();
5652 int RootElt = MaskVal;
5653 Value *SourceOp = Op0;
5654 if (MaskVal >= InVecNumElts) {
5655 RootElt = MaskVal - InVecNumElts;
5656 SourceOp = Op1;
5657 }
5658
5659 // If the source operand is a shuffle itself, look through it to find the
5660 // matching root vector.
5661 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(Val: SourceOp)) {
5662 return foldIdentityShuffles(
5663 DestElt, Op0: SourceShuf->getOperand(i_nocapture: 0), Op1: SourceShuf->getOperand(i_nocapture: 1),
5664 MaskVal: SourceShuf->getMaskValue(Elt: RootElt), RootVec, MaxRecurse);
5665 }
5666
5667 // The source operand is not a shuffle. Initialize the root vector value for
5668 // this shuffle if that has not been done yet.
5669 if (!RootVec)
5670 RootVec = SourceOp;
5671
5672 // Give up as soon as a source operand does not match the existing root value.
5673 if (RootVec != SourceOp)
5674 return nullptr;
5675
5676 // The element must be coming from the same lane in the source vector
5677 // (although it may have crossed lanes in intermediate shuffles).
5678 if (RootElt != DestElt)
5679 return nullptr;
5680
5681 return RootVec;
5682}
5683
5684static Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5685 ArrayRef<int> Mask, Type *RetTy,
5686 const SimplifyQuery &Q,
5687 unsigned MaxRecurse) {
5688 if (all_of(Range&: Mask, P: equal_to(Arg: PoisonMaskElem)))
5689 return PoisonValue::get(T: RetTy);
5690
5691 auto *InVecTy = cast<VectorType>(Val: Op0->getType());
5692 unsigned MaskNumElts = Mask.size();
5693 ElementCount InVecEltCount = InVecTy->getElementCount();
5694
5695 bool Scalable = InVecEltCount.isScalable();
5696
5697 SmallVector<int, 32> Indices;
5698 Indices.assign(in_start: Mask.begin(), in_end: Mask.end());
5699
5700 // Canonicalization: If mask does not select elements from an input vector,
5701 // replace that input vector with poison.
5702 if (!Scalable) {
5703 bool MaskSelects0 = false, MaskSelects1 = false;
5704 unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
5705 for (unsigned i = 0; i != MaskNumElts; ++i) {
5706 if (Indices[i] == -1)
5707 continue;
5708 if ((unsigned)Indices[i] < InVecNumElts)
5709 MaskSelects0 = true;
5710 else
5711 MaskSelects1 = true;
5712 }
5713 if (!MaskSelects0)
5714 Op0 = PoisonValue::get(T: InVecTy);
5715 if (!MaskSelects1)
5716 Op1 = PoisonValue::get(T: InVecTy);
5717 }
5718
5719 auto *Op0Const = dyn_cast<Constant>(Val: Op0);
5720 auto *Op1Const = dyn_cast<Constant>(Val: Op1);
5721
5722 // If all operands are constant, constant fold the shuffle. This
5723 // transformation depends on the value of the mask which is not known at
5724 // compile time for scalable vectors
5725 if (Op0Const && Op1Const)
5726 return ConstantExpr::getShuffleVector(V1: Op0Const, V2: Op1Const, Mask);
5727
5728 // Canonicalization: if only one input vector is constant, it shall be the
5729 // second one. This transformation depends on the value of the mask which
5730 // is not known at compile time for scalable vectors
5731 if (!Scalable && Op0Const && !Op1Const) {
5732 std::swap(a&: Op0, b&: Op1);
5733 ShuffleVectorInst::commuteShuffleMask(Mask: Indices,
5734 InVecNumElts: InVecEltCount.getKnownMinValue());
5735 }
5736
5737 // A splat of an inserted scalar constant becomes a vector constant:
5738 // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
5739 // NOTE: We may have commuted above, so analyze the updated Indices, not the
5740 // original mask constant.
5741 // NOTE: This transformation depends on the value of the mask which is not
5742 // known at compile time for scalable vectors
5743 Constant *C;
5744 ConstantInt *IndexC;
5745 if (!Scalable && match(V: Op0, P: m_InsertElt(Val: m_Value(), Elt: m_Constant(C),
5746 Idx: m_ConstantInt(CI&: IndexC)))) {
5747 // Match a splat shuffle mask of the insert index allowing undef elements.
5748 int InsertIndex = IndexC->getZExtValue();
5749 if (all_of(Range&: Indices, P: [InsertIndex](int MaskElt) {
5750 return MaskElt == InsertIndex || MaskElt == -1;
5751 })) {
5752 assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
5753
5754 // Shuffle mask poisons become poison constant result elements.
5755 SmallVector<Constant *, 16> VecC(MaskNumElts, C);
5756 for (unsigned i = 0; i != MaskNumElts; ++i)
5757 if (Indices[i] == -1)
5758 VecC[i] = PoisonValue::get(T: C->getType());
5759 return ConstantVector::get(V: VecC);
5760 }
5761 }
5762
5763 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
5764 // value type is same as the input vectors' type.
5765 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Val: Op0))
5766 if (Q.isUndefValue(V: Op1) && RetTy == InVecTy &&
5767 all_equal(Range: OpShuf->getShuffleMask()))
5768 return Op0;
5769
5770 // All remaining transformation depend on the value of the mask, which is
5771 // not known at compile time for scalable vectors.
5772 if (Scalable)
5773 return nullptr;
5774
5775 // Don't fold a shuffle with undef mask elements. This may get folded in a
5776 // better way using demanded bits or other analysis.
5777 // TODO: Should we allow this?
5778 if (is_contained(Range&: Indices, Element: -1))
5779 return nullptr;
5780
5781 // Check if every element of this shuffle can be mapped back to the
5782 // corresponding element of a single root vector. If so, we don't need this
5783 // shuffle. This handles simple identity shuffles as well as chains of
5784 // shuffles that may widen/narrow and/or move elements across lanes and back.
5785 Value *RootVec = nullptr;
5786 for (unsigned i = 0; i != MaskNumElts; ++i) {
5787 // Note that recursion is limited for each vector element, so if any element
5788 // exceeds the limit, this will fail to simplify.
5789 RootVec =
5790 foldIdentityShuffles(DestElt: i, Op0, Op1, MaskVal: Indices[i], RootVec, MaxRecurse);
5791
5792 // We can't replace a widening/narrowing shuffle with one of its operands.
5793 if (!RootVec || RootVec->getType() != RetTy)
5794 return nullptr;
5795 }
5796 return RootVec;
5797}
5798
5799/// Given operands for a ShuffleVectorInst, fold the result or return null.
5800Value *llvm::simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5801 ArrayRef<int> Mask, Type *RetTy,
5802 const SimplifyQuery &Q) {
5803 return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, MaxRecurse: RecursionLimit);
5804}
5805
5806static Constant *foldConstant(Instruction::UnaryOps Opcode, Value *&Op,
5807 const SimplifyQuery &Q) {
5808 if (auto *C = dyn_cast<Constant>(Val: Op))
5809 return ConstantFoldUnaryOpOperand(Opcode, Op: C, DL: Q.DL);
5810 return nullptr;
5811}
5812
5813/// Given the operand for an FNeg, see if we can fold the result. If not, this
5814/// returns null.
5815static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
5816 const SimplifyQuery &Q, unsigned MaxRecurse) {
5817 if (Constant *C = foldConstant(Opcode: Instruction::FNeg, Op, Q))
5818 return C;
5819
5820 Value *X;
5821 // fneg (fneg X) ==> X
5822 if (match(V: Op, P: m_FNeg(X: m_Value(V&: X))))
5823 return X;
5824
5825 return nullptr;
5826}
5827
5828Value *llvm::simplifyFNegInst(Value *Op, FastMathFlags FMF,
5829 const SimplifyQuery &Q) {
5830 return ::simplifyFNegInst(Op, FMF, Q, MaxRecurse: RecursionLimit);
5831}
5832
5833/// Try to propagate existing NaN values when possible. If not, replace the
5834/// constant or elements in the constant with a canonical NaN.
5835static Constant *propagateNaN(Constant *In) {
5836 Type *Ty = In->getType();
5837 if (auto *VecTy = dyn_cast<FixedVectorType>(Val: Ty)) {
5838 unsigned NumElts = VecTy->getNumElements();
5839 SmallVector<Constant *, 32> NewC(NumElts);
5840 for (unsigned i = 0; i != NumElts; ++i) {
5841 Constant *EltC = In->getAggregateElement(Elt: i);
5842 // Poison elements propagate. NaN propagates except signaling is quieted.
5843 // Replace unknown or undef elements with canonical NaN.
5844 if (EltC && isa<PoisonValue>(Val: EltC))
5845 NewC[i] = EltC;
5846 else if (EltC && EltC->isNaN())
5847 NewC[i] = ConstantFP::get(
5848 Ty: EltC->getType(), V: cast<ConstantFP>(Val: EltC)->getValue().makeQuiet());
5849 else
5850 NewC[i] = ConstantFP::getNaN(Ty: VecTy->getElementType());
5851 }
5852 return ConstantVector::get(V: NewC);
5853 }
5854
5855 // If it is not a fixed vector, but not a simple NaN either, return a
5856 // canonical NaN.
5857 if (!In->isNaN())
5858 return ConstantFP::getNaN(Ty);
5859
5860 // If we known this is a NaN, and it's scalable vector, we must have a splat
5861 // on our hands. Grab that before splatting a QNaN constant.
5862 if (isa<ScalableVectorType>(Val: Ty)) {
5863 auto *Splat = In->getSplatValue();
5864 assert(Splat && Splat->isNaN() &&
5865 "Found a scalable-vector NaN but not a splat");
5866 In = Splat;
5867 }
5868
5869 // Propagate an existing QNaN constant. If it is an SNaN, make it quiet, but
5870 // preserve the sign/payload.
5871 return ConstantFP::get(Ty, V: cast<ConstantFP>(Val: In)->getValue().makeQuiet());
5872}
5873
5874/// Perform folds that are common to any floating-point operation. This implies
5875/// transforms based on poison/undef/NaN because the operation itself makes no
5876/// difference to the result.
5877static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
5878 const SimplifyQuery &Q,
5879 fp::ExceptionBehavior ExBehavior,
5880 RoundingMode Rounding) {
5881 // Poison is independent of anything else. It always propagates from an
5882 // operand to a math result.
5883 if (any_of(Range&: Ops, P: IsaPred<PoisonValue>))
5884 return PoisonValue::get(T: Ops[0]->getType());
5885
5886 for (Value *V : Ops) {
5887 bool IsNan = match(V, P: m_NaN());
5888 bool IsInf = match(V, P: m_Inf());
5889 bool IsUndef = Q.isUndefValue(V);
5890
5891 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5892 // (an undef operand can be chosen to be Nan/Inf), then the result of
5893 // this operation is poison.
5894 if (FMF.noNaNs() && (IsNan || IsUndef))
5895 return PoisonValue::get(T: V->getType());
5896 if (FMF.noInfs() && (IsInf || IsUndef))
5897 return PoisonValue::get(T: V->getType());
5898
5899 if (isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding)) {
5900 // Undef does not propagate because undef means that all bits can take on
5901 // any value. If this is undef * NaN for example, then the result values
5902 // (at least the exponent bits) are limited. Assume the undef is a
5903 // canonical NaN and propagate that.
5904 if (IsUndef)
5905 return ConstantFP::getNaN(Ty: V->getType());
5906 if (IsNan)
5907 return propagateNaN(In: cast<Constant>(Val: V));
5908 } else if (ExBehavior != fp::ebStrict) {
5909 if (IsNan)
5910 return propagateNaN(In: cast<Constant>(Val: V));
5911 }
5912 }
5913 return nullptr;
5914}
5915
5916/// Given operands for an FAdd, see if we can fold the result. If not, this
5917/// returns null.
5918static Value *
5919simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5920 const SimplifyQuery &Q, unsigned MaxRecurse,
5921 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5922 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5923 if (isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
5924 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::FAdd, Op0, Op1, Q))
5925 return C;
5926
5927 if (Constant *C = simplifyFPOp(Ops: {Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5928 return C;
5929
5930 // fadd X, -0 ==> X
5931 // With strict/constrained FP, we have these possible edge cases that do
5932 // not simplify to Op0:
5933 // fadd SNaN, -0.0 --> QNaN
5934 // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5935 if (canIgnoreSNaN(EB: ExBehavior, FMF) &&
5936 (!canRoundingModeBe(RM: Rounding, QRM: RoundingMode::TowardNegative) ||
5937 FMF.noSignedZeros()))
5938 if (match(V: Op1, P: m_NegZeroFP()))
5939 return Op0;
5940
5941 // fadd X, 0 ==> X, when we know X is not -0
5942 if (canIgnoreSNaN(EB: ExBehavior, FMF))
5943 if (match(V: Op1, P: m_PosZeroFP()) &&
5944 (FMF.noSignedZeros() || cannotBeNegativeZero(V: Op0, SQ: Q)))
5945 return Op0;
5946
5947 if (!isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
5948 return nullptr;
5949
5950 if (FMF.noNaNs()) {
5951 // With nnan: X + {+/-}Inf --> {+/-}Inf
5952 if (match(V: Op1, P: m_Inf()))
5953 return Op1;
5954
5955 // With nnan: -X + X --> 0.0 (and commuted variant)
5956 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
5957 // Negative zeros are allowed because we always end up with positive zero:
5958 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5959 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5960 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
5961 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
5962 if (match(V: Op0, P: m_FSub(L: m_AnyZeroFP(), R: m_Specific(V: Op1))) ||
5963 match(V: Op1, P: m_FSub(L: m_AnyZeroFP(), R: m_Specific(V: Op0))))
5964 return ConstantFP::getZero(Ty: Op0->getType());
5965
5966 if (match(V: Op0, P: m_FNeg(X: m_Specific(V: Op1))) ||
5967 match(V: Op1, P: m_FNeg(X: m_Specific(V: Op0))))
5968 return ConstantFP::getZero(Ty: Op0->getType());
5969 }
5970
5971 // (X - Y) + Y --> X
5972 // Y + (X - Y) --> X
5973 Value *X;
5974 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5975 (match(V: Op0, P: m_FSub(L: m_Value(V&: X), R: m_Specific(V: Op1))) ||
5976 match(V: Op1, P: m_FSub(L: m_Value(V&: X), R: m_Specific(V: Op0)))))
5977 return X;
5978
5979 return nullptr;
5980}
5981
5982/// Given operands for an FSub, see if we can fold the result. If not, this
5983/// returns null.
5984static Value *
5985simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5986 const SimplifyQuery &Q, unsigned MaxRecurse,
5987 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5988 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5989 if (isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
5990 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::FSub, Op0, Op1, Q))
5991 return C;
5992
5993 if (Constant *C = simplifyFPOp(Ops: {Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5994 return C;
5995
5996 // fsub X, +0 ==> X
5997 if (canIgnoreSNaN(EB: ExBehavior, FMF) &&
5998 (!canRoundingModeBe(RM: Rounding, QRM: RoundingMode::TowardNegative) ||
5999 FMF.noSignedZeros()))
6000 if (match(V: Op1, P: m_PosZeroFP()))
6001 return Op0;
6002
6003 // fsub X, -0 ==> X, when we know X is not -0
6004 if (canIgnoreSNaN(EB: ExBehavior, FMF))
6005 if (match(V: Op1, P: m_NegZeroFP()) &&
6006 (FMF.noSignedZeros() || cannotBeNegativeZero(V: Op0, SQ: Q)))
6007 return Op0;
6008
6009 // fsub -0.0, (fsub -0.0, X) ==> X
6010 // fsub -0.0, (fneg X) ==> X
6011 Value *X;
6012 if (canIgnoreSNaN(EB: ExBehavior, FMF))
6013 if (match(V: Op0, P: m_NegZeroFP()) && match(V: Op1, P: m_FNeg(X: m_Value(V&: X))))
6014 return X;
6015
6016 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
6017 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
6018 if (canIgnoreSNaN(EB: ExBehavior, FMF))
6019 if (FMF.noSignedZeros() && match(V: Op0, P: m_AnyZeroFP()) &&
6020 (match(V: Op1, P: m_FSub(L: m_AnyZeroFP(), R: m_Value(V&: X))) ||
6021 match(V: Op1, P: m_FNeg(X: m_Value(V&: X)))))
6022 return X;
6023
6024 if (!isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
6025 return nullptr;
6026
6027 if (FMF.noNaNs()) {
6028 // fsub nnan x, x ==> 0.0
6029 if (Op0 == Op1)
6030 return Constant::getNullValue(Ty: Op0->getType());
6031
6032 // With nnan: {+/-}Inf - X --> {+/-}Inf
6033 if (match(V: Op0, P: m_Inf()))
6034 return Op0;
6035
6036 // With nnan: X - {+/-}Inf --> {-/+}Inf
6037 if (match(V: Op1, P: m_Inf()))
6038 return foldConstant(Opcode: Instruction::FNeg, Op&: Op1, Q);
6039 }
6040
6041 // Y - (Y - X) --> X
6042 // (X + Y) - Y --> X
6043 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
6044 (match(V: Op1, P: m_FSub(L: m_Specific(V: Op0), R: m_Value(V&: X))) ||
6045 match(V: Op0, P: m_c_FAdd(L: m_Specific(V: Op1), R: m_Value(V&: X)))))
6046 return X;
6047
6048 return nullptr;
6049}
6050
6051static Value *simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
6052 const SimplifyQuery &Q, unsigned MaxRecurse,
6053 fp::ExceptionBehavior ExBehavior,
6054 RoundingMode Rounding) {
6055 if (Constant *C = simplifyFPOp(Ops: {Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6056 return C;
6057
6058 if (!isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
6059 return nullptr;
6060
6061 // Canonicalize special constants as operand 1.
6062 if (match(V: Op0, P: m_FPOne()) || match(V: Op0, P: m_AnyZeroFP()))
6063 std::swap(a&: Op0, b&: Op1);
6064
6065 // X * 1.0 --> X
6066 if (match(V: Op1, P: m_FPOne()))
6067 return Op0;
6068
6069 if (match(V: Op1, P: m_AnyZeroFP())) {
6070 // X * 0.0 --> 0.0 (with nnan and nsz)
6071 if (FMF.noNaNs() && FMF.noSignedZeros())
6072 return ConstantFP::getZero(Ty: Op0->getType());
6073
6074 KnownFPClass Known = computeKnownFPClass(V: Op0, FMF, InterestedClasses: fcInf | fcNan, SQ: Q);
6075 if (Known.isKnownNever(Mask: fcInf | fcNan)) {
6076 // if nsz is set, return 0.0
6077 if (FMF.noSignedZeros())
6078 return ConstantFP::getZero(Ty: Op0->getType());
6079 // +normal number * (-)0.0 --> (-)0.0
6080 if (Known.SignBit == false)
6081 return Op1;
6082 // -normal number * (-)0.0 --> -(-)0.0
6083 if (Known.SignBit == true)
6084 return foldConstant(Opcode: Instruction::FNeg, Op&: Op1, Q);
6085 }
6086 }
6087
6088 // sqrt(X) * sqrt(X) --> X, if we can:
6089 // 1. Remove the intermediate rounding (reassociate).
6090 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
6091 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
6092 Value *X;
6093 if (Op0 == Op1 && match(V: Op0, P: m_Sqrt(Op0: m_Value(V&: X))) && FMF.allowReassoc() &&
6094 FMF.noNaNs() && FMF.noSignedZeros())
6095 return X;
6096
6097 return nullptr;
6098}
6099
6100/// Given the operands for an FMul, see if we can fold the result
6101static Value *
6102simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6103 const SimplifyQuery &Q, unsigned MaxRecurse,
6104 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
6105 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
6106 if (isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
6107 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::FMul, Op0, Op1, Q))
6108 return C;
6109
6110 // Now apply simplifications that do not require rounding.
6111 return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
6112}
6113
6114Value *llvm::simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6115 const SimplifyQuery &Q,
6116 fp::ExceptionBehavior ExBehavior,
6117 RoundingMode Rounding) {
6118 return ::simplifyFAddInst(Op0, Op1, FMF, Q, MaxRecurse: RecursionLimit, ExBehavior,
6119 Rounding);
6120}
6121
6122Value *llvm::simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6123 const SimplifyQuery &Q,
6124 fp::ExceptionBehavior ExBehavior,
6125 RoundingMode Rounding) {
6126 return ::simplifyFSubInst(Op0, Op1, FMF, Q, MaxRecurse: RecursionLimit, ExBehavior,
6127 Rounding);
6128}
6129
6130Value *llvm::simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6131 const SimplifyQuery &Q,
6132 fp::ExceptionBehavior ExBehavior,
6133 RoundingMode Rounding) {
6134 return ::simplifyFMulInst(Op0, Op1, FMF, Q, MaxRecurse: RecursionLimit, ExBehavior,
6135 Rounding);
6136}
6137
6138Value *llvm::simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
6139 const SimplifyQuery &Q,
6140 fp::ExceptionBehavior ExBehavior,
6141 RoundingMode Rounding) {
6142 return ::simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse: RecursionLimit, ExBehavior,
6143 Rounding);
6144}
6145
6146static Value *
6147simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6148 const SimplifyQuery &Q, unsigned,
6149 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
6150 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
6151 if (isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
6152 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::FDiv, Op0, Op1, Q))
6153 return C;
6154
6155 if (Constant *C = simplifyFPOp(Ops: {Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6156 return C;
6157
6158 if (!isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
6159 return nullptr;
6160
6161 // X / 1.0 -> X
6162 if (match(V: Op1, P: m_FPOne()))
6163 return Op0;
6164
6165 // 0 / X -> 0
6166 // Requires that NaNs are off (X could be zero) and signed zeroes are
6167 // ignored (X could be positive or negative, so the output sign is unknown).
6168 if (FMF.noNaNs() && FMF.noSignedZeros() && match(V: Op0, P: m_AnyZeroFP()))
6169 return ConstantFP::getZero(Ty: Op0->getType());
6170
6171 if (FMF.noNaNs()) {
6172 // X / X -> 1.0 is legal when NaNs are ignored.
6173 // We can ignore infinities because INF/INF is NaN.
6174 if (Op0 == Op1)
6175 return ConstantFP::get(Ty: Op0->getType(), V: 1.0);
6176
6177 // (X * Y) / Y --> X if we can reassociate to the above form.
6178 Value *X;
6179 if (FMF.allowReassoc() && match(V: Op0, P: m_c_FMul(L: m_Value(V&: X), R: m_Specific(V: Op1))))
6180 return X;
6181
6182 // -X / X -> -1.0 and
6183 // X / -X -> -1.0 are legal when NaNs are ignored.
6184 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
6185 if (match(V: Op0, P: m_FNegNSZ(X: m_Specific(V: Op1))) ||
6186 match(V: Op1, P: m_FNegNSZ(X: m_Specific(V: Op0))))
6187 return ConstantFP::get(Ty: Op0->getType(), V: -1.0);
6188
6189 // nnan ninf X / [-]0.0 -> poison
6190 if (FMF.noInfs() && match(V: Op1, P: m_AnyZeroFP()))
6191 return PoisonValue::get(T: Op1->getType());
6192 }
6193
6194 return nullptr;
6195}
6196
6197Value *llvm::simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6198 const SimplifyQuery &Q,
6199 fp::ExceptionBehavior ExBehavior,
6200 RoundingMode Rounding) {
6201 return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6202 Rounding);
6203}
6204
6205static Value *
6206simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6207 const SimplifyQuery &Q, unsigned,
6208 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
6209 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
6210 if (isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
6211 if (Constant *C = foldOrCommuteConstant(Opcode: Instruction::FRem, Op0, Op1, Q))
6212 return C;
6213
6214 if (Constant *C = simplifyFPOp(Ops: {Op0, Op1}, FMF, Q, ExBehavior, Rounding))
6215 return C;
6216
6217 if (!isDefaultFPEnvironment(EB: ExBehavior, RM: Rounding))
6218 return nullptr;
6219
6220 // Unlike fdiv, the result of frem always matches the sign of the dividend.
6221 // The constant match may include undef elements in a vector, so return a full
6222 // zero constant as the result.
6223 if (FMF.noNaNs()) {
6224 // +0 % X -> 0
6225 if (match(V: Op0, P: m_PosZeroFP()))
6226 return ConstantFP::getZero(Ty: Op0->getType());
6227 // -0 % X -> -0
6228 if (match(V: Op0, P: m_NegZeroFP()))
6229 return ConstantFP::getNegativeZero(Ty: Op0->getType());
6230 }
6231
6232 return nullptr;
6233}
6234
6235Value *llvm::simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
6236 const SimplifyQuery &Q,
6237 fp::ExceptionBehavior ExBehavior,
6238 RoundingMode Rounding) {
6239 return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
6240 Rounding);
6241}
6242
6243//=== Helper functions for higher up the class hierarchy.
6244
6245/// Given the operand for a UnaryOperator, see if we can fold the result.
6246/// If not, this returns null.
6247static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
6248 unsigned MaxRecurse) {
6249 switch (Opcode) {
6250 case Instruction::FNeg:
6251 return simplifyFNegInst(Op, FMF: FastMathFlags(), Q, MaxRecurse);
6252 default:
6253 llvm_unreachable("Unexpected opcode");
6254 }
6255}
6256
6257/// Given the operand for a UnaryOperator, see if we can fold the result.
6258/// If not, this returns null.
6259/// Try to use FastMathFlags when folding the result.
6260static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
6261 const FastMathFlags &FMF, const SimplifyQuery &Q,
6262 unsigned MaxRecurse) {
6263 switch (Opcode) {
6264 case Instruction::FNeg:
6265 return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
6266 default:
6267 return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
6268 }
6269}
6270
6271Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
6272 return ::simplifyUnOp(Opcode, Op, Q, MaxRecurse: RecursionLimit);
6273}
6274
6275Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
6276 const SimplifyQuery &Q) {
6277 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, MaxRecurse: RecursionLimit);
6278}
6279
6280/// Given operands for a BinaryOperator, see if we can fold the result.
6281/// If not, this returns null.
6282static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6283 const SimplifyQuery &Q, unsigned MaxRecurse) {
6284 switch (Opcode) {
6285 case Instruction::Add:
6286 return simplifyAddInst(Op0: LHS, Op1: RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6287 MaxRecurse);
6288 case Instruction::Sub:
6289 return simplifySubInst(Op0: LHS, Op1: RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6290 MaxRecurse);
6291 case Instruction::Mul:
6292 return simplifyMulInst(Op0: LHS, Op1: RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6293 MaxRecurse);
6294 case Instruction::SDiv:
6295 return simplifySDivInst(Op0: LHS, Op1: RHS, /* IsExact */ false, Q, MaxRecurse);
6296 case Instruction::UDiv:
6297 return simplifyUDivInst(Op0: LHS, Op1: RHS, /* IsExact */ false, Q, MaxRecurse);
6298 case Instruction::SRem:
6299 return simplifySRemInst(Op0: LHS, Op1: RHS, Q, MaxRecurse);
6300 case Instruction::URem:
6301 return simplifyURemInst(Op0: LHS, Op1: RHS, Q, MaxRecurse);
6302 case Instruction::Shl:
6303 return simplifyShlInst(Op0: LHS, Op1: RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
6304 MaxRecurse);
6305 case Instruction::LShr:
6306 return simplifyLShrInst(Op0: LHS, Op1: RHS, /* IsExact */ false, Q, MaxRecurse);
6307 case Instruction::AShr:
6308 return simplifyAShrInst(Op0: LHS, Op1: RHS, /* IsExact */ false, Q, MaxRecurse);
6309 case Instruction::And:
6310 return simplifyAndInst(Op0: LHS, Op1: RHS, Q, MaxRecurse);
6311 case Instruction::Or:
6312 return simplifyOrInst(Op0: LHS, Op1: RHS, Q, MaxRecurse);
6313 case Instruction::Xor:
6314 return simplifyXorInst(Op0: LHS, Op1: RHS, Q, MaxRecurse);
6315 case Instruction::FAdd:
6316 return simplifyFAddInst(Op0: LHS, Op1: RHS, FMF: FastMathFlags(), Q, MaxRecurse);
6317 case Instruction::FSub:
6318 return simplifyFSubInst(Op0: LHS, Op1: RHS, FMF: FastMathFlags(), Q, MaxRecurse);
6319 case Instruction::FMul:
6320 return simplifyFMulInst(Op0: LHS, Op1: RHS, FMF: FastMathFlags(), Q, MaxRecurse);
6321 case Instruction::FDiv:
6322 return simplifyFDivInst(Op0: LHS, Op1: RHS, FMF: FastMathFlags(), Q, MaxRecurse);
6323 case Instruction::FRem:
6324 return simplifyFRemInst(Op0: LHS, Op1: RHS, FMF: FastMathFlags(), Q, MaxRecurse);
6325 default:
6326 llvm_unreachable("Unexpected opcode");
6327 }
6328}
6329
6330/// Given operands for a BinaryOperator, see if we can fold the result.
6331/// If not, this returns null.
6332/// Try to use FastMathFlags when folding the result.
6333static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6334 const FastMathFlags &FMF, const SimplifyQuery &Q,
6335 unsigned MaxRecurse) {
6336 switch (Opcode) {
6337 case Instruction::FAdd:
6338 return simplifyFAddInst(Op0: LHS, Op1: RHS, FMF, Q, MaxRecurse);
6339 case Instruction::FSub:
6340 return simplifyFSubInst(Op0: LHS, Op1: RHS, FMF, Q, MaxRecurse);
6341 case Instruction::FMul:
6342 return simplifyFMulInst(Op0: LHS, Op1: RHS, FMF, Q, MaxRecurse);
6343 case Instruction::FDiv:
6344 return simplifyFDivInst(Op0: LHS, Op1: RHS, FMF, Q, MaxRecurse);
6345 default:
6346 return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
6347 }
6348}
6349
6350Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6351 const SimplifyQuery &Q) {
6352 return ::simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse: RecursionLimit);
6353}
6354
6355Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6356 FastMathFlags FMF, const SimplifyQuery &Q) {
6357 return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, MaxRecurse: RecursionLimit);
6358}
6359
6360/// Given operands for a CmpInst, see if we can fold the result.
6361static Value *simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS,
6362 const SimplifyQuery &Q, unsigned MaxRecurse) {
6363 if (CmpInst::isIntPredicate(P: Predicate))
6364 return simplifyICmpInst(Pred: Predicate, LHS, RHS, Q, MaxRecurse);
6365 return simplifyFCmpInst(Pred: Predicate, LHS, RHS, FMF: FastMathFlags(), Q, MaxRecurse);
6366}
6367
6368Value *llvm::simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS,
6369 const SimplifyQuery &Q) {
6370 return ::simplifyCmpInst(Predicate, LHS, RHS, Q, MaxRecurse: RecursionLimit);
6371}
6372
6373static bool isIdempotent(Intrinsic::ID ID) {
6374 switch (ID) {
6375 default:
6376 return false;
6377
6378 // Unary idempotent: f(f(x)) = f(x)
6379 case Intrinsic::fabs:
6380 case Intrinsic::floor:
6381 case Intrinsic::ceil:
6382 case Intrinsic::trunc:
6383 case Intrinsic::rint:
6384 case Intrinsic::nearbyint:
6385 case Intrinsic::round:
6386 case Intrinsic::roundeven:
6387 case Intrinsic::canonicalize:
6388 case Intrinsic::arithmetic_fence:
6389 return true;
6390 }
6391}
6392
6393/// Return true if the intrinsic rounds a floating-point value to an integral
6394/// floating-point value (not an integer type).
6395static bool removesFPFraction(Intrinsic::ID ID) {
6396 switch (ID) {
6397 default:
6398 return false;
6399
6400 case Intrinsic::floor:
6401 case Intrinsic::ceil:
6402 case Intrinsic::trunc:
6403 case Intrinsic::rint:
6404 case Intrinsic::nearbyint:
6405 case Intrinsic::round:
6406 case Intrinsic::roundeven:
6407 return true;
6408 }
6409}
6410
6411static Value *simplifyRelativeLoad(Constant *Ptr, Constant *Offset,
6412 const DataLayout &DL) {
6413 GlobalValue *PtrSym;
6414 APInt PtrOffset;
6415 if (!IsConstantOffsetFromGlobal(C: Ptr, GV&: PtrSym, Offset&: PtrOffset, DL))
6416 return nullptr;
6417
6418 Type *Int32Ty = Type::getInt32Ty(C&: Ptr->getContext());
6419
6420 auto *OffsetConstInt = dyn_cast<ConstantInt>(Val: Offset);
6421 if (!OffsetConstInt || OffsetConstInt->getBitWidth() > 64)
6422 return nullptr;
6423
6424 APInt OffsetInt = OffsetConstInt->getValue().sextOrTrunc(
6425 width: DL.getIndexTypeSizeInBits(Ty: Ptr->getType()));
6426 if (OffsetInt.srem(RHS: 4) != 0)
6427 return nullptr;
6428
6429 Constant *Loaded =
6430 ConstantFoldLoadFromConstPtr(C: Ptr, Ty: Int32Ty, Offset: std::move(OffsetInt), DL);
6431 if (!Loaded)
6432 return nullptr;
6433
6434 auto *LoadedCE = dyn_cast<ConstantExpr>(Val: Loaded);
6435 if (!LoadedCE)
6436 return nullptr;
6437
6438 if (LoadedCE->getOpcode() == Instruction::Trunc) {
6439 LoadedCE = dyn_cast<ConstantExpr>(Val: LoadedCE->getOperand(i_nocapture: 0));
6440 if (!LoadedCE)
6441 return nullptr;
6442 }
6443
6444 if (LoadedCE->getOpcode() != Instruction::Sub)
6445 return nullptr;
6446
6447 auto *LoadedLHS = dyn_cast<ConstantExpr>(Val: LoadedCE->getOperand(i_nocapture: 0));
6448 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
6449 return nullptr;
6450 auto *LoadedLHSPtr = LoadedLHS->getOperand(i_nocapture: 0);
6451
6452 Constant *LoadedRHS = LoadedCE->getOperand(i_nocapture: 1);
6453 GlobalValue *LoadedRHSSym;
6454 APInt LoadedRHSOffset;
6455 if (!IsConstantOffsetFromGlobal(C: LoadedRHS, GV&: LoadedRHSSym, Offset&: LoadedRHSOffset,
6456 DL) ||
6457 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
6458 return nullptr;
6459
6460 return LoadedLHSPtr;
6461}
6462
6463// TODO: Need to pass in FastMathFlags
6464static Value *simplifyLdexp(Value *Op0, Value *Op1, const SimplifyQuery &Q,
6465 bool IsStrict) {
6466 // ldexp(poison, x) -> poison
6467 // ldexp(x, poison) -> poison
6468 if (isa<PoisonValue>(Val: Op0) || isa<PoisonValue>(Val: Op1))
6469 return Op0;
6470
6471 // ldexp(undef, x) -> nan
6472 if (Q.isUndefValue(V: Op0))
6473 return ConstantFP::getNaN(Ty: Op0->getType());
6474
6475 if (!IsStrict) {
6476 // TODO: Could insert a canonicalize for strict
6477
6478 // ldexp(x, undef) -> x
6479 if (Q.isUndefValue(V: Op1))
6480 return Op0;
6481 }
6482
6483 const APFloat *C = nullptr;
6484 match(V: Op0, P: PatternMatch::m_APFloat(Res&: C));
6485
6486 // These cases should be safe, even with strictfp.
6487 // ldexp(0.0, x) -> 0.0
6488 // ldexp(-0.0, x) -> -0.0
6489 // ldexp(inf, x) -> inf
6490 // ldexp(-inf, x) -> -inf
6491 if (C && (C->isZero() || C->isInfinity()))
6492 return Op0;
6493
6494 // These are canonicalization dropping, could do it if we knew how we could
6495 // ignore denormal flushes and target handling of nan payload bits.
6496 if (IsStrict)
6497 return nullptr;
6498
6499 // TODO: Could quiet this with strictfp if the exception mode isn't strict.
6500 if (C && C->isNaN())
6501 return ConstantFP::get(Ty: Op0->getType(), V: C->makeQuiet());
6502
6503 // ldexp(x, 0) -> x
6504
6505 // TODO: Could fold this if we know the exception mode isn't
6506 // strict, we know the denormal mode and other target modes.
6507 if (match(V: Op1, P: PatternMatch::m_ZeroInt()))
6508 return Op0;
6509
6510 return nullptr;
6511}
6512
6513static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
6514 const SimplifyQuery &Q,
6515 const CallBase *Call) {
6516 // Idempotent functions return the same result when called repeatedly.
6517 Intrinsic::ID IID = F->getIntrinsicID();
6518 if (isIdempotent(ID: IID))
6519 if (auto *II = dyn_cast<IntrinsicInst>(Val: Op0))
6520 if (II->getIntrinsicID() == IID)
6521 return II;
6522
6523 if (removesFPFraction(ID: IID)) {
6524 // Converting from int or calling a rounding function always results in a
6525 // finite integral number or infinity. For those inputs, rounding functions
6526 // always return the same value, so the (2nd) rounding is eliminated. Ex:
6527 // floor (sitofp x) -> sitofp x
6528 // round (ceil x) -> ceil x
6529 auto *II = dyn_cast<IntrinsicInst>(Val: Op0);
6530 if ((II && removesFPFraction(ID: II->getIntrinsicID())) ||
6531 match(V: Op0, P: m_SIToFP(Op: m_Value())) || match(V: Op0, P: m_UIToFP(Op: m_Value())))
6532 return Op0;
6533 }
6534
6535 Value *X;
6536 switch (IID) {
6537 case Intrinsic::fabs: {
6538 KnownFPClass KnownClass = computeKnownFPClass(V: Op0, InterestedClasses: fcAllFlags, SQ: Q);
6539 if (KnownClass.SignBit == false)
6540 return Op0;
6541
6542 if (KnownClass.cannotBeOrderedLessThanZero() &&
6543 KnownClass.isKnownNeverNaN() && Call->hasNoSignedZeros())
6544 return Op0;
6545
6546 break;
6547 }
6548 case Intrinsic::bswap:
6549 // bswap(bswap(x)) -> x
6550 if (match(V: Op0, P: m_BSwap(Op0: m_Value(V&: X))))
6551 return X;
6552 break;
6553 case Intrinsic::bitreverse:
6554 // bitreverse(bitreverse(x)) -> x
6555 if (match(V: Op0, P: m_BitReverse(Op0: m_Value(V&: X))))
6556 return X;
6557 break;
6558 case Intrinsic::ctpop: {
6559 // ctpop(X) -> 1 iff X is non-zero power of 2.
6560 if (isKnownToBeAPowerOfTwo(V: Op0, DL: Q.DL, /*OrZero*/ false, AC: Q.AC, CxtI: Q.CxtI, DT: Q.DT))
6561 return ConstantInt::get(Ty: Op0->getType(), V: 1);
6562 // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
6563 // ctpop(and X, 1) --> and X, 1
6564 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6565 if (MaskedValueIsZero(V: Op0, Mask: APInt::getHighBitsSet(numBits: BitWidth, hiBitsSet: BitWidth - 1),
6566 SQ: Q))
6567 return Op0;
6568 break;
6569 }
6570 case Intrinsic::exp:
6571 // exp(log(x)) -> x
6572 if (Call->hasAllowReassoc() &&
6573 match(V: Op0, P: m_Intrinsic<Intrinsic::log>(Op0: m_Value(V&: X))))
6574 return X;
6575 break;
6576 case Intrinsic::exp2:
6577 // exp2(log2(x)) -> x
6578 if (Call->hasAllowReassoc() &&
6579 match(V: Op0, P: m_Intrinsic<Intrinsic::log2>(Op0: m_Value(V&: X))))
6580 return X;
6581 break;
6582 case Intrinsic::exp10:
6583 // exp10(log10(x)) -> x
6584 if (Call->hasAllowReassoc() &&
6585 match(V: Op0, P: m_Intrinsic<Intrinsic::log10>(Op0: m_Value(V&: X))))
6586 return X;
6587 break;
6588 case Intrinsic::log:
6589 // log(exp(x)) -> x
6590 if (Call->hasAllowReassoc() &&
6591 match(V: Op0, P: m_Intrinsic<Intrinsic::exp>(Op0: m_Value(V&: X))))
6592 return X;
6593 break;
6594 case Intrinsic::log2:
6595 // log2(exp2(x)) -> x
6596 if (Call->hasAllowReassoc() &&
6597 (match(V: Op0, P: m_Intrinsic<Intrinsic::exp2>(Op0: m_Value(V&: X))) ||
6598 match(V: Op0,
6599 P: m_Intrinsic<Intrinsic::pow>(Op0: m_SpecificFP(V: 2.0), Op1: m_Value(V&: X)))))
6600 return X;
6601 break;
6602 case Intrinsic::log10:
6603 // log10(pow(10.0, x)) -> x
6604 // log10(exp10(x)) -> x
6605 if (Call->hasAllowReassoc() &&
6606 (match(V: Op0, P: m_Intrinsic<Intrinsic::exp10>(Op0: m_Value(V&: X))) ||
6607 match(V: Op0,
6608 P: m_Intrinsic<Intrinsic::pow>(Op0: m_SpecificFP(V: 10.0), Op1: m_Value(V&: X)))))
6609 return X;
6610 break;
6611 case Intrinsic::vector_reverse:
6612 // vector.reverse(vector.reverse(x)) -> x
6613 if (match(V: Op0, P: m_VecReverse(Op0: m_Value(V&: X))))
6614 return X;
6615 // vector.reverse(splat(X)) -> splat(X)
6616 if (isSplatValue(V: Op0))
6617 return Op0;
6618 break;
6619 default:
6620 break;
6621 }
6622
6623 return nullptr;
6624}
6625
6626/// Given a min/max intrinsic, see if it can be removed based on having an
6627/// operand that is another min/max intrinsic with shared operand(s). The caller
6628/// is expected to swap the operand arguments to handle commutation.
6629static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
6630 Value *X, *Y;
6631 if (!match(V: Op0, P: m_MaxOrMin(L: m_Value(V&: X), R: m_Value(V&: Y))))
6632 return nullptr;
6633
6634 auto *MM0 = dyn_cast<IntrinsicInst>(Val: Op0);
6635 if (!MM0)
6636 return nullptr;
6637 Intrinsic::ID IID0 = MM0->getIntrinsicID();
6638
6639 if (Op1 == X || Op1 == Y ||
6640 match(V: Op1, P: m_c_MaxOrMin(L: m_Specific(V: X), R: m_Specific(V: Y)))) {
6641 // max (max X, Y), X --> max X, Y
6642 if (IID0 == IID)
6643 return MM0;
6644 // max (min X, Y), X --> X
6645 if (IID0 == getInverseMinMaxIntrinsic(MinMaxID: IID))
6646 return Op1;
6647 }
6648 return nullptr;
6649}
6650
6651/// Given a min/max intrinsic, see if it can be removed based on having an
6652/// operand that is another min/max intrinsic with shared operand(s). The caller
6653/// is expected to swap the operand arguments to handle commutation.
6654static Value *foldMinimumMaximumSharedOp(Intrinsic::ID IID, Value *Op0,
6655 Value *Op1) {
6656 auto IsMinimumMaximumIntrinsic = [](Intrinsic::ID ID) {
6657 switch (ID) {
6658 case Intrinsic::maxnum:
6659 case Intrinsic::minnum:
6660 case Intrinsic::maximum:
6661 case Intrinsic::minimum:
6662 case Intrinsic::maximumnum:
6663 case Intrinsic::minimumnum:
6664 return true;
6665 default:
6666 return false;
6667 }
6668 };
6669
6670 assert(IsMinimumMaximumIntrinsic(IID) && "Unsupported intrinsic");
6671
6672 auto *M0 = dyn_cast<IntrinsicInst>(Val: Op0);
6673 // If Op0 is not the same intrinsic as IID, do not process.
6674 // This is a difference with integer min/max handling. We do not process the
6675 // case like max(min(X,Y),min(X,Y)) => min(X,Y). But it can be handled by GVN.
6676 if (!M0 || M0->getIntrinsicID() != IID)
6677 return nullptr;
6678 Value *X0 = M0->getOperand(i_nocapture: 0);
6679 Value *Y0 = M0->getOperand(i_nocapture: 1);
6680 // Simple case, m(m(X,Y), X) => m(X, Y)
6681 // m(m(X,Y), Y) => m(X, Y)
6682 // For minimum/maximum, X is NaN => m(NaN, Y) == NaN and m(NaN, NaN) == NaN.
6683 // For minimum/maximum, Y is NaN => m(X, NaN) == NaN and m(NaN, NaN) == NaN.
6684 // For minnum/maxnum, X is NaN => m(NaN, Y) == Y and m(Y, Y) == Y.
6685 // For minnum/maxnum, Y is NaN => m(X, NaN) == X and m(X, NaN) == X.
6686 if (X0 == Op1 || Y0 == Op1)
6687 return M0;
6688
6689 auto *M1 = dyn_cast<IntrinsicInst>(Val: Op1);
6690 if (!M1 || !IsMinimumMaximumIntrinsic(M1->getIntrinsicID()))
6691 return nullptr;
6692 Value *X1 = M1->getOperand(i_nocapture: 0);
6693 Value *Y1 = M1->getOperand(i_nocapture: 1);
6694 Intrinsic::ID IID1 = M1->getIntrinsicID();
6695 // we have a case m(m(X,Y),m'(X,Y)) taking into account m' is commutative.
6696 // if m' is m or inversion of m => m(m(X,Y),m'(X,Y)) == m(X,Y).
6697 // For minimum/maximum, X is NaN => m(NaN,Y) == m'(NaN, Y) == NaN.
6698 // For minimum/maximum, Y is NaN => m(X,NaN) == m'(X, NaN) == NaN.
6699 // For minnum/maxnum, X is NaN => m(NaN,Y) == m'(NaN, Y) == Y.
6700 // For minnum/maxnum, Y is NaN => m(X,NaN) == m'(X, NaN) == X.
6701 if ((X0 == X1 && Y0 == Y1) || (X0 == Y1 && Y0 == X1))
6702 if (IID1 == IID || getInverseMinMaxIntrinsic(MinMaxID: IID1) == IID)
6703 return M0;
6704
6705 return nullptr;
6706}
6707
6708enum class MinMaxOptResult {
6709 CannotOptimize = 0,
6710 UseNewConstVal = 1,
6711 UseOtherVal = 2,
6712 // For undef/poison, we can choose to either propgate undef/poison or
6713 // use the LHS value depending on what will allow more optimization.
6714 UseEither = 3
6715};
6716// Get the optimized value for a min/max instruction with a single constant
6717// input (either undef or scalar constantFP). The result may indicate to
6718// use the non-const LHS value, use a new constant value instead (with NaNs
6719// quieted), or to choose either option in the case of undef/poison.
6720static MinMaxOptResult OptimizeConstMinMax(const Constant *RHSConst,
6721 const Intrinsic::ID IID,
6722 const CallBase *Call,
6723 Constant **OutNewConstVal) {
6724 assert(OutNewConstVal != nullptr);
6725
6726 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
6727 bool ReturnsOtherForAllNaNs =
6728 IID == Intrinsic::minimumnum || IID == Intrinsic::maximumnum;
6729 bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum ||
6730 IID == Intrinsic::minimumnum;
6731
6732 // min/max(x, poison) -> either x or poison
6733 if (isa<UndefValue>(Val: RHSConst)) {
6734 *OutNewConstVal = const_cast<Constant *>(RHSConst);
6735 return MinMaxOptResult::UseEither;
6736 }
6737
6738 const ConstantFP *CFP = dyn_cast<ConstantFP>(Val: RHSConst);
6739 if (!CFP)
6740 return MinMaxOptResult::CannotOptimize;
6741 APFloat CAPF = CFP->getValueAPF();
6742
6743 // minnum(x, qnan) -> x
6744 // maxnum(x, qnan) -> x
6745 // minimum(X, nan) -> qnan
6746 // maximum(X, nan) -> qnan
6747 // minimumnum(X, nan) -> x
6748 // maximumnum(X, nan) -> x
6749 if (CAPF.isNaN()) {
6750 if (PropagateNaN) {
6751 *OutNewConstVal = ConstantFP::get(Ty: CFP->getType(), V: CAPF.makeQuiet());
6752 return MinMaxOptResult::UseNewConstVal;
6753 } else if (ReturnsOtherForAllNaNs || !CAPF.isSignaling()) {
6754 return MinMaxOptResult::UseOtherVal;
6755 }
6756 return MinMaxOptResult::CannotOptimize;
6757 }
6758
6759 if (CAPF.isInfinity() || (Call && Call->hasNoInfs() && CAPF.isLargest())) {
6760 // minimum(X, -inf) -> -inf if nnan
6761 // maximum(X, +inf) -> +inf if nnan
6762 // minimumnum(X, -inf) -> -inf
6763 // maximumnum(X, +inf) -> +inf
6764 if (CAPF.isNegative() == IsMin &&
6765 (ReturnsOtherForAllNaNs || (Call && Call->hasNoNaNs()))) {
6766 *OutNewConstVal = const_cast<Constant *>(RHSConst);
6767 return MinMaxOptResult::UseNewConstVal;
6768 }
6769
6770 // minnum(X, +inf) -> X if nnan
6771 // maxnum(X, -inf) -> X if nnan
6772 // minimum(X, +inf) -> X (ignoring quieting of sNaNs)
6773 // maximum(X, -inf) -> X (ignoring quieting of sNaNs)
6774 // minimumnum(X, +inf) -> X if nnan
6775 // maximumnum(X, -inf) -> X if nnan
6776 if (CAPF.isNegative() != IsMin &&
6777 (PropagateNaN || (Call && Call->hasNoNaNs())))
6778 return MinMaxOptResult::UseOtherVal;
6779 }
6780 return MinMaxOptResult::CannotOptimize;
6781}
6782
6783static Value *simplifySVEIntReduction(Intrinsic::ID IID, Type *ReturnType,
6784 Value *Op0, Value *Op1) {
6785 Constant *C0 = dyn_cast<Constant>(Val: Op0);
6786 Constant *C1 = dyn_cast<Constant>(Val: Op1);
6787 unsigned Width = ReturnType->getPrimitiveSizeInBits();
6788
6789 // All false predicate or reduction of neutral values ==> neutral result.
6790 switch (IID) {
6791 case Intrinsic::aarch64_sve_eorv:
6792 case Intrinsic::aarch64_sve_orv:
6793 case Intrinsic::aarch64_sve_saddv:
6794 case Intrinsic::aarch64_sve_uaddv:
6795 case Intrinsic::aarch64_sve_umaxv:
6796 if ((C0 && C0->isNullValue()) || (C1 && C1->isNullValue()))
6797 return ConstantInt::get(Ty: ReturnType, V: 0);
6798 break;
6799 case Intrinsic::aarch64_sve_andv:
6800 case Intrinsic::aarch64_sve_uminv:
6801 if ((C0 && C0->isNullValue()) || (C1 && C1->isAllOnesValue()))
6802 return ConstantInt::get(Ty: ReturnType, V: APInt::getMaxValue(numBits: Width));
6803 break;
6804 case Intrinsic::aarch64_sve_smaxv:
6805 if ((C0 && C0->isNullValue()) || (C1 && C1->isMinSignedValue()))
6806 return ConstantInt::get(Ty: ReturnType, V: APInt::getSignedMinValue(numBits: Width));
6807 break;
6808 case Intrinsic::aarch64_sve_sminv:
6809 if ((C0 && C0->isNullValue()) || (C1 && C1->isMaxSignedValue()))
6810 return ConstantInt::get(Ty: ReturnType, V: APInt::getSignedMaxValue(numBits: Width));
6811 break;
6812 }
6813
6814 switch (IID) {
6815 case Intrinsic::aarch64_sve_andv:
6816 case Intrinsic::aarch64_sve_orv:
6817 case Intrinsic::aarch64_sve_smaxv:
6818 case Intrinsic::aarch64_sve_sminv:
6819 case Intrinsic::aarch64_sve_umaxv:
6820 case Intrinsic::aarch64_sve_uminv:
6821 // sve_reduce_##(all, splat(X)) ==> X
6822 if (C0 && C0->isAllOnesValue()) {
6823 if (Value *SplatVal = getSplatValue(V: Op1)) {
6824 assert(SplatVal->getType() == ReturnType && "Unexpected result type!");
6825 return SplatVal;
6826 }
6827 }
6828 break;
6829 case Intrinsic::aarch64_sve_eorv:
6830 // sve_reduce_xor(all, splat(X)) ==> 0
6831 if (C0 && C0->isAllOnesValue())
6832 return ConstantInt::get(Ty: ReturnType, V: 0);
6833 break;
6834 }
6835
6836 return nullptr;
6837}
6838
6839Value *llvm::simplifyBinaryIntrinsic(Intrinsic::ID IID, Type *ReturnType,
6840 Value *Op0, Value *Op1,
6841 const SimplifyQuery &Q,
6842 const CallBase *Call) {
6843 unsigned BitWidth = ReturnType->getScalarSizeInBits();
6844 switch (IID) {
6845 case Intrinsic::get_active_lane_mask: {
6846 if (match(V: Op1, P: m_Zero()))
6847 return ConstantInt::getFalse(Ty: ReturnType);
6848
6849 const Function *F = Call->getFunction();
6850 auto *ScalableTy = dyn_cast<ScalableVectorType>(Val: ReturnType);
6851 Attribute Attr = F->getFnAttribute(Kind: Attribute::VScaleRange);
6852 if (ScalableTy && Attr.isValid()) {
6853 std::optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
6854 if (!VScaleMax)
6855 break;
6856 uint64_t MaxPossibleMaskElements =
6857 (uint64_t)ScalableTy->getMinNumElements() * (*VScaleMax);
6858
6859 const APInt *Op1Val;
6860 if (match(V: Op0, P: m_Zero()) && match(V: Op1, P: m_APInt(Res&: Op1Val)) &&
6861 Op1Val->uge(RHS: MaxPossibleMaskElements))
6862 return ConstantInt::getAllOnesValue(Ty: ReturnType);
6863 }
6864 break;
6865 }
6866 case Intrinsic::abs:
6867 // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
6868 // It is always ok to pick the earlier abs. We'll just lose nsw if its only
6869 // on the outer abs.
6870 if (match(V: Op0, P: m_Intrinsic<Intrinsic::abs>(Op0: m_Value(), Op1: m_Value())))
6871 return Op0;
6872 break;
6873
6874 case Intrinsic::cttz: {
6875 Value *X;
6876 if (match(V: Op0, P: m_Shl(L: m_One(), R: m_Value(V&: X))))
6877 return X;
6878 break;
6879 }
6880 case Intrinsic::ctlz: {
6881 Value *X;
6882 if (match(V: Op0, P: m_LShr(L: m_Negative(), R: m_Value(V&: X))))
6883 return X;
6884 if (match(V: Op0, P: m_AShr(L: m_Negative(), R: m_Value())))
6885 return Constant::getNullValue(Ty: ReturnType);
6886 break;
6887 }
6888 case Intrinsic::ptrmask: {
6889 // NOTE: We can't apply this simplifications based on the value of Op1
6890 // because we need to preserve provenance.
6891 if (Q.isUndefValue(V: Op0) || match(V: Op0, P: m_Zero()))
6892 return Constant::getNullValue(Ty: Op0->getType());
6893
6894 assert(Op1->getType()->getScalarSizeInBits() ==
6895 Q.DL.getIndexTypeSizeInBits(Op0->getType()) &&
6896 "Invalid mask width");
6897 // If index-width (mask size) is less than pointer-size then mask is
6898 // 1-extended.
6899 if (match(V: Op1, P: m_PtrToIntOrAddr(Op: m_Specific(V: Op0))))
6900 return Op0;
6901
6902 // NOTE: We may have attributes associated with the return value of the
6903 // llvm.ptrmask intrinsic that will be lost when we just return the
6904 // operand. We should try to preserve them.
6905 if (match(V: Op1, P: m_AllOnes()) || Q.isUndefValue(V: Op1))
6906 return Op0;
6907
6908 Constant *C;
6909 if (match(V: Op1, P: m_ImmConstant(C))) {
6910 KnownBits PtrKnown = computeKnownBits(V: Op0, Q);
6911 // See if we only masking off bits we know are already zero due to
6912 // alignment.
6913 APInt IrrelevantPtrBits =
6914 PtrKnown.Zero.zextOrTrunc(width: C->getType()->getScalarSizeInBits());
6915 C = ConstantFoldBinaryOpOperands(
6916 Opcode: Instruction::Or, LHS: C, RHS: ConstantInt::get(Ty: C->getType(), V: IrrelevantPtrBits),
6917 DL: Q.DL);
6918 if (C != nullptr && C->isAllOnesValue())
6919 return Op0;
6920 }
6921 break;
6922 }
6923 case Intrinsic::smax:
6924 case Intrinsic::smin:
6925 case Intrinsic::umax:
6926 case Intrinsic::umin: {
6927 // If the arguments are the same, this is a no-op.
6928 if (Op0 == Op1)
6929 return Op0;
6930
6931 // Canonicalize immediate constant operand as Op1.
6932 if (match(V: Op0, P: m_ImmConstant()))
6933 std::swap(a&: Op0, b&: Op1);
6934
6935 // Assume undef is the limit value.
6936 if (Q.isUndefValue(V: Op1))
6937 return ConstantInt::get(
6938 Ty: ReturnType, V: MinMaxIntrinsic::getSaturationPoint(ID: IID, numBits: BitWidth));
6939
6940 const APInt *C;
6941 if (match(V: Op1, P: m_APIntAllowPoison(Res&: C))) {
6942 // Clamp to limit value. For example:
6943 // umax(i8 %x, i8 255) --> 255
6944 if (*C == MinMaxIntrinsic::getSaturationPoint(ID: IID, numBits: BitWidth))
6945 return ConstantInt::get(Ty: ReturnType, V: *C);
6946
6947 // If the constant op is the opposite of the limit value, the other must
6948 // be larger/smaller or equal. For example:
6949 // umin(i8 %x, i8 255) --> %x
6950 if (*C == MinMaxIntrinsic::getSaturationPoint(
6951 ID: getInverseMinMaxIntrinsic(MinMaxID: IID), numBits: BitWidth))
6952 return Op0;
6953
6954 // Remove nested call if constant operands allow it. Example:
6955 // max (max X, 7), 5 -> max X, 7
6956 auto *MinMax0 = dyn_cast<IntrinsicInst>(Val: Op0);
6957 if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
6958 // TODO: loosen undef/splat restrictions for vector constants.
6959 Value *M00 = MinMax0->getOperand(i_nocapture: 0), *M01 = MinMax0->getOperand(i_nocapture: 1);
6960 const APInt *InnerC;
6961 if ((match(V: M00, P: m_APInt(Res&: InnerC)) || match(V: M01, P: m_APInt(Res&: InnerC))) &&
6962 ICmpInst::compare(LHS: *InnerC, RHS: *C,
6963 Pred: ICmpInst::getNonStrictPredicate(
6964 pred: MinMaxIntrinsic::getPredicate(ID: IID))))
6965 return Op0;
6966 }
6967 }
6968
6969 if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
6970 return V;
6971 if (Value *V = foldMinMaxSharedOp(IID, Op0: Op1, Op1: Op0))
6972 return V;
6973
6974 ICmpInst::Predicate Pred =
6975 ICmpInst::getNonStrictPredicate(pred: MinMaxIntrinsic::getPredicate(ID: IID));
6976 if (isICmpTrue(Pred, LHS: Op0, RHS: Op1, Q: Q.getWithoutUndef(), MaxRecurse: RecursionLimit))
6977 return Op0;
6978 if (isICmpTrue(Pred, LHS: Op1, RHS: Op0, Q: Q.getWithoutUndef(), MaxRecurse: RecursionLimit))
6979 return Op1;
6980
6981 break;
6982 }
6983 case Intrinsic::scmp:
6984 case Intrinsic::ucmp: {
6985 // Fold to a constant if the relationship between operands can be
6986 // established with certainty
6987 if (isICmpTrue(Pred: CmpInst::ICMP_EQ, LHS: Op0, RHS: Op1, Q, MaxRecurse: RecursionLimit))
6988 return Constant::getNullValue(Ty: ReturnType);
6989
6990 ICmpInst::Predicate PredGT =
6991 IID == Intrinsic::scmp ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
6992 if (isICmpTrue(Pred: PredGT, LHS: Op0, RHS: Op1, Q, MaxRecurse: RecursionLimit))
6993 return ConstantInt::get(Ty: ReturnType, V: 1);
6994
6995 ICmpInst::Predicate PredLT =
6996 IID == Intrinsic::scmp ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
6997 if (isICmpTrue(Pred: PredLT, LHS: Op0, RHS: Op1, Q, MaxRecurse: RecursionLimit))
6998 return ConstantInt::getSigned(Ty: ReturnType, V: -1);
6999
7000 break;
7001 }
7002 case Intrinsic::usub_with_overflow:
7003 case Intrinsic::ssub_with_overflow:
7004 // X - X -> { 0, false }
7005 // X - undef -> { 0, false }
7006 // undef - X -> { 0, false }
7007 if (Op0 == Op1 || Q.isUndefValue(V: Op0) || Q.isUndefValue(V: Op1))
7008 return Constant::getNullValue(Ty: ReturnType);
7009 break;
7010 case Intrinsic::uadd_with_overflow:
7011 case Intrinsic::sadd_with_overflow:
7012 // X + undef -> { -1, false }
7013 // undef + x -> { -1, false }
7014 if (Q.isUndefValue(V: Op0) || Q.isUndefValue(V: Op1)) {
7015 return ConstantStruct::get(
7016 T: cast<StructType>(Val: ReturnType),
7017 V: {Constant::getAllOnesValue(Ty: ReturnType->getStructElementType(N: 0)),
7018 Constant::getNullValue(Ty: ReturnType->getStructElementType(N: 1))});
7019 }
7020 break;
7021 case Intrinsic::umul_with_overflow:
7022 case Intrinsic::smul_with_overflow:
7023 // 0 * X -> { 0, false }
7024 // X * 0 -> { 0, false }
7025 if (match(V: Op0, P: m_Zero()) || match(V: Op1, P: m_Zero()))
7026 return Constant::getNullValue(Ty: ReturnType);
7027 // undef * X -> { 0, false }
7028 // X * undef -> { 0, false }
7029 if (Q.isUndefValue(V: Op0) || Q.isUndefValue(V: Op1))
7030 return Constant::getNullValue(Ty: ReturnType);
7031 break;
7032 case Intrinsic::uadd_sat:
7033 // sat(MAX + X) -> MAX
7034 // sat(X + MAX) -> MAX
7035 if (match(V: Op0, P: m_AllOnes()) || match(V: Op1, P: m_AllOnes()))
7036 return Constant::getAllOnesValue(Ty: ReturnType);
7037 [[fallthrough]];
7038 case Intrinsic::sadd_sat:
7039 // sat(X + undef) -> -1
7040 // sat(undef + X) -> -1
7041 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
7042 // For signed: Assume undef is ~X, in which case X + ~X = -1.
7043 if (Q.isUndefValue(V: Op0) || Q.isUndefValue(V: Op1))
7044 return Constant::getAllOnesValue(Ty: ReturnType);
7045
7046 // X + 0 -> X
7047 if (match(V: Op1, P: m_Zero()))
7048 return Op0;
7049 // 0 + X -> X
7050 if (match(V: Op0, P: m_Zero()))
7051 return Op1;
7052 break;
7053 case Intrinsic::usub_sat:
7054 // sat(0 - X) -> 0, sat(X - MAX) -> 0
7055 if (match(V: Op0, P: m_Zero()) || match(V: Op1, P: m_AllOnes()))
7056 return Constant::getNullValue(Ty: ReturnType);
7057 [[fallthrough]];
7058 case Intrinsic::ssub_sat:
7059 // X - X -> 0, X - undef -> 0, undef - X -> 0
7060 if (Op0 == Op1 || Q.isUndefValue(V: Op0) || Q.isUndefValue(V: Op1))
7061 return Constant::getNullValue(Ty: ReturnType);
7062 // X - 0 -> X
7063 if (match(V: Op1, P: m_Zero()))
7064 return Op0;
7065 break;
7066 case Intrinsic::load_relative:
7067 if (auto *C0 = dyn_cast<Constant>(Val: Op0))
7068 if (auto *C1 = dyn_cast<Constant>(Val: Op1))
7069 return simplifyRelativeLoad(Ptr: C0, Offset: C1, DL: Q.DL);
7070 break;
7071 case Intrinsic::powi:
7072 if (auto *Power = dyn_cast<ConstantInt>(Val: Op1)) {
7073 // powi(x, 0) -> 1.0
7074 if (Power->isZero())
7075 return ConstantFP::get(Ty: Op0->getType(), V: 1.0);
7076 // powi(x, 1) -> x
7077 if (Power->isOne())
7078 return Op0;
7079 }
7080 break;
7081 case Intrinsic::ldexp:
7082 return simplifyLdexp(Op0, Op1, Q, IsStrict: false);
7083 case Intrinsic::copysign:
7084 // copysign X, X --> X
7085 if (Op0 == Op1)
7086 return Op0;
7087 // copysign -X, X --> X
7088 // copysign X, -X --> -X
7089 if (match(V: Op0, P: m_FNeg(X: m_Specific(V: Op1))) ||
7090 match(V: Op1, P: m_FNeg(X: m_Specific(V: Op0))))
7091 return Op1;
7092 break;
7093 case Intrinsic::is_fpclass: {
7094 uint64_t Mask = cast<ConstantInt>(Val: Op1)->getZExtValue();
7095 // If all tests are made, it doesn't matter what the value is.
7096 if ((Mask & fcAllFlags) == fcAllFlags)
7097 return ConstantInt::get(Ty: ReturnType, V: true);
7098 if ((Mask & fcAllFlags) == 0)
7099 return ConstantInt::get(Ty: ReturnType, V: false);
7100 if (Q.isUndefValue(V: Op0))
7101 return UndefValue::get(T: ReturnType);
7102 break;
7103 }
7104 case Intrinsic::maxnum:
7105 case Intrinsic::minnum:
7106 case Intrinsic::maximum:
7107 case Intrinsic::minimum:
7108 case Intrinsic::maximumnum:
7109 case Intrinsic::minimumnum: {
7110 // In some cases here, we deviate from exact IEEE-754 semantics to enable
7111 // optimizations (as allowed by the LLVM IR spec) by returning one of the
7112 // arguments unmodified instead of inserting an llvm.canonicalize to
7113 // transform input sNaNs into qNaNs,
7114
7115 // If the arguments are the same, this is a no-op (ignoring NaN quieting)
7116 if (Op0 == Op1)
7117 return Op0;
7118
7119 // Canonicalize constant operand as Op1.
7120 if (isa<Constant>(Val: Op0))
7121 std::swap(a&: Op0, b&: Op1);
7122
7123 if (Constant *C = dyn_cast<Constant>(Val: Op1)) {
7124 MinMaxOptResult OptResult = MinMaxOptResult::CannotOptimize;
7125 Constant *NewConst = nullptr;
7126
7127 if (VectorType *VTy = dyn_cast<VectorType>(Val: C->getType())) {
7128 ElementCount ElemCount = VTy->getElementCount();
7129
7130 if (Constant *SplatVal = C->getSplatValue()) {
7131 // Handle splat vectors (including scalable vectors)
7132 OptResult = OptimizeConstMinMax(RHSConst: SplatVal, IID, Call, OutNewConstVal: &NewConst);
7133 if (OptResult == MinMaxOptResult::UseNewConstVal)
7134 NewConst = ConstantVector::getSplat(EC: ElemCount, Elt: NewConst);
7135
7136 } else if (ElemCount.isFixed()) {
7137 // Storage to build up new const return value (with NaNs quieted)
7138 SmallVector<Constant *, 16> NewC(ElemCount.getFixedValue());
7139
7140 // Check elementwise whether we can optimize to either a constant
7141 // value or return the LHS value. We cannot mix and match LHS +
7142 // constant elements, as this would require inserting a new
7143 // VectorShuffle instruction, which is not allowed in simplifyBinOp.
7144 OptResult = MinMaxOptResult::UseEither;
7145 for (unsigned i = 0; i != ElemCount.getFixedValue(); ++i) {
7146 auto *Elt = C->getAggregateElement(Elt: i);
7147 if (!Elt) {
7148 OptResult = MinMaxOptResult::CannotOptimize;
7149 break;
7150 }
7151 auto ElemResult = OptimizeConstMinMax(RHSConst: Elt, IID, Call, OutNewConstVal: &NewConst);
7152 if (ElemResult == MinMaxOptResult::CannotOptimize ||
7153 (ElemResult != OptResult &&
7154 OptResult != MinMaxOptResult::UseEither &&
7155 ElemResult != MinMaxOptResult::UseEither)) {
7156 OptResult = MinMaxOptResult::CannotOptimize;
7157 break;
7158 }
7159 NewC[i] = NewConst;
7160 if (ElemResult != MinMaxOptResult::UseEither)
7161 OptResult = ElemResult;
7162 }
7163 if (OptResult == MinMaxOptResult::UseNewConstVal)
7164 NewConst = ConstantVector::get(V: NewC);
7165 }
7166 } else {
7167 // Handle scalar inputs
7168 OptResult = OptimizeConstMinMax(RHSConst: C, IID, Call, OutNewConstVal: &NewConst);
7169 }
7170
7171 if (OptResult == MinMaxOptResult::UseOtherVal ||
7172 OptResult == MinMaxOptResult::UseEither)
7173 return Op0; // Return the other arg (ignoring NaN quieting)
7174 else if (OptResult == MinMaxOptResult::UseNewConstVal)
7175 return NewConst;
7176 }
7177
7178 // Min/max of the same operation with common operand:
7179 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
7180 if (Value *V = foldMinimumMaximumSharedOp(IID, Op0, Op1))
7181 return V;
7182 if (Value *V = foldMinimumMaximumSharedOp(IID, Op0: Op1, Op1: Op0))
7183 return V;
7184
7185 break;
7186 }
7187 case Intrinsic::vector_extract: {
7188 // (extract_vector (insert_vector _, X, 0), 0) -> X
7189 unsigned IdxN = cast<ConstantInt>(Val: Op1)->getZExtValue();
7190 Value *X = nullptr;
7191 if (match(V: Op0, P: m_Intrinsic<Intrinsic::vector_insert>(Op0: m_Value(), Op1: m_Value(V&: X),
7192 Op2: m_Zero())) &&
7193 IdxN == 0 && X->getType() == ReturnType)
7194 return X;
7195
7196 break;
7197 }
7198
7199 case Intrinsic::aarch64_sve_andv:
7200 case Intrinsic::aarch64_sve_eorv:
7201 case Intrinsic::aarch64_sve_orv:
7202 case Intrinsic::aarch64_sve_saddv:
7203 case Intrinsic::aarch64_sve_smaxv:
7204 case Intrinsic::aarch64_sve_sminv:
7205 case Intrinsic::aarch64_sve_uaddv:
7206 case Intrinsic::aarch64_sve_umaxv:
7207 case Intrinsic::aarch64_sve_uminv:
7208 return simplifySVEIntReduction(IID, ReturnType, Op0, Op1);
7209 default:
7210 break;
7211 }
7212
7213 return nullptr;
7214}
7215
7216static Value *simplifyIntrinsic(CallBase *Call, Value *Callee,
7217 ArrayRef<Value *> Args,
7218 const SimplifyQuery &Q) {
7219 // Operand bundles should not be in Args.
7220 assert(Call->arg_size() == Args.size());
7221 unsigned NumOperands = Args.size();
7222 Function *F = cast<Function>(Val: Callee);
7223 Intrinsic::ID IID = F->getIntrinsicID();
7224
7225 if (IID != Intrinsic::not_intrinsic && intrinsicPropagatesPoison(IID) &&
7226 any_of(Range&: Args, P: IsaPred<PoisonValue>))
7227 return PoisonValue::get(T: F->getReturnType());
7228 // Most of the intrinsics with no operands have some kind of side effect.
7229 // Don't simplify.
7230 if (!NumOperands) {
7231 switch (IID) {
7232 case Intrinsic::vscale: {
7233 Type *RetTy = F->getReturnType();
7234 ConstantRange CR = getVScaleRange(F: Call->getFunction(), BitWidth: 64);
7235 if (const APInt *C = CR.getSingleElement())
7236 return ConstantInt::get(Ty: RetTy, V: C->getZExtValue());
7237 return nullptr;
7238 }
7239 default:
7240 return nullptr;
7241 }
7242 }
7243
7244 if (NumOperands == 1)
7245 return simplifyUnaryIntrinsic(F, Op0: Args[0], Q, Call);
7246
7247 if (NumOperands == 2)
7248 return simplifyBinaryIntrinsic(IID, ReturnType: F->getReturnType(), Op0: Args[0], Op1: Args[1], Q,
7249 Call);
7250
7251 // Handle intrinsics with 3 or more arguments.
7252 switch (IID) {
7253 case Intrinsic::masked_load:
7254 case Intrinsic::masked_gather: {
7255 Value *MaskArg = Args[1];
7256 Value *PassthruArg = Args[2];
7257 // If the mask is all zeros or undef, the "passthru" argument is the result.
7258 if (maskIsAllZeroOrUndef(Mask: MaskArg))
7259 return PassthruArg;
7260 return nullptr;
7261 }
7262 case Intrinsic::fshl:
7263 case Intrinsic::fshr: {
7264 Value *Op0 = Args[0], *Op1 = Args[1], *ShAmtArg = Args[2];
7265
7266 // If both operands are undef, the result is undef.
7267 if (Q.isUndefValue(V: Op0) && Q.isUndefValue(V: Op1))
7268 return UndefValue::get(T: F->getReturnType());
7269
7270 // If shift amount is undef, assume it is zero.
7271 if (Q.isUndefValue(V: ShAmtArg))
7272 return Args[IID == Intrinsic::fshl ? 0 : 1];
7273
7274 const APInt *ShAmtC;
7275 if (match(V: ShAmtArg, P: m_APInt(Res&: ShAmtC))) {
7276 // If there's effectively no shift, return the 1st arg or 2nd arg.
7277 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
7278 if (ShAmtC->urem(RHS: BitWidth).isZero())
7279 return Args[IID == Intrinsic::fshl ? 0 : 1];
7280 }
7281
7282 // Rotating zero by anything is zero.
7283 if (match(V: Op0, P: m_Zero()) && match(V: Op1, P: m_Zero()))
7284 return ConstantInt::getNullValue(Ty: F->getReturnType());
7285
7286 // Rotating -1 by anything is -1.
7287 if (match(V: Op0, P: m_AllOnes()) && match(V: Op1, P: m_AllOnes()))
7288 return ConstantInt::getAllOnesValue(Ty: F->getReturnType());
7289
7290 return nullptr;
7291 }
7292 case Intrinsic::experimental_constrained_fma: {
7293 auto *FPI = cast<ConstrainedFPIntrinsic>(Val: Call);
7294 if (Value *V = simplifyFPOp(Ops: Args, FMF: {}, Q, ExBehavior: *FPI->getExceptionBehavior(),
7295 Rounding: *FPI->getRoundingMode()))
7296 return V;
7297 return nullptr;
7298 }
7299 case Intrinsic::fma:
7300 case Intrinsic::fmuladd: {
7301 if (Value *V = simplifyFPOp(Ops: Args, FMF: {}, Q, ExBehavior: fp::ebIgnore,
7302 Rounding: RoundingMode::NearestTiesToEven))
7303 return V;
7304 return nullptr;
7305 }
7306 case Intrinsic::smul_fix:
7307 case Intrinsic::smul_fix_sat: {
7308 Value *Op0 = Args[0];
7309 Value *Op1 = Args[1];
7310 Value *Op2 = Args[2];
7311 Type *ReturnType = F->getReturnType();
7312
7313 // Canonicalize constant operand as Op1 (ConstantFolding handles the case
7314 // when both Op0 and Op1 are constant so we do not care about that special
7315 // case here).
7316 if (isa<Constant>(Val: Op0))
7317 std::swap(a&: Op0, b&: Op1);
7318
7319 // X * 0 -> 0
7320 if (match(V: Op1, P: m_Zero()))
7321 return Constant::getNullValue(Ty: ReturnType);
7322
7323 // X * undef -> 0
7324 if (Q.isUndefValue(V: Op1))
7325 return Constant::getNullValue(Ty: ReturnType);
7326
7327 // X * (1 << Scale) -> X
7328 APInt ScaledOne =
7329 APInt::getOneBitSet(numBits: ReturnType->getScalarSizeInBits(),
7330 BitNo: cast<ConstantInt>(Val: Op2)->getZExtValue());
7331 if (ScaledOne.isNonNegative() && match(V: Op1, P: m_SpecificInt(V: ScaledOne)))
7332 return Op0;
7333
7334 return nullptr;
7335 }
7336 case Intrinsic::vector_insert: {
7337 Value *Vec = Args[0];
7338 Value *SubVec = Args[1];
7339 Value *Idx = Args[2];
7340 Type *ReturnType = F->getReturnType();
7341
7342 // (insert_vector Y, (extract_vector X, 0), 0) -> X
7343 // where: Y is X, or Y is undef
7344 unsigned IdxN = cast<ConstantInt>(Val: Idx)->getZExtValue();
7345 Value *X = nullptr;
7346 if (match(V: SubVec,
7347 P: m_Intrinsic<Intrinsic::vector_extract>(Op0: m_Value(V&: X), Op1: m_Zero())) &&
7348 (Q.isUndefValue(V: Vec) || Vec == X) && IdxN == 0 &&
7349 X->getType() == ReturnType)
7350 return X;
7351
7352 return nullptr;
7353 }
7354 case Intrinsic::vector_splice_left:
7355 case Intrinsic::vector_splice_right: {
7356 Value *Offset = Args[2];
7357 auto *Ty = cast<VectorType>(Val: F->getReturnType());
7358 if (Q.isUndefValue(V: Offset))
7359 return PoisonValue::get(T: Ty);
7360
7361 unsigned BitWidth = Offset->getType()->getScalarSizeInBits();
7362 ConstantRange NumElts(
7363 APInt(BitWidth, Ty->getElementCount().getKnownMinValue()));
7364 if (Ty->isScalableTy())
7365 NumElts = NumElts.multiply(Other: getVScaleRange(F: Call->getFunction(), BitWidth));
7366
7367 // If we know Offset > NumElts, simplify to poison.
7368 ConstantRange CR = computeConstantRangeIncludingKnownBits(V: Offset, ForSigned: false, SQ: Q);
7369 if (CR.getUnsignedMin().ugt(RHS: NumElts.getUnsignedMax()))
7370 return PoisonValue::get(T: Ty);
7371
7372 // splice.left(a, b, 0) --> a, splice.right(a, b, 0) --> b
7373 if (CR.isSingleElement() && CR.getSingleElement()->isZero())
7374 return IID == Intrinsic::vector_splice_left ? Args[0] : Args[1];
7375
7376 return nullptr;
7377 }
7378 case Intrinsic::experimental_constrained_fadd: {
7379 auto *FPI = cast<ConstrainedFPIntrinsic>(Val: Call);
7380 return simplifyFAddInst(Op0: Args[0], Op1: Args[1], FMF: FPI->getFastMathFlags(), Q,
7381 ExBehavior: *FPI->getExceptionBehavior(),
7382 Rounding: *FPI->getRoundingMode());
7383 }
7384 case Intrinsic::experimental_constrained_fsub: {
7385 auto *FPI = cast<ConstrainedFPIntrinsic>(Val: Call);
7386 return simplifyFSubInst(Op0: Args[0], Op1: Args[1], FMF: FPI->getFastMathFlags(), Q,
7387 ExBehavior: *FPI->getExceptionBehavior(),
7388 Rounding: *FPI->getRoundingMode());
7389 }
7390 case Intrinsic::experimental_constrained_fmul: {
7391 auto *FPI = cast<ConstrainedFPIntrinsic>(Val: Call);
7392 return simplifyFMulInst(Op0: Args[0], Op1: Args[1], FMF: FPI->getFastMathFlags(), Q,
7393 ExBehavior: *FPI->getExceptionBehavior(),
7394 Rounding: *FPI->getRoundingMode());
7395 }
7396 case Intrinsic::experimental_constrained_fdiv: {
7397 auto *FPI = cast<ConstrainedFPIntrinsic>(Val: Call);
7398 return simplifyFDivInst(Op0: Args[0], Op1: Args[1], FMF: FPI->getFastMathFlags(), Q,
7399 ExBehavior: *FPI->getExceptionBehavior(),
7400 Rounding: *FPI->getRoundingMode());
7401 }
7402 case Intrinsic::experimental_constrained_frem: {
7403 auto *FPI = cast<ConstrainedFPIntrinsic>(Val: Call);
7404 return simplifyFRemInst(Op0: Args[0], Op1: Args[1], FMF: FPI->getFastMathFlags(), Q,
7405 ExBehavior: *FPI->getExceptionBehavior(),
7406 Rounding: *FPI->getRoundingMode());
7407 }
7408 case Intrinsic::experimental_constrained_ldexp:
7409 return simplifyLdexp(Op0: Args[0], Op1: Args[1], Q, IsStrict: true);
7410 case Intrinsic::experimental_gc_relocate: {
7411 GCRelocateInst &GCR = *cast<GCRelocateInst>(Val: Call);
7412 Value *DerivedPtr = GCR.getDerivedPtr();
7413 Value *BasePtr = GCR.getBasePtr();
7414
7415 // Undef is undef, even after relocation.
7416 if (isa<UndefValue>(Val: DerivedPtr) || isa<UndefValue>(Val: BasePtr)) {
7417 return UndefValue::get(T: GCR.getType());
7418 }
7419
7420 if (auto *PT = dyn_cast<PointerType>(Val: GCR.getType())) {
7421 // For now, the assumption is that the relocation of null will be null
7422 // for most any collector. If this ever changes, a corresponding hook
7423 // should be added to GCStrategy and this code should check it first.
7424 if (isa<ConstantPointerNull>(Val: DerivedPtr)) {
7425 // Use null-pointer of gc_relocate's type to replace it.
7426 return ConstantPointerNull::get(T: PT);
7427 }
7428 }
7429 return nullptr;
7430 }
7431 case Intrinsic::experimental_vp_reverse: {
7432 Value *Vec = Call->getArgOperand(i: 0);
7433 Value *EVL = Call->getArgOperand(i: 2);
7434
7435 Value *X;
7436 // vp.reverse(vp.reverse(X)) == X (mask doesn't matter)
7437 if (match(V: Vec, P: m_Intrinsic<Intrinsic::experimental_vp_reverse>(
7438 Op0: m_Value(V&: X), Op1: m_Value(), Op2: m_Specific(V: EVL))))
7439 return X;
7440
7441 // vp.reverse(splat(X)) -> splat(X) (regardless of mask and EVL)
7442 if (isSplatValue(V: Vec))
7443 return Vec;
7444 return nullptr;
7445 }
7446 default:
7447 return nullptr;
7448 }
7449}
7450
7451static Value *tryConstantFoldCall(CallBase *Call, Value *Callee,
7452 ArrayRef<Value *> Args,
7453 const SimplifyQuery &Q) {
7454 auto *F = dyn_cast<Function>(Val: Callee);
7455 if (!F || !canConstantFoldCallTo(Call, F))
7456 return nullptr;
7457
7458 SmallVector<Constant *, 4> ConstantArgs;
7459 ConstantArgs.reserve(N: Args.size());
7460 for (Value *Arg : Args) {
7461 Constant *C = dyn_cast<Constant>(Val: Arg);
7462 if (!C) {
7463 if (isa<MetadataAsValue>(Val: Arg))
7464 continue;
7465 return nullptr;
7466 }
7467 ConstantArgs.push_back(Elt: C);
7468 }
7469
7470 return ConstantFoldCall(Call, F, Operands: ConstantArgs, TLI: Q.TLI);
7471}
7472
7473Value *llvm::simplifyCall(CallBase *Call, Value *Callee, ArrayRef<Value *> Args,
7474 const SimplifyQuery &Q) {
7475 // Args should not contain operand bundle operands.
7476 assert(Call->arg_size() == Args.size());
7477
7478 // musttail calls can only be simplified if they are also DCEd.
7479 // As we can't guarantee this here, don't simplify them.
7480 if (Call->isMustTailCall())
7481 return nullptr;
7482
7483 // call undef -> poison
7484 // call null -> poison
7485 if (isa<UndefValue>(Val: Callee) || isa<ConstantPointerNull>(Val: Callee))
7486 return PoisonValue::get(T: Call->getType());
7487
7488 if (Value *V = tryConstantFoldCall(Call, Callee, Args, Q))
7489 return V;
7490
7491 auto *F = dyn_cast<Function>(Val: Callee);
7492 if (F && F->isIntrinsic())
7493 if (Value *Ret = simplifyIntrinsic(Call, Callee, Args, Q))
7494 return Ret;
7495
7496 return nullptr;
7497}
7498
7499Value *llvm::simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q) {
7500 assert(isa<ConstrainedFPIntrinsic>(Call));
7501 SmallVector<Value *, 4> Args(Call->args());
7502 if (Value *V = tryConstantFoldCall(Call, Callee: Call->getCalledOperand(), Args, Q))
7503 return V;
7504 if (Value *Ret = simplifyIntrinsic(Call, Callee: Call->getCalledOperand(), Args, Q))
7505 return Ret;
7506 return nullptr;
7507}
7508
7509/// Given operands for a Freeze, see if we can fold the result.
7510static Value *simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
7511 // Use a utility function defined in ValueTracking.
7512 if (llvm::isGuaranteedNotToBeUndefOrPoison(V: Op0, AC: Q.AC, CtxI: Q.CxtI, DT: Q.DT))
7513 return Op0;
7514 // We have room for improvement.
7515 return nullptr;
7516}
7517
7518Value *llvm::simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
7519 return ::simplifyFreezeInst(Op0, Q);
7520}
7521
7522Value *llvm::simplifyLoadInst(LoadInst *LI, Value *PtrOp,
7523 const SimplifyQuery &Q) {
7524 if (LI->isVolatile())
7525 return nullptr;
7526
7527 if (auto *PtrOpC = dyn_cast<Constant>(Val: PtrOp))
7528 return ConstantFoldLoadFromConstPtr(C: PtrOpC, Ty: LI->getType(), DL: Q.DL);
7529
7530 // We can only fold the load if it is from a constant global with definitive
7531 // initializer. Skip expensive logic if this is not the case.
7532 auto *GV = dyn_cast<GlobalVariable>(Val: getUnderlyingObject(V: PtrOp));
7533 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
7534 return nullptr;
7535
7536 // If GlobalVariable's initializer is uniform, then return the constant
7537 // regardless of its offset.
7538 if (Constant *C = ConstantFoldLoadFromUniformValue(C: GV->getInitializer(),
7539 Ty: LI->getType(), DL: Q.DL))
7540 return C;
7541
7542 // Try to convert operand into a constant by stripping offsets while looking
7543 // through invariant.group intrinsics.
7544 APInt Offset(Q.DL.getIndexTypeSizeInBits(Ty: PtrOp->getType()), 0);
7545 PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
7546 DL: Q.DL, Offset, /* AllowNonInbounts */ AllowNonInbounds: true,
7547 /* AllowInvariantGroup */ true);
7548 if (PtrOp == GV) {
7549 // Index size may have changed due to address space casts.
7550 Offset = Offset.sextOrTrunc(width: Q.DL.getIndexTypeSizeInBits(Ty: PtrOp->getType()));
7551 return ConstantFoldLoadFromConstPtr(C: GV, Ty: LI->getType(), Offset: std::move(Offset),
7552 DL: Q.DL);
7553 }
7554
7555 return nullptr;
7556}
7557
7558/// See if we can compute a simplified version of this instruction.
7559/// If not, this returns null.
7560
7561static Value *simplifyInstructionWithOperands(Instruction *I,
7562 ArrayRef<Value *> NewOps,
7563 const SimplifyQuery &SQ,
7564 unsigned MaxRecurse) {
7565 assert(I->getFunction() && "instruction should be inserted in a function");
7566 assert((!SQ.CxtI || SQ.CxtI->getFunction() == I->getFunction()) &&
7567 "context instruction should be in the same function");
7568
7569 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
7570
7571 switch (I->getOpcode()) {
7572 default:
7573 if (all_of(Range&: NewOps, P: IsaPred<Constant>)) {
7574 SmallVector<Constant *, 8> NewConstOps(NewOps.size());
7575 transform(Range&: NewOps, d_first: NewConstOps.begin(),
7576 F: [](Value *V) { return cast<Constant>(Val: V); });
7577 return ConstantFoldInstOperands(I, Ops: NewConstOps, DL: Q.DL, TLI: Q.TLI);
7578 }
7579 return nullptr;
7580 case Instruction::FNeg:
7581 return simplifyFNegInst(Op: NewOps[0], FMF: I->getFastMathFlags(), Q, MaxRecurse);
7582 case Instruction::FAdd:
7583 return simplifyFAddInst(Op0: NewOps[0], Op1: NewOps[1], FMF: I->getFastMathFlags(), Q,
7584 MaxRecurse);
7585 case Instruction::Add:
7586 return simplifyAddInst(
7587 Op0: NewOps[0], Op1: NewOps[1], IsNSW: Q.IIQ.hasNoSignedWrap(Op: cast<BinaryOperator>(Val: I)),
7588 IsNUW: Q.IIQ.hasNoUnsignedWrap(Op: cast<BinaryOperator>(Val: I)), Q, MaxRecurse);
7589 case Instruction::FSub:
7590 return simplifyFSubInst(Op0: NewOps[0], Op1: NewOps[1], FMF: I->getFastMathFlags(), Q,
7591 MaxRecurse);
7592 case Instruction::Sub:
7593 return simplifySubInst(
7594 Op0: NewOps[0], Op1: NewOps[1], IsNSW: Q.IIQ.hasNoSignedWrap(Op: cast<BinaryOperator>(Val: I)),
7595 IsNUW: Q.IIQ.hasNoUnsignedWrap(Op: cast<BinaryOperator>(Val: I)), Q, MaxRecurse);
7596 case Instruction::FMul:
7597 return simplifyFMulInst(Op0: NewOps[0], Op1: NewOps[1], FMF: I->getFastMathFlags(), Q,
7598 MaxRecurse);
7599 case Instruction::Mul:
7600 return simplifyMulInst(
7601 Op0: NewOps[0], Op1: NewOps[1], IsNSW: Q.IIQ.hasNoSignedWrap(Op: cast<BinaryOperator>(Val: I)),
7602 IsNUW: Q.IIQ.hasNoUnsignedWrap(Op: cast<BinaryOperator>(Val: I)), Q, MaxRecurse);
7603 case Instruction::SDiv:
7604 return simplifySDivInst(Op0: NewOps[0], Op1: NewOps[1],
7605 IsExact: Q.IIQ.isExact(Op: cast<BinaryOperator>(Val: I)), Q,
7606 MaxRecurse);
7607 case Instruction::UDiv:
7608 return simplifyUDivInst(Op0: NewOps[0], Op1: NewOps[1],
7609 IsExact: Q.IIQ.isExact(Op: cast<BinaryOperator>(Val: I)), Q,
7610 MaxRecurse);
7611 case Instruction::FDiv:
7612 return simplifyFDivInst(Op0: NewOps[0], Op1: NewOps[1], FMF: I->getFastMathFlags(), Q,
7613 MaxRecurse);
7614 case Instruction::SRem:
7615 return simplifySRemInst(Op0: NewOps[0], Op1: NewOps[1], Q, MaxRecurse);
7616 case Instruction::URem:
7617 return simplifyURemInst(Op0: NewOps[0], Op1: NewOps[1], Q, MaxRecurse);
7618 case Instruction::FRem:
7619 return simplifyFRemInst(Op0: NewOps[0], Op1: NewOps[1], FMF: I->getFastMathFlags(), Q,
7620 MaxRecurse);
7621 case Instruction::Shl:
7622 return simplifyShlInst(
7623 Op0: NewOps[0], Op1: NewOps[1], IsNSW: Q.IIQ.hasNoSignedWrap(Op: cast<BinaryOperator>(Val: I)),
7624 IsNUW: Q.IIQ.hasNoUnsignedWrap(Op: cast<BinaryOperator>(Val: I)), Q, MaxRecurse);
7625 case Instruction::LShr:
7626 return simplifyLShrInst(Op0: NewOps[0], Op1: NewOps[1],
7627 IsExact: Q.IIQ.isExact(Op: cast<BinaryOperator>(Val: I)), Q,
7628 MaxRecurse);
7629 case Instruction::AShr:
7630 return simplifyAShrInst(Op0: NewOps[0], Op1: NewOps[1],
7631 IsExact: Q.IIQ.isExact(Op: cast<BinaryOperator>(Val: I)), Q,
7632 MaxRecurse);
7633 case Instruction::And:
7634 return simplifyAndInst(Op0: NewOps[0], Op1: NewOps[1], Q, MaxRecurse);
7635 case Instruction::Or:
7636 return simplifyOrInst(Op0: NewOps[0], Op1: NewOps[1], Q, MaxRecurse);
7637 case Instruction::Xor:
7638 return simplifyXorInst(Op0: NewOps[0], Op1: NewOps[1], Q, MaxRecurse);
7639 case Instruction::ICmp:
7640 return simplifyICmpInst(Pred: cast<ICmpInst>(Val: I)->getCmpPredicate(), LHS: NewOps[0],
7641 RHS: NewOps[1], Q, MaxRecurse);
7642 case Instruction::FCmp:
7643 return simplifyFCmpInst(Pred: cast<FCmpInst>(Val: I)->getPredicate(), LHS: NewOps[0],
7644 RHS: NewOps[1], FMF: I->getFastMathFlags(), Q, MaxRecurse);
7645 case Instruction::Select:
7646 return simplifySelectInst(Cond: NewOps[0], TrueVal: NewOps[1], FalseVal: NewOps[2], Q, MaxRecurse);
7647 case Instruction::GetElementPtr: {
7648 auto *GEPI = cast<GetElementPtrInst>(Val: I);
7649 return simplifyGEPInst(SrcTy: GEPI->getSourceElementType(), Ptr: NewOps[0],
7650 Indices: ArrayRef(NewOps).slice(N: 1), NW: GEPI->getNoWrapFlags(), Q,
7651 MaxRecurse);
7652 }
7653 case Instruction::InsertValue: {
7654 InsertValueInst *IV = cast<InsertValueInst>(Val: I);
7655 return simplifyInsertValueInst(Agg: NewOps[0], Val: NewOps[1], Idxs: IV->getIndices(), Q,
7656 MaxRecurse);
7657 }
7658 case Instruction::InsertElement:
7659 return simplifyInsertElementInst(Vec: NewOps[0], Val: NewOps[1], Idx: NewOps[2], Q);
7660 case Instruction::ExtractValue: {
7661 auto *EVI = cast<ExtractValueInst>(Val: I);
7662 return simplifyExtractValueInst(Agg: NewOps[0], Idxs: EVI->getIndices(), Q,
7663 MaxRecurse);
7664 }
7665 case Instruction::ExtractElement:
7666 return simplifyExtractElementInst(Vec: NewOps[0], Idx: NewOps[1], Q, MaxRecurse);
7667 case Instruction::ShuffleVector: {
7668 auto *SVI = cast<ShuffleVectorInst>(Val: I);
7669 return simplifyShuffleVectorInst(Op0: NewOps[0], Op1: NewOps[1],
7670 Mask: SVI->getShuffleMask(), RetTy: SVI->getType(), Q,
7671 MaxRecurse);
7672 }
7673 case Instruction::PHI:
7674 return simplifyPHINode(PN: cast<PHINode>(Val: I), IncomingValues: NewOps, Q);
7675 case Instruction::Call:
7676 return simplifyCall(
7677 Call: cast<CallInst>(Val: I), Callee: NewOps.back(),
7678 Args: NewOps.drop_back(N: 1 + cast<CallInst>(Val: I)->getNumTotalBundleOperands()), Q);
7679 case Instruction::Freeze:
7680 return llvm::simplifyFreezeInst(Op0: NewOps[0], Q);
7681#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
7682#include "llvm/IR/Instruction.def"
7683#undef HANDLE_CAST_INST
7684 return simplifyCastInst(CastOpc: I->getOpcode(), Op: NewOps[0], Ty: I->getType(), Q,
7685 MaxRecurse);
7686 case Instruction::Alloca:
7687 // No simplifications for Alloca and it can't be constant folded.
7688 return nullptr;
7689 case Instruction::Load:
7690 return simplifyLoadInst(LI: cast<LoadInst>(Val: I), PtrOp: NewOps[0], Q);
7691 }
7692}
7693
7694Value *llvm::simplifyInstructionWithOperands(Instruction *I,
7695 ArrayRef<Value *> NewOps,
7696 const SimplifyQuery &SQ) {
7697 assert(NewOps.size() == I->getNumOperands() &&
7698 "Number of operands should match the instruction!");
7699 return ::simplifyInstructionWithOperands(I, NewOps, SQ, MaxRecurse: RecursionLimit);
7700}
7701
7702Value *llvm::simplifyInstruction(Instruction *I, const SimplifyQuery &SQ) {
7703 SmallVector<Value *, 8> Ops(I->operands());
7704 Value *Result = ::simplifyInstructionWithOperands(I, NewOps: Ops, SQ, MaxRecurse: RecursionLimit);
7705
7706 /// If called on unreachable code, the instruction may simplify to itself.
7707 /// Make life easier for users by detecting that case here, and returning a
7708 /// safe value instead.
7709 return Result == I ? PoisonValue::get(T: I->getType()) : Result;
7710}
7711
7712/// Implementation of recursive simplification through an instruction's
7713/// uses.
7714///
7715/// This is the common implementation of the recursive simplification routines.
7716/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
7717/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
7718/// instructions to process and attempt to simplify it using
7719/// InstructionSimplify. Recursively visited users which could not be
7720/// simplified themselves are to the optional UnsimplifiedUsers set for
7721/// further processing by the caller.
7722///
7723/// This routine returns 'true' only when *it* simplifies something. The passed
7724/// in simplified value does not count toward this.
7725static bool replaceAndRecursivelySimplifyImpl(
7726 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
7727 const DominatorTree *DT, AssumptionCache *AC,
7728 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
7729 bool Simplified = false;
7730 SmallSetVector<Instruction *, 8> Worklist;
7731 const DataLayout &DL = I->getDataLayout();
7732
7733 // If we have an explicit value to collapse to, do that round of the
7734 // simplification loop by hand initially.
7735 if (SimpleV) {
7736 for (User *U : I->users())
7737 if (U != I)
7738 Worklist.insert(X: cast<Instruction>(Val: U));
7739
7740 // Replace the instruction with its simplified value.
7741 I->replaceAllUsesWith(V: SimpleV);
7742
7743 if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
7744 I->eraseFromParent();
7745 } else {
7746 Worklist.insert(X: I);
7747 }
7748
7749 // Note that we must test the size on each iteration, the worklist can grow.
7750 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
7751 I = Worklist[Idx];
7752
7753 // See if this instruction simplifies.
7754 SimpleV = simplifyInstruction(I, SQ: {DL, TLI, DT, AC});
7755 if (!SimpleV) {
7756 if (UnsimplifiedUsers)
7757 UnsimplifiedUsers->insert(X: I);
7758 continue;
7759 }
7760
7761 Simplified = true;
7762
7763 // Stash away all the uses of the old instruction so we can check them for
7764 // recursive simplifications after a RAUW. This is cheaper than checking all
7765 // uses of To on the recursive step in most cases.
7766 for (User *U : I->users())
7767 Worklist.insert(X: cast<Instruction>(Val: U));
7768
7769 // Replace the instruction with its simplified value.
7770 I->replaceAllUsesWith(V: SimpleV);
7771
7772 if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
7773 I->eraseFromParent();
7774 }
7775 return Simplified;
7776}
7777
7778bool llvm::replaceAndRecursivelySimplify(
7779 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
7780 const DominatorTree *DT, AssumptionCache *AC,
7781 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
7782 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
7783 assert(SimpleV && "Must provide a simplified value.");
7784 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
7785 UnsimplifiedUsers);
7786}
7787
7788namespace llvm {
7789const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
7790 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
7791 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
7792 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7793 auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
7794 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
7795 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
7796 return {F.getDataLayout(), TLI, DT, AC};
7797}
7798
7799const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
7800 const DataLayout &DL) {
7801 return {DL, &AR.TLI, &AR.DT, &AR.AC};
7802}
7803
7804template <class T, class... TArgs>
7805const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
7806 Function &F) {
7807 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
7808 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
7809 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
7810 return {F.getDataLayout(), TLI, DT, AC};
7811}
7812template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
7813 Function &);
7814
7815bool SimplifyQuery::isUndefValue(Value *V) const {
7816 if (!CanUseUndef)
7817 return false;
7818
7819 return match(V, P: m_Undef());
7820}
7821
7822} // namespace llvm
7823
7824void InstSimplifyFolder::anchor() {}
7825