Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / llvm / lib / Analysis / InstructionSimplify.cpp
blobfe3d7d679129fd5a93ca6b22435ab89b21df778e
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).
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Analysis/InstructionSimplify.h"
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/InstSimplifyFolder.h"
30 #include "llvm/Analysis/LoopAnalysisManager.h"
31 #include "llvm/Analysis/MemoryBuiltins.h"
32 #include "llvm/Analysis/OverflowInstAnalysis.h"
33 #include "llvm/Analysis/ValueTracking.h"
34 #include "llvm/Analysis/VectorUtils.h"
35 #include "llvm/IR/ConstantRange.h"
36 #include "llvm/IR/DataLayout.h"
37 #include "llvm/IR/Dominators.h"
38 #include "llvm/IR/InstrTypes.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Operator.h"
41 #include "llvm/IR/PatternMatch.h"
42 #include "llvm/Support/KnownBits.h"
43 #include <algorithm>
44 #include <optional>
45 using namespace llvm;
46 using namespace llvm::PatternMatch;
48 #define DEBUG_TYPE "instsimplify"
50 enum { RecursionLimit = 3 };
52 STATISTIC(NumExpand, "Number of expansions");
53 STATISTIC(NumReassoc, "Number of reassociations");
55 static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
56 unsigned);
57 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
58 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
59 const SimplifyQuery &, unsigned);
60 static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
61 unsigned);
62 static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
63 const SimplifyQuery &, unsigned);
64 static Value *simplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
65 unsigned);
66 static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
67 const SimplifyQuery &Q, unsigned MaxRecurse);
68 static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
69 static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
70 unsigned);
71 static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
72 unsigned);
73 static Value *simplifyGEPInst(Type *, Value *, ArrayRef<Value *>, bool,
74 const SimplifyQuery &, unsigned);
75 static Value *simplifySelectInst(Value *, Value *, Value *,
76 const SimplifyQuery &, unsigned);
77 static Value *simplifyInstructionWithOperands(Instruction *I,
78 ArrayRef<Value *> NewOps,
79 const SimplifyQuery &SQ,
80 unsigned MaxRecurse);
82 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
83 Value *FalseVal) {
84 BinaryOperator::BinaryOps BinOpCode;
85 if (auto *BO = dyn_cast<BinaryOperator>(Cond))
86 BinOpCode = BO->getOpcode();
87 else
88 return nullptr;
90 CmpInst::Predicate ExpectedPred, Pred1, Pred2;
91 if (BinOpCode == BinaryOperator::Or) {
92 ExpectedPred = ICmpInst::ICMP_NE;
93 } else if (BinOpCode == BinaryOperator::And) {
94 ExpectedPred = ICmpInst::ICMP_EQ;
95 } else
96 return nullptr;
98 // %A = icmp eq %TV, %FV
99 // %B = icmp eq %X, %Y (and one of these is a select operand)
100 // %C = and %A, %B
101 // %D = select %C, %TV, %FV
102 // -->
103 // %FV
105 // %A = icmp ne %TV, %FV
106 // %B = icmp ne %X, %Y (and one of these is a select operand)
107 // %C = or %A, %B
108 // %D = select %C, %TV, %FV
109 // -->
110 // %TV
111 Value *X, *Y;
112 if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
113 m_Specific(FalseVal)),
114 m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
115 Pred1 != Pred2 || Pred1 != ExpectedPred)
116 return nullptr;
118 if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
119 return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
121 return nullptr;
124 /// For a boolean type or a vector of boolean type, return false or a vector
125 /// with every element false.
126 static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
128 /// For a boolean type or a vector of boolean type, return true or a vector
129 /// with every element true.
130 static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
132 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
133 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
134 Value *RHS) {
135 CmpInst *Cmp = dyn_cast<CmpInst>(V);
136 if (!Cmp)
137 return false;
138 CmpInst::Predicate CPred = Cmp->getPredicate();
139 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
140 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
141 return true;
142 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
143 CRHS == LHS;
146 /// Simplify comparison with true or false branch of select:
147 /// %sel = select i1 %cond, i32 %tv, i32 %fv
148 /// %cmp = icmp sle i32 %sel, %rhs
149 /// Compose new comparison by substituting %sel with either %tv or %fv
150 /// and see if it simplifies.
151 static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS,
152 Value *RHS, Value *Cond,
153 const SimplifyQuery &Q, unsigned MaxRecurse,
154 Constant *TrueOrFalse) {
155 Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
156 if (SimplifiedCmp == Cond) {
157 // %cmp simplified to the select condition (%cond).
158 return TrueOrFalse;
159 } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
160 // It didn't simplify. However, if composed comparison is equivalent
161 // to the select condition (%cond) then we can replace it.
162 return TrueOrFalse;
164 return SimplifiedCmp;
167 /// Simplify comparison with true branch of select
168 static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS,
169 Value *RHS, Value *Cond,
170 const SimplifyQuery &Q,
171 unsigned MaxRecurse) {
172 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
173 getTrue(Cond->getType()));
176 /// Simplify comparison with false branch of select
177 static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS,
178 Value *RHS, Value *Cond,
179 const SimplifyQuery &Q,
180 unsigned MaxRecurse) {
181 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
182 getFalse(Cond->getType()));
185 /// We know comparison with both branches of select can be simplified, but they
186 /// are not equal. This routine handles some logical simplifications.
187 static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
188 Value *Cond,
189 const SimplifyQuery &Q,
190 unsigned MaxRecurse) {
191 // If the false value simplified to false, then the result of the compare
192 // is equal to "Cond && TCmp". This also catches the case when the false
193 // value simplified to false and the true value to true, returning "Cond".
194 // Folding select to and/or isn't poison-safe in general; impliesPoison
195 // checks whether folding it does not convert a well-defined value into
196 // poison.
197 if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
198 if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
199 return V;
200 // If the true value simplified to true, then the result of the compare
201 // is equal to "Cond || FCmp".
202 if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
203 if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
204 return V;
205 // Finally, if the false value simplified to true and the true value to
206 // false, then the result of the compare is equal to "!Cond".
207 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
208 if (Value *V = simplifyXorInst(
209 Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
210 return V;
211 return nullptr;
214 /// Does the given value dominate the specified phi node?
215 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
216 Instruction *I = dyn_cast<Instruction>(V);
217 if (!I)
218 // Arguments and constants dominate all instructions.
219 return true;
221 // If we have a DominatorTree then do a precise test.
222 if (DT)
223 return DT->dominates(I, P);
225 // Otherwise, if the instruction is in the entry block and is not an invoke,
226 // then it obviously dominates all phi nodes.
227 if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
228 !isa<CallBrInst>(I))
229 return true;
231 return false;
234 /// Try to simplify a binary operator of form "V op OtherOp" where V is
235 /// "(B0 opex B1)" by distributing 'op' across 'opex' as
236 /// "(B0 op OtherOp) opex (B1 op OtherOp)".
237 static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
238 Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
239 const SimplifyQuery &Q, unsigned MaxRecurse) {
240 auto *B = dyn_cast<BinaryOperator>(V);
241 if (!B || B->getOpcode() != OpcodeToExpand)
242 return nullptr;
243 Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
244 Value *L =
245 simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
246 if (!L)
247 return nullptr;
248 Value *R =
249 simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
250 if (!R)
251 return nullptr;
253 // Does the expanded pair of binops simplify to the existing binop?
254 if ((L == B0 && R == B1) ||
255 (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
256 ++NumExpand;
257 return B;
260 // Otherwise, return "L op' R" if it simplifies.
261 Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
262 if (!S)
263 return nullptr;
265 ++NumExpand;
266 return S;
269 /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
270 /// distributing op over op'.
271 static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L,
272 Value *R,
273 Instruction::BinaryOps OpcodeToExpand,
274 const SimplifyQuery &Q,
275 unsigned MaxRecurse) {
276 // Recursion is always used, so bail out at once if we already hit the limit.
277 if (!MaxRecurse--)
278 return nullptr;
280 if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
281 return V;
282 if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
283 return V;
284 return nullptr;
287 /// Generic simplifications for associative binary operations.
288 /// Returns the simpler value, or null if none was found.
289 static Value *simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
290 Value *LHS, Value *RHS,
291 const SimplifyQuery &Q,
292 unsigned MaxRecurse) {
293 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
295 // Recursion is always used, so bail out at once if we already hit the limit.
296 if (!MaxRecurse--)
297 return nullptr;
299 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
300 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
302 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
303 if (Op0 && Op0->getOpcode() == Opcode) {
304 Value *A = Op0->getOperand(0);
305 Value *B = Op0->getOperand(1);
306 Value *C = RHS;
308 // Does "B op C" simplify?
309 if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
310 // It does! Return "A op V" if it simplifies or is already available.
311 // If V equals B then "A op V" is just the LHS.
312 if (V == B)
313 return LHS;
314 // Otherwise return "A op V" if it simplifies.
315 if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
316 ++NumReassoc;
317 return W;
322 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
323 if (Op1 && Op1->getOpcode() == Opcode) {
324 Value *A = LHS;
325 Value *B = Op1->getOperand(0);
326 Value *C = Op1->getOperand(1);
328 // Does "A op B" simplify?
329 if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
330 // It does! Return "V op C" if it simplifies or is already available.
331 // If V equals B then "V op C" is just the RHS.
332 if (V == B)
333 return RHS;
334 // Otherwise return "V op C" if it simplifies.
335 if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
336 ++NumReassoc;
337 return W;
342 // The remaining transforms require commutativity as well as associativity.
343 if (!Instruction::isCommutative(Opcode))
344 return nullptr;
346 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
347 if (Op0 && Op0->getOpcode() == Opcode) {
348 Value *A = Op0->getOperand(0);
349 Value *B = Op0->getOperand(1);
350 Value *C = RHS;
352 // Does "C op A" simplify?
353 if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
354 // It does! Return "V op B" if it simplifies or is already available.
355 // If V equals A then "V op B" is just the LHS.
356 if (V == A)
357 return LHS;
358 // Otherwise return "V op B" if it simplifies.
359 if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
360 ++NumReassoc;
361 return W;
366 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
367 if (Op1 && Op1->getOpcode() == Opcode) {
368 Value *A = LHS;
369 Value *B = Op1->getOperand(0);
370 Value *C = Op1->getOperand(1);
372 // Does "C op A" simplify?
373 if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
374 // It does! Return "B op V" if it simplifies or is already available.
375 // If V equals C then "B op V" is just the RHS.
376 if (V == C)
377 return RHS;
378 // Otherwise return "B op V" if it simplifies.
379 if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
380 ++NumReassoc;
381 return W;
386 return nullptr;
389 /// In the case of a binary operation with a select instruction as an operand,
390 /// try to simplify the binop by seeing whether evaluating it on both branches
391 /// of the select results in the same value. Returns the common value if so,
392 /// otherwise returns null.
393 static Value *threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
394 Value *RHS, const SimplifyQuery &Q,
395 unsigned MaxRecurse) {
396 // Recursion is always used, so bail out at once if we already hit the limit.
397 if (!MaxRecurse--)
398 return nullptr;
400 SelectInst *SI;
401 if (isa<SelectInst>(LHS)) {
402 SI = cast<SelectInst>(LHS);
403 } else {
404 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
405 SI = cast<SelectInst>(RHS);
408 // Evaluate the BinOp on the true and false branches of the select.
409 Value *TV;
410 Value *FV;
411 if (SI == LHS) {
412 TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
413 FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
414 } else {
415 TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
416 FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
419 // If they simplified to the same value, then return the common value.
420 // If they both failed to simplify then return null.
421 if (TV == FV)
422 return TV;
424 // If one branch simplified to undef, return the other one.
425 if (TV && Q.isUndefValue(TV))
426 return FV;
427 if (FV && Q.isUndefValue(FV))
428 return TV;
430 // If applying the operation did not change the true and false select values,
431 // then the result of the binop is the select itself.
432 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
433 return SI;
435 // If one branch simplified and the other did not, and the simplified
436 // value is equal to the unsimplified one, return the simplified value.
437 // For example, select (cond, X, X & Z) & Z -> X & Z.
438 if ((FV && !TV) || (TV && !FV)) {
439 // Check that the simplified value has the form "X op Y" where "op" is the
440 // same as the original operation.
441 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
442 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
443 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
444 // We already know that "op" is the same as for the simplified value. See
445 // if the operands match too. If so, return the simplified value.
446 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
447 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
448 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
449 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
450 Simplified->getOperand(1) == UnsimplifiedRHS)
451 return Simplified;
452 if (Simplified->isCommutative() &&
453 Simplified->getOperand(1) == UnsimplifiedLHS &&
454 Simplified->getOperand(0) == UnsimplifiedRHS)
455 return Simplified;
459 return nullptr;
462 /// In the case of a comparison with a select instruction, try to simplify the
463 /// comparison by seeing whether both branches of the select result in the same
464 /// value. Returns the common value if so, otherwise returns null.
465 /// For example, if we have:
466 /// %tmp = select i1 %cmp, i32 1, i32 2
467 /// %cmp1 = icmp sle i32 %tmp, 3
468 /// We can simplify %cmp1 to true, because both branches of select are
469 /// less than 3. We compose new comparison by substituting %tmp with both
470 /// branches of select and see if it can be simplified.
471 static Value *threadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
472 Value *RHS, const SimplifyQuery &Q,
473 unsigned MaxRecurse) {
474 // Recursion is always used, so bail out at once if we already hit the limit.
475 if (!MaxRecurse--)
476 return nullptr;
478 // Make sure the select is on the LHS.
479 if (!isa<SelectInst>(LHS)) {
480 std::swap(LHS, RHS);
481 Pred = CmpInst::getSwappedPredicate(Pred);
483 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
484 SelectInst *SI = cast<SelectInst>(LHS);
485 Value *Cond = SI->getCondition();
486 Value *TV = SI->getTrueValue();
487 Value *FV = SI->getFalseValue();
489 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
490 // Does "cmp TV, RHS" simplify?
491 Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
492 if (!TCmp)
493 return nullptr;
495 // Does "cmp FV, RHS" simplify?
496 Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
497 if (!FCmp)
498 return nullptr;
500 // If both sides simplified to the same value, then use it as the result of
501 // the original comparison.
502 if (TCmp == FCmp)
503 return TCmp;
505 // The remaining cases only make sense if the select condition has the same
506 // type as the result of the comparison, so bail out if this is not so.
507 if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
508 return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
510 return nullptr;
513 /// In the case of a binary operation with an operand that is a PHI instruction,
514 /// try to simplify the binop by seeing whether evaluating it on the incoming
515 /// phi values yields the same result for every value. If so returns the common
516 /// value, otherwise returns null.
517 static Value *threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
518 Value *RHS, const SimplifyQuery &Q,
519 unsigned MaxRecurse) {
520 // Recursion is always used, so bail out at once if we already hit the limit.
521 if (!MaxRecurse--)
522 return nullptr;
524 PHINode *PI;
525 if (isa<PHINode>(LHS)) {
526 PI = cast<PHINode>(LHS);
527 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
528 if (!valueDominatesPHI(RHS, PI, Q.DT))
529 return nullptr;
530 } else {
531 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
532 PI = cast<PHINode>(RHS);
533 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
534 if (!valueDominatesPHI(LHS, PI, Q.DT))
535 return nullptr;
538 // Evaluate the BinOp on the incoming phi values.
539 Value *CommonValue = nullptr;
540 for (Use &Incoming : PI->incoming_values()) {
541 // If the incoming value is the phi node itself, it can safely be skipped.
542 if (Incoming == PI)
543 continue;
544 Instruction *InTI = PI->getIncomingBlock(Incoming)->getTerminator();
545 Value *V = PI == LHS
546 ? simplifyBinOp(Opcode, Incoming, RHS,
547 Q.getWithInstruction(InTI), MaxRecurse)
548 : simplifyBinOp(Opcode, LHS, Incoming,
549 Q.getWithInstruction(InTI), MaxRecurse);
550 // If the operation failed to simplify, or simplified to a different value
551 // to previously, then give up.
552 if (!V || (CommonValue && V != CommonValue))
553 return nullptr;
554 CommonValue = V;
557 return CommonValue;
560 /// In the case of a comparison with a PHI instruction, try to simplify the
561 /// comparison by seeing whether comparing with all of the incoming phi values
562 /// yields the same result every time. If so returns the common result,
563 /// otherwise returns null.
564 static Value *threadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
565 const SimplifyQuery &Q, unsigned MaxRecurse) {
566 // Recursion is always used, so bail out at once if we already hit the limit.
567 if (!MaxRecurse--)
568 return nullptr;
570 // Make sure the phi is on the LHS.
571 if (!isa<PHINode>(LHS)) {
572 std::swap(LHS, RHS);
573 Pred = CmpInst::getSwappedPredicate(Pred);
575 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
576 PHINode *PI = cast<PHINode>(LHS);
578 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
579 if (!valueDominatesPHI(RHS, PI, Q.DT))
580 return nullptr;
582 // Evaluate the BinOp on the incoming phi values.
583 Value *CommonValue = nullptr;
584 for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
585 Value *Incoming = PI->getIncomingValue(u);
586 Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
587 // If the incoming value is the phi node itself, it can safely be skipped.
588 if (Incoming == PI)
589 continue;
590 // Change the context instruction to the "edge" that flows into the phi.
591 // This is important because that is where incoming is actually "evaluated"
592 // even though it is used later somewhere else.
593 Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
594 MaxRecurse);
595 // If the operation failed to simplify, or simplified to a different value
596 // to previously, then give up.
597 if (!V || (CommonValue && V != CommonValue))
598 return nullptr;
599 CommonValue = V;
602 return CommonValue;
605 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
606 Value *&Op0, Value *&Op1,
607 const SimplifyQuery &Q) {
608 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
609 if (auto *CRHS = dyn_cast<Constant>(Op1)) {
610 switch (Opcode) {
611 default:
612 break;
613 case Instruction::FAdd:
614 case Instruction::FSub:
615 case Instruction::FMul:
616 case Instruction::FDiv:
617 case Instruction::FRem:
618 if (Q.CxtI != nullptr)
619 return ConstantFoldFPInstOperands(Opcode, CLHS, CRHS, Q.DL, Q.CxtI);
621 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
624 // Canonicalize the constant to the RHS if this is a commutative operation.
625 if (Instruction::isCommutative(Opcode))
626 std::swap(Op0, Op1);
628 return nullptr;
631 /// Given operands for an Add, see if we can fold the result.
632 /// If not, this returns null.
633 static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
634 const SimplifyQuery &Q, unsigned MaxRecurse) {
635 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
636 return C;
638 // X + poison -> poison
639 if (isa<PoisonValue>(Op1))
640 return Op1;
642 // X + undef -> undef
643 if (Q.isUndefValue(Op1))
644 return Op1;
646 // X + 0 -> X
647 if (match(Op1, m_Zero()))
648 return Op0;
650 // If two operands are negative, return 0.
651 if (isKnownNegation(Op0, Op1))
652 return Constant::getNullValue(Op0->getType());
654 // X + (Y - X) -> Y
655 // (Y - X) + X -> Y
656 // Eg: X + -X -> 0
657 Value *Y = nullptr;
658 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
659 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
660 return Y;
662 // X + ~X -> -1 since ~X = -X-1
663 Type *Ty = Op0->getType();
664 if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
665 return Constant::getAllOnesValue(Ty);
667 // add nsw/nuw (xor Y, signmask), signmask --> Y
668 // The no-wrapping add guarantees that the top bit will be set by the add.
669 // Therefore, the xor must be clearing the already set sign bit of Y.
670 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
671 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
672 return Y;
674 // add nuw %x, -1 -> -1, because %x can only be 0.
675 if (IsNUW && match(Op1, m_AllOnes()))
676 return Op1; // Which is -1.
678 /// i1 add -> xor.
679 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
680 if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
681 return V;
683 // Try some generic simplifications for associative operations.
684 if (Value *V =
685 simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
686 return V;
688 // Threading Add over selects and phi nodes is pointless, so don't bother.
689 // Threading over the select in "A + select(cond, B, C)" means evaluating
690 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
691 // only if B and C are equal. If B and C are equal then (since we assume
692 // that operands have already been simplified) "select(cond, B, C)" should
693 // have been simplified to the common value of B and C already. Analysing
694 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
695 // for threading over phi nodes.
697 return nullptr;
700 Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
701 const SimplifyQuery &Query) {
702 return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
705 /// Compute the base pointer and cumulative constant offsets for V.
707 /// This strips all constant offsets off of V, leaving it the base pointer, and
708 /// accumulates the total constant offset applied in the returned constant.
709 /// It returns zero if there are no constant offsets applied.
711 /// This is very similar to stripAndAccumulateConstantOffsets(), except it
712 /// normalizes the offset bitwidth to the stripped pointer type, not the
713 /// original pointer type.
714 static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
715 bool AllowNonInbounds = false) {
716 assert(V->getType()->isPtrOrPtrVectorTy());
718 APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
719 V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
720 // As that strip may trace through `addrspacecast`, need to sext or trunc
721 // the offset calculated.
722 return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
725 /// Compute the constant difference between two pointer values.
726 /// If the difference is not a constant, returns zero.
727 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
728 Value *RHS) {
729 APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
730 APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
732 // If LHS and RHS are not related via constant offsets to the same base
733 // value, there is nothing we can do here.
734 if (LHS != RHS)
735 return nullptr;
737 // Otherwise, the difference of LHS - RHS can be computed as:
738 // LHS - RHS
739 // = (LHSOffset + Base) - (RHSOffset + Base)
740 // = LHSOffset - RHSOffset
741 Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
742 if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
743 Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
744 return Res;
747 /// Test if there is a dominating equivalence condition for the
748 /// two operands. If there is, try to reduce the binary operation
749 /// between the two operands.
750 /// Example: Op0 - Op1 --> 0 when Op0 == Op1
751 static Value *simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1,
752 const SimplifyQuery &Q, unsigned MaxRecurse) {
753 // Recursive run it can not get any benefit
754 if (MaxRecurse != RecursionLimit)
755 return nullptr;
757 std::optional<bool> Imp =
758 isImpliedByDomCondition(CmpInst::ICMP_EQ, Op0, Op1, Q.CxtI, Q.DL);
759 if (Imp && *Imp) {
760 Type *Ty = Op0->getType();
761 switch (Opcode) {
762 case Instruction::Sub:
763 case Instruction::Xor:
764 case Instruction::URem:
765 case Instruction::SRem:
766 return Constant::getNullValue(Ty);
768 case Instruction::SDiv:
769 case Instruction::UDiv:
770 return ConstantInt::get(Ty, 1);
772 case Instruction::And:
773 case Instruction::Or:
774 // Could be either one - choose Op1 since that's more likely a constant.
775 return Op1;
776 default:
777 break;
780 return nullptr;
783 /// Given operands for a Sub, see if we can fold the result.
784 /// If not, this returns null.
785 static Value *simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
786 const SimplifyQuery &Q, unsigned MaxRecurse) {
787 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
788 return C;
790 // X - poison -> poison
791 // poison - X -> poison
792 if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
793 return PoisonValue::get(Op0->getType());
795 // X - undef -> undef
796 // undef - X -> undef
797 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
798 return UndefValue::get(Op0->getType());
800 // X - 0 -> X
801 if (match(Op1, m_Zero()))
802 return Op0;
804 // X - X -> 0
805 if (Op0 == Op1)
806 return Constant::getNullValue(Op0->getType());
808 // Is this a negation?
809 if (match(Op0, m_Zero())) {
810 // 0 - X -> 0 if the sub is NUW.
811 if (IsNUW)
812 return Constant::getNullValue(Op0->getType());
814 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
815 if (Known.Zero.isMaxSignedValue()) {
816 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
817 // Op1 must be 0 because negating the minimum signed value is undefined.
818 if (IsNSW)
819 return Constant::getNullValue(Op0->getType());
821 // 0 - X -> X if X is 0 or the minimum signed value.
822 return Op1;
826 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
827 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
828 Value *X = nullptr, *Y = nullptr, *Z = Op1;
829 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
830 // See if "V === Y - Z" simplifies.
831 if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
832 // It does! Now see if "X + V" simplifies.
833 if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
834 // It does, we successfully reassociated!
835 ++NumReassoc;
836 return W;
838 // See if "V === X - Z" simplifies.
839 if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
840 // It does! Now see if "Y + V" simplifies.
841 if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
842 // It does, we successfully reassociated!
843 ++NumReassoc;
844 return W;
848 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
849 // For example, X - (X + 1) -> -1
850 X = Op0;
851 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
852 // See if "V === X - Y" simplifies.
853 if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
854 // It does! Now see if "V - Z" simplifies.
855 if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
856 // It does, we successfully reassociated!
857 ++NumReassoc;
858 return W;
860 // See if "V === X - Z" simplifies.
861 if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
862 // It does! Now see if "V - Y" simplifies.
863 if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
864 // It does, we successfully reassociated!
865 ++NumReassoc;
866 return W;
870 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
871 // For example, X - (X - Y) -> Y.
872 Z = Op0;
873 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
874 // See if "V === Z - X" simplifies.
875 if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
876 // It does! Now see if "V + Y" simplifies.
877 if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
878 // It does, we successfully reassociated!
879 ++NumReassoc;
880 return W;
883 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
884 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
885 match(Op1, m_Trunc(m_Value(Y))))
886 if (X->getType() == Y->getType())
887 // See if "V === X - Y" simplifies.
888 if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
889 // It does! Now see if "trunc V" simplifies.
890 if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
891 Q, MaxRecurse - 1))
892 // It does, return the simplified "trunc V".
893 return W;
895 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
896 if (match(Op0, m_PtrToInt(m_Value(X))) && match(Op1, m_PtrToInt(m_Value(Y))))
897 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
898 return ConstantFoldIntegerCast(Result, Op0->getType(), /*IsSigned*/ true,
899 Q.DL);
901 // i1 sub -> xor.
902 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
903 if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
904 return V;
906 // Threading Sub over selects and phi nodes is pointless, so don't bother.
907 // Threading over the select in "A - select(cond, B, C)" means evaluating
908 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
909 // only if B and C are equal. If B and C are equal then (since we assume
910 // that operands have already been simplified) "select(cond, B, C)" should
911 // have been simplified to the common value of B and C already. Analysing
912 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
913 // for threading over phi nodes.
915 if (Value *V = simplifyByDomEq(Instruction::Sub, Op0, Op1, Q, MaxRecurse))
916 return V;
918 return nullptr;
921 Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
922 const SimplifyQuery &Q) {
923 return ::simplifySubInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
926 /// Given operands for a Mul, see if we can fold the result.
927 /// If not, this returns null.
928 static Value *simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
929 const SimplifyQuery &Q, unsigned MaxRecurse) {
930 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
931 return C;
933 // X * poison -> poison
934 if (isa<PoisonValue>(Op1))
935 return Op1;
937 // X * undef -> 0
938 // X * 0 -> 0
939 if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
940 return Constant::getNullValue(Op0->getType());
942 // X * 1 -> X
943 if (match(Op1, m_One()))
944 return Op0;
946 // (X / Y) * Y -> X if the division is exact.
947 Value *X = nullptr;
948 if (Q.IIQ.UseInstrInfo &&
949 (match(Op0,
950 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
951 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
952 return X;
954 if (Op0->getType()->isIntOrIntVectorTy(1)) {
955 // mul i1 nsw is a special-case because -1 * -1 is poison (+1 is not
956 // representable). All other cases reduce to 0, so just return 0.
957 if (IsNSW)
958 return ConstantInt::getNullValue(Op0->getType());
960 // Treat "mul i1" as "and i1".
961 if (MaxRecurse)
962 if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
963 return V;
966 // Try some generic simplifications for associative operations.
967 if (Value *V =
968 simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
969 return V;
971 // Mul distributes over Add. Try some generic simplifications based on this.
972 if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
973 Instruction::Add, Q, MaxRecurse))
974 return V;
976 // If the operation is with the result of a select instruction, check whether
977 // operating on either branch of the select always yields the same value.
978 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
979 if (Value *V =
980 threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
981 return V;
983 // If the operation is with the result of a phi instruction, check whether
984 // operating on all incoming values of the phi always yields the same value.
985 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
986 if (Value *V =
987 threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
988 return V;
990 return nullptr;
993 Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
994 const SimplifyQuery &Q) {
995 return ::simplifyMulInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
998 /// Given a predicate and two operands, return true if the comparison is true.
999 /// This is a helper for div/rem simplification where we return some other value
1000 /// when we can prove a relationship between the operands.
1001 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
1002 const SimplifyQuery &Q, unsigned MaxRecurse) {
1003 Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
1004 Constant *C = dyn_cast_or_null<Constant>(V);
1005 return (C && C->isAllOnesValue());
1008 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
1009 /// to simplify X % Y to X.
1010 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
1011 unsigned MaxRecurse, bool IsSigned) {
1012 // Recursion is always used, so bail out at once if we already hit the limit.
1013 if (!MaxRecurse--)
1014 return false;
1016 if (IsSigned) {
1017 // (X srem Y) sdiv Y --> 0
1018 if (match(X, m_SRem(m_Value(), m_Specific(Y))))
1019 return true;
1021 // |X| / |Y| --> 0
1023 // We require that 1 operand is a simple constant. That could be extended to
1024 // 2 variables if we computed the sign bit for each.
1026 // Make sure that a constant is not the minimum signed value because taking
1027 // the abs() of that is undefined.
1028 Type *Ty = X->getType();
1029 const APInt *C;
1030 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
1031 // Is the variable divisor magnitude always greater than the constant
1032 // dividend magnitude?
1033 // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
1034 Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
1035 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
1036 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
1037 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
1038 return true;
1040 if (match(Y, m_APInt(C))) {
1041 // Special-case: we can't take the abs() of a minimum signed value. If
1042 // that's the divisor, then all we have to do is prove that the dividend
1043 // is also not the minimum signed value.
1044 if (C->isMinSignedValue())
1045 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
1047 // Is the variable dividend magnitude always less than the constant
1048 // divisor magnitude?
1049 // |X| < |C| --> X > -abs(C) and X < abs(C)
1050 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
1051 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
1052 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
1053 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
1054 return true;
1056 return false;
1059 // IsSigned == false.
1061 // Is the unsigned dividend known to be less than a constant divisor?
1062 // TODO: Convert this (and above) to range analysis
1063 // ("computeConstantRangeIncludingKnownBits")?
1064 const APInt *C;
1065 if (match(Y, m_APInt(C)) &&
1066 computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT).getMaxValue().ult(*C))
1067 return true;
1069 // Try again for any divisor:
1070 // Is the dividend unsigned less than the divisor?
1071 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
1074 /// Check for common or similar folds of integer division or integer remainder.
1075 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
1076 static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
1077 Value *Op1, const SimplifyQuery &Q,
1078 unsigned MaxRecurse) {
1079 bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
1080 bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
1082 Type *Ty = Op0->getType();
1084 // X / undef -> poison
1085 // X % undef -> poison
1086 if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
1087 return PoisonValue::get(Ty);
1089 // X / 0 -> poison
1090 // X % 0 -> poison
1091 // We don't need to preserve faults!
1092 if (match(Op1, m_Zero()))
1093 return PoisonValue::get(Ty);
1095 // If any element of a constant divisor fixed width vector is zero or undef
1096 // the behavior is undefined and we can fold the whole op to poison.
1097 auto *Op1C = dyn_cast<Constant>(Op1);
1098 auto *VTy = dyn_cast<FixedVectorType>(Ty);
1099 if (Op1C && VTy) {
1100 unsigned NumElts = VTy->getNumElements();
1101 for (unsigned i = 0; i != NumElts; ++i) {
1102 Constant *Elt = Op1C->getAggregateElement(i);
1103 if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
1104 return PoisonValue::get(Ty);
1108 // poison / X -> poison
1109 // poison % X -> poison
1110 if (isa<PoisonValue>(Op0))
1111 return Op0;
1113 // undef / X -> 0
1114 // undef % X -> 0
1115 if (Q.isUndefValue(Op0))
1116 return Constant::getNullValue(Ty);
1118 // 0 / X -> 0
1119 // 0 % X -> 0
1120 if (match(Op0, m_Zero()))
1121 return Constant::getNullValue(Op0->getType());
1123 // X / X -> 1
1124 // X % X -> 0
1125 if (Op0 == Op1)
1126 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1129 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1130 // X / 0 -> poison
1131 // X % 0 -> poison
1132 // If the divisor is known to be zero, just return poison. This can happen in
1133 // some cases where its provable indirectly the denominator is zero but it's
1134 // not trivially simplifiable (i.e known zero through a phi node).
1135 if (Known.isZero())
1136 return PoisonValue::get(Ty);
1138 // X / 1 -> X
1139 // X % 1 -> 0
1140 // If the divisor can only be zero or one, we can't have division-by-zero
1141 // or remainder-by-zero, so assume the divisor is 1.
1142 // e.g. 1, zext (i8 X), sdiv X (Y and 1)
1143 if (Known.countMinLeadingZeros() == Known.getBitWidth() - 1)
1144 return IsDiv ? Op0 : Constant::getNullValue(Ty);
1146 // If X * Y does not overflow, then:
1147 // X * Y / Y -> X
1148 // X * Y % Y -> 0
1149 Value *X;
1150 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
1151 auto *Mul = cast<OverflowingBinaryOperator>(Op0);
1152 // The multiplication can't overflow if it is defined not to, or if
1153 // X == A / Y for some A.
1154 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
1155 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
1156 (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
1157 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
1158 return IsDiv ? X : Constant::getNullValue(Op0->getType());
1162 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
1163 return IsDiv ? Constant::getNullValue(Op0->getType()) : Op0;
1165 if (Value *V = simplifyByDomEq(Opcode, Op0, Op1, Q, MaxRecurse))
1166 return V;
1168 // If the operation is with the result of a select instruction, check whether
1169 // operating on either branch of the select always yields the same value.
1170 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1171 if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1172 return V;
1174 // If the operation is with the result of a phi instruction, check whether
1175 // operating on all incoming values of the phi always yields the same value.
1176 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1177 if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1178 return V;
1180 return nullptr;
1183 /// These are simplifications common to SDiv and UDiv.
1184 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1185 bool IsExact, const SimplifyQuery &Q,
1186 unsigned MaxRecurse) {
1187 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1188 return C;
1190 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1191 return V;
1193 // If this is an exact divide by a constant, then the dividend (Op0) must have
1194 // at least as many trailing zeros as the divisor to divide evenly. If it has
1195 // less trailing zeros, then the result must be poison.
1196 const APInt *DivC;
1197 if (IsExact && match(Op1, m_APInt(DivC)) && DivC->countr_zero()) {
1198 KnownBits KnownOp0 = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1199 if (KnownOp0.countMaxTrailingZeros() < DivC->countr_zero())
1200 return PoisonValue::get(Op0->getType());
1203 return nullptr;
1206 /// These are simplifications common to SRem and URem.
1207 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1208 const SimplifyQuery &Q, unsigned MaxRecurse) {
1209 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1210 return C;
1212 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
1213 return V;
1215 // (X << Y) % X -> 0
1216 if (Q.IIQ.UseInstrInfo &&
1217 ((Opcode == Instruction::SRem &&
1218 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
1219 (Opcode == Instruction::URem &&
1220 match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
1221 return Constant::getNullValue(Op0->getType());
1223 return nullptr;
1226 /// Given operands for an SDiv, see if we can fold the result.
1227 /// If not, this returns null.
1228 static Value *simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1229 const SimplifyQuery &Q, unsigned MaxRecurse) {
1230 // If two operands are negated and no signed overflow, return -1.
1231 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
1232 return Constant::getAllOnesValue(Op0->getType());
1234 return simplifyDiv(Instruction::SDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1237 Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
1238 const SimplifyQuery &Q) {
1239 return ::simplifySDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
1242 /// Given operands for a UDiv, see if we can fold the result.
1243 /// If not, this returns null.
1244 static Value *simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1245 const SimplifyQuery &Q, unsigned MaxRecurse) {
1246 return simplifyDiv(Instruction::UDiv, Op0, Op1, IsExact, Q, MaxRecurse);
1249 Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
1250 const SimplifyQuery &Q) {
1251 return ::simplifyUDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
1254 /// Given operands for an SRem, see if we can fold the result.
1255 /// If not, this returns null.
1256 static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1257 unsigned MaxRecurse) {
1258 // If the divisor is 0, the result is undefined, so assume the divisor is -1.
1259 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
1260 Value *X;
1261 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
1262 return ConstantInt::getNullValue(Op0->getType());
1264 // If the two operands are negated, return 0.
1265 if (isKnownNegation(Op0, Op1))
1266 return ConstantInt::getNullValue(Op0->getType());
1268 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
1271 Value *llvm::simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1272 return ::simplifySRemInst(Op0, Op1, Q, RecursionLimit);
1275 /// Given operands for a URem, see if we can fold the result.
1276 /// If not, this returns null.
1277 static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
1278 unsigned MaxRecurse) {
1279 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
1282 Value *llvm::simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1283 return ::simplifyURemInst(Op0, Op1, Q, RecursionLimit);
1286 /// Returns true if a shift by \c Amount always yields poison.
1287 static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
1288 Constant *C = dyn_cast<Constant>(Amount);
1289 if (!C)
1290 return false;
1292 // X shift by undef -> poison because it may shift by the bitwidth.
1293 if (Q.isUndefValue(C))
1294 return true;
1296 // Shifting by the bitwidth or more is poison. This covers scalars and
1297 // fixed/scalable vectors with splat constants.
1298 const APInt *AmountC;
1299 if (match(C, m_APInt(AmountC)) && AmountC->uge(AmountC->getBitWidth()))
1300 return true;
1302 // Try harder for fixed-length vectors:
1303 // If all lanes of a vector shift are poison, the whole shift is poison.
1304 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1305 for (unsigned I = 0,
1306 E = cast<FixedVectorType>(C->getType())->getNumElements();
1307 I != E; ++I)
1308 if (!isPoisonShift(C->getAggregateElement(I), Q))
1309 return false;
1310 return true;
1313 return false;
1316 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1317 /// If not, this returns null.
1318 static Value *simplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1319 Value *Op1, bool IsNSW, const SimplifyQuery &Q,
1320 unsigned MaxRecurse) {
1321 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1322 return C;
1324 // poison shift by X -> poison
1325 if (isa<PoisonValue>(Op0))
1326 return Op0;
1328 // 0 shift by X -> 0
1329 if (match(Op0, m_Zero()))
1330 return Constant::getNullValue(Op0->getType());
1332 // X shift by 0 -> X
1333 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
1334 // would be poison.
1335 Value *X;
1336 if (match(Op1, m_Zero()) ||
1337 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
1338 return Op0;
1340 // Fold undefined shifts.
1341 if (isPoisonShift(Op1, Q))
1342 return PoisonValue::get(Op0->getType());
1344 // If the operation is with the result of a select instruction, check whether
1345 // operating on either branch of the select always yields the same value.
1346 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1347 if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1348 return V;
1350 // If the operation is with the result of a phi instruction, check whether
1351 // operating on all incoming values of the phi always yields the same value.
1352 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1353 if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1354 return V;
1356 // If any bits in the shift amount make that value greater than or equal to
1357 // the number of bits in the type, the shift is undefined.
1358 KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1359 if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
1360 return PoisonValue::get(Op0->getType());
1362 // If all valid bits in the shift amount are known zero, the first operand is
1363 // unchanged.
1364 unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
1365 if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
1366 return Op0;
1368 // Check for nsw shl leading to a poison value.
1369 if (IsNSW) {
1370 assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
1371 KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1372 KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
1374 if (KnownVal.Zero.isSignBitSet())
1375 KnownShl.Zero.setSignBit();
1376 if (KnownVal.One.isSignBitSet())
1377 KnownShl.One.setSignBit();
1379 if (KnownShl.hasConflict())
1380 return PoisonValue::get(Op0->getType());
1383 return nullptr;
1386 /// Given operands for an LShr or AShr, see if we can fold the result. If not,
1387 /// this returns null.
1388 static Value *simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1389 Value *Op1, bool IsExact,
1390 const SimplifyQuery &Q, unsigned MaxRecurse) {
1391 if (Value *V =
1392 simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
1393 return V;
1395 // X >> X -> 0
1396 if (Op0 == Op1)
1397 return Constant::getNullValue(Op0->getType());
1399 // undef >> X -> 0
1400 // undef >> X -> undef (if it's exact)
1401 if (Q.isUndefValue(Op0))
1402 return IsExact ? Op0 : Constant::getNullValue(Op0->getType());
1404 // The low bit cannot be shifted out of an exact shift if it is set.
1405 // TODO: Generalize by counting trailing zeros (see fold for exact division).
1406 if (IsExact) {
1407 KnownBits Op0Known =
1408 computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1409 if (Op0Known.One[0])
1410 return Op0;
1413 return nullptr;
1416 /// Given operands for an Shl, see if we can fold the result.
1417 /// If not, this returns null.
1418 static Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1419 const SimplifyQuery &Q, unsigned MaxRecurse) {
1420 if (Value *V =
1421 simplifyShift(Instruction::Shl, Op0, Op1, IsNSW, Q, MaxRecurse))
1422 return V;
1424 Type *Ty = Op0->getType();
1425 // undef << X -> 0
1426 // undef << X -> undef if (if it's NSW/NUW)
1427 if (Q.isUndefValue(Op0))
1428 return IsNSW || IsNUW ? Op0 : Constant::getNullValue(Ty);
1430 // (X >> A) << A -> X
1431 Value *X;
1432 if (Q.IIQ.UseInstrInfo &&
1433 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1434 return X;
1436 // shl nuw i8 C, %x -> C iff C has sign bit set.
1437 if (IsNUW && match(Op0, m_Negative()))
1438 return Op0;
1439 // NOTE: could use computeKnownBits() / LazyValueInfo,
1440 // but the cost-benefit analysis suggests it isn't worth it.
1442 // "nuw" guarantees that only zeros are shifted out, and "nsw" guarantees
1443 // that the sign-bit does not change, so the only input that does not
1444 // produce poison is 0, and "0 << (bitwidth-1) --> 0".
1445 if (IsNSW && IsNUW &&
1446 match(Op1, m_SpecificInt(Ty->getScalarSizeInBits() - 1)))
1447 return Constant::getNullValue(Ty);
1449 return nullptr;
1452 Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
1453 const SimplifyQuery &Q) {
1454 return ::simplifyShlInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
1457 /// Given operands for an LShr, see if we can fold the result.
1458 /// If not, this returns null.
1459 static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1460 const SimplifyQuery &Q, unsigned MaxRecurse) {
1461 if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, IsExact, Q,
1462 MaxRecurse))
1463 return V;
1465 // (X << A) >> A -> X
1466 Value *X;
1467 if (Q.IIQ.UseInstrInfo && match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1468 return X;
1470 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
1471 // We can return X as we do in the above case since OR alters no bits in X.
1472 // SimplifyDemandedBits in InstCombine can do more general optimization for
1473 // bit manipulation. This pattern aims to provide opportunities for other
1474 // optimizers by supporting a simple but common case in InstSimplify.
1475 Value *Y;
1476 const APInt *ShRAmt, *ShLAmt;
1477 if (Q.IIQ.UseInstrInfo && match(Op1, m_APInt(ShRAmt)) &&
1478 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
1479 *ShRAmt == *ShLAmt) {
1480 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1481 const unsigned EffWidthY = YKnown.countMaxActiveBits();
1482 if (ShRAmt->uge(EffWidthY))
1483 return X;
1486 return nullptr;
1489 Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
1490 const SimplifyQuery &Q) {
1491 return ::simplifyLShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
1494 /// Given operands for an AShr, see if we can fold the result.
1495 /// If not, this returns null.
1496 static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1497 const SimplifyQuery &Q, unsigned MaxRecurse) {
1498 if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, IsExact, Q,
1499 MaxRecurse))
1500 return V;
1502 // -1 >>a X --> -1
1503 // (-1 << X) a>> X --> -1
1504 // Do not return Op0 because it may contain undef elements if it's a vector.
1505 if (match(Op0, m_AllOnes()) ||
1506 match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
1507 return Constant::getAllOnesValue(Op0->getType());
1509 // (X << A) >> A -> X
1510 Value *X;
1511 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1512 return X;
1514 // Arithmetic shifting an all-sign-bit value is a no-op.
1515 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1516 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1517 return Op0;
1519 return nullptr;
1522 Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
1523 const SimplifyQuery &Q) {
1524 return ::simplifyAShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
1527 /// Commuted variants are assumed to be handled by calling this function again
1528 /// with the parameters swapped.
1529 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1530 ICmpInst *UnsignedICmp, bool IsAnd,
1531 const SimplifyQuery &Q) {
1532 Value *X, *Y;
1534 ICmpInst::Predicate EqPred;
1535 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1536 !ICmpInst::isEquality(EqPred))
1537 return nullptr;
1539 ICmpInst::Predicate UnsignedPred;
1541 Value *A, *B;
1542 // Y = (A - B);
1543 if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
1544 if (match(UnsignedICmp,
1545 m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
1546 ICmpInst::isUnsigned(UnsignedPred)) {
1547 // A >=/<= B || (A - B) != 0 <--> true
1548 if ((UnsignedPred == ICmpInst::ICMP_UGE ||
1549 UnsignedPred == ICmpInst::ICMP_ULE) &&
1550 EqPred == ICmpInst::ICMP_NE && !IsAnd)
1551 return ConstantInt::getTrue(UnsignedICmp->getType());
1552 // A </> B && (A - B) == 0 <--> false
1553 if ((UnsignedPred == ICmpInst::ICMP_ULT ||
1554 UnsignedPred == ICmpInst::ICMP_UGT) &&
1555 EqPred == ICmpInst::ICMP_EQ && IsAnd)
1556 return ConstantInt::getFalse(UnsignedICmp->getType());
1558 // A </> B && (A - B) != 0 <--> A </> B
1559 // A </> B || (A - B) != 0 <--> (A - B) != 0
1560 if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
1561 UnsignedPred == ICmpInst::ICMP_UGT))
1562 return IsAnd ? UnsignedICmp : ZeroICmp;
1564 // A <=/>= B && (A - B) == 0 <--> (A - B) == 0
1565 // A <=/>= B || (A - B) == 0 <--> A <=/>= B
1566 if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
1567 UnsignedPred == ICmpInst::ICMP_UGE))
1568 return IsAnd ? ZeroICmp : UnsignedICmp;
1571 // Given Y = (A - B)
1572 // Y >= A && Y != 0 --> Y >= A iff B != 0
1573 // Y < A || Y == 0 --> Y < A iff B != 0
1574 if (match(UnsignedICmp,
1575 m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
1576 if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
1577 EqPred == ICmpInst::ICMP_NE &&
1578 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1579 return UnsignedICmp;
1580 if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
1581 EqPred == ICmpInst::ICMP_EQ &&
1582 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1583 return UnsignedICmp;
1587 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1588 ICmpInst::isUnsigned(UnsignedPred))
1590 else if (match(UnsignedICmp,
1591 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
1592 ICmpInst::isUnsigned(UnsignedPred))
1593 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1594 else
1595 return nullptr;
1597 // X > Y && Y == 0 --> Y == 0 iff X != 0
1598 // X > Y || Y == 0 --> X > Y iff X != 0
1599 if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
1600 isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1601 return IsAnd ? ZeroICmp : UnsignedICmp;
1603 // X <= Y && Y != 0 --> X <= Y iff X != 0
1604 // X <= Y || Y != 0 --> Y != 0 iff X != 0
1605 if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
1606 isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
1607 return IsAnd ? UnsignedICmp : ZeroICmp;
1609 // The transforms below here are expected to be handled more generally with
1610 // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
1611 // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
1612 // these are candidates for removal.
1614 // X < Y && Y != 0 --> X < Y
1615 // X < Y || Y != 0 --> Y != 0
1616 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1617 return IsAnd ? UnsignedICmp : ZeroICmp;
1619 // X >= Y && Y == 0 --> Y == 0
1620 // X >= Y || Y == 0 --> X >= Y
1621 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
1622 return IsAnd ? ZeroICmp : UnsignedICmp;
1624 // X < Y && Y == 0 --> false
1625 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1626 IsAnd)
1627 return getFalse(UnsignedICmp->getType());
1629 // X >= Y || Y != 0 --> true
1630 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
1631 !IsAnd)
1632 return getTrue(UnsignedICmp->getType());
1634 return nullptr;
1637 /// Test if a pair of compares with a shared operand and 2 constants has an
1638 /// empty set intersection, full set union, or if one compare is a superset of
1639 /// the other.
1640 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
1641 bool IsAnd) {
1642 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
1643 if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
1644 return nullptr;
1646 const APInt *C0, *C1;
1647 if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
1648 !match(Cmp1->getOperand(1), m_APInt(C1)))
1649 return nullptr;
1651 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
1652 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
1654 // For and-of-compares, check if the intersection is empty:
1655 // (icmp X, C0) && (icmp X, C1) --> empty set --> false
1656 if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
1657 return getFalse(Cmp0->getType());
1659 // For or-of-compares, check if the union is full:
1660 // (icmp X, C0) || (icmp X, C1) --> full set --> true
1661 if (!IsAnd && Range0.unionWith(Range1).isFullSet())
1662 return getTrue(Cmp0->getType());
1664 // Is one range a superset of the other?
1665 // If this is and-of-compares, take the smaller set:
1666 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
1667 // If this is or-of-compares, take the larger set:
1668 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
1669 if (Range0.contains(Range1))
1670 return IsAnd ? Cmp1 : Cmp0;
1671 if (Range1.contains(Range0))
1672 return IsAnd ? Cmp0 : Cmp1;
1674 return nullptr;
1677 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
1678 bool IsAnd) {
1679 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
1680 if (!match(Cmp0->getOperand(1), m_Zero()) ||
1681 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
1682 return nullptr;
1684 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
1685 return nullptr;
1687 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
1688 Value *X = Cmp0->getOperand(0);
1689 Value *Y = Cmp1->getOperand(0);
1691 // If one of the compares is a masked version of a (not) null check, then
1692 // that compare implies the other, so we eliminate the other. Optionally, look
1693 // through a pointer-to-int cast to match a null check of a pointer type.
1695 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
1696 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
1697 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
1698 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
1699 if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
1700 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
1701 return Cmp1;
1703 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
1704 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
1705 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
1706 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
1707 if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
1708 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
1709 return Cmp0;
1711 return nullptr;
1714 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1715 const InstrInfoQuery &IIQ) {
1716 // (icmp (add V, C0), C1) & (icmp V, C0)
1717 ICmpInst::Predicate Pred0, Pred1;
1718 const APInt *C0, *C1;
1719 Value *V;
1720 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1721 return nullptr;
1723 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1724 return nullptr;
1726 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
1727 if (AddInst->getOperand(1) != Op1->getOperand(1))
1728 return nullptr;
1730 Type *ITy = Op0->getType();
1731 bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1732 bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
1734 const APInt Delta = *C1 - *C0;
1735 if (C0->isStrictlyPositive()) {
1736 if (Delta == 2) {
1737 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1738 return getFalse(ITy);
1739 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1740 return getFalse(ITy);
1742 if (Delta == 1) {
1743 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1744 return getFalse(ITy);
1745 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
1746 return getFalse(ITy);
1749 if (C0->getBoolValue() && IsNUW) {
1750 if (Delta == 2)
1751 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1752 return getFalse(ITy);
1753 if (Delta == 1)
1754 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1755 return getFalse(ITy);
1758 return nullptr;
1761 /// Try to eliminate compares with signed or unsigned min/max constants.
1762 static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1,
1763 bool IsAnd) {
1764 // Canonicalize an equality compare as Cmp0.
1765 if (Cmp1->isEquality())
1766 std::swap(Cmp0, Cmp1);
1767 if (!Cmp0->isEquality())
1768 return nullptr;
1770 // The non-equality compare must include a common operand (X). Canonicalize
1771 // the common operand as operand 0 (the predicate is swapped if the common
1772 // operand was operand 1).
1773 ICmpInst::Predicate Pred0 = Cmp0->getPredicate();
1774 Value *X = Cmp0->getOperand(0);
1775 ICmpInst::Predicate Pred1;
1776 bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value()));
1777 if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value())))
1778 return nullptr;
1779 if (ICmpInst::isEquality(Pred1))
1780 return nullptr;
1782 // The equality compare must be against a constant. Flip bits if we matched
1783 // a bitwise not. Convert a null pointer constant to an integer zero value.
1784 APInt MinMaxC;
1785 const APInt *C;
1786 if (match(Cmp0->getOperand(1), m_APInt(C)))
1787 MinMaxC = HasNotOp ? ~*C : *C;
1788 else if (isa<ConstantPointerNull>(Cmp0->getOperand(1)))
1789 MinMaxC = APInt::getZero(8);
1790 else
1791 return nullptr;
1793 // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1.
1794 if (!IsAnd) {
1795 Pred0 = ICmpInst::getInversePredicate(Pred0);
1796 Pred1 = ICmpInst::getInversePredicate(Pred1);
1799 // Normalize to unsigned compare and unsigned min/max value.
1800 // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255
1801 if (ICmpInst::isSigned(Pred1)) {
1802 Pred1 = ICmpInst::getUnsignedPredicate(Pred1);
1803 MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth());
1806 // (X != MAX) && (X < Y) --> X < Y
1807 // (X == MAX) || (X >= Y) --> X >= Y
1808 if (MinMaxC.isMaxValue())
1809 if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT)
1810 return Cmp1;
1812 // (X != MIN) && (X > Y) --> X > Y
1813 // (X == MIN) || (X <= Y) --> X <= Y
1814 if (MinMaxC.isMinValue())
1815 if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT)
1816 return Cmp1;
1818 return nullptr;
1821 /// Try to simplify and/or of icmp with ctpop intrinsic.
1822 static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
1823 bool IsAnd) {
1824 ICmpInst::Predicate Pred0, Pred1;
1825 Value *X;
1826 const APInt *C;
1827 if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
1828 m_APInt(C))) ||
1829 !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
1830 return nullptr;
1832 // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
1833 if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
1834 return Cmp1;
1835 // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
1836 if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
1837 return Cmp1;
1839 return nullptr;
1842 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1843 const SimplifyQuery &Q) {
1844 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
1845 return X;
1846 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
1847 return X;
1849 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
1850 return X;
1852 if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
1853 return X;
1855 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
1856 return X;
1858 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
1859 return X;
1860 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
1861 return X;
1863 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1864 return X;
1865 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1866 return X;
1868 return nullptr;
1871 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
1872 const InstrInfoQuery &IIQ) {
1873 // (icmp (add V, C0), C1) | (icmp V, C0)
1874 ICmpInst::Predicate Pred0, Pred1;
1875 const APInt *C0, *C1;
1876 Value *V;
1877 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
1878 return nullptr;
1880 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1881 return nullptr;
1883 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1884 if (AddInst->getOperand(1) != Op1->getOperand(1))
1885 return nullptr;
1887 Type *ITy = Op0->getType();
1888 bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
1889 bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
1891 const APInt Delta = *C1 - *C0;
1892 if (C0->isStrictlyPositive()) {
1893 if (Delta == 2) {
1894 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1895 return getTrue(ITy);
1896 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1897 return getTrue(ITy);
1899 if (Delta == 1) {
1900 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1901 return getTrue(ITy);
1902 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
1903 return getTrue(ITy);
1906 if (C0->getBoolValue() && IsNUW) {
1907 if (Delta == 2)
1908 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1909 return getTrue(ITy);
1910 if (Delta == 1)
1911 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1912 return getTrue(ITy);
1915 return nullptr;
1918 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
1919 const SimplifyQuery &Q) {
1920 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
1921 return X;
1922 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
1923 return X;
1925 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
1926 return X;
1928 if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
1929 return X;
1931 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
1932 return X;
1934 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
1935 return X;
1936 if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
1937 return X;
1939 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
1940 return X;
1941 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
1942 return X;
1944 return nullptr;
1947 static Value *simplifyAndOrOfFCmps(const SimplifyQuery &Q, FCmpInst *LHS,
1948 FCmpInst *RHS, bool IsAnd) {
1949 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
1950 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
1951 if (LHS0->getType() != RHS0->getType())
1952 return nullptr;
1954 const DataLayout &DL = Q.DL;
1955 const TargetLibraryInfo *TLI = Q.TLI;
1957 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
1958 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
1959 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
1960 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
1961 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
1962 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
1963 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
1964 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
1965 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
1966 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
1967 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
1968 if (((LHS1 == RHS0 || LHS1 == RHS1) &&
1969 isKnownNeverNaN(LHS0, DL, TLI, 0, Q.AC, Q.CxtI, Q.DT)) ||
1970 ((LHS0 == RHS0 || LHS0 == RHS1) &&
1971 isKnownNeverNaN(LHS1, DL, TLI, 0, Q.AC, Q.CxtI, Q.DT)))
1972 return RHS;
1974 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
1975 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
1976 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
1977 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
1978 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
1979 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
1980 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
1981 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
1982 if (((RHS1 == LHS0 || RHS1 == LHS1) &&
1983 isKnownNeverNaN(RHS0, DL, TLI, 0, Q.AC, Q.CxtI, Q.DT)) ||
1984 ((RHS0 == LHS0 || RHS0 == LHS1) &&
1985 isKnownNeverNaN(RHS1, DL, TLI, 0, Q.AC, Q.CxtI, Q.DT)))
1986 return LHS;
1989 return nullptr;
1992 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0,
1993 Value *Op1, bool IsAnd) {
1994 // Look through casts of the 'and' operands to find compares.
1995 auto *Cast0 = dyn_cast<CastInst>(Op0);
1996 auto *Cast1 = dyn_cast<CastInst>(Op1);
1997 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1998 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1999 Op0 = Cast0->getOperand(0);
2000 Op1 = Cast1->getOperand(0);
2003 Value *V = nullptr;
2004 auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
2005 auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
2006 if (ICmp0 && ICmp1)
2007 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
2008 : simplifyOrOfICmps(ICmp0, ICmp1, Q);
2010 auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
2011 auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
2012 if (FCmp0 && FCmp1)
2013 V = simplifyAndOrOfFCmps(Q, FCmp0, FCmp1, IsAnd);
2015 if (!V)
2016 return nullptr;
2017 if (!Cast0)
2018 return V;
2020 // If we looked through casts, we can only handle a constant simplification
2021 // because we are not allowed to create a cast instruction here.
2022 if (auto *C = dyn_cast<Constant>(V))
2023 return ConstantFoldCastOperand(Cast0->getOpcode(), C, Cast0->getType(),
2024 Q.DL);
2026 return nullptr;
2029 /// Given a bitwise logic op, check if the operands are add/sub with a common
2030 /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
2031 static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
2032 Instruction::BinaryOps Opcode) {
2033 assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
2034 assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
2035 Value *X;
2036 Constant *C1, *C2;
2037 if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
2038 match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
2039 (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
2040 match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
2041 if (ConstantExpr::getNot(C1) == C2) {
2042 // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
2043 // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
2044 // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
2045 Type *Ty = Op0->getType();
2046 return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
2047 : ConstantInt::getAllOnesValue(Ty);
2050 return nullptr;
2053 /// Given operands for an And, see if we can fold the result.
2054 /// If not, this returns null.
2055 static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2056 unsigned MaxRecurse) {
2057 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
2058 return C;
2060 // X & poison -> poison
2061 if (isa<PoisonValue>(Op1))
2062 return Op1;
2064 // X & undef -> 0
2065 if (Q.isUndefValue(Op1))
2066 return Constant::getNullValue(Op0->getType());
2068 // X & X = X
2069 if (Op0 == Op1)
2070 return Op0;
2072 // X & 0 = 0
2073 if (match(Op1, m_Zero()))
2074 return Constant::getNullValue(Op0->getType());
2076 // X & -1 = X
2077 if (match(Op1, m_AllOnes()))
2078 return Op0;
2080 // A & ~A = ~A & A = 0
2081 if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2082 return Constant::getNullValue(Op0->getType());
2084 // (A | ?) & A = A
2085 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
2086 return Op1;
2088 // A & (A | ?) = A
2089 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
2090 return Op0;
2092 // (X | Y) & (X | ~Y) --> X (commuted 8 ways)
2093 Value *X, *Y;
2094 if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2095 match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2096 return X;
2097 if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
2098 match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
2099 return X;
2101 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
2102 return V;
2104 // A mask that only clears known zeros of a shifted value is a no-op.
2105 const APInt *Mask;
2106 const APInt *ShAmt;
2107 if (match(Op1, m_APInt(Mask))) {
2108 // If all bits in the inverted and shifted mask are clear:
2109 // and (shl X, ShAmt), Mask --> shl X, ShAmt
2110 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
2111 (~(*Mask)).lshr(*ShAmt).isZero())
2112 return Op0;
2114 // If all bits in the inverted and shifted mask are clear:
2115 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
2116 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
2117 (~(*Mask)).shl(*ShAmt).isZero())
2118 return Op0;
2121 // and 2^x-1, 2^C --> 0 where x <= C.
2122 const APInt *PowerC;
2123 Value *Shift;
2124 if (match(Op1, m_Power2(PowerC)) &&
2125 match(Op0, m_Add(m_Value(Shift), m_AllOnes())) &&
2126 isKnownToBeAPowerOfTwo(Shift, Q.DL, /*OrZero*/ false, 0, Q.AC, Q.CxtI,
2127 Q.DT)) {
2128 KnownBits Known = computeKnownBits(Shift, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2129 // Use getActiveBits() to make use of the additional power of two knowledge
2130 if (PowerC->getActiveBits() >= Known.getMaxValue().getActiveBits())
2131 return ConstantInt::getNullValue(Op1->getType());
2134 // If we have a multiplication overflow check that is being 'and'ed with a
2135 // check that one of the multipliers is not zero, we can omit the 'and', and
2136 // only keep the overflow check.
2137 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
2138 return Op1;
2139 if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
2140 return Op0;
2142 // A & (-A) = A if A is a power of two or zero.
2143 if (match(Op0, m_Neg(m_Specific(Op1))) ||
2144 match(Op1, m_Neg(m_Specific(Op0)))) {
2145 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2146 Q.DT))
2147 return Op0;
2148 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
2149 Q.DT))
2150 return Op1;
2153 // This is a similar pattern used for checking if a value is a power-of-2:
2154 // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
2155 // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
2156 if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
2157 isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2158 return Constant::getNullValue(Op1->getType());
2159 if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
2160 isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
2161 return Constant::getNullValue(Op0->getType());
2163 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
2164 return V;
2166 // Try some generic simplifications for associative operations.
2167 if (Value *V =
2168 simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
2169 return V;
2171 // And distributes over Or. Try some generic simplifications based on this.
2172 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2173 Instruction::Or, Q, MaxRecurse))
2174 return V;
2176 // And distributes over Xor. Try some generic simplifications based on this.
2177 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
2178 Instruction::Xor, Q, MaxRecurse))
2179 return V;
2181 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2182 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2183 // A & (A && B) -> A && B
2184 if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
2185 return Op1;
2186 else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
2187 return Op0;
2189 // If the operation is with the result of a select instruction, check
2190 // whether operating on either branch of the select always yields the same
2191 // value.
2192 if (Value *V =
2193 threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
2194 return V;
2197 // If the operation is with the result of a phi instruction, check whether
2198 // operating on all incoming values of the phi always yields the same value.
2199 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2200 if (Value *V =
2201 threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
2202 return V;
2204 // Assuming the effective width of Y is not larger than A, i.e. all bits
2205 // from X and Y are disjoint in (X << A) | Y,
2206 // if the mask of this AND op covers all bits of X or Y, while it covers
2207 // no bits from the other, we can bypass this AND op. E.g.,
2208 // ((X << A) | Y) & Mask -> Y,
2209 // if Mask = ((1 << effective_width_of(Y)) - 1)
2210 // ((X << A) | Y) & Mask -> X << A,
2211 // if Mask = ((1 << effective_width_of(X)) - 1) << A
2212 // SimplifyDemandedBits in InstCombine can optimize the general case.
2213 // This pattern aims to help other passes for a common case.
2214 Value *XShifted;
2215 if (Q.IIQ.UseInstrInfo && match(Op1, m_APInt(Mask)) &&
2216 match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
2217 m_Value(XShifted)),
2218 m_Value(Y)))) {
2219 const unsigned Width = Op0->getType()->getScalarSizeInBits();
2220 const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
2221 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2222 const unsigned EffWidthY = YKnown.countMaxActiveBits();
2223 if (EffWidthY <= ShftCnt) {
2224 const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
2225 const unsigned EffWidthX = XKnown.countMaxActiveBits();
2226 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
2227 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
2228 // If the mask is extracting all bits from X or Y as is, we can skip
2229 // this AND op.
2230 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
2231 return Y;
2232 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
2233 return XShifted;
2237 // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
2238 // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
2239 BinaryOperator *Or;
2240 if (match(Op0, m_c_Xor(m_Value(X),
2241 m_CombineAnd(m_BinOp(Or),
2242 m_c_Or(m_Deferred(X), m_Value(Y))))) &&
2243 match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
2244 return Constant::getNullValue(Op0->getType());
2246 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2247 if (std::optional<bool> Implied = isImpliedCondition(Op0, Op1, Q.DL)) {
2248 // If Op0 is true implies Op1 is true, then Op0 is a subset of Op1.
2249 if (*Implied == true)
2250 return Op0;
2251 // If Op0 is true implies Op1 is false, then they are not true together.
2252 if (*Implied == false)
2253 return ConstantInt::getFalse(Op0->getType());
2255 if (std::optional<bool> Implied = isImpliedCondition(Op1, Op0, Q.DL)) {
2256 // If Op1 is true implies Op0 is true, then Op1 is a subset of Op0.
2257 if (*Implied)
2258 return Op1;
2259 // If Op1 is true implies Op0 is false, then they are not true together.
2260 if (!*Implied)
2261 return ConstantInt::getFalse(Op1->getType());
2265 if (Value *V = simplifyByDomEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
2266 return V;
2268 return nullptr;
2271 Value *llvm::simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2272 return ::simplifyAndInst(Op0, Op1, Q, RecursionLimit);
2275 // TODO: Many of these folds could use LogicalAnd/LogicalOr.
2276 static Value *simplifyOrLogic(Value *X, Value *Y) {
2277 assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
2278 Type *Ty = X->getType();
2280 // X | ~X --> -1
2281 if (match(Y, m_Not(m_Specific(X))))
2282 return ConstantInt::getAllOnesValue(Ty);
2284 // X | ~(X & ?) = -1
2285 if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
2286 return ConstantInt::getAllOnesValue(Ty);
2288 // X | (X & ?) --> X
2289 if (match(Y, m_c_And(m_Specific(X), m_Value())))
2290 return X;
2292 Value *A, *B;
2294 // (A ^ B) | (A | B) --> A | B
2295 // (A ^ B) | (B | A) --> B | A
2296 if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
2297 match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2298 return Y;
2300 // ~(A ^ B) | (A | B) --> -1
2301 // ~(A ^ B) | (B | A) --> -1
2302 if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
2303 match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2304 return ConstantInt::getAllOnesValue(Ty);
2306 // (A & ~B) | (A ^ B) --> A ^ B
2307 // (~B & A) | (A ^ B) --> A ^ B
2308 // (A & ~B) | (B ^ A) --> B ^ A
2309 // (~B & A) | (B ^ A) --> B ^ A
2310 if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
2311 match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2312 return Y;
2314 // (~A ^ B) | (A & B) --> ~A ^ B
2315 // (B ^ ~A) | (A & B) --> B ^ ~A
2316 // (~A ^ B) | (B & A) --> ~A ^ B
2317 // (B ^ ~A) | (B & A) --> B ^ ~A
2318 if (match(X, m_c_Xor(m_NotForbidUndef(m_Value(A)), m_Value(B))) &&
2319 match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2320 return X;
2322 // (~A | B) | (A ^ B) --> -1
2323 // (~A | B) | (B ^ A) --> -1
2324 // (B | ~A) | (A ^ B) --> -1
2325 // (B | ~A) | (B ^ A) --> -1
2326 if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
2327 match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2328 return ConstantInt::getAllOnesValue(Ty);
2330 // (~A & B) | ~(A | B) --> ~A
2331 // (~A & B) | ~(B | A) --> ~A
2332 // (B & ~A) | ~(A | B) --> ~A
2333 // (B & ~A) | ~(B | A) --> ~A
2334 Value *NotA;
2335 if (match(X,
2336 m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
2337 m_Value(B))) &&
2338 match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
2339 return NotA;
2340 // The same is true of Logical And
2341 // TODO: This could share the logic of the version above if there was a
2342 // version of LogicalAnd that allowed more than just i1 types.
2343 if (match(X, m_c_LogicalAnd(
2344 m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
2345 m_Value(B))) &&
2346 match(Y, m_Not(m_c_LogicalOr(m_Specific(A), m_Specific(B)))))
2347 return NotA;
2349 // ~(A ^ B) | (A & B) --> ~(A ^ B)
2350 // ~(A ^ B) | (B & A) --> ~(A ^ B)
2351 Value *NotAB;
2352 if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))),
2353 m_Value(NotAB))) &&
2354 match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2355 return NotAB;
2357 // ~(A & B) | (A ^ B) --> ~(A & B)
2358 // ~(A & B) | (B ^ A) --> ~(A & B)
2359 if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))),
2360 m_Value(NotAB))) &&
2361 match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
2362 return NotAB;
2364 return nullptr;
2367 /// Given operands for an Or, see if we can fold the result.
2368 /// If not, this returns null.
2369 static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2370 unsigned MaxRecurse) {
2371 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
2372 return C;
2374 // X | poison -> poison
2375 if (isa<PoisonValue>(Op1))
2376 return Op1;
2378 // X | undef -> -1
2379 // X | -1 = -1
2380 // Do not return Op1 because it may contain undef elements if it's a vector.
2381 if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
2382 return Constant::getAllOnesValue(Op0->getType());
2384 // X | X = X
2385 // X | 0 = X
2386 if (Op0 == Op1 || match(Op1, m_Zero()))
2387 return Op0;
2389 if (Value *R = simplifyOrLogic(Op0, Op1))
2390 return R;
2391 if (Value *R = simplifyOrLogic(Op1, Op0))
2392 return R;
2394 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
2395 return V;
2397 // Rotated -1 is still -1:
2398 // (-1 << X) | (-1 >> (C - X)) --> -1
2399 // (-1 >> X) | (-1 << (C - X)) --> -1
2400 // ...with C <= bitwidth (and commuted variants).
2401 Value *X, *Y;
2402 if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
2403 match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
2404 (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
2405 match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
2406 const APInt *C;
2407 if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
2408 match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
2409 C->ule(X->getType()->getScalarSizeInBits())) {
2410 return ConstantInt::getAllOnesValue(X->getType());
2414 // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
2415 // are mixing in another shift that is redundant with the funnel shift.
2417 // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
2418 // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
2419 if (match(Op0,
2420 m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2421 match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
2422 return Op0;
2423 if (match(Op1,
2424 m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
2425 match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
2426 return Op1;
2428 // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
2429 // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
2430 if (match(Op0,
2431 m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2432 match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
2433 return Op0;
2434 if (match(Op1,
2435 m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
2436 match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
2437 return Op1;
2439 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
2440 return V;
2442 // If we have a multiplication overflow check that is being 'and'ed with a
2443 // check that one of the multipliers is not zero, we can omit the 'and', and
2444 // only keep the overflow check.
2445 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
2446 return Op1;
2447 if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
2448 return Op0;
2450 // Try some generic simplifications for associative operations.
2451 if (Value *V =
2452 simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2453 return V;
2455 // Or distributes over And. Try some generic simplifications based on this.
2456 if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
2457 Instruction::And, Q, MaxRecurse))
2458 return V;
2460 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
2461 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2462 // A | (A || B) -> A || B
2463 if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
2464 return Op1;
2465 else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
2466 return Op0;
2468 // If the operation is with the result of a select instruction, check
2469 // whether operating on either branch of the select always yields the same
2470 // value.
2471 if (Value *V =
2472 threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2473 return V;
2476 // (A & C1)|(B & C2)
2477 Value *A, *B;
2478 const APInt *C1, *C2;
2479 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
2480 match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
2481 if (*C1 == ~*C2) {
2482 // (A & C1)|(B & C2)
2483 // If we have: ((V + N) & C1) | (V & C2)
2484 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2485 // replace with V+N.
2486 Value *N;
2487 if (C2->isMask() && // C2 == 0+1+
2488 match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
2489 // Add commutes, try both ways.
2490 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2491 return A;
2493 // Or commutes, try both ways.
2494 if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
2495 // Add commutes, try both ways.
2496 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2497 return B;
2502 // If the operation is with the result of a phi instruction, check whether
2503 // operating on all incoming values of the phi always yields the same value.
2504 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
2505 if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2506 return V;
2508 if (Op0->getType()->isIntOrIntVectorTy(1)) {
2509 if (std::optional<bool> Implied =
2510 isImpliedCondition(Op0, Op1, Q.DL, false)) {
2511 // If Op0 is false implies Op1 is false, then Op1 is a subset of Op0.
2512 if (*Implied == false)
2513 return Op0;
2514 // If Op0 is false implies Op1 is true, then at least one is always true.
2515 if (*Implied == true)
2516 return ConstantInt::getTrue(Op0->getType());
2518 if (std::optional<bool> Implied =
2519 isImpliedCondition(Op1, Op0, Q.DL, false)) {
2520 // If Op1 is false implies Op0 is false, then Op0 is a subset of Op1.
2521 if (*Implied == false)
2522 return Op1;
2523 // If Op1 is false implies Op0 is true, then at least one is always true.
2524 if (*Implied == true)
2525 return ConstantInt::getTrue(Op1->getType());
2529 if (Value *V = simplifyByDomEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
2530 return V;
2532 return nullptr;
2535 Value *llvm::simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2536 return ::simplifyOrInst(Op0, Op1, Q, RecursionLimit);
2539 /// Given operands for a Xor, see if we can fold the result.
2540 /// If not, this returns null.
2541 static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
2542 unsigned MaxRecurse) {
2543 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
2544 return C;
2546 // X ^ poison -> poison
2547 if (isa<PoisonValue>(Op1))
2548 return Op1;
2550 // A ^ undef -> undef
2551 if (Q.isUndefValue(Op1))
2552 return Op1;
2554 // A ^ 0 = A
2555 if (match(Op1, m_Zero()))
2556 return Op0;
2558 // A ^ A = 0
2559 if (Op0 == Op1)
2560 return Constant::getNullValue(Op0->getType());
2562 // A ^ ~A = ~A ^ A = -1
2563 if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
2564 return Constant::getAllOnesValue(Op0->getType());
2566 auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
2567 Value *A, *B;
2568 // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
2569 if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
2570 match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
2571 return A;
2573 // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
2574 // The 'not' op must contain a complete -1 operand (no undef elements for
2575 // vector) for the transform to be safe.
2576 Value *NotA;
2577 if (match(X,
2578 m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)),
2579 m_Value(B))) &&
2580 match(Y, m_c_And(m_Specific(A), m_Specific(B))))
2581 return NotA;
2583 return nullptr;
2585 if (Value *R = foldAndOrNot(Op0, Op1))
2586 return R;
2587 if (Value *R = foldAndOrNot(Op1, Op0))
2588 return R;
2590 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
2591 return V;
2593 // Try some generic simplifications for associative operations.
2594 if (Value *V =
2595 simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2596 return V;
2598 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2599 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2600 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2601 // only if B and C are equal. If B and C are equal then (since we assume
2602 // that operands have already been simplified) "select(cond, B, C)" should
2603 // have been simplified to the common value of B and C already. Analysing
2604 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2605 // for threading over phi nodes.
2607 if (Value *V = simplifyByDomEq(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
2608 return V;
2610 return nullptr;
2613 Value *llvm::simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
2614 return ::simplifyXorInst(Op0, Op1, Q, RecursionLimit);
2617 static Type *getCompareTy(Value *Op) {
2618 return CmpInst::makeCmpResultType(Op->getType());
2621 /// Rummage around inside V looking for something equivalent to the comparison
2622 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
2623 /// Helper function for analyzing max/min idioms.
2624 static Value *extractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2625 Value *LHS, Value *RHS) {
2626 SelectInst *SI = dyn_cast<SelectInst>(V);
2627 if (!SI)
2628 return nullptr;
2629 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2630 if (!Cmp)
2631 return nullptr;
2632 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2633 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2634 return Cmp;
2635 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2636 LHS == CmpRHS && RHS == CmpLHS)
2637 return Cmp;
2638 return nullptr;
2641 /// Return true if the underlying object (storage) must be disjoint from
2642 /// storage returned by any noalias return call.
2643 static bool isAllocDisjoint(const Value *V) {
2644 // For allocas, we consider only static ones (dynamic
2645 // allocas might be transformed into calls to malloc not simultaneously
2646 // live with the compared-to allocation). For globals, we exclude symbols
2647 // that might be resolve lazily to symbols in another dynamically-loaded
2648 // library (and, thus, could be malloc'ed by the implementation).
2649 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2650 return AI->isStaticAlloca();
2651 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2652 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2653 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2654 !GV->isThreadLocal();
2655 if (const Argument *A = dyn_cast<Argument>(V))
2656 return A->hasByValAttr();
2657 return false;
2660 /// Return true if V1 and V2 are each the base of some distict storage region
2661 /// [V, object_size(V)] which do not overlap. Note that zero sized regions
2662 /// *are* possible, and that zero sized regions do not overlap with any other.
2663 static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
2664 // Global variables always exist, so they always exist during the lifetime
2665 // of each other and all allocas. Global variables themselves usually have
2666 // non-overlapping storage, but since their addresses are constants, the
2667 // case involving two globals does not reach here and is instead handled in
2668 // constant folding.
2670 // Two different allocas usually have different addresses...
2672 // However, if there's an @llvm.stackrestore dynamically in between two
2673 // allocas, they may have the same address. It's tempting to reduce the
2674 // scope of the problem by only looking at *static* allocas here. That would
2675 // cover the majority of allocas while significantly reducing the likelihood
2676 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2677 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2678 // an entry block. Also, if we have a block that's not attached to a
2679 // function, we can't tell if it's "static" under the current definition.
2680 // Theoretically, this problem could be fixed by creating a new kind of
2681 // instruction kind specifically for static allocas. Such a new instruction
2682 // could be required to be at the top of the entry block, thus preventing it
2683 // from being subject to a @llvm.stackrestore. Instcombine could even
2684 // convert regular allocas into these special allocas. It'd be nifty.
2685 // However, until then, this problem remains open.
2687 // So, we'll assume that two non-empty allocas have different addresses
2688 // for now.
2689 auto isByValArg = [](const Value *V) {
2690 const Argument *A = dyn_cast<Argument>(V);
2691 return A && A->hasByValAttr();
2694 // Byval args are backed by store which does not overlap with each other,
2695 // allocas, or globals.
2696 if (isByValArg(V1))
2697 return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
2698 if (isByValArg(V2))
2699 return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
2701 return isa<AllocaInst>(V1) &&
2702 (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
2705 // A significant optimization not implemented here is assuming that alloca
2706 // addresses are not equal to incoming argument values. They don't *alias*,
2707 // as we say, but that doesn't mean they aren't equal, so we take a
2708 // conservative approach.
2710 // This is inspired in part by C++11 5.10p1:
2711 // "Two pointers of the same type compare equal if and only if they are both
2712 // null, both point to the same function, or both represent the same
2713 // address."
2715 // This is pretty permissive.
2717 // It's also partly due to C11 6.5.9p6:
2718 // "Two pointers compare equal if and only if both are null pointers, both are
2719 // pointers to the same object (including a pointer to an object and a
2720 // subobject at its beginning) or function, both are pointers to one past the
2721 // last element of the same array object, or one is a pointer to one past the
2722 // end of one array object and the other is a pointer to the start of a
2723 // different array object that happens to immediately follow the first array
2724 // object in the address space.)
2726 // C11's version is more restrictive, however there's no reason why an argument
2727 // couldn't be a one-past-the-end value for a stack object in the caller and be
2728 // equal to the beginning of a stack object in the callee.
2730 // If the C and C++ standards are ever made sufficiently restrictive in this
2731 // area, it may be possible to update LLVM's semantics accordingly and reinstate
2732 // this optimization.
2733 static Constant *computePointerICmp(CmpInst::Predicate Pred, Value *LHS,
2734 Value *RHS, const SimplifyQuery &Q) {
2735 assert(LHS->getType() == RHS->getType() && "Must have same types");
2736 const DataLayout &DL = Q.DL;
2737 const TargetLibraryInfo *TLI = Q.TLI;
2738 const DominatorTree *DT = Q.DT;
2739 const Instruction *CxtI = Q.CxtI;
2741 // We can only fold certain predicates on pointer comparisons.
2742 switch (Pred) {
2743 default:
2744 return nullptr;
2746 // Equality comparisons are easy to fold.
2747 case CmpInst::ICMP_EQ:
2748 case CmpInst::ICMP_NE:
2749 break;
2751 // We can only handle unsigned relational comparisons because 'inbounds' on
2752 // a GEP only protects against unsigned wrapping.
2753 case CmpInst::ICMP_UGT:
2754 case CmpInst::ICMP_UGE:
2755 case CmpInst::ICMP_ULT:
2756 case CmpInst::ICMP_ULE:
2757 // However, we have to switch them to their signed variants to handle
2758 // negative indices from the base pointer.
2759 Pred = ICmpInst::getSignedPredicate(Pred);
2760 break;
2763 // Strip off any constant offsets so that we can reason about them.
2764 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2765 // here and compare base addresses like AliasAnalysis does, however there are
2766 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2767 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2768 // doesn't need to guarantee pointer inequality when it says NoAlias.
2770 // Even if an non-inbounds GEP occurs along the path we can still optimize
2771 // equality comparisons concerning the result.
2772 bool AllowNonInbounds = ICmpInst::isEquality(Pred);
2773 unsigned IndexSize = DL.getIndexTypeSizeInBits(LHS->getType());
2774 APInt LHSOffset(IndexSize, 0), RHSOffset(IndexSize, 0);
2775 LHS = LHS->stripAndAccumulateConstantOffsets(DL, LHSOffset, AllowNonInbounds);
2776 RHS = RHS->stripAndAccumulateConstantOffsets(DL, RHSOffset, AllowNonInbounds);
2778 // If LHS and RHS are related via constant offsets to the same base
2779 // value, we can replace it with an icmp which just compares the offsets.
2780 if (LHS == RHS)
2781 return ConstantInt::get(getCompareTy(LHS),
2782 ICmpInst::compare(LHSOffset, RHSOffset, Pred));
2784 // Various optimizations for (in)equality comparisons.
2785 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2786 // Different non-empty allocations that exist at the same time have
2787 // different addresses (if the program can tell). If the offsets are
2788 // within the bounds of their allocations (and not one-past-the-end!
2789 // so we can't use inbounds!), and their allocations aren't the same,
2790 // the pointers are not equal.
2791 if (haveNonOverlappingStorage(LHS, RHS)) {
2792 uint64_t LHSSize, RHSSize;
2793 ObjectSizeOpts Opts;
2794 Opts.EvalMode = ObjectSizeOpts::Mode::Min;
2795 auto *F = [](Value *V) -> Function * {
2796 if (auto *I = dyn_cast<Instruction>(V))
2797 return I->getFunction();
2798 if (auto *A = dyn_cast<Argument>(V))
2799 return A->getParent();
2800 return nullptr;
2801 }(LHS);
2802 Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
2803 if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
2804 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) {
2805 APInt Dist = LHSOffset - RHSOffset;
2806 if (Dist.isNonNegative() ? Dist.ult(LHSSize) : (-Dist).ult(RHSSize))
2807 return ConstantInt::get(getCompareTy(LHS),
2808 !CmpInst::isTrueWhenEqual(Pred));
2812 // If one side of the equality comparison must come from a noalias call
2813 // (meaning a system memory allocation function), and the other side must
2814 // come from a pointer that cannot overlap with dynamically-allocated
2815 // memory within the lifetime of the current function (allocas, byval
2816 // arguments, globals), then determine the comparison result here.
2817 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
2818 getUnderlyingObjects(LHS, LHSUObjs);
2819 getUnderlyingObjects(RHS, RHSUObjs);
2821 // Is the set of underlying objects all noalias calls?
2822 auto IsNAC = [](ArrayRef<const Value *> Objects) {
2823 return all_of(Objects, isNoAliasCall);
2826 // Is the set of underlying objects all things which must be disjoint from
2827 // noalias calls. We assume that indexing from such disjoint storage
2828 // into the heap is undefined, and thus offsets can be safely ignored.
2829 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
2830 return all_of(Objects, ::isAllocDisjoint);
2833 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2834 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2835 return ConstantInt::get(getCompareTy(LHS),
2836 !CmpInst::isTrueWhenEqual(Pred));
2838 // Fold comparisons for non-escaping pointer even if the allocation call
2839 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2840 // dynamic allocation call could be either of the operands. Note that
2841 // the other operand can not be based on the alloc - if it were, then
2842 // the cmp itself would be a capture.
2843 Value *MI = nullptr;
2844 if (isAllocLikeFn(LHS, TLI) &&
2845 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
2846 MI = LHS;
2847 else if (isAllocLikeFn(RHS, TLI) &&
2848 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
2849 MI = RHS;
2850 if (MI) {
2851 // FIXME: This is incorrect, see PR54002. While we can assume that the
2852 // allocation is at an address that makes the comparison false, this
2853 // requires that *all* comparisons to that address be false, which
2854 // InstSimplify cannot guarantee.
2855 struct CustomCaptureTracker : public CaptureTracker {
2856 bool Captured = false;
2857 void tooManyUses() override { Captured = true; }
2858 bool captured(const Use *U) override {
2859 if (auto *ICmp = dyn_cast<ICmpInst>(U->getUser())) {
2860 // Comparison against value stored in global variable. Given the
2861 // pointer does not escape, its value cannot be guessed and stored
2862 // separately in a global variable.
2863 unsigned OtherIdx = 1 - U->getOperandNo();
2864 auto *LI = dyn_cast<LoadInst>(ICmp->getOperand(OtherIdx));
2865 if (LI && isa<GlobalVariable>(LI->getPointerOperand()))
2866 return false;
2869 Captured = true;
2870 return true;
2873 CustomCaptureTracker Tracker;
2874 PointerMayBeCaptured(MI, &Tracker);
2875 if (!Tracker.Captured)
2876 return ConstantInt::get(getCompareTy(LHS),
2877 CmpInst::isFalseWhenEqual(Pred));
2881 // Otherwise, fail.
2882 return nullptr;
2885 /// Fold an icmp when its operands have i1 scalar type.
2886 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2887 Value *RHS, const SimplifyQuery &Q) {
2888 Type *ITy = getCompareTy(LHS); // The return type.
2889 Type *OpTy = LHS->getType(); // The operand type.
2890 if (!OpTy->isIntOrIntVectorTy(1))
2891 return nullptr;
2893 // A boolean compared to true/false can be reduced in 14 out of the 20
2894 // (10 predicates * 2 constants) possible combinations. The other
2895 // 6 cases require a 'not' of the LHS.
2897 auto ExtractNotLHS = [](Value *V) -> Value * {
2898 Value *X;
2899 if (match(V, m_Not(m_Value(X))))
2900 return X;
2901 return nullptr;
2904 if (match(RHS, m_Zero())) {
2905 switch (Pred) {
2906 case CmpInst::ICMP_NE: // X != 0 -> X
2907 case CmpInst::ICMP_UGT: // X >u 0 -> X
2908 case CmpInst::ICMP_SLT: // X <s 0 -> X
2909 return LHS;
2911 case CmpInst::ICMP_EQ: // not(X) == 0 -> X != 0 -> X
2912 case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
2913 case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
2914 if (Value *X = ExtractNotLHS(LHS))
2915 return X;
2916 break;
2918 case CmpInst::ICMP_ULT: // X <u 0 -> false
2919 case CmpInst::ICMP_SGT: // X >s 0 -> false
2920 return getFalse(ITy);
2922 case CmpInst::ICMP_UGE: // X >=u 0 -> true
2923 case CmpInst::ICMP_SLE: // X <=s 0 -> true
2924 return getTrue(ITy);
2926 default:
2927 break;
2929 } else if (match(RHS, m_One())) {
2930 switch (Pred) {
2931 case CmpInst::ICMP_EQ: // X == 1 -> X
2932 case CmpInst::ICMP_UGE: // X >=u 1 -> X
2933 case CmpInst::ICMP_SLE: // X <=s -1 -> X
2934 return LHS;
2936 case CmpInst::ICMP_NE: // not(X) != 1 -> X == 1 -> X
2937 case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u 1 -> X
2938 case CmpInst::ICMP_SGT: // not(X) >s 1 -> X <=s -1 -> X
2939 if (Value *X = ExtractNotLHS(LHS))
2940 return X;
2941 break;
2943 case CmpInst::ICMP_UGT: // X >u 1 -> false
2944 case CmpInst::ICMP_SLT: // X <s -1 -> false
2945 return getFalse(ITy);
2947 case CmpInst::ICMP_ULE: // X <=u 1 -> true
2948 case CmpInst::ICMP_SGE: // X >=s -1 -> true
2949 return getTrue(ITy);
2951 default:
2952 break;
2956 switch (Pred) {
2957 default:
2958 break;
2959 case ICmpInst::ICMP_UGE:
2960 if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2961 return getTrue(ITy);
2962 break;
2963 case ICmpInst::ICMP_SGE:
2964 /// For signed comparison, the values for an i1 are 0 and -1
2965 /// respectively. This maps into a truth table of:
2966 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2967 /// 0 | 0 | 1 (0 >= 0) | 1
2968 /// 0 | 1 | 1 (0 >= -1) | 1
2969 /// 1 | 0 | 0 (-1 >= 0) | 0
2970 /// 1 | 1 | 1 (-1 >= -1) | 1
2971 if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2972 return getTrue(ITy);
2973 break;
2974 case ICmpInst::ICMP_ULE:
2975 if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
2976 return getTrue(ITy);
2977 break;
2978 case ICmpInst::ICMP_SLE:
2979 /// SLE follows the same logic as SGE with the LHS and RHS swapped.
2980 if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
2981 return getTrue(ITy);
2982 break;
2985 return nullptr;
2988 /// Try hard to fold icmp with zero RHS because this is a common case.
2989 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2990 Value *RHS, const SimplifyQuery &Q) {
2991 if (!match(RHS, m_Zero()))
2992 return nullptr;
2994 Type *ITy = getCompareTy(LHS); // The return type.
2995 switch (Pred) {
2996 default:
2997 llvm_unreachable("Unknown ICmp predicate!");
2998 case ICmpInst::ICMP_ULT:
2999 return getFalse(ITy);
3000 case ICmpInst::ICMP_UGE:
3001 return getTrue(ITy);
3002 case ICmpInst::ICMP_EQ:
3003 case ICmpInst::ICMP_ULE:
3004 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
3005 return getFalse(ITy);
3006 break;
3007 case ICmpInst::ICMP_NE:
3008 case ICmpInst::ICMP_UGT:
3009 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
3010 return getTrue(ITy);
3011 break;
3012 case ICmpInst::ICMP_SLT: {
3013 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3014 if (LHSKnown.isNegative())
3015 return getTrue(ITy);
3016 if (LHSKnown.isNonNegative())
3017 return getFalse(ITy);
3018 break;
3020 case ICmpInst::ICMP_SLE: {
3021 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3022 if (LHSKnown.isNegative())
3023 return getTrue(ITy);
3024 if (LHSKnown.isNonNegative() &&
3025 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
3026 return getFalse(ITy);
3027 break;
3029 case ICmpInst::ICMP_SGE: {
3030 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3031 if (LHSKnown.isNegative())
3032 return getFalse(ITy);
3033 if (LHSKnown.isNonNegative())
3034 return getTrue(ITy);
3035 break;
3037 case ICmpInst::ICMP_SGT: {
3038 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3039 if (LHSKnown.isNegative())
3040 return getFalse(ITy);
3041 if (LHSKnown.isNonNegative() &&
3042 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
3043 return getTrue(ITy);
3044 break;
3048 return nullptr;
3051 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
3052 Value *RHS, const InstrInfoQuery &IIQ) {
3053 Type *ITy = getCompareTy(RHS); // The return type.
3055 Value *X;
3056 // Sign-bit checks can be optimized to true/false after unsigned
3057 // floating-point casts:
3058 // icmp slt (bitcast (uitofp X)), 0 --> false
3059 // icmp sgt (bitcast (uitofp X)), -1 --> true
3060 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
3061 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
3062 return ConstantInt::getFalse(ITy);
3063 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
3064 return ConstantInt::getTrue(ITy);
3067 const APInt *C;
3068 if (!match(RHS, m_APIntAllowUndef(C)))
3069 return nullptr;
3071 // Rule out tautological comparisons (eg., ult 0 or uge 0).
3072 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
3073 if (RHS_CR.isEmptySet())
3074 return ConstantInt::getFalse(ITy);
3075 if (RHS_CR.isFullSet())
3076 return ConstantInt::getTrue(ITy);
3078 ConstantRange LHS_CR =
3079 computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
3080 if (!LHS_CR.isFullSet()) {
3081 if (RHS_CR.contains(LHS_CR))
3082 return ConstantInt::getTrue(ITy);
3083 if (RHS_CR.inverse().contains(LHS_CR))
3084 return ConstantInt::getFalse(ITy);
3087 // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC)
3088 // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
3089 const APInt *MulC;
3090 if (IIQ.UseInstrInfo && ICmpInst::isEquality(Pred) &&
3091 ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
3092 *MulC != 0 && C->urem(*MulC) != 0) ||
3093 (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
3094 *MulC != 0 && C->srem(*MulC) != 0)))
3095 return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
3097 return nullptr;
3100 static Value *simplifyICmpWithBinOpOnLHS(CmpInst::Predicate Pred,
3101 BinaryOperator *LBO, Value *RHS,
3102 const SimplifyQuery &Q,
3103 unsigned MaxRecurse) {
3104 Type *ITy = getCompareTy(RHS); // The return type.
3106 Value *Y = nullptr;
3107 // icmp pred (or X, Y), X
3108 if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
3109 if (Pred == ICmpInst::ICMP_ULT)
3110 return getFalse(ITy);
3111 if (Pred == ICmpInst::ICMP_UGE)
3112 return getTrue(ITy);
3114 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
3115 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3116 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3117 if (RHSKnown.isNonNegative() && YKnown.isNegative())
3118 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
3119 if (RHSKnown.isNegative() || YKnown.isNonNegative())
3120 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
3124 // icmp pred (and X, Y), X
3125 if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
3126 if (Pred == ICmpInst::ICMP_UGT)
3127 return getFalse(ITy);
3128 if (Pred == ICmpInst::ICMP_ULE)
3129 return getTrue(ITy);
3132 // icmp pred (urem X, Y), Y
3133 if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
3134 switch (Pred) {
3135 default:
3136 break;
3137 case ICmpInst::ICMP_SGT:
3138 case ICmpInst::ICMP_SGE: {
3139 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3140 if (!Known.isNonNegative())
3141 break;
3142 [[fallthrough]];
3144 case ICmpInst::ICMP_EQ:
3145 case ICmpInst::ICMP_UGT:
3146 case ICmpInst::ICMP_UGE:
3147 return getFalse(ITy);
3148 case ICmpInst::ICMP_SLT:
3149 case ICmpInst::ICMP_SLE: {
3150 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
3151 if (!Known.isNonNegative())
3152 break;
3153 [[fallthrough]];
3155 case ICmpInst::ICMP_NE:
3156 case ICmpInst::ICMP_ULT:
3157 case ICmpInst::ICMP_ULE:
3158 return getTrue(ITy);
3162 // icmp pred (urem X, Y), X
3163 if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
3164 if (Pred == ICmpInst::ICMP_ULE)
3165 return getTrue(ITy);
3166 if (Pred == ICmpInst::ICMP_UGT)
3167 return getFalse(ITy);
3170 // x >>u y <=u x --> true.
3171 // x >>u y >u x --> false.
3172 // x udiv y <=u x --> true.
3173 // x udiv y >u x --> false.
3174 if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
3175 match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
3176 // icmp pred (X op Y), X
3177 if (Pred == ICmpInst::ICMP_UGT)
3178 return getFalse(ITy);
3179 if (Pred == ICmpInst::ICMP_ULE)
3180 return getTrue(ITy);
3183 // If x is nonzero:
3184 // x >>u C <u x --> true for C != 0.
3185 // x >>u C != x --> true for C != 0.
3186 // x >>u C >=u x --> false for C != 0.
3187 // x >>u C == x --> false for C != 0.
3188 // x udiv C <u x --> true for C != 1.
3189 // x udiv C != x --> true for C != 1.
3190 // x udiv C >=u x --> false for C != 1.
3191 // x udiv C == x --> false for C != 1.
3192 // TODO: allow non-constant shift amount/divisor
3193 const APInt *C;
3194 if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
3195 (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
3196 if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
3197 switch (Pred) {
3198 default:
3199 break;
3200 case ICmpInst::ICMP_EQ:
3201 case ICmpInst::ICMP_UGE:
3202 return getFalse(ITy);
3203 case ICmpInst::ICMP_NE:
3204 case ICmpInst::ICMP_ULT:
3205 return getTrue(ITy);
3206 case ICmpInst::ICMP_UGT:
3207 case ICmpInst::ICMP_ULE:
3208 // UGT/ULE are handled by the more general case just above
3209 llvm_unreachable("Unexpected UGT/ULE, should have been handled");
3214 // (x*C1)/C2 <= x for C1 <= C2.
3215 // This holds even if the multiplication overflows: Assume that x != 0 and
3216 // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
3217 // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
3219 // Additionally, either the multiplication and division might be represented
3220 // as shifts:
3221 // (x*C1)>>C2 <= x for C1 < 2**C2.
3222 // (x<<C1)/C2 <= x for 2**C1 < C2.
3223 const APInt *C1, *C2;
3224 if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3225 C1->ule(*C2)) ||
3226 (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3227 C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
3228 (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
3229 (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
3230 if (Pred == ICmpInst::ICMP_UGT)
3231 return getFalse(ITy);
3232 if (Pred == ICmpInst::ICMP_ULE)
3233 return getTrue(ITy);
3236 // (sub C, X) == X, C is odd --> false
3237 // (sub C, X) != X, C is odd --> true
3238 if (match(LBO, m_Sub(m_APIntAllowUndef(C), m_Specific(RHS))) &&
3239 (*C & 1) == 1 && ICmpInst::isEquality(Pred))
3240 return (Pred == ICmpInst::ICMP_EQ) ? getFalse(ITy) : getTrue(ITy);
3242 return nullptr;
3245 // If only one of the icmp's operands has NSW flags, try to prove that:
3247 // icmp slt (x + C1), (x +nsw C2)
3249 // is equivalent to:
3251 // icmp slt C1, C2
3253 // which is true if x + C2 has the NSW flags set and:
3254 // *) C1 < C2 && C1 >= 0, or
3255 // *) C2 < C1 && C1 <= 0.
3257 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
3258 Value *RHS, const InstrInfoQuery &IIQ) {
3259 // TODO: only support icmp slt for now.
3260 if (Pred != CmpInst::ICMP_SLT || !IIQ.UseInstrInfo)
3261 return false;
3263 // Canonicalize nsw add as RHS.
3264 if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3265 std::swap(LHS, RHS);
3266 if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
3267 return false;
3269 Value *X;
3270 const APInt *C1, *C2;
3271 if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
3272 !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
3273 return false;
3275 return (C1->slt(*C2) && C1->isNonNegative()) ||
3276 (C2->slt(*C1) && C1->isNonPositive());
3279 /// TODO: A large part of this logic is duplicated in InstCombine's
3280 /// foldICmpBinOp(). We should be able to share that and avoid the code
3281 /// duplication.
3282 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
3283 Value *RHS, const SimplifyQuery &Q,
3284 unsigned MaxRecurse) {
3285 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
3286 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
3287 if (MaxRecurse && (LBO || RBO)) {
3288 // Analyze the case when either LHS or RHS is an add instruction.
3289 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
3290 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
3291 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
3292 if (LBO && LBO->getOpcode() == Instruction::Add) {
3293 A = LBO->getOperand(0);
3294 B = LBO->getOperand(1);
3295 NoLHSWrapProblem =
3296 ICmpInst::isEquality(Pred) ||
3297 (CmpInst::isUnsigned(Pred) &&
3298 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
3299 (CmpInst::isSigned(Pred) &&
3300 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
3302 if (RBO && RBO->getOpcode() == Instruction::Add) {
3303 C = RBO->getOperand(0);
3304 D = RBO->getOperand(1);
3305 NoRHSWrapProblem =
3306 ICmpInst::isEquality(Pred) ||
3307 (CmpInst::isUnsigned(Pred) &&
3308 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
3309 (CmpInst::isSigned(Pred) &&
3310 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
3313 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
3314 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
3315 if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
3316 Constant::getNullValue(RHS->getType()), Q,
3317 MaxRecurse - 1))
3318 return V;
3320 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
3321 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
3322 if (Value *V =
3323 simplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
3324 C == LHS ? D : C, Q, MaxRecurse - 1))
3325 return V;
3327 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
3328 bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
3329 trySimplifyICmpWithAdds(Pred, LHS, RHS, Q.IIQ);
3330 if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
3331 // Determine Y and Z in the form icmp (X+Y), (X+Z).
3332 Value *Y, *Z;
3333 if (A == C) {
3334 // C + B == C + D -> B == D
3335 Y = B;
3336 Z = D;
3337 } else if (A == D) {
3338 // D + B == C + D -> B == C
3339 Y = B;
3340 Z = C;
3341 } else if (B == C) {
3342 // A + C == C + D -> A == D
3343 Y = A;
3344 Z = D;
3345 } else {
3346 assert(B == D);
3347 // A + D == C + D -> A == C
3348 Y = A;
3349 Z = C;
3351 if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
3352 return V;
3356 if (LBO)
3357 if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
3358 return V;
3360 if (RBO)
3361 if (Value *V = simplifyICmpWithBinOpOnLHS(
3362 ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
3363 return V;
3365 // 0 - (zext X) pred C
3366 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
3367 const APInt *C;
3368 if (match(RHS, m_APInt(C))) {
3369 if (C->isStrictlyPositive()) {
3370 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
3371 return ConstantInt::getTrue(getCompareTy(RHS));
3372 if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
3373 return ConstantInt::getFalse(getCompareTy(RHS));
3375 if (C->isNonNegative()) {
3376 if (Pred == ICmpInst::ICMP_SLE)
3377 return ConstantInt::getTrue(getCompareTy(RHS));
3378 if (Pred == ICmpInst::ICMP_SGT)
3379 return ConstantInt::getFalse(getCompareTy(RHS));
3384 // If C2 is a power-of-2 and C is not:
3385 // (C2 << X) == C --> false
3386 // (C2 << X) != C --> true
3387 const APInt *C;
3388 if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
3389 match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
3390 // C2 << X can equal zero in some circumstances.
3391 // This simplification might be unsafe if C is zero.
3393 // We know it is safe if:
3394 // - The shift is nsw. We can't shift out the one bit.
3395 // - The shift is nuw. We can't shift out the one bit.
3396 // - C2 is one.
3397 // - C isn't zero.
3398 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3399 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
3400 match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
3401 if (Pred == ICmpInst::ICMP_EQ)
3402 return ConstantInt::getFalse(getCompareTy(RHS));
3403 if (Pred == ICmpInst::ICMP_NE)
3404 return ConstantInt::getTrue(getCompareTy(RHS));
3408 // If C is a power-of-2:
3409 // (C << X) >u 0x8000 --> false
3410 // (C << X) <=u 0x8000 --> true
3411 if (match(LHS, m_Shl(m_Power2(), m_Value())) && match(RHS, m_SignMask())) {
3412 if (Pred == ICmpInst::ICMP_UGT)
3413 return ConstantInt::getFalse(getCompareTy(RHS));
3414 if (Pred == ICmpInst::ICMP_ULE)
3415 return ConstantInt::getTrue(getCompareTy(RHS));
3418 if (!MaxRecurse || !LBO || !RBO || LBO->getOpcode() != RBO->getOpcode())
3419 return nullptr;
3421 if (LBO->getOperand(0) == RBO->getOperand(0)) {
3422 switch (LBO->getOpcode()) {
3423 default:
3424 break;
3425 case Instruction::Shl: {
3426 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3427 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3428 if (!NUW || (ICmpInst::isSigned(Pred) && !NSW) ||
3429 !isKnownNonZero(LBO->getOperand(0), Q.DL))
3430 break;
3431 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(1),
3432 RBO->getOperand(1), Q, MaxRecurse - 1))
3433 return V;
3434 break;
3436 // If C1 & C2 == C1, A = X and/or C1, B = X and/or C2:
3437 // icmp ule A, B -> true
3438 // icmp ugt A, B -> false
3439 // icmp sle A, B -> true (C1 and C2 are the same sign)
3440 // icmp sgt A, B -> false (C1 and C2 are the same sign)
3441 case Instruction::And:
3442 case Instruction::Or: {
3443 const APInt *C1, *C2;
3444 if (ICmpInst::isRelational(Pred) &&
3445 match(LBO->getOperand(1), m_APInt(C1)) &&
3446 match(RBO->getOperand(1), m_APInt(C2))) {
3447 if (!C1->isSubsetOf(*C2)) {
3448 std::swap(C1, C2);
3449 Pred = ICmpInst::getSwappedPredicate(Pred);
3451 if (C1->isSubsetOf(*C2)) {
3452 if (Pred == ICmpInst::ICMP_ULE)
3453 return ConstantInt::getTrue(getCompareTy(LHS));
3454 if (Pred == ICmpInst::ICMP_UGT)
3455 return ConstantInt::getFalse(getCompareTy(LHS));
3456 if (C1->isNonNegative() == C2->isNonNegative()) {
3457 if (Pred == ICmpInst::ICMP_SLE)
3458 return ConstantInt::getTrue(getCompareTy(LHS));
3459 if (Pred == ICmpInst::ICMP_SGT)
3460 return ConstantInt::getFalse(getCompareTy(LHS));
3464 break;
3469 if (LBO->getOperand(1) == RBO->getOperand(1)) {
3470 switch (LBO->getOpcode()) {
3471 default:
3472 break;
3473 case Instruction::UDiv:
3474 case Instruction::LShr:
3475 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
3476 !Q.IIQ.isExact(RBO))
3477 break;
3478 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3479 RBO->getOperand(0), Q, MaxRecurse - 1))
3480 return V;
3481 break;
3482 case Instruction::SDiv:
3483 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
3484 !Q.IIQ.isExact(RBO))
3485 break;
3486 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3487 RBO->getOperand(0), Q, MaxRecurse - 1))
3488 return V;
3489 break;
3490 case Instruction::AShr:
3491 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
3492 break;
3493 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3494 RBO->getOperand(0), Q, MaxRecurse - 1))
3495 return V;
3496 break;
3497 case Instruction::Shl: {
3498 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
3499 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
3500 if (!NUW && !NSW)
3501 break;
3502 if (!NSW && ICmpInst::isSigned(Pred))
3503 break;
3504 if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
3505 RBO->getOperand(0), Q, MaxRecurse - 1))
3506 return V;
3507 break;
3511 return nullptr;
3514 /// simplify integer comparisons where at least one operand of the compare
3515 /// matches an integer min/max idiom.
3516 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
3517 Value *RHS, const SimplifyQuery &Q,
3518 unsigned MaxRecurse) {
3519 Type *ITy = getCompareTy(LHS); // The return type.
3520 Value *A, *B;
3521 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
3522 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
3524 // Signed variants on "max(a,b)>=a -> true".
3525 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3526 if (A != RHS)
3527 std::swap(A, B); // smax(A, B) pred A.
3528 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3529 // We analyze this as smax(A, B) pred A.
3530 P = Pred;
3531 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
3532 (A == LHS || B == LHS)) {
3533 if (A != LHS)
3534 std::swap(A, B); // A pred smax(A, B).
3535 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
3536 // We analyze this as smax(A, B) swapped-pred A.
3537 P = CmpInst::getSwappedPredicate(Pred);
3538 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3539 (A == RHS || B == RHS)) {
3540 if (A != RHS)
3541 std::swap(A, B); // smin(A, B) pred A.
3542 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3543 // We analyze this as smax(-A, -B) swapped-pred -A.
3544 // Note that we do not need to actually form -A or -B thanks to EqP.
3545 P = CmpInst::getSwappedPredicate(Pred);
3546 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
3547 (A == LHS || B == LHS)) {
3548 if (A != LHS)
3549 std::swap(A, B); // A pred smin(A, B).
3550 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
3551 // We analyze this as smax(-A, -B) pred -A.
3552 // Note that we do not need to actually form -A or -B thanks to EqP.
3553 P = Pred;
3555 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3556 // Cases correspond to "max(A, B) p A".
3557 switch (P) {
3558 default:
3559 break;
3560 case CmpInst::ICMP_EQ:
3561 case CmpInst::ICMP_SLE:
3562 // Equivalent to "A EqP B". This may be the same as the condition tested
3563 // in the max/min; if so, we can just return that.
3564 if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3565 return V;
3566 if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3567 return V;
3568 // Otherwise, see if "A EqP B" simplifies.
3569 if (MaxRecurse)
3570 if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3571 return V;
3572 break;
3573 case CmpInst::ICMP_NE:
3574 case CmpInst::ICMP_SGT: {
3575 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3576 // Equivalent to "A InvEqP B". This may be the same as the condition
3577 // tested in the max/min; if so, we can just return that.
3578 if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3579 return V;
3580 if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3581 return V;
3582 // Otherwise, see if "A InvEqP B" simplifies.
3583 if (MaxRecurse)
3584 if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3585 return V;
3586 break;
3588 case CmpInst::ICMP_SGE:
3589 // Always true.
3590 return getTrue(ITy);
3591 case CmpInst::ICMP_SLT:
3592 // Always false.
3593 return getFalse(ITy);
3597 // Unsigned variants on "max(a,b)>=a -> true".
3598 P = CmpInst::BAD_ICMP_PREDICATE;
3599 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
3600 if (A != RHS)
3601 std::swap(A, B); // umax(A, B) pred A.
3602 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3603 // We analyze this as umax(A, B) pred A.
3604 P = Pred;
3605 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
3606 (A == LHS || B == LHS)) {
3607 if (A != LHS)
3608 std::swap(A, B); // A pred umax(A, B).
3609 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
3610 // We analyze this as umax(A, B) swapped-pred A.
3611 P = CmpInst::getSwappedPredicate(Pred);
3612 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3613 (A == RHS || B == RHS)) {
3614 if (A != RHS)
3615 std::swap(A, B); // umin(A, B) pred A.
3616 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3617 // We analyze this as umax(-A, -B) swapped-pred -A.
3618 // Note that we do not need to actually form -A or -B thanks to EqP.
3619 P = CmpInst::getSwappedPredicate(Pred);
3620 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3621 (A == LHS || B == LHS)) {
3622 if (A != LHS)
3623 std::swap(A, B); // A pred umin(A, B).
3624 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3625 // We analyze this as umax(-A, -B) pred -A.
3626 // Note that we do not need to actually form -A or -B thanks to EqP.
3627 P = Pred;
3629 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3630 // Cases correspond to "max(A, B) p A".
3631 switch (P) {
3632 default:
3633 break;
3634 case CmpInst::ICMP_EQ:
3635 case CmpInst::ICMP_ULE:
3636 // Equivalent to "A EqP B". This may be the same as the condition tested
3637 // in the max/min; if so, we can just return that.
3638 if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
3639 return V;
3640 if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
3641 return V;
3642 // Otherwise, see if "A EqP B" simplifies.
3643 if (MaxRecurse)
3644 if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3645 return V;
3646 break;
3647 case CmpInst::ICMP_NE:
3648 case CmpInst::ICMP_UGT: {
3649 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3650 // Equivalent to "A InvEqP B". This may be the same as the condition
3651 // tested in the max/min; if so, we can just return that.
3652 if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
3653 return V;
3654 if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
3655 return V;
3656 // Otherwise, see if "A InvEqP B" simplifies.
3657 if (MaxRecurse)
3658 if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3659 return V;
3660 break;
3662 case CmpInst::ICMP_UGE:
3663 return getTrue(ITy);
3664 case CmpInst::ICMP_ULT:
3665 return getFalse(ITy);
3669 // Comparing 1 each of min/max with a common operand?
3670 // Canonicalize min operand to RHS.
3671 if (match(LHS, m_UMin(m_Value(), m_Value())) ||
3672 match(LHS, m_SMin(m_Value(), m_Value()))) {
3673 std::swap(LHS, RHS);
3674 Pred = ICmpInst::getSwappedPredicate(Pred);
3677 Value *C, *D;
3678 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3679 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3680 (A == C || A == D || B == C || B == D)) {
3681 // smax(A, B) >=s smin(A, D) --> true
3682 if (Pred == CmpInst::ICMP_SGE)
3683 return getTrue(ITy);
3684 // smax(A, B) <s smin(A, D) --> false
3685 if (Pred == CmpInst::ICMP_SLT)
3686 return getFalse(ITy);
3687 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3688 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3689 (A == C || A == D || B == C || B == D)) {
3690 // umax(A, B) >=u umin(A, D) --> true
3691 if (Pred == CmpInst::ICMP_UGE)
3692 return getTrue(ITy);
3693 // umax(A, B) <u umin(A, D) --> false
3694 if (Pred == CmpInst::ICMP_ULT)
3695 return getFalse(ITy);
3698 return nullptr;
3701 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
3702 Value *LHS, Value *RHS,
3703 const SimplifyQuery &Q) {
3704 // Gracefully handle instructions that have not been inserted yet.
3705 if (!Q.AC || !Q.CxtI)
3706 return nullptr;
3708 for (Value *AssumeBaseOp : {LHS, RHS}) {
3709 for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
3710 if (!AssumeVH)
3711 continue;
3713 CallInst *Assume = cast<CallInst>(AssumeVH);
3714 if (std::optional<bool> Imp = isImpliedCondition(
3715 Assume->getArgOperand(0), Predicate, LHS, RHS, Q.DL))
3716 if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
3717 return ConstantInt::get(getCompareTy(LHS), *Imp);
3721 return nullptr;
3724 static Value *simplifyICmpWithIntrinsicOnLHS(CmpInst::Predicate Pred,
3725 Value *LHS, Value *RHS) {
3726 auto *II = dyn_cast<IntrinsicInst>(LHS);
3727 if (!II)
3728 return nullptr;
3730 switch (II->getIntrinsicID()) {
3731 case Intrinsic::uadd_sat:
3732 // uadd.sat(X, Y) uge X, uadd.sat(X, Y) uge Y
3733 if (II->getArgOperand(0) == RHS || II->getArgOperand(1) == RHS) {
3734 if (Pred == ICmpInst::ICMP_UGE)
3735 return ConstantInt::getTrue(getCompareTy(II));
3736 if (Pred == ICmpInst::ICMP_ULT)
3737 return ConstantInt::getFalse(getCompareTy(II));
3739 return nullptr;
3740 case Intrinsic::usub_sat:
3741 // usub.sat(X, Y) ule X
3742 if (II->getArgOperand(0) == RHS) {
3743 if (Pred == ICmpInst::ICMP_ULE)
3744 return ConstantInt::getTrue(getCompareTy(II));
3745 if (Pred == ICmpInst::ICMP_UGT)
3746 return ConstantInt::getFalse(getCompareTy(II));
3748 return nullptr;
3749 default:
3750 return nullptr;
3754 /// Given operands for an ICmpInst, see if we can fold the result.
3755 /// If not, this returns null.
3756 static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3757 const SimplifyQuery &Q, unsigned MaxRecurse) {
3758 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3759 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
3761 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3762 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3763 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3765 // If we have a constant, make sure it is on the RHS.
3766 std::swap(LHS, RHS);
3767 Pred = CmpInst::getSwappedPredicate(Pred);
3769 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
3771 Type *ITy = getCompareTy(LHS); // The return type.
3773 // icmp poison, X -> poison
3774 if (isa<PoisonValue>(RHS))
3775 return PoisonValue::get(ITy);
3777 // For EQ and NE, we can always pick a value for the undef to make the
3778 // predicate pass or fail, so we can return undef.
3779 // Matches behavior in llvm::ConstantFoldCompareInstruction.
3780 if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
3781 return UndefValue::get(ITy);
3783 // icmp X, X -> true/false
3784 // icmp X, undef -> true/false because undef could be X.
3785 if (LHS == RHS || Q.isUndefValue(RHS))
3786 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
3788 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3789 return V;
3791 // TODO: Sink/common this with other potentially expensive calls that use
3792 // ValueTracking? See comment below for isKnownNonEqual().
3793 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3794 return V;
3796 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
3797 return V;
3799 // If both operands have range metadata, use the metadata
3800 // to simplify the comparison.
3801 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3802 auto RHS_Instr = cast<Instruction>(RHS);
3803 auto LHS_Instr = cast<Instruction>(LHS);
3805 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
3806 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
3807 auto RHS_CR = getConstantRangeFromMetadata(
3808 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3809 auto LHS_CR = getConstantRangeFromMetadata(
3810 *LHS_Instr->getMetadata(LLVMContext::MD_range));
3812 if (LHS_CR.icmp(Pred, RHS_CR))
3813 return ConstantInt::getTrue(RHS->getContext());
3815 if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
3816 return ConstantInt::getFalse(RHS->getContext());
3820 // Compare of cast, for example (zext X) != 0 -> X != 0
3821 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3822 Instruction *LI = cast<CastInst>(LHS);
3823 Value *SrcOp = LI->getOperand(0);
3824 Type *SrcTy = SrcOp->getType();
3825 Type *DstTy = LI->getType();
3827 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3828 // if the integer type is the same size as the pointer type.
3829 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3830 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
3831 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3832 // Transfer the cast to the constant.
3833 if (Value *V = simplifyICmpInst(Pred, SrcOp,
3834 ConstantExpr::getIntToPtr(RHSC, SrcTy),
3835 Q, MaxRecurse - 1))
3836 return V;
3837 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3838 if (RI->getOperand(0)->getType() == SrcTy)
3839 // Compare without the cast.
3840 if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3841 MaxRecurse - 1))
3842 return V;
3846 if (isa<ZExtInst>(LHS)) {
3847 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3848 // same type.
3849 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3850 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3851 // Compare X and Y. Note that signed predicates become unsigned.
3852 if (Value *V =
3853 simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), SrcOp,
3854 RI->getOperand(0), Q, MaxRecurse - 1))
3855 return V;
3857 // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
3858 else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3859 if (SrcOp == RI->getOperand(0)) {
3860 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
3861 return ConstantInt::getTrue(ITy);
3862 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
3863 return ConstantInt::getFalse(ITy);
3866 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3867 // too. If not, then try to deduce the result of the comparison.
3868 else if (match(RHS, m_ImmConstant())) {
3869 Constant *C = dyn_cast<Constant>(RHS);
3870 assert(C != nullptr);
3872 // Compute the constant that would happen if we truncated to SrcTy then
3873 // reextended to DstTy.
3874 Constant *Trunc =
3875 ConstantFoldCastOperand(Instruction::Trunc, C, SrcTy, Q.DL);
3876 assert(Trunc && "Constant-fold of ImmConstant should not fail");
3877 Constant *RExt =
3878 ConstantFoldCastOperand(CastInst::ZExt, Trunc, DstTy, Q.DL);
3879 assert(RExt && "Constant-fold of ImmConstant should not fail");
3880 Constant *AnyEq =
3881 ConstantFoldCompareInstOperands(ICmpInst::ICMP_EQ, RExt, C, Q.DL);
3882 assert(AnyEq && "Constant-fold of ImmConstant should not fail");
3884 // If the re-extended constant didn't change any of the elements then
3885 // this is effectively also a case of comparing two zero-extended
3886 // values.
3887 if (AnyEq->isAllOnesValue() && MaxRecurse)
3888 if (Value *V = simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
3889 SrcOp, Trunc, Q, MaxRecurse - 1))
3890 return V;
3892 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3893 // there. Use this to work out the result of the comparison.
3894 if (AnyEq->isNullValue()) {
3895 switch (Pred) {
3896 default:
3897 llvm_unreachable("Unknown ICmp predicate!");
3898 // LHS <u RHS.
3899 case ICmpInst::ICMP_EQ:
3900 case ICmpInst::ICMP_UGT:
3901 case ICmpInst::ICMP_UGE:
3902 return Constant::getNullValue(ITy);
3904 case ICmpInst::ICMP_NE:
3905 case ICmpInst::ICMP_ULT:
3906 case ICmpInst::ICMP_ULE:
3907 return Constant::getAllOnesValue(ITy);
3909 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3910 // is non-negative then LHS <s RHS.
3911 case ICmpInst::ICMP_SGT:
3912 case ICmpInst::ICMP_SGE:
3913 return ConstantFoldCompareInstOperands(
3914 ICmpInst::ICMP_SLT, C, Constant::getNullValue(C->getType()),
3915 Q.DL);
3916 case ICmpInst::ICMP_SLT:
3917 case ICmpInst::ICMP_SLE:
3918 return ConstantFoldCompareInstOperands(
3919 ICmpInst::ICMP_SGE, C, Constant::getNullValue(C->getType()),
3920 Q.DL);
3926 if (isa<SExtInst>(LHS)) {
3927 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3928 // same type.
3929 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3930 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3931 // Compare X and Y. Note that the predicate does not change.
3932 if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
3933 MaxRecurse - 1))
3934 return V;
3936 // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
3937 else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3938 if (SrcOp == RI->getOperand(0)) {
3939 if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
3940 return ConstantInt::getTrue(ITy);
3941 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
3942 return ConstantInt::getFalse(ITy);
3945 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3946 // too. If not, then try to deduce the result of the comparison.
3947 else if (match(RHS, m_ImmConstant())) {
3948 Constant *C = cast<Constant>(RHS);
3950 // Compute the constant that would happen if we truncated to SrcTy then
3951 // reextended to DstTy.
3952 Constant *Trunc =
3953 ConstantFoldCastOperand(Instruction::Trunc, C, SrcTy, Q.DL);
3954 assert(Trunc && "Constant-fold of ImmConstant should not fail");
3955 Constant *RExt =
3956 ConstantFoldCastOperand(CastInst::SExt, Trunc, DstTy, Q.DL);
3957 assert(RExt && "Constant-fold of ImmConstant should not fail");
3958 Constant *AnyEq =
3959 ConstantFoldCompareInstOperands(ICmpInst::ICMP_EQ, RExt, C, Q.DL);
3960 assert(AnyEq && "Constant-fold of ImmConstant should not fail");
3962 // If the re-extended constant didn't change then this is effectively
3963 // also a case of comparing two sign-extended values.
3964 if (AnyEq->isAllOnesValue() && MaxRecurse)
3965 if (Value *V =
3966 simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
3967 return V;
3969 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3970 // bits there. Use this to work out the result of the comparison.
3971 if (AnyEq->isNullValue()) {
3972 switch (Pred) {
3973 default:
3974 llvm_unreachable("Unknown ICmp predicate!");
3975 case ICmpInst::ICMP_EQ:
3976 return Constant::getNullValue(ITy);
3977 case ICmpInst::ICMP_NE:
3978 return Constant::getAllOnesValue(ITy);
3980 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3981 // LHS >s RHS.
3982 case ICmpInst::ICMP_SGT:
3983 case ICmpInst::ICMP_SGE:
3984 return ConstantExpr::getICmp(ICmpInst::ICMP_SLT, C,
3985 Constant::getNullValue(C->getType()));
3986 case ICmpInst::ICMP_SLT:
3987 case ICmpInst::ICMP_SLE:
3988 return ConstantExpr::getICmp(ICmpInst::ICMP_SGE, C,
3989 Constant::getNullValue(C->getType()));
3991 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3992 // LHS >u RHS.
3993 case ICmpInst::ICMP_UGT:
3994 case ICmpInst::ICMP_UGE:
3995 // Comparison is true iff the LHS <s 0.
3996 if (MaxRecurse)
3997 if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3998 Constant::getNullValue(SrcTy), Q,
3999 MaxRecurse - 1))
4000 return V;
4001 break;
4002 case ICmpInst::ICMP_ULT:
4003 case ICmpInst::ICMP_ULE:
4004 // Comparison is true iff the LHS >=s 0.
4005 if (MaxRecurse)
4006 if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
4007 Constant::getNullValue(SrcTy), Q,
4008 MaxRecurse - 1))
4009 return V;
4010 break;
4017 // icmp eq|ne X, Y -> false|true if X != Y
4018 // This is potentially expensive, and we have already computedKnownBits for
4019 // compares with 0 above here, so only try this for a non-zero compare.
4020 if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
4021 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
4022 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
4025 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
4026 return V;
4028 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
4029 return V;
4031 if (Value *V = simplifyICmpWithIntrinsicOnLHS(Pred, LHS, RHS))
4032 return V;
4033 if (Value *V = simplifyICmpWithIntrinsicOnLHS(
4034 ICmpInst::getSwappedPredicate(Pred), RHS, LHS))
4035 return V;
4037 if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
4038 return V;
4040 if (std::optional<bool> Res =
4041 isImpliedByDomCondition(Pred, LHS, RHS, Q.CxtI, Q.DL))
4042 return ConstantInt::getBool(ITy, *Res);
4044 // Simplify comparisons of related pointers using a powerful, recursive
4045 // GEP-walk when we have target data available..
4046 if (LHS->getType()->isPointerTy())
4047 if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
4048 return C;
4049 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
4050 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
4051 if (CLHS->getPointerOperandType() == CRHS->getPointerOperandType() &&
4052 Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
4053 Q.DL.getTypeSizeInBits(CLHS->getType()))
4054 if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
4055 CRHS->getPointerOperand(), Q))
4056 return C;
4058 // If the comparison is with the result of a select instruction, check whether
4059 // comparing with either branch of the select always yields the same value.
4060 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4061 if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4062 return V;
4064 // If the comparison is with the result of a phi instruction, check whether
4065 // doing the compare with each incoming phi value yields a common result.
4066 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4067 if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4068 return V;
4070 return nullptr;
4073 Value *llvm::simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4074 const SimplifyQuery &Q) {
4075 return ::simplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4078 /// Given operands for an FCmpInst, see if we can fold the result.
4079 /// If not, this returns null.
4080 static Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4081 FastMathFlags FMF, const SimplifyQuery &Q,
4082 unsigned MaxRecurse) {
4083 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
4084 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
4086 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
4087 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4088 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI,
4089 Q.CxtI);
4091 // If we have a constant, make sure it is on the RHS.
4092 std::swap(LHS, RHS);
4093 Pred = CmpInst::getSwappedPredicate(Pred);
4096 // Fold trivial predicates.
4097 Type *RetTy = getCompareTy(LHS);
4098 if (Pred == FCmpInst::FCMP_FALSE)
4099 return getFalse(RetTy);
4100 if (Pred == FCmpInst::FCMP_TRUE)
4101 return getTrue(RetTy);
4103 // fcmp pred x, poison and fcmp pred poison, x
4104 // fold to poison
4105 if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
4106 return PoisonValue::get(RetTy);
4108 // fcmp pred x, undef and fcmp pred undef, x
4109 // fold to true if unordered, false if ordered
4110 if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
4111 // Choosing NaN for the undef will always make unordered comparison succeed
4112 // and ordered comparison fail.
4113 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
4116 // fcmp x,x -> true/false. Not all compares are foldable.
4117 if (LHS == RHS) {
4118 if (CmpInst::isTrueWhenEqual(Pred))
4119 return getTrue(RetTy);
4120 if (CmpInst::isFalseWhenEqual(Pred))
4121 return getFalse(RetTy);
4124 // Fold (un)ordered comparison if we can determine there are no NaNs.
4126 // This catches the 2 variable input case, constants are handled below as a
4127 // class-like compare.
4128 if (Pred == FCmpInst::FCMP_ORD || Pred == FCmpInst::FCMP_UNO) {
4129 if (FMF.noNaNs() ||
4130 (isKnownNeverNaN(RHS, Q.DL, Q.TLI, 0, Q.AC, Q.CxtI, Q.DT) &&
4131 isKnownNeverNaN(LHS, Q.DL, Q.TLI, 0, Q.AC, Q.CxtI, Q.DT)))
4132 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
4135 const APFloat *C = nullptr;
4136 match(RHS, m_APFloatAllowUndef(C));
4137 std::optional<KnownFPClass> FullKnownClassLHS;
4139 // Lazily compute the possible classes for LHS. Avoid computing it twice if
4140 // RHS is a 0.
4141 auto computeLHSClass = [=, &FullKnownClassLHS](FPClassTest InterestedFlags =
4142 fcAllFlags) {
4143 if (FullKnownClassLHS)
4144 return *FullKnownClassLHS;
4145 return computeKnownFPClass(LHS, FMF, Q.DL, InterestedFlags, 0, Q.TLI, Q.AC,
4146 Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo);
4149 if (C && Q.CxtI) {
4150 // Fold out compares that express a class test.
4152 // FIXME: Should be able to perform folds without context
4153 // instruction. Always pass in the context function?
4155 const Function *ParentF = Q.CxtI->getFunction();
4156 auto [ClassVal, ClassTest] = fcmpToClassTest(Pred, *ParentF, LHS, C);
4157 if (ClassVal) {
4158 FullKnownClassLHS = computeLHSClass();
4159 if ((FullKnownClassLHS->KnownFPClasses & ClassTest) == fcNone)
4160 return getFalse(RetTy);
4161 if ((FullKnownClassLHS->KnownFPClasses & ~ClassTest) == fcNone)
4162 return getTrue(RetTy);
4166 // Handle fcmp with constant RHS.
4167 if (C) {
4168 // TODO: If we always required a context function, we wouldn't need to
4169 // special case nans.
4170 if (C->isNaN())
4171 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
4173 // TODO: Need version fcmpToClassTest which returns implied class when the
4174 // compare isn't a complete class test. e.g. > 1.0 implies fcPositive, but
4175 // isn't implementable as a class call.
4176 if (C->isNegative() && !C->isNegZero()) {
4177 FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4179 // TODO: We can catch more cases by using a range check rather than
4180 // relying on CannotBeOrderedLessThanZero.
4181 switch (Pred) {
4182 case FCmpInst::FCMP_UGE:
4183 case FCmpInst::FCMP_UGT:
4184 case FCmpInst::FCMP_UNE: {
4185 KnownFPClass KnownClass = computeLHSClass(Interested);
4187 // (X >= 0) implies (X > C) when (C < 0)
4188 if (KnownClass.cannotBeOrderedLessThanZero())
4189 return getTrue(RetTy);
4190 break;
4192 case FCmpInst::FCMP_OEQ:
4193 case FCmpInst::FCMP_OLE:
4194 case FCmpInst::FCMP_OLT: {
4195 KnownFPClass KnownClass = computeLHSClass(Interested);
4197 // (X >= 0) implies !(X < C) when (C < 0)
4198 if (KnownClass.cannotBeOrderedLessThanZero())
4199 return getFalse(RetTy);
4200 break;
4202 default:
4203 break;
4206 // Check comparison of [minnum/maxnum with constant] with other constant.
4207 const APFloat *C2;
4208 if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
4209 *C2 < *C) ||
4210 (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
4211 *C2 > *C)) {
4212 bool IsMaxNum =
4213 cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
4214 // The ordered relationship and minnum/maxnum guarantee that we do not
4215 // have NaN constants, so ordered/unordered preds are handled the same.
4216 switch (Pred) {
4217 case FCmpInst::FCMP_OEQ:
4218 case FCmpInst::FCMP_UEQ:
4219 // minnum(X, LesserC) == C --> false
4220 // maxnum(X, GreaterC) == C --> false
4221 return getFalse(RetTy);
4222 case FCmpInst::FCMP_ONE:
4223 case FCmpInst::FCMP_UNE:
4224 // minnum(X, LesserC) != C --> true
4225 // maxnum(X, GreaterC) != C --> true
4226 return getTrue(RetTy);
4227 case FCmpInst::FCMP_OGE:
4228 case FCmpInst::FCMP_UGE:
4229 case FCmpInst::FCMP_OGT:
4230 case FCmpInst::FCMP_UGT:
4231 // minnum(X, LesserC) >= C --> false
4232 // minnum(X, LesserC) > C --> false
4233 // maxnum(X, GreaterC) >= C --> true
4234 // maxnum(X, GreaterC) > C --> true
4235 return ConstantInt::get(RetTy, IsMaxNum);
4236 case FCmpInst::FCMP_OLE:
4237 case FCmpInst::FCMP_ULE:
4238 case FCmpInst::FCMP_OLT:
4239 case FCmpInst::FCMP_ULT:
4240 // minnum(X, LesserC) <= C --> true
4241 // minnum(X, LesserC) < C --> true
4242 // maxnum(X, GreaterC) <= C --> false
4243 // maxnum(X, GreaterC) < C --> false
4244 return ConstantInt::get(RetTy, !IsMaxNum);
4245 default:
4246 // TRUE/FALSE/ORD/UNO should be handled before this.
4247 llvm_unreachable("Unexpected fcmp predicate");
4252 // TODO: Could fold this with above if there were a matcher which returned all
4253 // classes in a non-splat vector.
4254 if (match(RHS, m_AnyZeroFP())) {
4255 switch (Pred) {
4256 case FCmpInst::FCMP_OGE:
4257 case FCmpInst::FCMP_ULT: {
4258 FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4259 if (!FMF.noNaNs())
4260 Interested |= fcNan;
4262 KnownFPClass Known = computeLHSClass(Interested);
4264 // Positive or zero X >= 0.0 --> true
4265 // Positive or zero X < 0.0 --> false
4266 if ((FMF.noNaNs() || Known.isKnownNeverNaN()) &&
4267 Known.cannotBeOrderedLessThanZero())
4268 return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
4269 break;
4271 case FCmpInst::FCMP_UGE:
4272 case FCmpInst::FCMP_OLT: {
4273 FPClassTest Interested = KnownFPClass::OrderedLessThanZeroMask;
4274 KnownFPClass Known = computeLHSClass(Interested);
4276 // Positive or zero or nan X >= 0.0 --> true
4277 // Positive or zero or nan X < 0.0 --> false
4278 if (Known.cannotBeOrderedLessThanZero())
4279 return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
4280 break;
4282 default:
4283 break;
4287 // If the comparison is with the result of a select instruction, check whether
4288 // comparing with either branch of the select always yields the same value.
4289 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
4290 if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
4291 return V;
4293 // If the comparison is with the result of a phi instruction, check whether
4294 // doing the compare with each incoming phi value yields a common result.
4295 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
4296 if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
4297 return V;
4299 return nullptr;
4302 Value *llvm::simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
4303 FastMathFlags FMF, const SimplifyQuery &Q) {
4304 return ::simplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
4307 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4308 const SimplifyQuery &Q,
4309 bool AllowRefinement,
4310 SmallVectorImpl<Instruction *> *DropFlags,
4311 unsigned MaxRecurse) {
4312 // Trivial replacement.
4313 if (V == Op)
4314 return RepOp;
4316 if (!MaxRecurse--)
4317 return nullptr;
4319 // We cannot replace a constant, and shouldn't even try.
4320 if (isa<Constant>(Op))
4321 return nullptr;
4323 auto *I = dyn_cast<Instruction>(V);
4324 if (!I)
4325 return nullptr;
4327 // The arguments of a phi node might refer to a value from a previous
4328 // cycle iteration.
4329 if (isa<PHINode>(I))
4330 return nullptr;
4332 if (Op->getType()->isVectorTy()) {
4333 // For vector types, the simplification must hold per-lane, so forbid
4334 // potentially cross-lane operations like shufflevector.
4335 if (!I->getType()->isVectorTy() || isa<ShuffleVectorInst>(I) ||
4336 isa<CallBase>(I))
4337 return nullptr;
4340 // Replace Op with RepOp in instruction operands.
4341 SmallVector<Value *, 8> NewOps;
4342 bool AnyReplaced = false;
4343 for (Value *InstOp : I->operands()) {
4344 if (Value *NewInstOp = simplifyWithOpReplaced(
4345 InstOp, Op, RepOp, Q, AllowRefinement, DropFlags, MaxRecurse)) {
4346 NewOps.push_back(NewInstOp);
4347 AnyReplaced = InstOp != NewInstOp;
4348 } else {
4349 NewOps.push_back(InstOp);
4353 if (!AnyReplaced)
4354 return nullptr;
4356 if (!AllowRefinement) {
4357 // General InstSimplify functions may refine the result, e.g. by returning
4358 // a constant for a potentially poison value. To avoid this, implement only
4359 // a few non-refining but profitable transforms here.
4361 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4362 unsigned Opcode = BO->getOpcode();
4363 // id op x -> x, x op id -> x
4364 if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
4365 return NewOps[1];
4366 if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
4367 /* RHS */ true))
4368 return NewOps[0];
4370 // x & x -> x, x | x -> x
4371 if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
4372 NewOps[0] == NewOps[1])
4373 return NewOps[0];
4375 // x - x -> 0, x ^ x -> 0. This is non-refining, because x is non-poison
4376 // by assumption and this case never wraps, so nowrap flags can be
4377 // ignored.
4378 if ((Opcode == Instruction::Sub || Opcode == Instruction::Xor) &&
4379 NewOps[0] == RepOp && NewOps[1] == RepOp)
4380 return Constant::getNullValue(I->getType());
4382 // If we are substituting an absorber constant into a binop and extra
4383 // poison can't leak if we remove the select -- because both operands of
4384 // the binop are based on the same value -- then it may be safe to replace
4385 // the value with the absorber constant. Examples:
4386 // (Op == 0) ? 0 : (Op & -Op) --> Op & -Op
4387 // (Op == 0) ? 0 : (Op * (binop Op, C)) --> Op * (binop Op, C)
4388 // (Op == -1) ? -1 : (Op | (binop C, Op) --> Op | (binop C, Op)
4389 Constant *Absorber =
4390 ConstantExpr::getBinOpAbsorber(Opcode, I->getType());
4391 if ((NewOps[0] == Absorber || NewOps[1] == Absorber) &&
4392 impliesPoison(BO, Op))
4393 return Absorber;
4396 if (isa<GetElementPtrInst>(I)) {
4397 // getelementptr x, 0 -> x.
4398 // This never returns poison, even if inbounds is set.
4399 if (NewOps.size() == 2 && match(NewOps[1], m_Zero()))
4400 return NewOps[0];
4402 } else {
4403 // The simplification queries below may return the original value. Consider:
4404 // %div = udiv i32 %arg, %arg2
4405 // %mul = mul nsw i32 %div, %arg2
4406 // %cmp = icmp eq i32 %mul, %arg
4407 // %sel = select i1 %cmp, i32 %div, i32 undef
4408 // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
4409 // simplifies back to %arg. This can only happen because %mul does not
4410 // dominate %div. To ensure a consistent return value contract, we make sure
4411 // that this case returns nullptr as well.
4412 auto PreventSelfSimplify = [V](Value *Simplified) {
4413 return Simplified != V ? Simplified : nullptr;
4416 return PreventSelfSimplify(
4417 ::simplifyInstructionWithOperands(I, NewOps, Q, MaxRecurse));
4420 // If all operands are constant after substituting Op for RepOp then we can
4421 // constant fold the instruction.
4422 SmallVector<Constant *, 8> ConstOps;
4423 for (Value *NewOp : NewOps) {
4424 if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
4425 ConstOps.push_back(ConstOp);
4426 else
4427 return nullptr;
4430 // Consider:
4431 // %cmp = icmp eq i32 %x, 2147483647
4432 // %add = add nsw i32 %x, 1
4433 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
4435 // We can't replace %sel with %add unless we strip away the flags (which
4436 // will be done in InstCombine).
4437 // TODO: This may be unsound, because it only catches some forms of
4438 // refinement.
4439 if (!AllowRefinement) {
4440 if (canCreatePoison(cast<Operator>(I), !DropFlags)) {
4441 // abs cannot create poison if the value is known to never be int_min.
4442 if (auto *II = dyn_cast<IntrinsicInst>(I);
4443 II && II->getIntrinsicID() == Intrinsic::abs) {
4444 if (!ConstOps[0]->isNotMinSignedValue())
4445 return nullptr;
4446 } else
4447 return nullptr;
4449 Constant *Res = ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4450 if (DropFlags && Res && I->hasPoisonGeneratingFlagsOrMetadata())
4451 DropFlags->push_back(I);
4452 return Res;
4455 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
4458 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
4459 const SimplifyQuery &Q,
4460 bool AllowRefinement,
4461 SmallVectorImpl<Instruction *> *DropFlags) {
4462 return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement, DropFlags,
4463 RecursionLimit);
4466 /// Try to simplify a select instruction when its condition operand is an
4467 /// integer comparison where one operand of the compare is a constant.
4468 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
4469 const APInt *Y, bool TrueWhenUnset) {
4470 const APInt *C;
4472 // (X & Y) == 0 ? X & ~Y : X --> X
4473 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
4474 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
4475 *Y == ~*C)
4476 return TrueWhenUnset ? FalseVal : TrueVal;
4478 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
4479 // (X & Y) != 0 ? X : X & ~Y --> X
4480 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
4481 *Y == ~*C)
4482 return TrueWhenUnset ? FalseVal : TrueVal;
4484 if (Y->isPowerOf2()) {
4485 // (X & Y) == 0 ? X | Y : X --> X | Y
4486 // (X & Y) != 0 ? X | Y : X --> X
4487 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
4488 *Y == *C)
4489 return TrueWhenUnset ? TrueVal : FalseVal;
4491 // (X & Y) == 0 ? X : X | Y --> X
4492 // (X & Y) != 0 ? X : X | Y --> X | Y
4493 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
4494 *Y == *C)
4495 return TrueWhenUnset ? TrueVal : FalseVal;
4498 return nullptr;
4501 static Value *simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS,
4502 ICmpInst::Predicate Pred, Value *TVal,
4503 Value *FVal) {
4504 // Canonicalize common cmp+sel operand as CmpLHS.
4505 if (CmpRHS == TVal || CmpRHS == FVal) {
4506 std::swap(CmpLHS, CmpRHS);
4507 Pred = ICmpInst::getSwappedPredicate(Pred);
4510 // Canonicalize common cmp+sel operand as TVal.
4511 if (CmpLHS == FVal) {
4512 std::swap(TVal, FVal);
4513 Pred = ICmpInst::getInversePredicate(Pred);
4516 // A vector select may be shuffling together elements that are equivalent
4517 // based on the max/min/select relationship.
4518 Value *X = CmpLHS, *Y = CmpRHS;
4519 bool PeekedThroughSelectShuffle = false;
4520 auto *Shuf = dyn_cast<ShuffleVectorInst>(FVal);
4521 if (Shuf && Shuf->isSelect()) {
4522 if (Shuf->getOperand(0) == Y)
4523 FVal = Shuf->getOperand(1);
4524 else if (Shuf->getOperand(1) == Y)
4525 FVal = Shuf->getOperand(0);
4526 else
4527 return nullptr;
4528 PeekedThroughSelectShuffle = true;
4531 // (X pred Y) ? X : max/min(X, Y)
4532 auto *MMI = dyn_cast<MinMaxIntrinsic>(FVal);
4533 if (!MMI || TVal != X ||
4534 !match(FVal, m_c_MaxOrMin(m_Specific(X), m_Specific(Y))))
4535 return nullptr;
4537 // (X > Y) ? X : max(X, Y) --> max(X, Y)
4538 // (X >= Y) ? X : max(X, Y) --> max(X, Y)
4539 // (X < Y) ? X : min(X, Y) --> min(X, Y)
4540 // (X <= Y) ? X : min(X, Y) --> min(X, Y)
4542 // The equivalence allows a vector select (shuffle) of max/min and Y. Ex:
4543 // (X > Y) ? X : (Z ? max(X, Y) : Y)
4544 // If Z is true, this reduces as above, and if Z is false:
4545 // (X > Y) ? X : Y --> max(X, Y)
4546 ICmpInst::Predicate MMPred = MMI->getPredicate();
4547 if (MMPred == CmpInst::getStrictPredicate(Pred))
4548 return MMI;
4550 // Other transforms are not valid with a shuffle.
4551 if (PeekedThroughSelectShuffle)
4552 return nullptr;
4554 // (X == Y) ? X : max/min(X, Y) --> max/min(X, Y)
4555 if (Pred == CmpInst::ICMP_EQ)
4556 return MMI;
4558 // (X != Y) ? X : max/min(X, Y) --> X
4559 if (Pred == CmpInst::ICMP_NE)
4560 return X;
4562 // (X < Y) ? X : max(X, Y) --> X
4563 // (X <= Y) ? X : max(X, Y) --> X
4564 // (X > Y) ? X : min(X, Y) --> X
4565 // (X >= Y) ? X : min(X, Y) --> X
4566 ICmpInst::Predicate InvPred = CmpInst::getInversePredicate(Pred);
4567 if (MMPred == CmpInst::getStrictPredicate(InvPred))
4568 return X;
4570 return nullptr;
4573 /// An alternative way to test if a bit is set or not uses sgt/slt instead of
4574 /// eq/ne.
4575 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
4576 ICmpInst::Predicate Pred,
4577 Value *TrueVal, Value *FalseVal) {
4578 Value *X;
4579 APInt Mask;
4580 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
4581 return nullptr;
4583 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
4584 Pred == ICmpInst::ICMP_EQ);
4587 /// Try to simplify a select instruction when its condition operand is an
4588 /// integer equality comparison.
4589 static Value *simplifySelectWithICmpEq(Value *CmpLHS, Value *CmpRHS,
4590 Value *TrueVal, Value *FalseVal,
4591 const SimplifyQuery &Q,
4592 unsigned MaxRecurse) {
4593 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
4594 /* AllowRefinement */ false,
4595 /* DropFlags */ nullptr, MaxRecurse) == TrueVal)
4596 return FalseVal;
4597 if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
4598 /* AllowRefinement */ true,
4599 /* DropFlags */ nullptr, MaxRecurse) == FalseVal)
4600 return FalseVal;
4602 return nullptr;
4605 /// Try to simplify a select instruction when its condition operand is an
4606 /// integer comparison.
4607 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
4608 Value *FalseVal,
4609 const SimplifyQuery &Q,
4610 unsigned MaxRecurse) {
4611 ICmpInst::Predicate Pred;
4612 Value *CmpLHS, *CmpRHS;
4613 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
4614 return nullptr;
4616 if (Value *V = simplifyCmpSelOfMaxMin(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
4617 return V;
4619 // Canonicalize ne to eq predicate.
4620 if (Pred == ICmpInst::ICMP_NE) {
4621 Pred = ICmpInst::ICMP_EQ;
4622 std::swap(TrueVal, FalseVal);
4625 // Check for integer min/max with a limit constant:
4626 // X > MIN_INT ? X : MIN_INT --> X
4627 // X < MAX_INT ? X : MAX_INT --> X
4628 if (TrueVal->getType()->isIntOrIntVectorTy()) {
4629 Value *X, *Y;
4630 SelectPatternFlavor SPF =
4631 matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
4632 X, Y)
4633 .Flavor;
4634 if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
4635 APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
4636 X->getType()->getScalarSizeInBits());
4637 if (match(Y, m_SpecificInt(LimitC)))
4638 return X;
4642 if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
4643 Value *X;
4644 const APInt *Y;
4645 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
4646 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
4647 /*TrueWhenUnset=*/true))
4648 return V;
4650 // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
4651 Value *ShAmt;
4652 auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
4653 m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
4654 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
4655 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
4656 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
4657 return X;
4659 // Test for a zero-shift-guard-op around rotates. These are used to
4660 // avoid UB from oversized shifts in raw IR rotate patterns, but the
4661 // intrinsics do not have that problem.
4662 // We do not allow this transform for the general funnel shift case because
4663 // that would not preserve the poison safety of the original code.
4664 auto isRotate =
4665 m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
4666 m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
4667 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
4668 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
4669 if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
4670 Pred == ICmpInst::ICMP_EQ)
4671 return FalseVal;
4673 // X == 0 ? abs(X) : -abs(X) --> -abs(X)
4674 // X == 0 ? -abs(X) : abs(X) --> abs(X)
4675 if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
4676 match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
4677 return FalseVal;
4678 if (match(TrueVal,
4679 m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
4680 match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
4681 return FalseVal;
4684 // Check for other compares that behave like bit test.
4685 if (Value *V =
4686 simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
4687 return V;
4689 // If we have a scalar equality comparison, then we know the value in one of
4690 // the arms of the select. See if substituting this value into the arm and
4691 // simplifying the result yields the same value as the other arm.
4692 if (Pred == ICmpInst::ICMP_EQ) {
4693 if (Value *V = simplifySelectWithICmpEq(CmpLHS, CmpRHS, TrueVal, FalseVal,
4694 Q, MaxRecurse))
4695 return V;
4696 if (Value *V = simplifySelectWithICmpEq(CmpRHS, CmpLHS, TrueVal, FalseVal,
4697 Q, MaxRecurse))
4698 return V;
4700 Value *X;
4701 Value *Y;
4702 // select((X | Y) == 0 ? X : 0) --> 0 (commuted 2 ways)
4703 if (match(CmpLHS, m_Or(m_Value(X), m_Value(Y))) &&
4704 match(CmpRHS, m_Zero())) {
4705 // (X | Y) == 0 implies X == 0 and Y == 0.
4706 if (Value *V = simplifySelectWithICmpEq(X, CmpRHS, TrueVal, FalseVal, Q,
4707 MaxRecurse))
4708 return V;
4709 if (Value *V = simplifySelectWithICmpEq(Y, CmpRHS, TrueVal, FalseVal, Q,
4710 MaxRecurse))
4711 return V;
4714 // select((X & Y) == -1 ? X : -1) --> -1 (commuted 2 ways)
4715 if (match(CmpLHS, m_And(m_Value(X), m_Value(Y))) &&
4716 match(CmpRHS, m_AllOnes())) {
4717 // (X & Y) == -1 implies X == -1 and Y == -1.
4718 if (Value *V = simplifySelectWithICmpEq(X, CmpRHS, TrueVal, FalseVal, Q,
4719 MaxRecurse))
4720 return V;
4721 if (Value *V = simplifySelectWithICmpEq(Y, CmpRHS, TrueVal, FalseVal, Q,
4722 MaxRecurse))
4723 return V;
4727 return nullptr;
4730 /// Try to simplify a select instruction when its condition operand is a
4731 /// floating-point comparison.
4732 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
4733 const SimplifyQuery &Q) {
4734 FCmpInst::Predicate Pred;
4735 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
4736 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
4737 return nullptr;
4739 // This transform is safe if we do not have (do not care about) -0.0 or if
4740 // at least one operand is known to not be -0.0. Otherwise, the select can
4741 // change the sign of a zero operand.
4742 bool HasNoSignedZeros =
4743 Q.CxtI && isa<FPMathOperator>(Q.CxtI) && Q.CxtI->hasNoSignedZeros();
4744 const APFloat *C;
4745 if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
4746 (match(F, m_APFloat(C)) && C->isNonZero())) {
4747 // (T == F) ? T : F --> F
4748 // (F == T) ? T : F --> F
4749 if (Pred == FCmpInst::FCMP_OEQ)
4750 return F;
4752 // (T != F) ? T : F --> T
4753 // (F != T) ? T : F --> T
4754 if (Pred == FCmpInst::FCMP_UNE)
4755 return T;
4758 return nullptr;
4761 /// Given operands for a SelectInst, see if we can fold the result.
4762 /// If not, this returns null.
4763 static Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4764 const SimplifyQuery &Q, unsigned MaxRecurse) {
4765 if (auto *CondC = dyn_cast<Constant>(Cond)) {
4766 if (auto *TrueC = dyn_cast<Constant>(TrueVal))
4767 if (auto *FalseC = dyn_cast<Constant>(FalseVal))
4768 if (Constant *C = ConstantFoldSelectInstruction(CondC, TrueC, FalseC))
4769 return C;
4771 // select poison, X, Y -> poison
4772 if (isa<PoisonValue>(CondC))
4773 return PoisonValue::get(TrueVal->getType());
4775 // select undef, X, Y -> X or Y
4776 if (Q.isUndefValue(CondC))
4777 return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
4779 // select true, X, Y --> X
4780 // select false, X, Y --> Y
4781 // For vectors, allow undef/poison elements in the condition to match the
4782 // defined elements, so we can eliminate the select.
4783 if (match(CondC, m_One()))
4784 return TrueVal;
4785 if (match(CondC, m_Zero()))
4786 return FalseVal;
4789 assert(Cond->getType()->isIntOrIntVectorTy(1) &&
4790 "Select must have bool or bool vector condition");
4791 assert(TrueVal->getType() == FalseVal->getType() &&
4792 "Select must have same types for true/false ops");
4794 if (Cond->getType() == TrueVal->getType()) {
4795 // select i1 Cond, i1 true, i1 false --> i1 Cond
4796 if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
4797 return Cond;
4799 // (X && Y) ? X : Y --> Y (commuted 2 ways)
4800 if (match(Cond, m_c_LogicalAnd(m_Specific(TrueVal), m_Specific(FalseVal))))
4801 return FalseVal;
4803 // (X || Y) ? X : Y --> X (commuted 2 ways)
4804 if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Specific(FalseVal))))
4805 return TrueVal;
4807 // (X || Y) ? false : X --> false (commuted 2 ways)
4808 if (match(Cond, m_c_LogicalOr(m_Specific(FalseVal), m_Value())) &&
4809 match(TrueVal, m_ZeroInt()))
4810 return ConstantInt::getFalse(Cond->getType());
4812 // Match patterns that end in logical-and.
4813 if (match(FalseVal, m_ZeroInt())) {
4814 // !(X || Y) && X --> false (commuted 2 ways)
4815 if (match(Cond, m_Not(m_c_LogicalOr(m_Specific(TrueVal), m_Value()))))
4816 return ConstantInt::getFalse(Cond->getType());
4817 // X && !(X || Y) --> false (commuted 2 ways)
4818 if (match(TrueVal, m_Not(m_c_LogicalOr(m_Specific(Cond), m_Value()))))
4819 return ConstantInt::getFalse(Cond->getType());
4821 // (X || Y) && Y --> Y (commuted 2 ways)
4822 if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Value())))
4823 return TrueVal;
4824 // Y && (X || Y) --> Y (commuted 2 ways)
4825 if (match(TrueVal, m_c_LogicalOr(m_Specific(Cond), m_Value())))
4826 return Cond;
4828 // (X || Y) && (X || !Y) --> X (commuted 8 ways)
4829 Value *X, *Y;
4830 if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4831 match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4832 return X;
4833 if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
4834 match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
4835 return X;
4838 // Match patterns that end in logical-or.
4839 if (match(TrueVal, m_One())) {
4840 // !(X && Y) || X --> true (commuted 2 ways)
4841 if (match(Cond, m_Not(m_c_LogicalAnd(m_Specific(FalseVal), m_Value()))))
4842 return ConstantInt::getTrue(Cond->getType());
4843 // X || !(X && Y) --> true (commuted 2 ways)
4844 if (match(FalseVal, m_Not(m_c_LogicalAnd(m_Specific(Cond), m_Value()))))
4845 return ConstantInt::getTrue(Cond->getType());
4847 // (X && Y) || Y --> Y (commuted 2 ways)
4848 if (match(Cond, m_c_LogicalAnd(m_Specific(FalseVal), m_Value())))
4849 return FalseVal;
4850 // Y || (X && Y) --> Y (commuted 2 ways)
4851 if (match(FalseVal, m_c_LogicalAnd(m_Specific(Cond), m_Value())))
4852 return Cond;
4856 // select ?, X, X -> X
4857 if (TrueVal == FalseVal)
4858 return TrueVal;
4860 if (Cond == TrueVal) {
4861 // select i1 X, i1 X, i1 false --> X (logical-and)
4862 if (match(FalseVal, m_ZeroInt()))
4863 return Cond;
4864 // select i1 X, i1 X, i1 true --> true
4865 if (match(FalseVal, m_One()))
4866 return ConstantInt::getTrue(Cond->getType());
4868 if (Cond == FalseVal) {
4869 // select i1 X, i1 true, i1 X --> X (logical-or)
4870 if (match(TrueVal, m_One()))
4871 return Cond;
4872 // select i1 X, i1 false, i1 X --> false
4873 if (match(TrueVal, m_ZeroInt()))
4874 return ConstantInt::getFalse(Cond->getType());
4877 // If the true or false value is poison, we can fold to the other value.
4878 // If the true or false value is undef, we can fold to the other value as
4879 // long as the other value isn't poison.
4880 // select ?, poison, X -> X
4881 // select ?, undef, X -> X
4882 if (isa<PoisonValue>(TrueVal) ||
4883 (Q.isUndefValue(TrueVal) &&
4884 isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
4885 return FalseVal;
4886 // select ?, X, poison -> X
4887 // select ?, X, undef -> X
4888 if (isa<PoisonValue>(FalseVal) ||
4889 (Q.isUndefValue(FalseVal) &&
4890 isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
4891 return TrueVal;
4893 // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
4894 Constant *TrueC, *FalseC;
4895 if (isa<FixedVectorType>(TrueVal->getType()) &&
4896 match(TrueVal, m_Constant(TrueC)) &&
4897 match(FalseVal, m_Constant(FalseC))) {
4898 unsigned NumElts =
4899 cast<FixedVectorType>(TrueC->getType())->getNumElements();
4900 SmallVector<Constant *, 16> NewC;
4901 for (unsigned i = 0; i != NumElts; ++i) {
4902 // Bail out on incomplete vector constants.
4903 Constant *TEltC = TrueC->getAggregateElement(i);
4904 Constant *FEltC = FalseC->getAggregateElement(i);
4905 if (!TEltC || !FEltC)
4906 break;
4908 // If the elements match (undef or not), that value is the result. If only
4909 // one element is undef, choose the defined element as the safe result.
4910 if (TEltC == FEltC)
4911 NewC.push_back(TEltC);
4912 else if (isa<PoisonValue>(TEltC) ||
4913 (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
4914 NewC.push_back(FEltC);
4915 else if (isa<PoisonValue>(FEltC) ||
4916 (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
4917 NewC.push_back(TEltC);
4918 else
4919 break;
4921 if (NewC.size() == NumElts)
4922 return ConstantVector::get(NewC);
4925 if (Value *V =
4926 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
4927 return V;
4929 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
4930 return V;
4932 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
4933 return V;
4935 std::optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
4936 if (Imp)
4937 return *Imp ? TrueVal : FalseVal;
4939 return nullptr;
4942 Value *llvm::simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
4943 const SimplifyQuery &Q) {
4944 return ::simplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
4947 /// Given operands for an GetElementPtrInst, see if we can fold the result.
4948 /// If not, this returns null.
4949 static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
4950 ArrayRef<Value *> Indices, bool InBounds,
4951 const SimplifyQuery &Q, unsigned) {
4952 // The type of the GEP pointer operand.
4953 unsigned AS =
4954 cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
4956 // getelementptr P -> P.
4957 if (Indices.empty())
4958 return Ptr;
4960 // Compute the (pointer) type returned by the GEP instruction.
4961 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
4962 Type *GEPTy = PointerType::get(LastType, AS);
4963 if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
4964 GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4965 else {
4966 for (Value *Op : Indices) {
4967 // If one of the operands is a vector, the result type is a vector of
4968 // pointers. All vector operands must have the same number of elements.
4969 if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
4970 GEPTy = VectorType::get(GEPTy, VT->getElementCount());
4971 break;
4976 // All-zero GEP is a no-op, unless it performs a vector splat.
4977 if (Ptr->getType() == GEPTy &&
4978 all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
4979 return Ptr;
4981 // getelementptr poison, idx -> poison
4982 // getelementptr baseptr, poison -> poison
4983 if (isa<PoisonValue>(Ptr) ||
4984 any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
4985 return PoisonValue::get(GEPTy);
4987 // getelementptr undef, idx -> undef
4988 if (Q.isUndefValue(Ptr))
4989 return UndefValue::get(GEPTy);
4991 bool IsScalableVec =
4992 SrcTy->isScalableTy() || any_of(Indices, [](const Value *V) {
4993 return isa<ScalableVectorType>(V->getType());
4996 if (Indices.size() == 1) {
4997 // getelementptr P, 0 -> P.
4998 if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
4999 return Ptr;
5001 Type *Ty = SrcTy;
5002 if (!IsScalableVec && Ty->isSized()) {
5003 Value *P;
5004 uint64_t C;
5005 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
5006 // getelementptr P, N -> P if P points to a type of zero size.
5007 if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
5008 return Ptr;
5010 // The following transforms are only safe if the ptrtoint cast
5011 // doesn't truncate the pointers.
5012 if (Indices[0]->getType()->getScalarSizeInBits() ==
5013 Q.DL.getPointerSizeInBits(AS)) {
5014 auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
5015 return P->getType() == GEPTy &&
5016 getUnderlyingObject(P) == getUnderlyingObject(Ptr);
5018 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
5019 if (TyAllocSize == 1 &&
5020 match(Indices[0],
5021 m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
5022 CanSimplify())
5023 return P;
5025 // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
5026 // size 1 << C.
5027 if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
5028 m_PtrToInt(m_Specific(Ptr))),
5029 m_ConstantInt(C))) &&
5030 TyAllocSize == 1ULL << C && CanSimplify())
5031 return P;
5033 // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
5034 // size C.
5035 if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
5036 m_PtrToInt(m_Specific(Ptr))),
5037 m_SpecificInt(TyAllocSize))) &&
5038 CanSimplify())
5039 return P;
5044 if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
5045 all_of(Indices.drop_back(1),
5046 [](Value *Idx) { return match(Idx, m_Zero()); })) {
5047 unsigned IdxWidth =
5048 Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
5049 if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
5050 APInt BasePtrOffset(IdxWidth, 0);
5051 Value *StrippedBasePtr =
5052 Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
5054 // Avoid creating inttoptr of zero here: While LLVMs treatment of
5055 // inttoptr is generally conservative, this particular case is folded to
5056 // a null pointer, which will have incorrect provenance.
5058 // gep (gep V, C), (sub 0, V) -> C
5059 if (match(Indices.back(),
5060 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
5061 !BasePtrOffset.isZero()) {
5062 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
5063 return ConstantExpr::getIntToPtr(CI, GEPTy);
5065 // gep (gep V, C), (xor V, -1) -> C-1
5066 if (match(Indices.back(),
5067 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
5068 !BasePtrOffset.isOne()) {
5069 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
5070 return ConstantExpr::getIntToPtr(CI, GEPTy);
5075 // Check to see if this is constant foldable.
5076 if (!isa<Constant>(Ptr) ||
5077 !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
5078 return nullptr;
5080 if (!ConstantExpr::isSupportedGetElementPtr(SrcTy))
5081 return ConstantFoldGetElementPtr(SrcTy, cast<Constant>(Ptr), InBounds,
5082 std::nullopt, Indices);
5084 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
5085 InBounds);
5086 return ConstantFoldConstant(CE, Q.DL);
5089 Value *llvm::simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
5090 bool InBounds, const SimplifyQuery &Q) {
5091 return ::simplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
5094 /// Given operands for an InsertValueInst, see if we can fold the result.
5095 /// If not, this returns null.
5096 static Value *simplifyInsertValueInst(Value *Agg, Value *Val,
5097 ArrayRef<unsigned> Idxs,
5098 const SimplifyQuery &Q, unsigned) {
5099 if (Constant *CAgg = dyn_cast<Constant>(Agg))
5100 if (Constant *CVal = dyn_cast<Constant>(Val))
5101 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
5103 // insertvalue x, poison, n -> x
5104 // insertvalue x, undef, n -> x if x cannot be poison
5105 if (isa<PoisonValue>(Val) ||
5106 (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Agg)))
5107 return Agg;
5109 // insertvalue x, (extractvalue y, n), n
5110 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
5111 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
5112 EV->getIndices() == Idxs) {
5113 // insertvalue poison, (extractvalue y, n), n -> y
5114 // insertvalue undef, (extractvalue y, n), n -> y if y cannot be poison
5115 if (isa<PoisonValue>(Agg) ||
5116 (Q.isUndefValue(Agg) &&
5117 isGuaranteedNotToBePoison(EV->getAggregateOperand())))
5118 return EV->getAggregateOperand();
5120 // insertvalue y, (extractvalue y, n), n -> y
5121 if (Agg == EV->getAggregateOperand())
5122 return Agg;
5125 return nullptr;
5128 Value *llvm::simplifyInsertValueInst(Value *Agg, Value *Val,
5129 ArrayRef<unsigned> Idxs,
5130 const SimplifyQuery &Q) {
5131 return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
5134 Value *llvm::simplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
5135 const SimplifyQuery &Q) {
5136 // Try to constant fold.
5137 auto *VecC = dyn_cast<Constant>(Vec);
5138 auto *ValC = dyn_cast<Constant>(Val);
5139 auto *IdxC = dyn_cast<Constant>(Idx);
5140 if (VecC && ValC && IdxC)
5141 return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
5143 // For fixed-length vector, fold into poison if index is out of bounds.
5144 if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
5145 if (isa<FixedVectorType>(Vec->getType()) &&
5146 CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
5147 return PoisonValue::get(Vec->getType());
5150 // If index is undef, it might be out of bounds (see above case)
5151 if (Q.isUndefValue(Idx))
5152 return PoisonValue::get(Vec->getType());
5154 // If the scalar is poison, or it is undef and there is no risk of
5155 // propagating poison from the vector value, simplify to the vector value.
5156 if (isa<PoisonValue>(Val) ||
5157 (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
5158 return Vec;
5160 // If we are extracting a value from a vector, then inserting it into the same
5161 // place, that's the input vector:
5162 // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
5163 if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
5164 return Vec;
5166 return nullptr;
5169 /// Given operands for an ExtractValueInst, see if we can fold the result.
5170 /// If not, this returns null.
5171 static Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
5172 const SimplifyQuery &, unsigned) {
5173 if (auto *CAgg = dyn_cast<Constant>(Agg))
5174 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
5176 // extractvalue x, (insertvalue y, elt, n), n -> elt
5177 unsigned NumIdxs = Idxs.size();
5178 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
5179 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
5180 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
5181 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
5182 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
5183 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
5184 Idxs.slice(0, NumCommonIdxs)) {
5185 if (NumIdxs == NumInsertValueIdxs)
5186 return IVI->getInsertedValueOperand();
5187 break;
5191 return nullptr;
5194 Value *llvm::simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
5195 const SimplifyQuery &Q) {
5196 return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
5199 /// Given operands for an ExtractElementInst, see if we can fold the result.
5200 /// If not, this returns null.
5201 static Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
5202 const SimplifyQuery &Q, unsigned) {
5203 auto *VecVTy = cast<VectorType>(Vec->getType());
5204 if (auto *CVec = dyn_cast<Constant>(Vec)) {
5205 if (auto *CIdx = dyn_cast<Constant>(Idx))
5206 return ConstantExpr::getExtractElement(CVec, CIdx);
5208 if (Q.isUndefValue(Vec))
5209 return UndefValue::get(VecVTy->getElementType());
5212 // An undef extract index can be arbitrarily chosen to be an out-of-range
5213 // index value, which would result in the instruction being poison.
5214 if (Q.isUndefValue(Idx))
5215 return PoisonValue::get(VecVTy->getElementType());
5217 // If extracting a specified index from the vector, see if we can recursively
5218 // find a previously computed scalar that was inserted into the vector.
5219 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
5220 // For fixed-length vector, fold into undef if index is out of bounds.
5221 unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
5222 if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
5223 return PoisonValue::get(VecVTy->getElementType());
5224 // Handle case where an element is extracted from a splat.
5225 if (IdxC->getValue().ult(MinNumElts))
5226 if (auto *Splat = getSplatValue(Vec))
5227 return Splat;
5228 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
5229 return Elt;
5230 } else {
5231 // extractelt x, (insertelt y, elt, n), n -> elt
5232 // If the possibly-variable indices are trivially known to be equal
5233 // (because they are the same operand) then use the value that was
5234 // inserted directly.
5235 auto *IE = dyn_cast<InsertElementInst>(Vec);
5236 if (IE && IE->getOperand(2) == Idx)
5237 return IE->getOperand(1);
5239 // The index is not relevant if our vector is a splat.
5240 if (Value *Splat = getSplatValue(Vec))
5241 return Splat;
5243 return nullptr;
5246 Value *llvm::simplifyExtractElementInst(Value *Vec, Value *Idx,
5247 const SimplifyQuery &Q) {
5248 return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
5251 /// See if we can fold the given phi. If not, returns null.
5252 static Value *simplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
5253 const SimplifyQuery &Q) {
5254 // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
5255 // here, because the PHI we may succeed simplifying to was not
5256 // def-reachable from the original PHI!
5258 // If all of the PHI's incoming values are the same then replace the PHI node
5259 // with the common value.
5260 Value *CommonValue = nullptr;
5261 bool HasUndefInput = false;
5262 for (Value *Incoming : IncomingValues) {
5263 // If the incoming value is the phi node itself, it can safely be skipped.
5264 if (Incoming == PN)
5265 continue;
5266 if (Q.isUndefValue(Incoming)) {
5267 // Remember that we saw an undef value, but otherwise ignore them.
5268 HasUndefInput = true;
5269 continue;
5271 if (CommonValue && Incoming != CommonValue)
5272 return nullptr; // Not the same, bail out.
5273 CommonValue = Incoming;
5276 // If CommonValue is null then all of the incoming values were either undef or
5277 // equal to the phi node itself.
5278 if (!CommonValue)
5279 return UndefValue::get(PN->getType());
5281 if (HasUndefInput) {
5282 // If we have a PHI node like phi(X, undef, X), where X is defined by some
5283 // instruction, we cannot return X as the result of the PHI node unless it
5284 // dominates the PHI block.
5285 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
5288 return CommonValue;
5291 static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5292 const SimplifyQuery &Q, unsigned MaxRecurse) {
5293 if (auto *C = dyn_cast<Constant>(Op))
5294 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
5296 if (auto *CI = dyn_cast<CastInst>(Op)) {
5297 auto *Src = CI->getOperand(0);
5298 Type *SrcTy = Src->getType();
5299 Type *MidTy = CI->getType();
5300 Type *DstTy = Ty;
5301 if (Src->getType() == Ty) {
5302 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
5303 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
5304 Type *SrcIntPtrTy =
5305 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
5306 Type *MidIntPtrTy =
5307 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
5308 Type *DstIntPtrTy =
5309 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
5310 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
5311 SrcIntPtrTy, MidIntPtrTy,
5312 DstIntPtrTy) == Instruction::BitCast)
5313 return Src;
5317 // bitcast x -> x
5318 if (CastOpc == Instruction::BitCast)
5319 if (Op->getType() == Ty)
5320 return Op;
5322 return nullptr;
5325 Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
5326 const SimplifyQuery &Q) {
5327 return ::simplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
5330 /// For the given destination element of a shuffle, peek through shuffles to
5331 /// match a root vector source operand that contains that element in the same
5332 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
5333 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
5334 int MaskVal, Value *RootVec,
5335 unsigned MaxRecurse) {
5336 if (!MaxRecurse--)
5337 return nullptr;
5339 // Bail out if any mask value is undefined. That kind of shuffle may be
5340 // simplified further based on demanded bits or other folds.
5341 if (MaskVal == -1)
5342 return nullptr;
5344 // The mask value chooses which source operand we need to look at next.
5345 int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
5346 int RootElt = MaskVal;
5347 Value *SourceOp = Op0;
5348 if (MaskVal >= InVecNumElts) {
5349 RootElt = MaskVal - InVecNumElts;
5350 SourceOp = Op1;
5353 // If the source operand is a shuffle itself, look through it to find the
5354 // matching root vector.
5355 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
5356 return foldIdentityShuffles(
5357 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
5358 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
5361 // TODO: Look through bitcasts? What if the bitcast changes the vector element
5362 // size?
5364 // The source operand is not a shuffle. Initialize the root vector value for
5365 // this shuffle if that has not been done yet.
5366 if (!RootVec)
5367 RootVec = SourceOp;
5369 // Give up as soon as a source operand does not match the existing root value.
5370 if (RootVec != SourceOp)
5371 return nullptr;
5373 // The element must be coming from the same lane in the source vector
5374 // (although it may have crossed lanes in intermediate shuffles).
5375 if (RootElt != DestElt)
5376 return nullptr;
5378 return RootVec;
5381 static Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5382 ArrayRef<int> Mask, Type *RetTy,
5383 const SimplifyQuery &Q,
5384 unsigned MaxRecurse) {
5385 if (all_of(Mask, [](int Elem) { return Elem == PoisonMaskElem; }))
5386 return PoisonValue::get(RetTy);
5388 auto *InVecTy = cast<VectorType>(Op0->getType());
5389 unsigned MaskNumElts = Mask.size();
5390 ElementCount InVecEltCount = InVecTy->getElementCount();
5392 bool Scalable = InVecEltCount.isScalable();
5394 SmallVector<int, 32> Indices;
5395 Indices.assign(Mask.begin(), Mask.end());
5397 // Canonicalization: If mask does not select elements from an input vector,
5398 // replace that input vector with poison.
5399 if (!Scalable) {
5400 bool MaskSelects0 = false, MaskSelects1 = false;
5401 unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
5402 for (unsigned i = 0; i != MaskNumElts; ++i) {
5403 if (Indices[i] == -1)
5404 continue;
5405 if ((unsigned)Indices[i] < InVecNumElts)
5406 MaskSelects0 = true;
5407 else
5408 MaskSelects1 = true;
5410 if (!MaskSelects0)
5411 Op0 = PoisonValue::get(InVecTy);
5412 if (!MaskSelects1)
5413 Op1 = PoisonValue::get(InVecTy);
5416 auto *Op0Const = dyn_cast<Constant>(Op0);
5417 auto *Op1Const = dyn_cast<Constant>(Op1);
5419 // If all operands are constant, constant fold the shuffle. This
5420 // transformation depends on the value of the mask which is not known at
5421 // compile time for scalable vectors
5422 if (Op0Const && Op1Const)
5423 return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
5425 // Canonicalization: if only one input vector is constant, it shall be the
5426 // second one. This transformation depends on the value of the mask which
5427 // is not known at compile time for scalable vectors
5428 if (!Scalable && Op0Const && !Op1Const) {
5429 std::swap(Op0, Op1);
5430 ShuffleVectorInst::commuteShuffleMask(Indices,
5431 InVecEltCount.getKnownMinValue());
5434 // A splat of an inserted scalar constant becomes a vector constant:
5435 // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
5436 // NOTE: We may have commuted above, so analyze the updated Indices, not the
5437 // original mask constant.
5438 // NOTE: This transformation depends on the value of the mask which is not
5439 // known at compile time for scalable vectors
5440 Constant *C;
5441 ConstantInt *IndexC;
5442 if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
5443 m_ConstantInt(IndexC)))) {
5444 // Match a splat shuffle mask of the insert index allowing undef elements.
5445 int InsertIndex = IndexC->getZExtValue();
5446 if (all_of(Indices, [InsertIndex](int MaskElt) {
5447 return MaskElt == InsertIndex || MaskElt == -1;
5448 })) {
5449 assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
5451 // Shuffle mask poisons become poison constant result elements.
5452 SmallVector<Constant *, 16> VecC(MaskNumElts, C);
5453 for (unsigned i = 0; i != MaskNumElts; ++i)
5454 if (Indices[i] == -1)
5455 VecC[i] = PoisonValue::get(C->getType());
5456 return ConstantVector::get(VecC);
5460 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
5461 // value type is same as the input vectors' type.
5462 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
5463 if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
5464 all_equal(OpShuf->getShuffleMask()))
5465 return Op0;
5467 // All remaining transformation depend on the value of the mask, which is
5468 // not known at compile time for scalable vectors.
5469 if (Scalable)
5470 return nullptr;
5472 // Don't fold a shuffle with undef mask elements. This may get folded in a
5473 // better way using demanded bits or other analysis.
5474 // TODO: Should we allow this?
5475 if (is_contained(Indices, -1))
5476 return nullptr;
5478 // Check if every element of this shuffle can be mapped back to the
5479 // corresponding element of a single root vector. If so, we don't need this
5480 // shuffle. This handles simple identity shuffles as well as chains of
5481 // shuffles that may widen/narrow and/or move elements across lanes and back.
5482 Value *RootVec = nullptr;
5483 for (unsigned i = 0; i != MaskNumElts; ++i) {
5484 // Note that recursion is limited for each vector element, so if any element
5485 // exceeds the limit, this will fail to simplify.
5486 RootVec =
5487 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
5489 // We can't replace a widening/narrowing shuffle with one of its operands.
5490 if (!RootVec || RootVec->getType() != RetTy)
5491 return nullptr;
5493 return RootVec;
5496 /// Given operands for a ShuffleVectorInst, fold the result or return null.
5497 Value *llvm::simplifyShuffleVectorInst(Value *Op0, Value *Op1,
5498 ArrayRef<int> Mask, Type *RetTy,
5499 const SimplifyQuery &Q) {
5500 return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
5503 static Constant *foldConstant(Instruction::UnaryOps Opcode, Value *&Op,
5504 const SimplifyQuery &Q) {
5505 if (auto *C = dyn_cast<Constant>(Op))
5506 return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
5507 return nullptr;
5510 /// Given the operand for an FNeg, see if we can fold the result. If not, this
5511 /// returns null.
5512 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
5513 const SimplifyQuery &Q, unsigned MaxRecurse) {
5514 if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
5515 return C;
5517 Value *X;
5518 // fneg (fneg X) ==> X
5519 if (match(Op, m_FNeg(m_Value(X))))
5520 return X;
5522 return nullptr;
5525 Value *llvm::simplifyFNegInst(Value *Op, FastMathFlags FMF,
5526 const SimplifyQuery &Q) {
5527 return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
5530 /// Try to propagate existing NaN values when possible. If not, replace the
5531 /// constant or elements in the constant with a canonical NaN.
5532 static Constant *propagateNaN(Constant *In) {
5533 Type *Ty = In->getType();
5534 if (auto *VecTy = dyn_cast<FixedVectorType>(Ty)) {
5535 unsigned NumElts = VecTy->getNumElements();
5536 SmallVector<Constant *, 32> NewC(NumElts);
5537 for (unsigned i = 0; i != NumElts; ++i) {
5538 Constant *EltC = In->getAggregateElement(i);
5539 // Poison elements propagate. NaN propagates except signaling is quieted.
5540 // Replace unknown or undef elements with canonical NaN.
5541 if (EltC && isa<PoisonValue>(EltC))
5542 NewC[i] = EltC;
5543 else if (EltC && EltC->isNaN())
5544 NewC[i] = ConstantFP::get(
5545 EltC->getType(), cast<ConstantFP>(EltC)->getValue().makeQuiet());
5546 else
5547 NewC[i] = ConstantFP::getNaN(VecTy->getElementType());
5549 return ConstantVector::get(NewC);
5552 // If it is not a fixed vector, but not a simple NaN either, return a
5553 // canonical NaN.
5554 if (!In->isNaN())
5555 return ConstantFP::getNaN(Ty);
5557 // If we known this is a NaN, and it's scalable vector, we must have a splat
5558 // on our hands. Grab that before splatting a QNaN constant.
5559 if (isa<ScalableVectorType>(Ty)) {
5560 auto *Splat = In->getSplatValue();
5561 assert(Splat && Splat->isNaN() &&
5562 "Found a scalable-vector NaN but not a splat");
5563 In = Splat;
5566 // Propagate an existing QNaN constant. If it is an SNaN, make it quiet, but
5567 // preserve the sign/payload.
5568 return ConstantFP::get(Ty, cast<ConstantFP>(In)->getValue().makeQuiet());
5571 /// Perform folds that are common to any floating-point operation. This implies
5572 /// transforms based on poison/undef/NaN because the operation itself makes no
5573 /// difference to the result.
5574 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
5575 const SimplifyQuery &Q,
5576 fp::ExceptionBehavior ExBehavior,
5577 RoundingMode Rounding) {
5578 // Poison is independent of anything else. It always propagates from an
5579 // operand to a math result.
5580 if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
5581 return PoisonValue::get(Ops[0]->getType());
5583 for (Value *V : Ops) {
5584 bool IsNan = match(V, m_NaN());
5585 bool IsInf = match(V, m_Inf());
5586 bool IsUndef = Q.isUndefValue(V);
5588 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
5589 // (an undef operand can be chosen to be Nan/Inf), then the result of
5590 // this operation is poison.
5591 if (FMF.noNaNs() && (IsNan || IsUndef))
5592 return PoisonValue::get(V->getType());
5593 if (FMF.noInfs() && (IsInf || IsUndef))
5594 return PoisonValue::get(V->getType());
5596 if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
5597 // Undef does not propagate because undef means that all bits can take on
5598 // any value. If this is undef * NaN for example, then the result values
5599 // (at least the exponent bits) are limited. Assume the undef is a
5600 // canonical NaN and propagate that.
5601 if (IsUndef)
5602 return ConstantFP::getNaN(V->getType());
5603 if (IsNan)
5604 return propagateNaN(cast<Constant>(V));
5605 } else if (ExBehavior != fp::ebStrict) {
5606 if (IsNan)
5607 return propagateNaN(cast<Constant>(V));
5610 return nullptr;
5613 /// Given operands for an FAdd, see if we can fold the result. If not, this
5614 /// returns null.
5615 static Value *
5616 simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5617 const SimplifyQuery &Q, unsigned MaxRecurse,
5618 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5619 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5620 if (isDefaultFPEnvironment(ExBehavior, Rounding))
5621 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
5622 return C;
5624 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5625 return C;
5627 // fadd X, -0 ==> X
5628 // With strict/constrained FP, we have these possible edge cases that do
5629 // not simplify to Op0:
5630 // fadd SNaN, -0.0 --> QNaN
5631 // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
5632 if (canIgnoreSNaN(ExBehavior, FMF) &&
5633 (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5634 FMF.noSignedZeros()))
5635 if (match(Op1, m_NegZeroFP()))
5636 return Op0;
5638 // fadd X, 0 ==> X, when we know X is not -0
5639 if (canIgnoreSNaN(ExBehavior, FMF))
5640 if (match(Op1, m_PosZeroFP()) &&
5641 (FMF.noSignedZeros() || cannotBeNegativeZero(Op0, Q.DL, Q.TLI)))
5642 return Op0;
5644 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5645 return nullptr;
5647 if (FMF.noNaNs()) {
5648 // With nnan: X + {+/-}Inf --> {+/-}Inf
5649 if (match(Op1, m_Inf()))
5650 return Op1;
5652 // With nnan: -X + X --> 0.0 (and commuted variant)
5653 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
5654 // Negative zeros are allowed because we always end up with positive zero:
5655 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5656 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
5657 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
5658 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
5659 if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
5660 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
5661 return ConstantFP::getZero(Op0->getType());
5663 if (match(Op0, m_FNeg(m_Specific(Op1))) ||
5664 match(Op1, m_FNeg(m_Specific(Op0))))
5665 return ConstantFP::getZero(Op0->getType());
5668 // (X - Y) + Y --> X
5669 // Y + (X - Y) --> X
5670 Value *X;
5671 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5672 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
5673 match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
5674 return X;
5676 return nullptr;
5679 /// Given operands for an FSub, see if we can fold the result. If not, this
5680 /// returns null.
5681 static Value *
5682 simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5683 const SimplifyQuery &Q, unsigned MaxRecurse,
5684 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5685 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5686 if (isDefaultFPEnvironment(ExBehavior, Rounding))
5687 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
5688 return C;
5690 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5691 return C;
5693 // fsub X, +0 ==> X
5694 if (canIgnoreSNaN(ExBehavior, FMF) &&
5695 (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
5696 FMF.noSignedZeros()))
5697 if (match(Op1, m_PosZeroFP()))
5698 return Op0;
5700 // fsub X, -0 ==> X, when we know X is not -0
5701 if (canIgnoreSNaN(ExBehavior, FMF))
5702 if (match(Op1, m_NegZeroFP()) &&
5703 (FMF.noSignedZeros() || cannotBeNegativeZero(Op0, Q.DL, Q.TLI)))
5704 return Op0;
5706 // fsub -0.0, (fsub -0.0, X) ==> X
5707 // fsub -0.0, (fneg X) ==> X
5708 Value *X;
5709 if (canIgnoreSNaN(ExBehavior, FMF))
5710 if (match(Op0, m_NegZeroFP()) && match(Op1, m_FNeg(m_Value(X))))
5711 return X;
5713 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
5714 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
5715 if (canIgnoreSNaN(ExBehavior, FMF))
5716 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
5717 (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
5718 match(Op1, m_FNeg(m_Value(X)))))
5719 return X;
5721 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5722 return nullptr;
5724 if (FMF.noNaNs()) {
5725 // fsub nnan x, x ==> 0.0
5726 if (Op0 == Op1)
5727 return Constant::getNullValue(Op0->getType());
5729 // With nnan: {+/-}Inf - X --> {+/-}Inf
5730 if (match(Op0, m_Inf()))
5731 return Op0;
5733 // With nnan: X - {+/-}Inf --> {-/+}Inf
5734 if (match(Op1, m_Inf()))
5735 return foldConstant(Instruction::FNeg, Op1, Q);
5738 // Y - (Y - X) --> X
5739 // (X + Y) - Y --> X
5740 if (FMF.noSignedZeros() && FMF.allowReassoc() &&
5741 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
5742 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
5743 return X;
5745 return nullptr;
5748 static Value *simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5749 const SimplifyQuery &Q, unsigned MaxRecurse,
5750 fp::ExceptionBehavior ExBehavior,
5751 RoundingMode Rounding) {
5752 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5753 return C;
5755 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5756 return nullptr;
5758 // Canonicalize special constants as operand 1.
5759 if (match(Op0, m_FPOne()) || match(Op0, m_AnyZeroFP()))
5760 std::swap(Op0, Op1);
5762 // X * 1.0 --> X
5763 if (match(Op1, m_FPOne()))
5764 return Op0;
5766 if (match(Op1, m_AnyZeroFP())) {
5767 // X * 0.0 --> 0.0 (with nnan and nsz)
5768 if (FMF.noNaNs() && FMF.noSignedZeros())
5769 return ConstantFP::getZero(Op0->getType());
5771 // +normal number * (-)0.0 --> (-)0.0
5772 if (isKnownNeverInfOrNaN(Op0, Q.DL, Q.TLI, 0, Q.AC, Q.CxtI, Q.DT) &&
5773 // TODO: Check SignBit from computeKnownFPClass when it's more complete.
5774 SignBitMustBeZero(Op0, Q.DL, Q.TLI))
5775 return Op1;
5778 // sqrt(X) * sqrt(X) --> X, if we can:
5779 // 1. Remove the intermediate rounding (reassociate).
5780 // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
5781 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
5782 Value *X;
5783 if (Op0 == Op1 && match(Op0, m_Sqrt(m_Value(X))) && FMF.allowReassoc() &&
5784 FMF.noNaNs() && FMF.noSignedZeros())
5785 return X;
5787 return nullptr;
5790 /// Given the operands for an FMul, see if we can fold the result
5791 static Value *
5792 simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5793 const SimplifyQuery &Q, unsigned MaxRecurse,
5794 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5795 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5796 if (isDefaultFPEnvironment(ExBehavior, Rounding))
5797 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
5798 return C;
5800 // Now apply simplifications that do not require rounding.
5801 return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
5804 Value *llvm::simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5805 const SimplifyQuery &Q,
5806 fp::ExceptionBehavior ExBehavior,
5807 RoundingMode Rounding) {
5808 return ::simplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5809 Rounding);
5812 Value *llvm::simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5813 const SimplifyQuery &Q,
5814 fp::ExceptionBehavior ExBehavior,
5815 RoundingMode Rounding) {
5816 return ::simplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5817 Rounding);
5820 Value *llvm::simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5821 const SimplifyQuery &Q,
5822 fp::ExceptionBehavior ExBehavior,
5823 RoundingMode Rounding) {
5824 return ::simplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5825 Rounding);
5828 Value *llvm::simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
5829 const SimplifyQuery &Q,
5830 fp::ExceptionBehavior ExBehavior,
5831 RoundingMode Rounding) {
5832 return ::simplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5833 Rounding);
5836 static Value *
5837 simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5838 const SimplifyQuery &Q, unsigned,
5839 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5840 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5841 if (isDefaultFPEnvironment(ExBehavior, Rounding))
5842 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
5843 return C;
5845 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5846 return C;
5848 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5849 return nullptr;
5851 // X / 1.0 -> X
5852 if (match(Op1, m_FPOne()))
5853 return Op0;
5855 // 0 / X -> 0
5856 // Requires that NaNs are off (X could be zero) and signed zeroes are
5857 // ignored (X could be positive or negative, so the output sign is unknown).
5858 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
5859 return ConstantFP::getZero(Op0->getType());
5861 if (FMF.noNaNs()) {
5862 // X / X -> 1.0 is legal when NaNs are ignored.
5863 // We can ignore infinities because INF/INF is NaN.
5864 if (Op0 == Op1)
5865 return ConstantFP::get(Op0->getType(), 1.0);
5867 // (X * Y) / Y --> X if we can reassociate to the above form.
5868 Value *X;
5869 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
5870 return X;
5872 // -X / X -> -1.0 and
5873 // X / -X -> -1.0 are legal when NaNs are ignored.
5874 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
5875 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
5876 match(Op1, m_FNegNSZ(m_Specific(Op0))))
5877 return ConstantFP::get(Op0->getType(), -1.0);
5879 // nnan ninf X / [-]0.0 -> poison
5880 if (FMF.noInfs() && match(Op1, m_AnyZeroFP()))
5881 return PoisonValue::get(Op1->getType());
5884 return nullptr;
5887 Value *llvm::simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5888 const SimplifyQuery &Q,
5889 fp::ExceptionBehavior ExBehavior,
5890 RoundingMode Rounding) {
5891 return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5892 Rounding);
5895 static Value *
5896 simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5897 const SimplifyQuery &Q, unsigned,
5898 fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
5899 RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
5900 if (isDefaultFPEnvironment(ExBehavior, Rounding))
5901 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
5902 return C;
5904 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
5905 return C;
5907 if (!isDefaultFPEnvironment(ExBehavior, Rounding))
5908 return nullptr;
5910 // Unlike fdiv, the result of frem always matches the sign of the dividend.
5911 // The constant match may include undef elements in a vector, so return a full
5912 // zero constant as the result.
5913 if (FMF.noNaNs()) {
5914 // +0 % X -> 0
5915 if (match(Op0, m_PosZeroFP()))
5916 return ConstantFP::getZero(Op0->getType());
5917 // -0 % X -> -0
5918 if (match(Op0, m_NegZeroFP()))
5919 return ConstantFP::getNegativeZero(Op0->getType());
5922 return nullptr;
5925 Value *llvm::simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
5926 const SimplifyQuery &Q,
5927 fp::ExceptionBehavior ExBehavior,
5928 RoundingMode Rounding) {
5929 return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
5930 Rounding);
5933 //=== Helper functions for higher up the class hierarchy.
5935 /// Given the operand for a UnaryOperator, see if we can fold the result.
5936 /// If not, this returns null.
5937 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
5938 unsigned MaxRecurse) {
5939 switch (Opcode) {
5940 case Instruction::FNeg:
5941 return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
5942 default:
5943 llvm_unreachable("Unexpected opcode");
5947 /// Given the operand for a UnaryOperator, see if we can fold the result.
5948 /// If not, this returns null.
5949 /// Try to use FastMathFlags when folding the result.
5950 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
5951 const FastMathFlags &FMF, const SimplifyQuery &Q,
5952 unsigned MaxRecurse) {
5953 switch (Opcode) {
5954 case Instruction::FNeg:
5955 return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
5956 default:
5957 return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
5961 Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
5962 return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
5965 Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
5966 const SimplifyQuery &Q) {
5967 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
5970 /// Given operands for a BinaryOperator, see if we can fold the result.
5971 /// If not, this returns null.
5972 static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
5973 const SimplifyQuery &Q, unsigned MaxRecurse) {
5974 switch (Opcode) {
5975 case Instruction::Add:
5976 return simplifyAddInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5977 MaxRecurse);
5978 case Instruction::Sub:
5979 return simplifySubInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5980 MaxRecurse);
5981 case Instruction::Mul:
5982 return simplifyMulInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5983 MaxRecurse);
5984 case Instruction::SDiv:
5985 return simplifySDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
5986 case Instruction::UDiv:
5987 return simplifyUDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
5988 case Instruction::SRem:
5989 return simplifySRemInst(LHS, RHS, Q, MaxRecurse);
5990 case Instruction::URem:
5991 return simplifyURemInst(LHS, RHS, Q, MaxRecurse);
5992 case Instruction::Shl:
5993 return simplifyShlInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
5994 MaxRecurse);
5995 case Instruction::LShr:
5996 return simplifyLShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
5997 case Instruction::AShr:
5998 return simplifyAShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
5999 case Instruction::And:
6000 return simplifyAndInst(LHS, RHS, Q, MaxRecurse);
6001 case Instruction::Or:
6002 return simplifyOrInst(LHS, RHS, Q, MaxRecurse);
6003 case Instruction::Xor:
6004 return simplifyXorInst(LHS, RHS, Q, MaxRecurse);
6005 case Instruction::FAdd:
6006 return simplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6007 case Instruction::FSub:
6008 return simplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6009 case Instruction::FMul:
6010 return simplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6011 case Instruction::FDiv:
6012 return simplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6013 case Instruction::FRem:
6014 return simplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6015 default:
6016 llvm_unreachable("Unexpected opcode");
6020 /// Given operands for a BinaryOperator, see if we can fold the result.
6021 /// If not, this returns null.
6022 /// Try to use FastMathFlags when folding the result.
6023 static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6024 const FastMathFlags &FMF, const SimplifyQuery &Q,
6025 unsigned MaxRecurse) {
6026 switch (Opcode) {
6027 case Instruction::FAdd:
6028 return simplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
6029 case Instruction::FSub:
6030 return simplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
6031 case Instruction::FMul:
6032 return simplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
6033 case Instruction::FDiv:
6034 return simplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
6035 default:
6036 return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
6040 Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6041 const SimplifyQuery &Q) {
6042 return ::simplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
6045 Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
6046 FastMathFlags FMF, const SimplifyQuery &Q) {
6047 return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
6050 /// Given operands for a CmpInst, see if we can fold the result.
6051 static Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
6052 const SimplifyQuery &Q, unsigned MaxRecurse) {
6053 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
6054 return simplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
6055 return simplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
6058 Value *llvm::simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
6059 const SimplifyQuery &Q) {
6060 return ::simplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
6063 static bool isIdempotent(Intrinsic::ID ID) {
6064 switch (ID) {
6065 default:
6066 return false;
6068 // Unary idempotent: f(f(x)) = f(x)
6069 case Intrinsic::fabs:
6070 case Intrinsic::floor:
6071 case Intrinsic::ceil:
6072 case Intrinsic::trunc:
6073 case Intrinsic::rint:
6074 case Intrinsic::nearbyint:
6075 case Intrinsic::round:
6076 case Intrinsic::roundeven:
6077 case Intrinsic::canonicalize:
6078 case Intrinsic::arithmetic_fence:
6079 return true;
6083 /// Return true if the intrinsic rounds a floating-point value to an integral
6084 /// floating-point value (not an integer type).
6085 static bool removesFPFraction(Intrinsic::ID ID) {
6086 switch (ID) {
6087 default:
6088 return false;
6090 case Intrinsic::floor:
6091 case Intrinsic::ceil:
6092 case Intrinsic::trunc:
6093 case Intrinsic::rint:
6094 case Intrinsic::nearbyint:
6095 case Intrinsic::round:
6096 case Intrinsic::roundeven:
6097 return true;
6101 static Value *simplifyRelativeLoad(Constant *Ptr, Constant *Offset,
6102 const DataLayout &DL) {
6103 GlobalValue *PtrSym;
6104 APInt PtrOffset;
6105 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
6106 return nullptr;
6108 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
6110 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
6111 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
6112 return nullptr;
6114 APInt OffsetInt = OffsetConstInt->getValue().sextOrTrunc(
6115 DL.getIndexTypeSizeInBits(Ptr->getType()));
6116 if (OffsetInt.srem(4) != 0)
6117 return nullptr;
6119 Constant *Loaded = ConstantFoldLoadFromConstPtr(Ptr, Int32Ty, OffsetInt, DL);
6120 if (!Loaded)
6121 return nullptr;
6123 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
6124 if (!LoadedCE)
6125 return nullptr;
6127 if (LoadedCE->getOpcode() == Instruction::Trunc) {
6128 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
6129 if (!LoadedCE)
6130 return nullptr;
6133 if (LoadedCE->getOpcode() != Instruction::Sub)
6134 return nullptr;
6136 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
6137 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
6138 return nullptr;
6139 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
6141 Constant *LoadedRHS = LoadedCE->getOperand(1);
6142 GlobalValue *LoadedRHSSym;
6143 APInt LoadedRHSOffset;
6144 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
6145 DL) ||
6146 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
6147 return nullptr;
6149 return LoadedLHSPtr;
6152 // TODO: Need to pass in FastMathFlags
6153 static Value *simplifyLdexp(Value *Op0, Value *Op1, const SimplifyQuery &Q,
6154 bool IsStrict) {
6155 // ldexp(poison, x) -> poison
6156 // ldexp(x, poison) -> poison
6157 if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
6158 return Op0;
6160 // ldexp(undef, x) -> nan
6161 if (Q.isUndefValue(Op0))
6162 return ConstantFP::getNaN(Op0->getType());
6164 if (!IsStrict) {
6165 // TODO: Could insert a canonicalize for strict
6167 // ldexp(x, undef) -> x
6168 if (Q.isUndefValue(Op1))
6169 return Op0;
6172 const APFloat *C = nullptr;
6173 match(Op0, PatternMatch::m_APFloat(C));
6175 // These cases should be safe, even with strictfp.
6176 // ldexp(0.0, x) -> 0.0
6177 // ldexp(-0.0, x) -> -0.0
6178 // ldexp(inf, x) -> inf
6179 // ldexp(-inf, x) -> -inf
6180 if (C && (C->isZero() || C->isInfinity()))
6181 return Op0;
6183 // These are canonicalization dropping, could do it if we knew how we could
6184 // ignore denormal flushes and target handling of nan payload bits.
6185 if (IsStrict)
6186 return nullptr;
6188 // TODO: Could quiet this with strictfp if the exception mode isn't strict.
6189 if (C && C->isNaN())
6190 return ConstantFP::get(Op0->getType(), C->makeQuiet());
6192 // ldexp(x, 0) -> x
6194 // TODO: Could fold this if we know the exception mode isn't
6195 // strict, we know the denormal mode and other target modes.
6196 if (match(Op1, PatternMatch::m_ZeroInt()))
6197 return Op0;
6199 return nullptr;
6202 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
6203 const SimplifyQuery &Q) {
6204 // Idempotent functions return the same result when called repeatedly.
6205 Intrinsic::ID IID = F->getIntrinsicID();
6206 if (isIdempotent(IID))
6207 if (auto *II = dyn_cast<IntrinsicInst>(Op0))
6208 if (II->getIntrinsicID() == IID)
6209 return II;
6211 if (removesFPFraction(IID)) {
6212 // Converting from int or calling a rounding function always results in a
6213 // finite integral number or infinity. For those inputs, rounding functions
6214 // always return the same value, so the (2nd) rounding is eliminated. Ex:
6215 // floor (sitofp x) -> sitofp x
6216 // round (ceil x) -> ceil x
6217 auto *II = dyn_cast<IntrinsicInst>(Op0);
6218 if ((II && removesFPFraction(II->getIntrinsicID())) ||
6219 match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
6220 return Op0;
6223 Value *X;
6224 switch (IID) {
6225 case Intrinsic::fabs:
6226 if (SignBitMustBeZero(Op0, Q.DL, Q.TLI))
6227 return Op0;
6228 break;
6229 case Intrinsic::bswap:
6230 // bswap(bswap(x)) -> x
6231 if (match(Op0, m_BSwap(m_Value(X))))
6232 return X;
6233 break;
6234 case Intrinsic::bitreverse:
6235 // bitreverse(bitreverse(x)) -> x
6236 if (match(Op0, m_BitReverse(m_Value(X))))
6237 return X;
6238 break;
6239 case Intrinsic::ctpop: {
6240 // ctpop(X) -> 1 iff X is non-zero power of 2.
6241 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ false, 0, Q.AC, Q.CxtI,
6242 Q.DT))
6243 return ConstantInt::get(Op0->getType(), 1);
6244 // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
6245 // ctpop(and X, 1) --> and X, 1
6246 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
6247 if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
6248 Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
6249 return Op0;
6250 break;
6252 case Intrinsic::exp:
6253 // exp(log(x)) -> x
6254 if (Q.CxtI->hasAllowReassoc() &&
6255 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X))))
6256 return X;
6257 break;
6258 case Intrinsic::exp2:
6259 // exp2(log2(x)) -> x
6260 if (Q.CxtI->hasAllowReassoc() &&
6261 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
6262 return X;
6263 break;
6264 case Intrinsic::exp10:
6265 // exp10(log10(x)) -> x
6266 if (Q.CxtI->hasAllowReassoc() &&
6267 match(Op0, m_Intrinsic<Intrinsic::log10>(m_Value(X))))
6268 return X;
6269 break;
6270 case Intrinsic::log:
6271 // log(exp(x)) -> x
6272 if (Q.CxtI->hasAllowReassoc() &&
6273 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
6274 return X;
6275 break;
6276 case Intrinsic::log2:
6277 // log2(exp2(x)) -> x
6278 if (Q.CxtI->hasAllowReassoc() &&
6279 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
6280 match(Op0,
6281 m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), m_Value(X)))))
6282 return X;
6283 break;
6284 case Intrinsic::log10:
6285 // log10(pow(10.0, x)) -> x
6286 // log10(exp10(x)) -> x
6287 if (Q.CxtI->hasAllowReassoc() &&
6288 (match(Op0, m_Intrinsic<Intrinsic::exp10>(m_Value(X))) ||
6289 match(Op0,
6290 m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), m_Value(X)))))
6291 return X;
6292 break;
6293 case Intrinsic::experimental_vector_reverse:
6294 // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
6295 if (match(Op0, m_VecReverse(m_Value(X))))
6296 return X;
6297 // experimental.vector.reverse(splat(X)) -> splat(X)
6298 if (isSplatValue(Op0))
6299 return Op0;
6300 break;
6301 case Intrinsic::frexp: {
6302 // Frexp is idempotent with the added complication of the struct return.
6303 if (match(Op0, m_ExtractValue<0>(m_Value(X)))) {
6304 if (match(X, m_Intrinsic<Intrinsic::frexp>(m_Value())))
6305 return X;
6308 break;
6310 default:
6311 break;
6314 return nullptr;
6317 /// Given a min/max intrinsic, see if it can be removed based on having an
6318 /// operand that is another min/max intrinsic with shared operand(s). The caller
6319 /// is expected to swap the operand arguments to handle commutation.
6320 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
6321 Value *X, *Y;
6322 if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
6323 return nullptr;
6325 auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
6326 if (!MM0)
6327 return nullptr;
6328 Intrinsic::ID IID0 = MM0->getIntrinsicID();
6330 if (Op1 == X || Op1 == Y ||
6331 match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
6332 // max (max X, Y), X --> max X, Y
6333 if (IID0 == IID)
6334 return MM0;
6335 // max (min X, Y), X --> X
6336 if (IID0 == getInverseMinMaxIntrinsic(IID))
6337 return Op1;
6339 return nullptr;
6342 /// Given a min/max intrinsic, see if it can be removed based on having an
6343 /// operand that is another min/max intrinsic with shared operand(s). The caller
6344 /// is expected to swap the operand arguments to handle commutation.
6345 static Value *foldMinimumMaximumSharedOp(Intrinsic::ID IID, Value *Op0,
6346 Value *Op1) {
6347 assert((IID == Intrinsic::maxnum || IID == Intrinsic::minnum ||
6348 IID == Intrinsic::maximum || IID == Intrinsic::minimum) &&
6349 "Unsupported intrinsic");
6351 auto *M0 = dyn_cast<IntrinsicInst>(Op0);
6352 // If Op0 is not the same intrinsic as IID, do not process.
6353 // This is a difference with integer min/max handling. We do not process the
6354 // case like max(min(X,Y),min(X,Y)) => min(X,Y). But it can be handled by GVN.
6355 if (!M0 || M0->getIntrinsicID() != IID)
6356 return nullptr;
6357 Value *X0 = M0->getOperand(0);
6358 Value *Y0 = M0->getOperand(1);
6359 // Simple case, m(m(X,Y), X) => m(X, Y)
6360 // m(m(X,Y), Y) => m(X, Y)
6361 // For minimum/maximum, X is NaN => m(NaN, Y) == NaN and m(NaN, NaN) == NaN.
6362 // For minimum/maximum, Y is NaN => m(X, NaN) == NaN and m(NaN, NaN) == NaN.
6363 // For minnum/maxnum, X is NaN => m(NaN, Y) == Y and m(Y, Y) == Y.
6364 // For minnum/maxnum, Y is NaN => m(X, NaN) == X and m(X, NaN) == X.
6365 if (X0 == Op1 || Y0 == Op1)
6366 return M0;
6368 auto *M1 = dyn_cast<IntrinsicInst>(Op1);
6369 if (!M1)
6370 return nullptr;
6371 Value *X1 = M1->getOperand(0);
6372 Value *Y1 = M1->getOperand(1);
6373 Intrinsic::ID IID1 = M1->getIntrinsicID();
6374 // we have a case m(m(X,Y),m'(X,Y)) taking into account m' is commutative.
6375 // if m' is m or inversion of m => m(m(X,Y),m'(X,Y)) == m(X,Y).
6376 // For minimum/maximum, X is NaN => m(NaN,Y) == m'(NaN, Y) == NaN.
6377 // For minimum/maximum, Y is NaN => m(X,NaN) == m'(X, NaN) == NaN.
6378 // For minnum/maxnum, X is NaN => m(NaN,Y) == m'(NaN, Y) == Y.
6379 // For minnum/maxnum, Y is NaN => m(X,NaN) == m'(X, NaN) == X.
6380 if ((X0 == X1 && Y0 == Y1) || (X0 == Y1 && Y0 == X1))
6381 if (IID1 == IID || getInverseMinMaxIntrinsic(IID1) == IID)
6382 return M0;
6384 return nullptr;
6387 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
6388 const SimplifyQuery &Q) {
6389 Intrinsic::ID IID = F->getIntrinsicID();
6390 Type *ReturnType = F->getReturnType();
6391 unsigned BitWidth = ReturnType->getScalarSizeInBits();
6392 switch (IID) {
6393 case Intrinsic::abs:
6394 // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
6395 // It is always ok to pick the earlier abs. We'll just lose nsw if its only
6396 // on the outer abs.
6397 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
6398 return Op0;
6399 break;
6401 case Intrinsic::cttz: {
6402 Value *X;
6403 if (match(Op0, m_Shl(m_One(), m_Value(X))))
6404 return X;
6405 break;
6407 case Intrinsic::ctlz: {
6408 Value *X;
6409 if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
6410 return X;
6411 if (match(Op0, m_AShr(m_Negative(), m_Value())))
6412 return Constant::getNullValue(ReturnType);
6413 break;
6415 case Intrinsic::smax:
6416 case Intrinsic::smin:
6417 case Intrinsic::umax:
6418 case Intrinsic::umin: {
6419 // If the arguments are the same, this is a no-op.
6420 if (Op0 == Op1)
6421 return Op0;
6423 // Canonicalize immediate constant operand as Op1.
6424 if (match(Op0, m_ImmConstant()))
6425 std::swap(Op0, Op1);
6427 // Assume undef is the limit value.
6428 if (Q.isUndefValue(Op1))
6429 return ConstantInt::get(
6430 ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
6432 const APInt *C;
6433 if (match(Op1, m_APIntAllowUndef(C))) {
6434 // Clamp to limit value. For example:
6435 // umax(i8 %x, i8 255) --> 255
6436 if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
6437 return ConstantInt::get(ReturnType, *C);
6439 // If the constant op is the opposite of the limit value, the other must
6440 // be larger/smaller or equal. For example:
6441 // umin(i8 %x, i8 255) --> %x
6442 if (*C == MinMaxIntrinsic::getSaturationPoint(
6443 getInverseMinMaxIntrinsic(IID), BitWidth))
6444 return Op0;
6446 // Remove nested call if constant operands allow it. Example:
6447 // max (max X, 7), 5 -> max X, 7
6448 auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
6449 if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
6450 // TODO: loosen undef/splat restrictions for vector constants.
6451 Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
6452 const APInt *InnerC;
6453 if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
6454 ICmpInst::compare(*InnerC, *C,
6455 ICmpInst::getNonStrictPredicate(
6456 MinMaxIntrinsic::getPredicate(IID))))
6457 return Op0;
6461 if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
6462 return V;
6463 if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
6464 return V;
6466 ICmpInst::Predicate Pred =
6467 ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
6468 if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
6469 return Op0;
6470 if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
6471 return Op1;
6473 break;
6475 case Intrinsic::usub_with_overflow:
6476 case Intrinsic::ssub_with_overflow:
6477 // X - X -> { 0, false }
6478 // X - undef -> { 0, false }
6479 // undef - X -> { 0, false }
6480 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6481 return Constant::getNullValue(ReturnType);
6482 break;
6483 case Intrinsic::uadd_with_overflow:
6484 case Intrinsic::sadd_with_overflow:
6485 // X + undef -> { -1, false }
6486 // undef + x -> { -1, false }
6487 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
6488 return ConstantStruct::get(
6489 cast<StructType>(ReturnType),
6490 {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
6491 Constant::getNullValue(ReturnType->getStructElementType(1))});
6493 break;
6494 case Intrinsic::umul_with_overflow:
6495 case Intrinsic::smul_with_overflow:
6496 // 0 * X -> { 0, false }
6497 // X * 0 -> { 0, false }
6498 if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
6499 return Constant::getNullValue(ReturnType);
6500 // undef * X -> { 0, false }
6501 // X * undef -> { 0, false }
6502 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6503 return Constant::getNullValue(ReturnType);
6504 break;
6505 case Intrinsic::uadd_sat:
6506 // sat(MAX + X) -> MAX
6507 // sat(X + MAX) -> MAX
6508 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
6509 return Constant::getAllOnesValue(ReturnType);
6510 [[fallthrough]];
6511 case Intrinsic::sadd_sat:
6512 // sat(X + undef) -> -1
6513 // sat(undef + X) -> -1
6514 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
6515 // For signed: Assume undef is ~X, in which case X + ~X = -1.
6516 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6517 return Constant::getAllOnesValue(ReturnType);
6519 // X + 0 -> X
6520 if (match(Op1, m_Zero()))
6521 return Op0;
6522 // 0 + X -> X
6523 if (match(Op0, m_Zero()))
6524 return Op1;
6525 break;
6526 case Intrinsic::usub_sat:
6527 // sat(0 - X) -> 0, sat(X - MAX) -> 0
6528 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
6529 return Constant::getNullValue(ReturnType);
6530 [[fallthrough]];
6531 case Intrinsic::ssub_sat:
6532 // X - X -> 0, X - undef -> 0, undef - X -> 0
6533 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
6534 return Constant::getNullValue(ReturnType);
6535 // X - 0 -> X
6536 if (match(Op1, m_Zero()))
6537 return Op0;
6538 break;
6539 case Intrinsic::load_relative:
6540 if (auto *C0 = dyn_cast<Constant>(Op0))
6541 if (auto *C1 = dyn_cast<Constant>(Op1))
6542 return simplifyRelativeLoad(C0, C1, Q.DL);
6543 break;
6544 case Intrinsic::powi:
6545 if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
6546 // powi(x, 0) -> 1.0
6547 if (Power->isZero())
6548 return ConstantFP::get(Op0->getType(), 1.0);
6549 // powi(x, 1) -> x
6550 if (Power->isOne())
6551 return Op0;
6553 break;
6554 case Intrinsic::ldexp:
6555 return simplifyLdexp(Op0, Op1, Q, false);
6556 case Intrinsic::copysign:
6557 // copysign X, X --> X
6558 if (Op0 == Op1)
6559 return Op0;
6560 // copysign -X, X --> X
6561 // copysign X, -X --> -X
6562 if (match(Op0, m_FNeg(m_Specific(Op1))) ||
6563 match(Op1, m_FNeg(m_Specific(Op0))))
6564 return Op1;
6565 break;
6566 case Intrinsic::is_fpclass: {
6567 if (isa<PoisonValue>(Op0))
6568 return PoisonValue::get(ReturnType);
6570 uint64_t Mask = cast<ConstantInt>(Op1)->getZExtValue();
6571 // If all tests are made, it doesn't matter what the value is.
6572 if ((Mask & fcAllFlags) == fcAllFlags)
6573 return ConstantInt::get(ReturnType, true);
6574 if ((Mask & fcAllFlags) == 0)
6575 return ConstantInt::get(ReturnType, false);
6576 if (Q.isUndefValue(Op0))
6577 return UndefValue::get(ReturnType);
6578 break;
6580 case Intrinsic::maxnum:
6581 case Intrinsic::minnum:
6582 case Intrinsic::maximum:
6583 case Intrinsic::minimum: {
6584 // If the arguments are the same, this is a no-op.
6585 if (Op0 == Op1)
6586 return Op0;
6588 // Canonicalize constant operand as Op1.
6589 if (isa<Constant>(Op0))
6590 std::swap(Op0, Op1);
6592 // If an argument is undef, return the other argument.
6593 if (Q.isUndefValue(Op1))
6594 return Op0;
6596 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
6597 bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
6599 // minnum(X, nan) -> X
6600 // maxnum(X, nan) -> X
6601 // minimum(X, nan) -> nan
6602 // maximum(X, nan) -> nan
6603 if (match(Op1, m_NaN()))
6604 return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
6606 // In the following folds, inf can be replaced with the largest finite
6607 // float, if the ninf flag is set.
6608 const APFloat *C;
6609 if (match(Op1, m_APFloat(C)) &&
6610 (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
6611 // minnum(X, -inf) -> -inf
6612 // maxnum(X, +inf) -> +inf
6613 // minimum(X, -inf) -> -inf if nnan
6614 // maximum(X, +inf) -> +inf if nnan
6615 if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
6616 return ConstantFP::get(ReturnType, *C);
6618 // minnum(X, +inf) -> X if nnan
6619 // maxnum(X, -inf) -> X if nnan
6620 // minimum(X, +inf) -> X
6621 // maximum(X, -inf) -> X
6622 if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
6623 return Op0;
6626 // Min/max of the same operation with common operand:
6627 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
6628 if (Value *V = foldMinimumMaximumSharedOp(IID, Op0, Op1))
6629 return V;
6630 if (Value *V = foldMinimumMaximumSharedOp(IID, Op1, Op0))
6631 return V;
6633 break;
6635 case Intrinsic::vector_extract: {
6636 Type *ReturnType = F->getReturnType();
6638 // (extract_vector (insert_vector _, X, 0), 0) -> X
6639 unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
6640 Value *X = nullptr;
6641 if (match(Op0, m_Intrinsic<Intrinsic::vector_insert>(m_Value(), m_Value(X),
6642 m_Zero())) &&
6643 IdxN == 0 && X->getType() == ReturnType)
6644 return X;
6646 break;
6648 default:
6649 break;
6652 return nullptr;
6655 static Value *simplifyIntrinsic(CallBase *Call, Value *Callee,
6656 ArrayRef<Value *> Args,
6657 const SimplifyQuery &Q) {
6658 // Operand bundles should not be in Args.
6659 assert(Call->arg_size() == Args.size());
6660 unsigned NumOperands = Args.size();
6661 Function *F = cast<Function>(Callee);
6662 Intrinsic::ID IID = F->getIntrinsicID();
6664 // Most of the intrinsics with no operands have some kind of side effect.
6665 // Don't simplify.
6666 if (!NumOperands) {
6667 switch (IID) {
6668 case Intrinsic::vscale: {
6669 Type *RetTy = F->getReturnType();
6670 ConstantRange CR = getVScaleRange(Call->getFunction(), 64);
6671 if (const APInt *C = CR.getSingleElement())
6672 return ConstantInt::get(RetTy, C->getZExtValue());
6673 return nullptr;
6675 default:
6676 return nullptr;
6680 if (NumOperands == 1)
6681 return simplifyUnaryIntrinsic(F, Args[0], Q);
6683 if (NumOperands == 2)
6684 return simplifyBinaryIntrinsic(F, Args[0], Args[1], Q);
6686 // Handle intrinsics with 3 or more arguments.
6687 switch (IID) {
6688 case Intrinsic::masked_load:
6689 case Intrinsic::masked_gather: {
6690 Value *MaskArg = Args[2];
6691 Value *PassthruArg = Args[3];
6692 // If the mask is all zeros or undef, the "passthru" argument is the result.
6693 if (maskIsAllZeroOrUndef(MaskArg))
6694 return PassthruArg;
6695 return nullptr;
6697 case Intrinsic::fshl:
6698 case Intrinsic::fshr: {
6699 Value *Op0 = Args[0], *Op1 = Args[1], *ShAmtArg = Args[2];
6701 // If both operands are undef, the result is undef.
6702 if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
6703 return UndefValue::get(F->getReturnType());
6705 // If shift amount is undef, assume it is zero.
6706 if (Q.isUndefValue(ShAmtArg))
6707 return Args[IID == Intrinsic::fshl ? 0 : 1];
6709 const APInt *ShAmtC;
6710 if (match(ShAmtArg, m_APInt(ShAmtC))) {
6711 // If there's effectively no shift, return the 1st arg or 2nd arg.
6712 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
6713 if (ShAmtC->urem(BitWidth).isZero())
6714 return Args[IID == Intrinsic::fshl ? 0 : 1];
6717 // Rotating zero by anything is zero.
6718 if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
6719 return ConstantInt::getNullValue(F->getReturnType());
6721 // Rotating -1 by anything is -1.
6722 if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
6723 return ConstantInt::getAllOnesValue(F->getReturnType());
6725 return nullptr;
6727 case Intrinsic::experimental_constrained_fma: {
6728 auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6729 if (Value *V = simplifyFPOp(Args, {}, Q, *FPI->getExceptionBehavior(),
6730 *FPI->getRoundingMode()))
6731 return V;
6732 return nullptr;
6734 case Intrinsic::fma:
6735 case Intrinsic::fmuladd: {
6736 if (Value *V = simplifyFPOp(Args, {}, Q, fp::ebIgnore,
6737 RoundingMode::NearestTiesToEven))
6738 return V;
6739 return nullptr;
6741 case Intrinsic::smul_fix:
6742 case Intrinsic::smul_fix_sat: {
6743 Value *Op0 = Args[0];
6744 Value *Op1 = Args[1];
6745 Value *Op2 = Args[2];
6746 Type *ReturnType = F->getReturnType();
6748 // Canonicalize constant operand as Op1 (ConstantFolding handles the case
6749 // when both Op0 and Op1 are constant so we do not care about that special
6750 // case here).
6751 if (isa<Constant>(Op0))
6752 std::swap(Op0, Op1);
6754 // X * 0 -> 0
6755 if (match(Op1, m_Zero()))
6756 return Constant::getNullValue(ReturnType);
6758 // X * undef -> 0
6759 if (Q.isUndefValue(Op1))
6760 return Constant::getNullValue(ReturnType);
6762 // X * (1 << Scale) -> X
6763 APInt ScaledOne =
6764 APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
6765 cast<ConstantInt>(Op2)->getZExtValue());
6766 if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
6767 return Op0;
6769 return nullptr;
6771 case Intrinsic::vector_insert: {
6772 Value *Vec = Args[0];
6773 Value *SubVec = Args[1];
6774 Value *Idx = Args[2];
6775 Type *ReturnType = F->getReturnType();
6777 // (insert_vector Y, (extract_vector X, 0), 0) -> X
6778 // where: Y is X, or Y is undef
6779 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
6780 Value *X = nullptr;
6781 if (match(SubVec,
6782 m_Intrinsic<Intrinsic::vector_extract>(m_Value(X), m_Zero())) &&
6783 (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
6784 X->getType() == ReturnType)
6785 return X;
6787 return nullptr;
6789 case Intrinsic::experimental_constrained_fadd: {
6790 auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6791 return simplifyFAddInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6792 *FPI->getExceptionBehavior(),
6793 *FPI->getRoundingMode());
6795 case Intrinsic::experimental_constrained_fsub: {
6796 auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6797 return simplifyFSubInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6798 *FPI->getExceptionBehavior(),
6799 *FPI->getRoundingMode());
6801 case Intrinsic::experimental_constrained_fmul: {
6802 auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6803 return simplifyFMulInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6804 *FPI->getExceptionBehavior(),
6805 *FPI->getRoundingMode());
6807 case Intrinsic::experimental_constrained_fdiv: {
6808 auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6809 return simplifyFDivInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6810 *FPI->getExceptionBehavior(),
6811 *FPI->getRoundingMode());
6813 case Intrinsic::experimental_constrained_frem: {
6814 auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
6815 return simplifyFRemInst(Args[0], Args[1], FPI->getFastMathFlags(), Q,
6816 *FPI->getExceptionBehavior(),
6817 *FPI->getRoundingMode());
6819 case Intrinsic::experimental_constrained_ldexp:
6820 return simplifyLdexp(Args[0], Args[1], Q, true);
6821 default:
6822 return nullptr;
6826 static Value *tryConstantFoldCall(CallBase *Call, Value *Callee,
6827 ArrayRef<Value *> Args,
6828 const SimplifyQuery &Q) {
6829 auto *F = dyn_cast<Function>(Callee);
6830 if (!F || !canConstantFoldCallTo(Call, F))
6831 return nullptr;
6833 SmallVector<Constant *, 4> ConstantArgs;
6834 ConstantArgs.reserve(Args.size());
6835 for (Value *Arg : Args) {
6836 Constant *C = dyn_cast<Constant>(Arg);
6837 if (!C) {
6838 if (isa<MetadataAsValue>(Arg))
6839 continue;
6840 return nullptr;
6842 ConstantArgs.push_back(C);
6845 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
6848 Value *llvm::simplifyCall(CallBase *Call, Value *Callee, ArrayRef<Value *> Args,
6849 const SimplifyQuery &Q) {
6850 // Args should not contain operand bundle operands.
6851 assert(Call->arg_size() == Args.size());
6853 // musttail calls can only be simplified if they are also DCEd.
6854 // As we can't guarantee this here, don't simplify them.
6855 if (Call->isMustTailCall())
6856 return nullptr;
6858 // call undef -> poison
6859 // call null -> poison
6860 if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
6861 return PoisonValue::get(Call->getType());
6863 if (Value *V = tryConstantFoldCall(Call, Callee, Args, Q))
6864 return V;
6866 auto *F = dyn_cast<Function>(Callee);
6867 if (F && F->isIntrinsic())
6868 if (Value *Ret = simplifyIntrinsic(Call, Callee, Args, Q))
6869 return Ret;
6871 return nullptr;
6874 Value *llvm::simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q) {
6875 assert(isa<ConstrainedFPIntrinsic>(Call));
6876 SmallVector<Value *, 4> Args(Call->args());
6877 if (Value *V = tryConstantFoldCall(Call, Call->getCalledOperand(), Args, Q))
6878 return V;
6879 if (Value *Ret = simplifyIntrinsic(Call, Call->getCalledOperand(), Args, Q))
6880 return Ret;
6881 return nullptr;
6884 /// Given operands for a Freeze, see if we can fold the result.
6885 static Value *simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6886 // Use a utility function defined in ValueTracking.
6887 if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
6888 return Op0;
6889 // We have room for improvement.
6890 return nullptr;
6893 Value *llvm::simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
6894 return ::simplifyFreezeInst(Op0, Q);
6897 Value *llvm::simplifyLoadInst(LoadInst *LI, Value *PtrOp,
6898 const SimplifyQuery &Q) {
6899 if (LI->isVolatile())
6900 return nullptr;
6902 if (auto *PtrOpC = dyn_cast<Constant>(PtrOp))
6903 return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Q.DL);
6905 // We can only fold the load if it is from a constant global with definitive
6906 // initializer. Skip expensive logic if this is not the case.
6907 auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(PtrOp));
6908 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
6909 return nullptr;
6911 // If GlobalVariable's initializer is uniform, then return the constant
6912 // regardless of its offset.
6913 if (Constant *C =
6914 ConstantFoldLoadFromUniformValue(GV->getInitializer(), LI->getType()))
6915 return C;
6917 // Try to convert operand into a constant by stripping offsets while looking
6918 // through invariant.group intrinsics.
6919 APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
6920 PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
6921 Q.DL, Offset, /* AllowNonInbounts */ true,
6922 /* AllowInvariantGroup */ true);
6923 if (PtrOp == GV) {
6924 // Index size may have changed due to address space casts.
6925 Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
6926 return ConstantFoldLoadFromConstPtr(GV, LI->getType(), Offset, Q.DL);
6929 return nullptr;
6932 /// See if we can compute a simplified version of this instruction.
6933 /// If not, this returns null.
6935 static Value *simplifyInstructionWithOperands(Instruction *I,
6936 ArrayRef<Value *> NewOps,
6937 const SimplifyQuery &SQ,
6938 unsigned MaxRecurse) {
6939 assert(I->getFunction() && "instruction should be inserted in a function");
6940 assert((!SQ.CxtI || SQ.CxtI->getFunction() == I->getFunction()) &&
6941 "context instruction should be in the same function");
6943 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
6945 switch (I->getOpcode()) {
6946 default:
6947 if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
6948 SmallVector<Constant *, 8> NewConstOps(NewOps.size());
6949 transform(NewOps, NewConstOps.begin(),
6950 [](Value *V) { return cast<Constant>(V); });
6951 return ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
6953 return nullptr;
6954 case Instruction::FNeg:
6955 return simplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q, MaxRecurse);
6956 case Instruction::FAdd:
6957 return simplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
6958 MaxRecurse);
6959 case Instruction::Add:
6960 return simplifyAddInst(
6961 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6962 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
6963 case Instruction::FSub:
6964 return simplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
6965 MaxRecurse);
6966 case Instruction::Sub:
6967 return simplifySubInst(
6968 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6969 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
6970 case Instruction::FMul:
6971 return simplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
6972 MaxRecurse);
6973 case Instruction::Mul:
6974 return simplifyMulInst(
6975 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6976 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
6977 case Instruction::SDiv:
6978 return simplifySDivInst(NewOps[0], NewOps[1],
6979 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
6980 MaxRecurse);
6981 case Instruction::UDiv:
6982 return simplifyUDivInst(NewOps[0], NewOps[1],
6983 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
6984 MaxRecurse);
6985 case Instruction::FDiv:
6986 return simplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
6987 MaxRecurse);
6988 case Instruction::SRem:
6989 return simplifySRemInst(NewOps[0], NewOps[1], Q, MaxRecurse);
6990 case Instruction::URem:
6991 return simplifyURemInst(NewOps[0], NewOps[1], Q, MaxRecurse);
6992 case Instruction::FRem:
6993 return simplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q,
6994 MaxRecurse);
6995 case Instruction::Shl:
6996 return simplifyShlInst(
6997 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
6998 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q, MaxRecurse);
6999 case Instruction::LShr:
7000 return simplifyLShrInst(NewOps[0], NewOps[1],
7001 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
7002 MaxRecurse);
7003 case Instruction::AShr:
7004 return simplifyAShrInst(NewOps[0], NewOps[1],
7005 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q,
7006 MaxRecurse);
7007 case Instruction::And:
7008 return simplifyAndInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7009 case Instruction::Or:
7010 return simplifyOrInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7011 case Instruction::Xor:
7012 return simplifyXorInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7013 case Instruction::ICmp:
7014 return simplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
7015 NewOps[1], Q, MaxRecurse);
7016 case Instruction::FCmp:
7017 return simplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
7018 NewOps[1], I->getFastMathFlags(), Q, MaxRecurse);
7019 case Instruction::Select:
7020 return simplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q, MaxRecurse);
7021 break;
7022 case Instruction::GetElementPtr: {
7023 auto *GEPI = cast<GetElementPtrInst>(I);
7024 return simplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
7025 ArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q,
7026 MaxRecurse);
7028 case Instruction::InsertValue: {
7029 InsertValueInst *IV = cast<InsertValueInst>(I);
7030 return simplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q,
7031 MaxRecurse);
7033 case Instruction::InsertElement:
7034 return simplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
7035 case Instruction::ExtractValue: {
7036 auto *EVI = cast<ExtractValueInst>(I);
7037 return simplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q,
7038 MaxRecurse);
7040 case Instruction::ExtractElement:
7041 return simplifyExtractElementInst(NewOps[0], NewOps[1], Q, MaxRecurse);
7042 case Instruction::ShuffleVector: {
7043 auto *SVI = cast<ShuffleVectorInst>(I);
7044 return simplifyShuffleVectorInst(NewOps[0], NewOps[1],
7045 SVI->getShuffleMask(), SVI->getType(), Q,
7046 MaxRecurse);
7048 case Instruction::PHI:
7049 return simplifyPHINode(cast<PHINode>(I), NewOps, Q);
7050 case Instruction::Call:
7051 return simplifyCall(
7052 cast<CallInst>(I), NewOps.back(),
7053 NewOps.drop_back(1 + cast<CallInst>(I)->getNumTotalBundleOperands()), Q);
7054 case Instruction::Freeze:
7055 return llvm::simplifyFreezeInst(NewOps[0], Q);
7056 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
7057 #include "llvm/IR/Instruction.def"
7058 #undef HANDLE_CAST_INST
7059 return simplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q,
7060 MaxRecurse);
7061 case Instruction::Alloca:
7062 // No simplifications for Alloca and it can't be constant folded.
7063 return nullptr;
7064 case Instruction::Load:
7065 return simplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
7069 Value *llvm::simplifyInstructionWithOperands(Instruction *I,
7070 ArrayRef<Value *> NewOps,
7071 const SimplifyQuery &SQ) {
7072 assert(NewOps.size() == I->getNumOperands() &&
7073 "Number of operands should match the instruction!");
7074 return ::simplifyInstructionWithOperands(I, NewOps, SQ, RecursionLimit);
7077 Value *llvm::simplifyInstruction(Instruction *I, const SimplifyQuery &SQ) {
7078 SmallVector<Value *, 8> Ops(I->operands());
7079 Value *Result = ::simplifyInstructionWithOperands(I, Ops, SQ, RecursionLimit);
7081 /// If called on unreachable code, the instruction may simplify to itself.
7082 /// Make life easier for users by detecting that case here, and returning a
7083 /// safe value instead.
7084 return Result == I ? UndefValue::get(I->getType()) : Result;
7087 /// Implementation of recursive simplification through an instruction's
7088 /// uses.
7090 /// This is the common implementation of the recursive simplification routines.
7091 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
7092 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
7093 /// instructions to process and attempt to simplify it using
7094 /// InstructionSimplify. Recursively visited users which could not be
7095 /// simplified themselves are to the optional UnsimplifiedUsers set for
7096 /// further processing by the caller.
7098 /// This routine returns 'true' only when *it* simplifies something. The passed
7099 /// in simplified value does not count toward this.
7100 static bool replaceAndRecursivelySimplifyImpl(
7101 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
7102 const DominatorTree *DT, AssumptionCache *AC,
7103 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
7104 bool Simplified = false;
7105 SmallSetVector<Instruction *, 8> Worklist;
7106 const DataLayout &DL = I->getModule()->getDataLayout();
7108 // If we have an explicit value to collapse to, do that round of the
7109 // simplification loop by hand initially.
7110 if (SimpleV) {
7111 for (User *U : I->users())
7112 if (U != I)
7113 Worklist.insert(cast<Instruction>(U));
7115 // Replace the instruction with its simplified value.
7116 I->replaceAllUsesWith(SimpleV);
7118 if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
7119 I->eraseFromParent();
7120 } else {
7121 Worklist.insert(I);
7124 // Note that we must test the size on each iteration, the worklist can grow.
7125 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
7126 I = Worklist[Idx];
7128 // See if this instruction simplifies.
7129 SimpleV = simplifyInstruction(I, {DL, TLI, DT, AC});
7130 if (!SimpleV) {
7131 if (UnsimplifiedUsers)
7132 UnsimplifiedUsers->insert(I);
7133 continue;
7136 Simplified = true;
7138 // Stash away all the uses of the old instruction so we can check them for
7139 // recursive simplifications after a RAUW. This is cheaper than checking all
7140 // uses of To on the recursive step in most cases.
7141 for (User *U : I->users())
7142 Worklist.insert(cast<Instruction>(U));
7144 // Replace the instruction with its simplified value.
7145 I->replaceAllUsesWith(SimpleV);
7147 if (!I->isEHPad() && !I->isTerminator() && !I->mayHaveSideEffects())
7148 I->eraseFromParent();
7150 return Simplified;
7153 bool llvm::replaceAndRecursivelySimplify(
7154 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
7155 const DominatorTree *DT, AssumptionCache *AC,
7156 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
7157 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
7158 assert(SimpleV && "Must provide a simplified value.");
7159 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
7160 UnsimplifiedUsers);
7163 namespace llvm {
7164 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
7165 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
7166 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
7167 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7168 auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
7169 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
7170 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
7171 return {F.getParent()->getDataLayout(), TLI, DT, AC};
7174 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
7175 const DataLayout &DL) {
7176 return {DL, &AR.TLI, &AR.DT, &AR.AC};
7179 template <class T, class... TArgs>
7180 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
7181 Function &F) {
7182 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
7183 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
7184 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
7185 return {F.getParent()->getDataLayout(), TLI, DT, AC};
7187 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
7188 Function &);
7189 } // namespace llvm
7191 void InstSimplifyFolder::anchor() {}