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